| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700 |
- #include <juce_gui_basics/juce_gui_basics.h>
- #include "engine/FileSort.h"
- #include "platform/Paths.h"
- #include "core/EditorScale.h"
- #include "core/SimplePads.h"
- #include "core/ClipEnvelope.h"
- #include "core/ClipWarp.h"
- #include "core/KeyGuess.h"
- #include "core/EditorPolish.h"
- #include "core/FlpExport.h"
- #include "core/Groove.h"
- #include "core/DrawMode.h"
- #include "core/SessionOps.h"
- #include "ui/ClipGridComponent.h"
- #include "ui/ExternalDrag.h"
- #include "ui/SessionMixer.h"
- #include "core/FlSamplers.h"
- #include "core/ArrangeOps.h"
- #include "core/ClipSample.h"
- #include "core/WarpModes.h"
- #include "ui/ClipAudioPanel.h"
- #include "core/DetailChain.h"
- #include "core/SessionMixer.h"
- #include "core/PlaylistOps.h"
- #include "core/LastTweaked.h"
- #include "core/ClipOps.h"
- #include "core/SamplerPage.h"
- #include "core/FlTrackMenus.h"
- #include "core/FlClipMenu.h"
- #include "core/OneClickRec.h"
- #include "core/WarpTools.h"
- #include "core/Comping.h"
- #include "core/Drumaxx.h"
- #include "core/PatternBlocks.h"
- #include "core/LoadTrace.h"
- #include "core/ProjectSafety.h"
- #include "core/Patcher.h"
- #include "core/Rack.h"
- #include "ui/RackEditor.h"
- #include "ui/DrumRackShot.h"
- #include "ui/GroovePoolComponent.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/ChainPresets.h"
- #include "core/GoalKnobs.h"
- #include "core/MasterLooks.h"
- #include "core/Harmor.h"
- #include "flp/Flp.h"
- #include "core/DemoSongs.h"
- #include "core/FirstSongTour.h"
- #include "core/ShowcaseSong.h"
- #include "core/RenderAhead.h"
- #include "core/SynthPresets.h"
- #include "core/FlWrapper.h"
- #include "engine/AudioEngine.h"
- #include "engine/RemoteControl.h"
- #include "engine/RemoteError.h"
- #include "ui/RemoteControlSettings.h"
- #include "engine/PreviewPlayer.h"
- #include "engine/Metronome.h"
- #include "engine/AudioLogger.h"
- #include "engine/DllAsioDevice.h"
- #include "engine/PipeWireDevice.h"
- #include "platform/LinuxRealtime.h"
- #include "engine/PowerHints.h"
- #include "engine/Exporter.h"
- #include "engine/FlStudioExport.h"
- #include "engine/MidiFileIo.h"
- #include "engine/PluginHost.h"
- #include "engine/Vst3NoteTuning.h"
- #include "engine/PluginSandbox.h"
- #include "engine/Bridge32Test.h"
- #include "engine/ClapFormat.h"
- #include "engine/ClapTeardownTest.h"
- #include "core/EdisonFx.h"
- #include "engine/ProjectFile.h"
- #include "ui/RemoteControl.h"
- #include "core/FlControlMenus.h"
- #include "core/PlaylistOps.h"
- #include "core/Sha256.h"
- #include "engine/SessionPack.h"
- #include "engine/LiveTest.h"
- #include "engine/ShortExportTest.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 "core/AlsImport.h"
- #include "core/PianoRollScript.h"
- #include "ui/ScriptPanel.h"
- #include "ui/AlsExportDialog.h"
- #include "ui/LiveRemoteUi.h"
- #include "ui/GamepadInput.h"
- #include "ui/SettingsPages.h"
- #include "ui/OtherAppsExport.h"
- #include "ui/TimerWhileShowing.h"
- #include "ui/MixerBasicsCheck.h"
- #include "ui/VideoPlayerView.h"
- #include "ui/VideoMedia.h"
- #include "ui/VideoTracks.h"
- #include "ui/AdrWindow.h"
- #include "ui/PlaylistComponent.h"
- #include "ui/PictureCheck.h"
- #include "ui/PatternBlocksView.h"
- #include "ui/PaintAB.h"
- #include <typeinfo>
- #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/GeneratorPresetMenu.h"
- #include "core/GeneratorPresets.h"
- #include "ui/PluginWindow.h"
- #include "ui/Motion.h"
- #include "ui/NativeChild.h"
- #include "ui/Workspace.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 "ui/TempoDetectionDialog.h"
- #include "ui/AudioClipboard.h"
- #include "ui/FlVoicePanel.h"
- #include "ui/SlicexEditor.h"
- #include "ui/FruitySlicerEditor.h"
- #include "core/GrossBeat.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 "core/Slicex.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 "core/StandIns.h"
- #include "ui/ExportDialog.h"
- #include "ui/QuickAddPalette.h"
- #include "ui/I18n.h"
- #include "ui/MainComponent.h"
- #include "ui/SimpleDock.h"
- #include "core/ScaleKeys.h"
- #include "core/KeyFollow.h"
- #include "core/SoundLibrary.h"
- #include "ui/MidiToolsPanel.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/VersionsPanel.h"
- #include "ui/CleanVoiceMenu.h"
- #include "ui/LyricsPanel.h"
- #include "ui/ReferenceMatchPanel.h"
- #include "ui/StartFromPanel.h"
- #include "ui/FirstSongTour.h"
- #include "ui/PluginsOffPanel.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 "ui/PluginHeader.h"
- #include "core/Vfx.h"
- #include "core/TransistorBass.h"
- #include "ui/Splash.h"
- #include "ui/Theme.h"
- #include "ui/ThemeSettings.h"
- #include "ui/WaveformView.h"
- #include "ui/WindowOwner.h"
- #include "ui/PluginKeysTest.h"
- #include "ui/Toolbar.h"
- #include "ui/ToolWindow.h"
- #include "platform/CrashGuard.h"
- #include "ui/CrashReporter.h"
- #include "ui/Updater.h"
- #include "ui/AudioCheck.h"
- #include "ui/StemExtract.h"
- #include "ui/AudioToMidi.h"
- #include "ui/ShotScale.h"
- #include "core/Links.h"
- #include <algorithm>
- #include <atomic>
- #include <exception>
- #include <chrono>
- #include <cstdio>
- #include <ctime>
- #include <cstdlib>
- #include <future>
- #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 std::chrono::system_clock::time_point t0System = std::chrono::system_clock::now(); // (round 190hd: vs the process's creation)
- // (round 190go: always kept, as a field-readable start-up timeline; written to startup.log 5 s and 15 s after the
- // window — with LYNX_TRACE_STARTUP set, at every step as before, so a start that hangs still leaves its last step)
- const bool on = true;
- const bool eachStep = std::getenv ("LYNX_TRACE_STARTUP") != nullptr;
- juce::String text;
- clock::time_point last = t0;
- std::int64_t lastPrivate = 0;
- 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(); };
- // (round 190gd: the process's memory after each step too, so the log says where the megabytes of a start go)
- const auto mb = [] (std::int64_t bytes) { return juce::String ((double) bytes / 1048576.0, 1).paddedLeft (' ', 7); };
- const auto priv = lynx::toolbar::PerformanceMeter::processPrivateBytes();
- const auto ws = lynx::toolbar::PerformanceMeter::processMemoryBytes();
- text << juce::String (ms (now - t0), 1).paddedLeft (' ', 8) << " ms +" << juce::String (ms (now - last), 1).paddedLeft (' ', 7)
- << " private " << mb (priv) << " MB (+" << mb (priv - lastPrivate).trim() << ") ws " << mb (ws) << " MB " << step << "\n";
- lastPrivate = priv;
- last = now;
- if (eachStep)
- write();
- }
- void write() const { lynx::platform::settingsFile ("startup.log").replaceWithText (text); }
- };
- StartupTrace startupTrace;
- void startupMarkHook (const char* step) { startupTrace.mark (step); }
- juce::File crashFolderForTest; // --faulttest: where the crash file goes instead of the settings' autosave folder
- // Crashed: try to save the project and write the backtrace (like FL's "emergency save").
- void onCrash (void* exceptionPointers)
- {
- // (round 190ci: once. The hook for stacks Windows cannot walk, crashguard::setUnwalkableFaultHandler, may have run
- // this before the top-level filter does)
- static std::atomic<bool> reported { false };
- if (reported.exchange (true))
- return;
- const auto folder = crashFolderForTest != juce::File() ? crashFolderForTest : 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; }
- // A file handed to the running application. macOS does this for every Finder double-click, "Open With" and Dock drop,
- // also the one that starts LYNX (its argv has no file). On Windows and Linux a second start is a second process
- // (moreThanOneInstanceAllowed) with the file as an argument, so this is not called there. Only the first file of a
- // multiple selection opens: a project replaces the one before it. (D#92, round 180a)
- void anotherInstanceStarted (const juce::String& commandLine) override
- {
- const auto files = lynx::safety::filesInCommandLine (commandLine.toStdString());
- if (files.empty())
- return;
- const auto file = juce::File::getCurrentWorkingDirectory().getChildFile (juce::String::fromUTF8 (files.front().c_str()));
- if (! startupFileHandled) // still starting: openStartupFile takes it, nothing to ask about yet
- {
- fileToOpen = file;
- return;
- }
- if (mainWindow != nullptr)
- {
- mainWindow->toFront (true);
- mainWindow->getContent().openFileRequest (file);
- }
- }
- 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);
- // rollup 0.1.28 (REA 190hb action 4, FL's "Init DWM"): the compositor on MMCSS, steadier frames under CPU load
- // (Windows; LYNX_DWM_MMCSS=0 leaves it off)
- lynx::powerhints::enableCompositorMmcss();
- // round 190ci: also for a fault on a stack Windows cannot walk, which never reaches that handler (Windows)
- lynx::crashguard::setUnwalkableFaultHandler (onCrash);
- if (const auto args = juce::StringArray::fromTokens (commandLine, true); args.contains ("--faulttest"))
- {
- // LYNX.exe --faulttest plain|unwalkable <folder> (round 190ci): ends by an access violation on purpose,
- // before any window, so that --selftest can check that the crash file gets written (into <folder>)
- const auto i = args.indexOf ("--faulttest");
- crashFolderForTest = juce::File (args[i + 2].unquoted());
- lynx::crashguard::quietCrashReports();
- // round 190dt: guarded / guarded-libc = LYNX's own fault inside a guarded plugin call (Linux / macOS): it must
- // reach the crash handler like any other; a return means the guard swallowed it
- // round 190gg: thread / thread-libc = a fault on a thread of LYNX's own, with LYNX's executable watched as
- // a plugin's module: it must not be parked as a plugin's thread
- if (args[i + 1].startsWith ("thread"))
- {
- lynx::crashguard::faultOnOwnThreadForTest (args[i + 1] == "thread-libc");
- crashFolderForTest.getChildFile ("swallowed.txt").replaceWithText ("parked");
- lynx::crashguard::exitNow (4);
- }
- if (args[i + 1].startsWith ("guarded"))
- {
- const auto code = lynx::crashguard::faultInGuardedCallForTest (args[i + 1] == "guarded-libc");
- crashFolderForTest.getChildFile ("swallowed.txt").replaceWithText (lynx::crashguard::describe (code));
- lynx::crashguard::exitNow (4);
- }
- lynx::crashguard::faultForTest (args[i + 1] == "unwalkable");
- }
- lynx::crashguard::hardenSignals(); // issue #115: stack overflows and SIGTERM / SIGHUP leave a trace (Linux / macOS)
- // 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;
- }
- // --shot-scale <v> / --shot-suffix <text> (round 190bi, ui/ShotScale.h): the pixel scale and file-name suffix of every
- // picture route, taken out here so the routes' own arguments keep their places
- const auto args = lynx::shot::takeArguments (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);
- // interface font: saved in Settings › General; --uifont "Name" overrides it for this run
- const auto uiFontArg = args.indexOf ("--uifont");
- lookAndFeel.applyInterfaceFont (lynx::i18n::current(), uiFontArg >= 0 ? args[uiFontArg + 1].unquoted() : juce::String());
- 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 ("--demosongs"))
- {
- // round 190dv: LYNX's two short genre demos (core/DemoSongs.h) as .lynx files: --demosongs <folder>
- // (resources/demos/ in the repository)
- const auto i = args.indexOf ("--demosongs");
- runDemoSongs (args[i + 1].unquoted());
- 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 ("--renderaheadtest"))
- {
- // LYNX --renderaheadtest report.txt [project.flp|.lynx ...] [--buffer N] [--seconds S] (round 190gq): the engine's
- // own device callback (a stand-in device driven block by block, as --cliplooptest) plays the showcase song (from
- // the start, round a loop region that wraps mid-block, in Pattern mode) and each project with Options › Audio
- // settings › "Render ahead" off, then on. The two outputs must be the same to the bit, nothing rendered ahead
- // may be dropped, and most blocks must come from the ring. No window, no audio device.
- const auto i = args.indexOf ("--renderaheadtest");
- juce::StringArray projects;
- for (int k = i + 2; k < args.size() && ! args[k].startsWith ("--"); ++k)
- projects.add (args[k].unquoted());
- const auto buffer = args.contains ("--buffer") ? args[args.indexOf ("--buffer") + 1].getIntValue() : 128;
- const auto seconds = args.contains ("--seconds") ? args[args.indexOf ("--seconds") + 1].getDoubleValue() : 12.0;
- runRenderAheadTest (juce::File (args[i + 1].unquoted()), projects, juce::jlimit (16, 2048, buffer), seconds > 0.0 ? seconds : 12.0);
- 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 ("--devicechangetest"))
- {
- // LYNX --devicechangetest report.txt [switches] [--plugin file]... (round 190c, issue #134: changing the
- // output device with a project open crashed LYNX). The engine plays a project of every instrument and effect
- // it can make here on stand-in devices with real callback threads, while the output device, its sample
- // rate and its buffer size change the way Settings > Audio changes them (8 kHz mono to 192 kHz, buffers of
- // 32 to 16384 samples, a device plugged in, the open one unplugged, one that refuses to open). After every
- // change the song must sound, finite, at the new rate. No window, no real audio or MIDI device.
- const auto i = args.indexOf ("--devicechangetest");
- const juce::File report (args[i + 1].unquoted());
- const auto switches = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getIntValue() : 0;
- juce::StringArray plugins;
- for (int k = 0; k + 1 < args.size(); ++k)
- if (args[k] == "--plugin")
- plugins.add (args[k + 1].unquoted());
- auto text = std::make_shared<juce::String>();
- // --quick: the selftest's handful of instruments and effects instead of every one
- const auto result = lynx::AudioEngine::deviceChangeSelfTest (switches > 0 ? switches : 40, ! args.contains ("--quick"), plugins, [report, text] (const juce::String& line) {
- *text << line << "\n";
- report.replaceWithText (*text + "(running)\n"); // what was reached, if it crashes
- });
- *text << "device_change=" << result << "\nresult=" << (result.startsWith ("OK") ? "OK" : "FAILED") << "\n";
- report.replaceWithText (*text);
- setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
- quit();
- return;
- }
- if (args.contains ("--exportparitytest") || args.contains ("--midihotplugtest"))
- {
- // LYNX --exportparitytest report.txt (round 190gh, B7): the export against playback through a stand-in audio
- // device, stems adding up to the mix with one length, the PDC trim. LYNX --midihotplugtest report.txt (B8):
- // MIDI devices plugged in and out (stand-in device lists) while messages arrive. No window.
- const auto parity = args.contains ("--exportparitytest");
- const auto i = args.indexOf (parity ? "--exportparitytest" : "--midihotplugtest");
- const juce::File report (args[i + 1].unquoted());
- juce::String text;
- const auto result = parity ? lynx::AudioEngine::exportParitySelfTest ([&text] (const juce::String& line) { text << line << "\n"; })
- : lynx::AudioEngine::midiHotplugSelfTest();
- text << (parity ? "export_parity=" : "midi_hotplug=") << result << "\nresult=" << (result.startsWith ("OK") ? "OK" : "FAILED") << "\n";
- report.replaceWithText (text);
- setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
- quit();
- return;
- }
- if (args.contains ("--shortexporttest"))
- {
- // LYNX --shortexporttest report.txt [repeats] [--plugin file]... (round 190c, issue #138: a short note at
- // the very start of the Playlist exported quiet). Every instrument LYNX can make here, and a synth with
- // effects, tail modes, normalising and other rates, exported through the Export window's path (the job
- // made on the message thread, run on its own thread, the message loop running) with a 2-second note at
- // tick 0 and again with it at bar 2: the note must come out the same. No window.
- const auto i = args.indexOf ("--shortexporttest");
- const juce::File report (args[i + 1].unquoted());
- const auto repeats = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getIntValue() : 0;
- juce::StringArray plugins;
- for (int k = 0; k + 1 < args.size(); ++k)
- if (args[k] == "--plugin")
- plugins.add (args[k + 1].unquoted());
- auto text = std::make_shared<juce::String>();
- lynx::shortexport::run (true, repeats > 0 ? repeats : 3, plugins,
- [report, text] (const juce::String& line) {
- *text << line << "\n";
- report.replaceWithText (*text + "(running)\n");
- },
- [this, report, text] (juce::String result) {
- *text << "short_export=" << result << "\nresult=" << (result.startsWith ("OK") ? "OK" : "FAILED") << "\n";
- report.replaceWithText (*text);
- setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
- quit();
- });
- return;
- }
- if (args.contains ("--slicexedittest"))
- {
- // LYNX --slicexedittest project script.txt report.txt [png-prefix] (round 190aj): the Slicex editor of the
- // project's first Slicex channel, off screen, driven by the script's commands (ui/SlicexEditor.h; mouse
- // gestures at fractions of the deck's width, the menu entries, shortcuts). The report holds each command
- // and what the state held after it; "shot <name>" writes <png-prefix><name>.png.
- const auto i = args.indexOf ("--slicexedittest");
- runSlicexEditTest (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()), juce::File (args[i + 3].unquoted()),
- args.size() > i + 4 ? args[i + 4].unquoted() : juce::String());
- return;
- }
- if (args.contains ("--slicexkeytest"))
- {
- // LYNX --slicexkeytest report.txt (round 190ac): what a click on the Slicex editor's keyboard sends
- // (AudioEngine::sendLiveNote on the channel, velocity 100/128) through the real engine's device callback
- // (a stand-in device, driven block by block): the key's region must sound, on the channel's mixer meter
- // too, another key must play another region, and the note-off must end it.
- runSlicexKeyTest (juce::File (args[args.indexOf ("--slicexkeytest") + 1].unquoted()));
- 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 ("--cachetest"))
- {
- // LYNX --cachetest project.(flp|lynx) report.txt (round 174f): the Playlist's cached picture against exact
- // paints after zooms, scrolls and repaints, off screen (no window)
- const auto i = args.indexOf ("--cachetest");
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- runCacheTest (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
- return;
- }
- if (args.contains ("--picturetest"))
- {
- // LYNX --picturetest report.txt [project.(flp|lynx)] (round 190bm): the Playlist and the Mixer drawn through
- // their cached pictures at 100-300 %, into native and software targets, against straight paints; off
- // screen (no window)
- const auto i = args.indexOf ("--picturetest");
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- runPictureTest (juce::File (args[i + 1].unquoted()), i + 2 < args.size() ? juce::File (args[i + 2].unquoted()) : juce::File());
- return;
- }
- if (args.contains ("--timertest"))
- {
- // LYNX --timertest report.txt (round 174f): ui::TimerWhileShowing through hide / show / minimise (opens a small window)
- runTimerTest (juce::File (args[args.indexOf ("--timertest") + 1].unquoted()));
- return;
- }
- if (args.contains ("--livepeer"))
- {
- // LYNX --livepeer host|guest|rejoin <folder> [--relay URL] [--code CODE|@file]: one computer's side of a live
- // session between two real computers, no window (round 190ah)
- setApplicationReturnValue (lynx::livetest::runPeer (args));
- quit();
- 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 ("--splashshot"))
- {
- // LYNX --splashshot <folder> (round 190hd): the splash card drawn as the JUCE card is and as the card on its own
- // thread is (ui/Splash.h), side by side; no window
- const auto shots = lynx::writeSplashShots (juce::File (args[args.indexOf ("--splashshot") + 1].unquoted()));
- setApplicationReturnValue (shots.size() == 20 ? 0 : 1);
- quit();
- return;
- }
- if (args.contains ("--browser-indexer"))
- {
- // round 190hd: the Browser's indexer, a low-priority child of the LYNX window (BrowserComponent.h): no window,
- // no session, no audio; it ends with its parent
- lynx::crashguard::quietCrashReports();
- lynx::crashguard::exitNow (lynx::BrowserComponent::runIndexerProcess (args));
- }
- 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 ("--linktest"))
- {
- // LYNX --linktest report.txt [seconds] [peer] (round 190gl): Ableton Link with simulated audio callbacks; with
- // "peer" a second Link peer in this process, else a peer on the network (Ableton's LinkHut) is expected
- const auto i = args.indexOf ("--linktest");
- const auto seconds = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getDoubleValue() : 20.0;
- const auto ownPeer = args.contains ("peer");
- juce::File (args[i + 1].unquoted()).replaceWithText (juce::String (lynx::AbletonLink::selfTest (seconds > 0.0 ? seconds : 20.0, ownPeer)));
- 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 ("--wrappermiditest"))
- {
- // LYNX.exe --wrappermiditest plugin.dll report.txt (round 181c), with LYNX_TEST_VST2_MIDILOG set: what a
- // hosted plugin receives after a wrapper MIDI option changes while it runs
- const auto i = args.indexOf ("--wrappermiditest");
- runWrapperMidiTest (args[i + 1].unquoted(), args[i + 2].unquoted());
- return;
- }
- if (args.contains ("--wrappershot"))
- {
- const auto i = args.indexOf ("--wrappershot");
- runWrapperShot (args[i + 1].unquoted(), args[i + 2].unquoted());
- return;
- }
- if (args.contains ("--multiouttest"))
- {
- const auto i = args.indexOf ("--multiouttest");
- runMultiOutTest (args[i + 1].unquoted(), args[i + 2].unquoted());
- return;
- }
- if (args.contains ("--vstitest"))
- {
- // LYNX --vstitest plugin folder [project.lynx] (round 190fw, issue #162): an instrument plugin (Image-Line's
- // "FL Studio VSTi") on a channel: notes in, audio out, its state through a saved project, its outputs and
- // the host tempo it follows. See runVstiTest.
- const auto i = args.indexOf ("--vstitest");
- const auto project = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
- runVstiTest (args[i + 1].unquoted(), args[i + 2].unquoted(), project);
- return;
- }
- if (args.contains ("--vst2test"))
- {
- const auto i = args.indexOf ("--vst2test");
- runVst2Test (args[i + 1].unquoted(), args[i + 2].unquoted());
- return;
- }
- if (args.contains ("--vst3noteidtest"))
- {
- const auto i = args.indexOf ("--vst3noteidtest");
- runVst3NoteIdTest (args[i + 1].unquoted(), args[i + 2].unquoted());
- return;
- }
- if (args.contains ("--lv2scantest"))
- {
- runLv2ScanTest (args[args.indexOf ("--lv2scantest") + 1].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 ("--crashguardtest"))
- {
- // LYNX --crashguardtest "LYNX Test Crash.vst3|.clap" report.txt [process|memcpy] (round 190dt,
- // tools/testplugin/lynx_test_crash*.{c,cpp}): the plugin crashes in its 40th block on insert 1; LYNX must
- // catch it, mark the slot, keep playing the other inserts, save the project, reload the plugin; then the
- // saved project opens with the plugin crashing on its state; and LYNX's own faults are still crashes
- const auto i = args.indexOf ("--crashguardtest");
- runCrashGuardTest (args[i + 1].unquoted(), args[i + 2].unquoted(),
- i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String ("process"));
- 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 ("--clapteardowntest"))
- {
- // LYNX.exe --clapteardowntest "LYNX Test Restart.clap" report.txt (round 190az, engine/ClapTeardownTest.cpp)
- const auto i = args.indexOf ("--clapteardowntest");
- lynx::runClapTeardownTest (args[i + 1].unquoted(), args[i + 2].unquoted(), [this] (int code) {
- setApplicationReturnValue (code);
- quit();
- });
- return;
- }
- if (args.contains ("--mpetest"))
- {
- // LYNX.exe --mpetest "LYNX Test MPE.clap" report.txt (tools/testplugin/lynx_test_mpe.c, issue #108)
- const auto i = args.indexOf ("--mpetest");
- runMpeTest (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 ("--reloadtest"))
- {
- // LYNX --reloadtest plugin report.txt [shots folder] [--wait-kill]: round 190ao (reload a crashed plugin).
- // Hosts the plugin in a separate process (a channel for an instrument, insert 1 for an effect) in an offline
- // engine, crashes its process (--wait-kill: writes <report>.pid and waits for the process to be killed
- // from outside), checks that nothing reloads by itself, reloads it on request and checks the new process,
- // the state captured last, the untouched song and undo history; twice. With a shots folder: PNGs of the
- // plugin window's crash notice and of the prompt.
- const auto i = args.indexOf ("--reloadtest");
- runReloadTest (args[i + 1].unquoted(), args[i + 2].unquoted(),
- i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String(), args.contains ("--wait-kill"));
- return;
- }
- if (args.contains ("--pluginoptionstest"))
- {
- // LYNX --pluginoptionstest plugin report.txt [shots folder]: round 190ao. Hosts the plugin inside LYNX (a
- // channel for an instrument, insert 1 for an effect) in an offline engine, opens its window and checks
- // LYNX's own plugin-window options: Pin on top (set, kept above another window, saved with the plugin,
- // back when the window opens again). With a shots folder: PNGs of each state. The window is on screen.
- const auto i = args.indexOf ("--pluginoptionstest");
- runPluginOptionsTest (args[i + 1].unquoted(), args[i + 2].unquoted(),
- i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String());
- 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 ("--focustest"))
- {
- // LYNX --focustest report.txt (issue #161): the main window with the Playlist and the Piano roll (native
- // child windows with docking on). For each: LYNX goes to the background (the main window loses the focus),
- // the user comes back with a click in the panel, then presses Space: playback must start. Also: a text
- // field's focus comes back with the window, and inside the active window the click's answer is unchanged.
- // Shows a window (takes the foreground on Windows: GUI lock); exit code 0 = OK.
- runFocusTest (args[args.indexOf ("--focustest") + 1].unquoted());
- return;
- }
- if (args.contains ("--simplekeytest"))
- {
- // LYNX --simplekeytest report.txt (round 190fc, 0.1.27 RC H2): the main window in the Simple layout; after a
- // demo opened from Welcome › Start from and after clicks in the dock, its tabs, the Lyrics button, a track
- // header and the grid, Space must start playback (a text field clicked into keeps its typing keys). Shows a
- // window (takes the foreground on Windows: GUI lock); exit code 0 = OK.
- runSimpleKeyTest (args[args.indexOf ("--simplekeytest") + 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, lynx::natives::flDataReader (lynx::flStudioAccess())); 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());
- if (parityShotFailed)
- setApplicationReturnValue (2);
- if (parityShow == nullptr)
- 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 (lynx::shot::snapshot (*c), 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();
- // round 190bi: with --shot-scale / LYNX_SHOT_SCALE each plugin's whole editor at that scale, not the picker's
- // small thumbnail (never for the picker's own cache folder, whatever the environment says)
- const juce::File folder (args[i + 1].unquoted());
- const auto full = lynx::shot::given() && folder != lynx::pluginthumbs::nativeFolder() ? lynx::shot::scale() : 0.0f;
- const auto drawn = lynx::pluginthumbs::renderNative (folder, only, [] (const juce::String& line) {
- std::printf ("%s\n", line.toRawUTF8());
- std::fflush (stdout);
- }, full);
- std::printf ("drawn %d in %.0f ms\n", drawn, juce::Time::getMillisecondCounterHiRes() - t0);
- setApplicationReturnValue (0);
- quit();
- return;
- }
- if (args.contains ("--jsonroundtrip"))
- {
- // LYNX.exe --jsonroundtrip <folder>: round 183c's finding — a project saved, loaded and saved again: both texts
- // (a.json, b.json) and the first lines that differ (diff.txt) for the default song, with and without a Patcher
- const auto i = args.indexOf ("--jsonroundtrip");
- const juce::File out (args[i + 1].unquoted());
- out.createDirectory();
- juce::String report;
- auto check = [&] (const lynx::Song& song, const juce::String& name) {
- const auto a = lynx::ProjectFile::toJson (song);
- juce::String error;
- const auto back = lynx::ProjectFile::fromJson (a, error);
- const auto b = back ? lynx::ProjectFile::toJson (*back) : juce::String ("(not loaded: " + error + ")");
- out.getChildFile (name + "-a.json").replaceWithText (a);
- out.getChildFile (name + "-b.json").replaceWithText (b);
- juce::StringArray la, lb;
- la.addLines (a);
- lb.addLines (b);
- report << name << ": " << (a == b ? "stable" : "DIFFERS") << " (" << la.size() << " / " << lb.size() << " lines)\n";
- int shown = 0;
- for (int k = 0; k < juce::jmax (la.size(), lb.size()) && shown < 12; ++k)
- if (la[k] != lb[k])
- {
- report << " line " << (k + 1) << "\n a: " << la[k].trim().substring (0, 200) << "\n b: " << lb[k].trim().substring (0, 200) << "\n";
- ++shown;
- }
- };
- auto song = lynx::Song::makeDefault();
- check (song, "default");
- song.mixer.resize (3);
- song.mixer[1].effects = { lynx::makeEffectSlot (lynx::EffectKind::patcher) };
- check (song, "patcher");
- song.mixer[1].effects = { lynx::rack::makeRackSlot (lynx::RackDoc::Kind::audioEffect) };
- check (song, "rack");
- out.getChildFile ("diff.txt").replaceWithText (report);
- setApplicationReturnValue (0);
- quit();
- return;
- }
- if (args.contains ("--rackshot"))
- {
- // LYNX.exe --rackshot <folder>: round 183c's Rack view drawn off-screen (no window), for the LYNX | Live pairs:
- // rack-deviceview.png (an Audio Effect Rack laid out as in Live's reference shot), rack-mapmode.png (Map mode
- // with the mapping list), rack-instrument.png (an Instrument Rack with its key zones)
- const auto i = args.indexOf ("--rackshot");
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- const auto set = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
- setApplicationReturnValue (runRackShots (juce::File (args[i + 1].unquoted()), set) ? 0 : 1);
- 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 ("--edisonslottest"))
- {
- // LYNX.exe --edisonslottest folder [project.flp]: round 190cd — the audio editor as a mixer-slot plugin through
- // the engine and the project file (report.txt: one "name=ok|FAIL" per check), its window as slot-*.png, and
- // the Edison slots of an FL project (what was read of each)
- const auto i = args.indexOf ("--edisonslottest");
- const auto ok = runEdisonSlotTest (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
- setApplicationReturnValue (ok ? 0 : 1);
- 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 ("--videotrackshot") && args.indexOf ("--videotrackshot") + 2 < args.size())
- {
- // LYNX.exe --videotrackshot prefix video [video2]: round 174d — the Playlist with video tracks (filmstrips,
- // timecode row) and the video window at a few song positions, as PNGs + report.txt (the decoder, the
- // frame shown for each wanted time: frame accuracy, frames dropped)
- const auto i = args.indexOf ("--videotrackshot");
- runVideoTrackShot (args[i + 1].unquoted(), args[i + 2].unquoted(), i + 3 < args.size() ? args[i + 3].unquoted() : juce::String());
- 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 ("--audioxshot"))
- {
- // LYNX.exe --audioxshot prefix (round 190aq): the pre-fader send, the "Low latency while recording" mark on a
- // bypassed slot and the Browser's "Preview in time", drawn off-screen
- runAudioXShot (args[args.indexOf ("--audioxshot") + 1].unquoted());
- quit();
- return;
- }
- if (args.contains ("--comp177shot"))
- {
- // LYNX.exe --comp177shot prefix project (round 177c): a project of loop takes in the maximised
- // Playlist as it opened; every group after "Comp these takes", with a swipe on the first; the track and record menus
- const auto i = args.indexOf ("--comp177shot");
- runComp177Shot (args[i + 1].unquoted(), args[i + 2].unquoted());
- quit();
- return;
- }
- if (args.contains ("--evpaneshot"))
- {
- // LYNX --evpaneshot prefix [project] (round 190fz): the Piano roll's event editor divider driven with the mouse
- // handlers (drag, right-click = alternate size and back, middle-click = default, a drag into the snap zone),
- // a picture of each state and prefix-report.txt with the heights and the remembered settings file
- const auto i = args.indexOf ("--evpaneshot");
- setApplicationReturnValue (runEvPaneShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
- 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 ("--trackmodeshot"))
- {
- // LYNX --trackmodeshot prefix: rollup 190cv (UI gate of PR #151) — Playlist track header › Track mode › Audio
- // track, off-screen, in three states of FL's live check 190cu (q1-01 fresh, q1-02 one insert linked
- // elsewhere and one renamed, q1-07 the full state), plus a report that compares each list with FL's
- setApplicationReturnValue (runTrackModeShot (args[args.indexOf ("--trackmodeshot") + 1].unquoted()) ? 0 : 1);
- quit();
- return;
- }
- if (args.contains ("--curveshot"))
- {
- // LYNX.exe --curveshot prefix: round 190bw — an automation clip with one segment per FL curve mode in the
- // point editor and in the Playlist, and FL's point menu, off-screen
- runCurveShot (args[args.indexOf ("--curveshot") + 1].unquoted());
- quit();
- return;
- }
- if (args.contains ("--remoteshot"))
- {
- // LYNX.exe --remoteshot prefix: Online Sessions P5-A1 (round 190ai) — the host's "Share plugins with guests"
- // list and a guest's parameter editor of a plugin the host plays, off-screen with sample data
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- lynx::liveui::saveRemoteShots (args[args.indexOf ("--remoteshot") + 1].unquoted());
- juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
- quit();
- return;
- }
- if (args.contains ("--settingsshot") && ! args.contains ("--rtstress")) // (--rtstress has its own --settingsshot file.png option, round 161)
- {
- // LYNX.exe --settingsshot prefix: round 190bx — every Settings page off-screen at the window's size, in a
- // small window (390 x 390) and, for the long pages, whole (see runSettingsShot)
- runSettingsShot (args[args.indexOf ("--settingsshot") + 1].unquoted());
- 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 ("--freezetest"))
- {
- // LYNX.exe --freezetest prefix [project]: round 190ay's Freeze end to end, off-screen (see runFreezeTest)
- const auto i = args.indexOf ("--freezetest");
- const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
- // a word after the project: "keep" = freeze, save prefix-frozen.lynx and stop (the audio stays);
- // "measure" = only load and render the project, for the memory and time of a process of its own
- const auto mode = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
- setApplicationReturnValue (runFreezeTest (args[i + 1].unquoted(), project, mode) ? 0 : 1);
- quit();
- return;
- }
- if (args.contains ("--trackfreezetest"))
- {
- // LYNX --trackfreezetest prefix: round 190ff's Freeze Track, Flatten / Bounce Track in Place, Bounce to New
- // Track and Consolidate end to end in the Clip-launch workflow, off-screen (see runTrackFreezeTest)
- const auto i = args.indexOf ("--trackfreezetest");
- setApplicationReturnValue (runTrackFreezeTest (args[i + 1].unquoted()) ? 0 : 1);
- quit();
- return;
- }
- if (args.contains ("--paintbench"))
- {
- // LYNX --paintbench project.(flp|lynx|als) report.txt (round 190ge): each main view drawn off screen, whole, many
- // times (the message thread's CPU per frame), with the playhead mid-song; no window, no audio device
- const auto i = args.indexOf ("--paintbench");
- runPaintBench (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
- quit();
- return;
- }
- if (args.contains ("--gridshot"))
- {
- // LYNX.exe --gridshot prefix [project]: the Clip-launch workflow's layout off-screen, with a grid of sample
- // clips, some playing and waiting, at the size of LYNX_SNAPSHOT_SIZE (round 181a); with a project (.lynx,
- // .flp, .als), that project's grid instead (round 181c: a Live set's Session view as LYNX imports it)
- const auto i = args.indexOf ("--gridshot");
- const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
- runGridShot (args[i + 1].unquoted(), project);
- quit();
- return;
- }
- if (args.contains ("--tour190dvshot"))
- {
- // LYNX.exe --tour190dvshot prefix: round 190dv off-screen — the Simple workflow's Welcome screen, every step of
- // the first-song tour done with its "Do it for me" (a loop dropped for the loop step), the end card, Back /
- // Next / close, the Help menu, the chooser's tour button, Start from with the three demo songs, a demo
- // opened in Simple — and a text report of the checks (incl. resources/demos/*.lynx = the generated songs)
- const auto i = args.indexOf ("--tour190dvshot");
- runTour190dvShot (args[i + 1].unquoted());
- quit();
- return;
- }
- if (args.contains ("--donateshot"))
- {
- // LYNX --donateshot prefix: round 190fq off-screen (no window) — Help › Support LYNX SHARE... in the three
- // layouts, the Support window, the About window's Support button, the start-up support note in the main
- // window, and the note's rules end to end on its saved state (run it with LYNX_PROFILE_DIR: it writes
- // support-note.txt there, and puts the old one back at the end); report prefix-report.txt, exit 0 = OK
- const auto i = args.indexOf ("--donateshot");
- setApplicationReturnValue (runDonateShot (args[i + 1].unquoted()) ? 0 : 1);
- quit();
- return;
- }
- if (args.contains ("--simpleclosetest"))
- {
- // LYNX --simpleclosetest <report.txt>: round 190fc off-screen (no window) — the main window in the Simple
- // layout with Welcome, the tour, Start from, a demo, the dock's tabs, Finish and Lyrics open, then closed as at
- // shutdown (the 0.1.27 RC crashed on every such close); exit code 0 = OK
- const auto i = args.indexOf ("--simpleclosetest");
- setApplicationReturnValue (runSimpleCloseTest (args[i + 1].unquoted()) ? 0 : 1);
- quit();
- return;
- }
- if (args.contains ("--patterns190ea"))
- {
- // LYNX --patterns190ea <report.txt>: round 190ea off-screen (no window) — a song with no pattern at all
- // reaching the engine in every layout (the Simple dock's Editor tab, the Piano roll panel of the Pattern
- // layout, the Clip-launch layout), the last pattern deleted, all patterns cleared by an edit, undo / redo,
- // a live session's remote song and an out-of-range current pattern; each must leave one pattern and not crash
- const auto i = args.indexOf ("--patterns190ea");
- setApplicationReturnValue (runPatterns190ea (args[i + 1].unquoted()) ? 0 : 1);
- quit();
- return;
- }
- if (args.contains ("--reabl190foshot"))
- {
- // LYNX --reabl190foshot prefix: round 190fo off-screen — the Simple Sampler track's 16 pads in the dock, its
- // menus and kits, the typing keys, the .lynx round trip, a folder of stems and MIDI files — and a report
- const auto i = args.indexOf ("--reabl190foshot");
- runReabl190foShot (args[i + 1].unquoted());
- quit();
- return;
- }
- if (args.contains ("--simple190dsshot"))
- {
- // LYNX.exe --simple190dsshot prefix: round 190ds off-screen, at 1x and 2x — loops dropped in the Simple
- // workflow following the project key (the dock's switch, the clip menu), the docked Piano roll in the Editor
- // tab, the keyboard's modes Keys / Scale keys / Chord pad with the scale selector — and a text report
- const auto i = args.indexOf ("--simple190dsshot");
- runSimple190dsShot (args[i + 1].unquoted());
- quit();
- return;
- }
- if (args.contains ("--simple190dgshot"))
- {
- // LYNX.exe --simple190dgshot prefix: round 190dg's additions to the Simple dock off-screen, at 1x and 2x —
- // the Effects tab with all eight one-knob cards and each card alone, a chain preset with Blend, the
- // favourites in the Preset menu, the sound picker (a search, My plugins with a made-up plugin list) — and a
- // text report of the checks
- const auto i = args.indexOf ("--simple190dgshot");
- runSimple190dgShot (args[i + 1].unquoted());
- quit();
- return;
- }
- if (args.contains ("--simplefxshot"))
- {
- // LYNX.exe --simplefxshot prefix: round 190bu's track dock of the Simple workflow off-screen, at 1x and 2x —
- // the Instrument tab (LYNX sounds, My SoundFonts), the Effects tab (empty, a preset, its menus), and a text
- // report: the dock's edits, a user preset saved and loaded, the same slots in the Pattern workflow's Mixer
- const auto i = args.indexOf ("--simplefxshot");
- runSimpleFxShot (args[i + 1].unquoted());
- quit();
- return;
- }
- if (args.contains ("--simpleshot"))
- {
- // LYNX.exe --simpleshot prefix: round 184a's Simple workflow off-screen — View › Layout style with each style
- // chosen, Settings › General (Pattern, then Simple selected) with its style list, the window in Pattern, then
- // Simple, then Pattern again, and how many Simple workflow objects existed before and after (0 before)
- const auto i = args.indexOf ("--simpleshot");
- runSimpleShot (args[i + 1].unquoted());
- quit();
- return;
- }
- // --versionsshot <prefix> (round 190ap): the Versions panel, File's new items, a project opened without its
- // third-party plugins (window, list, File menu) and the Export window's additions, offscreen
- if (args.contains ("--versionsshot"))
- {
- runVersionsShot (args[args.indexOf ("--versionsshot") + 1].unquoted());
- quit();
- return;
- }
- // --linkshot <prefix> (round 190bt): FL's Remote control settings / Global link settings windows, the control
- // menu with "Link to controller...", the formula presets and controller menus and the Multilink items,
- // offscreen; prefix-checks.txt holds the round's checks of the engine, the project file and the settings
- if (args.contains ("--linkshot"))
- {
- setApplicationReturnValue (runLinkShot (args[args.indexOf ("--linkshot") + 1].unquoted()) ? 0 : 1);
- quit();
- return;
- }
- // --flctlshot <prefix> (round 190df): FL's multilink menu (on / off), the plugin menu's A/B and "Link all
- // parameters...", the sampler's File row with its Sample history, and the Envelope / instrument page of a sampler
- // running FL's voice with its envelope presets, offscreen; prefix-checks.txt holds the checks
- if (args.contains ("--flctlshot"))
- {
- setApplicationReturnValue (runFlCtlShot (args[args.indexOf ("--flctlshot") + 1].unquoted()) ? 0 : 1);
- quit();
- return;
- }
- // --samplerpageshot <prefix> (round 190dh): FL's Sampler page offscreen (shots and checks in prefix-checks.txt)
- if (args.contains ("--samplerpageshot"))
- {
- setApplicationReturnValue (runSamplerPageShot (args[args.indexOf ("--samplerpageshot") + 1].unquoted()) ? 0 : 1);
- quit();
- return;
- }
- // --flplshot <prefix> (round 190dx): the audio clip menu (Preview, Automate › Panning / Volume), the Playlist's "+"
- // and its menu, Track mode › Instrument track, the Channel rack's "Assign to new instrument track", Tools › One-click
- // audio recording and Mixer › Disk recording › Latency compensation, offscreen; prefix-checks.txt holds the checks
- // --hdrshot190ft <prefix> (round 190ft, issues #163 / #164): FL's track-header selection and resize rules driven
- // with synthetic mouse events on the Playlist headers and the mixer strips, offscreen; prefix-checks.txt
- if (args.contains ("--hdrshot190ft"))
- {
- setApplicationReturnValue (runHdrShot190ft (args[args.indexOf ("--hdrshot190ft") + 1].unquoted()) ? 0 : 1);
- quit();
- return;
- }
- // --userfixshot190ib <prefix> (round 190ib): issue #182's type-to-jump in a real popup menu (the Playlist's Edit menu
- // of the issue's screenshot, typed into), #183's Piano roll item, #181's Ctrl+, through the main window's keys;
- // prefix-checks.txt
- if (args.contains ("--userfixshot190ib"))
- {
- setApplicationReturnValue (runUserFixShot190ib (args[args.indexOf ("--userfixshot190ib") + 1].unquoted()) ? 0 : 1);
- quit();
- return;
- }
- // --trackautoshot190gz <prefix> (round 190gz, issue #170): LYNX's "Link Playlist tracks to mixer tracks" — the
- // switch, the linked headers' M / S / volume / pan driven with synthetic mouse events, row sizes, undo and the
- // .lynx round trip, offscreen; prefix-checks.txt
- if (args.contains ("--trackautoshot190gz"))
- {
- setApplicationReturnValue (runTrackAutoShot190gz (args[args.indexOf ("--trackautoshot190gz") + 1].unquoted()) ? 0 : 1);
- quit();
- return;
- }
- if (args.contains ("--flplshot"))
- {
- setApplicationReturnValue (runFlPlShot (args[args.indexOf ("--flplshot") + 1].unquoted()) ? 0 : 1);
- quit();
- return;
- }
- // --genpresetshot <prefix> (round 190fs): the channel window's preset box with the user's own presets (Save
- // preset..., Your presets, Delete preset, Show the presets folder) for Fruity DX10, 3x Osc and LYNX's synth, the
- // name box, a load (one undo step) and the Browser's new channel, offscreen; prefix-checks.txt holds the checks
- if (args.contains ("--genpresetshot"))
- {
- setApplicationReturnValue (runGenPresetShot (args[args.indexOf ("--genpresetshot") + 1].unquoted()) ? 0 : 1);
- quit();
- return;
- }
- // --flfixshot <prefix> (round 190ey): what the live FL session 190ew found different (the Sampler page, the
- // Multilink menu, the Playlist, issue #152's question), offscreen; prefix-checks.txt holds the checks
- if (args.contains ("--flfixshot"))
- {
- setApplicationReturnValue (runFlFixShot (args[args.indexOf ("--flfixshot") + 1].unquoted()) ? 0 : 1);
- quit();
- return;
- }
- // --flclipshot <prefix> (round 190dz): FL's audio clip menu layout (two columns, FL's sections, LYNX's own items at
- // the end) and the channel's Misc › Levels adjustment, offscreen; prefix-checks.txt holds the checks
- if (args.contains ("--flclipshot"))
- {
- setApplicationReturnValue (runFlClipShot (args[args.indexOf ("--flclipshot") + 1].unquoted()) ? 0 : 1);
- quit();
- return;
- }
- if (args.contains ("--warpshot"))
- {
- // LYNX.exe --warpshot prefix: round 190cg's pictures (warp commands in the audio editor, the Clip page's
- // Audio panel, the arrangement with the loop switched off, a folded track, signature changes), off-screen
- const auto i = args.indexOf ("--warpshot");
- runWarpShot (args[i + 1].unquoted());
- quit();
- return;
- }
- // --bandlabshot <prefix> (round 190ch): Lyrics / Notes, Reference match, Start from and Clean voice, offscreen
- if (args.contains ("--bandlabshot"))
- {
- runBandlabShot (args[args.indexOf ("--bandlabshot") + 1].unquoted());
- quit();
- return;
- }
- if (args.contains ("--detailshot"))
- {
- // LYNX.exe --detailshot prefix: the Clip-launch workflow's detail view off-screen (round 183a): a track's chain
- // (instrument, effects, one off, one folded), its clip page, and Pattern workflow before / after, at
- // LYNX_SNAPSHOT_SIZE. Writes prefix-counts.txt with what the chain shows.
- const auto i = args.indexOf ("--detailshot");
- runDetailShot (args[i + 1].unquoted());
- quit();
- return;
- }
- if (args.contains ("--liveshot190ce"))
- {
- // LYNX.exe --liveshot190ce prefix: round 190ce off-screen, in the Ableton-style layout: the Device View's cards
- // with their hot-swap and save buttons, a device's menu, hot-swap on (the Browser's bar, the lit button), a
- // swap and its undo, a duplicate, and the Browser's collections (STARRED tab, the Collections menu, a search
- // by a collection's name). Writes prefix-checks.txt.
- runLiveShot190ce (args[args.indexOf ("--liveshot190ce") + 1].unquoted());
- quit();
- return;
- }
- if (args.contains ("--missingsearchshot190eo"))
- {
- // LYNX --missingsearchshot190eo prefix folder...: round 190eo (integration of issue #159's fix) off-screen: the
- // Missing files window's Samples page while a real search of the folders runs (matches streamed in, Stop
- // shown, Apply usable). Writes prefix-searching.png and prefix-checks.txt; the search is let go at the end.
- const auto i = args.indexOf ("--missingsearchshot190eo");
- const auto prefix = args[i + 1].unquoted();
- juce::StringArray folders;
- for (int k = i + 2; k < args.size(); ++k)
- folders.add (args[k].unquoted());
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- std::shared_ptr<juce::Component> panel = lynx::makeMissingFilesPanelSearching (lynx::missingFilesSnapshotInfo(), folders);
- juce::Timer::callAfterDelay (700, [this, panel, prefix] {
- juce::String status;
- bool stopShown = false, applyEnabled = false;
- const auto searching = lynx::missingFilesSearchState (*panel, status, stopShown, applyEnabled);
- auto image = lynx::shot::paint (*panel, lynx::theme::panel);
- const auto file = juce::File (prefix + "-searching.png");
- file.deleteFile();
- if (auto out = file.createOutputStream())
- juce::PNGImageFormat().writeImageToStream (image, *out);
- juce::String checks;
- auto check = [&checks] (const char* name, bool ok, const juce::String& detail) {
- checks << name << "=" << (ok ? "OK" : "FAIL") << " " << detail << "\n";
- };
- check ("still_searching_at_the_shot", searching, {});
- check ("status_shows_the_walk", status.contains (lynx::tr ("Searching {0}... {1} files looked at").upToFirstOccurrenceOf ("{0}", false, false)), status);
- check ("stop_shown", stopShown, {});
- check ("apply_usable_during_the_search", applyEnabled, {});
- lynx::stopMissingFilesSearch (*panel);
- juce::File (prefix + "-checks.txt").replaceWithText (checks);
- quit();
- });
- return;
- }
- // --grooveshot190fm <prefix> (round 190fm): a Playlist pattern clip's menu with its Groove items (the chooser, Commit,
- // Extract) and the "Classic swing" folder, and a Groove Pool holding classic swing grooves, offscreen;
- // prefix-checks.txt holds the checks (also the .lynx round trip of a Playlist clip's groove)
- if (args.contains ("--grooveshot190fm"))
- {
- setApplicationReturnValue (runGrooveShot190fm (args[args.indexOf ("--grooveshot190fm") + 1].unquoted()) ? 0 : 1);
- quit();
- return;
- }
- if (args.contains ("--mtshot190fm"))
- {
- // LYNX --mtshot190fm prefix: round 190fm off-screen: the MIDI Tools panel's Generate tab with each generator
- // (prefix-generate-rhythm.png … -euclidean.png), the five side by side as Live's picture shows them
- // (prefix-generate-panels.png; Live's: ableton190o/shots/live-04-generate-panels.png), then each generator
- // written into a one-bar pattern and undone again: prefix-checks.txt.
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- runMtShot190fm (args[args.indexOf ("--mtshot190fm") + 1].unquoted());
- quit();
- return;
- }
- if (args.contains ("--drumshot190ec"))
- {
- // LYNX.exe --drumshot190ec prefix: round 190ec off-screen: a demo Drum Rack's pad view (default and scrolled), its
- // chain list with I-O, sends and return chains, a new empty Drum Rack and the Piano roll's pad names. Writes
- // prefix-checks.txt (hit tests: C1 bottom-left, overview scroll, a pad dragged onto another swaps them).
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- lynx::drumshot::run (args[args.indexOf ("--drumshot190ec") + 1].unquoted());
- quit();
- return;
- }
- if (args.contains ("--linkshot190gl"))
- {
- // LYNX --linkshot190gl prefix (round 190gl): Ableton Link off-screen with a second Link peer in this process —
- // the toolbar in FL's Pattern layout (hidden by default, then shown, off and on) and in the Clip-launch layout
- // ("1 Link", the position display's progress bar, Play waiting), Settings › Ableton Link, the toggle's
- // drop-down and the Options menu. Writes prefix-checks.txt.
- runLinkShot190gl (args[args.indexOf ("--linkshot190gl") + 1].unquoted());
- quit();
- return;
- }
- if (args.contains ("--mapshot190ef"))
- {
- // LYNX.exe --mapshot190ef prefix: round 190ef's map modes off-screen, in the Clip-launch workflow: MIDI Map Mode
- // (the overlay over the grid, the Session mixer, the Device View and the transport; the Mapping Browser with
- // Min / Max), Key Map Mode, the row menu, the title bar's Draw / Key / MIDI switches, Ctrl+M / Ctrl+K and the
- // Pattern layout keeping Ctrl+M. Writes prefix-checks.txt.
- runMapShot190ef (args[args.indexOf ("--mapshot190ef") + 1].unquoted());
- quit();
- return;
- }
- if (args.contains ("--sceneshot190ef"))
- {
- // LYNX.exe --sceneshot190ef prefix: round 190ef's scene work off-screen, in the Clip-launch workflow: the scene
- // column with its tempo / time signature fields, the scene menu, a scene field's menu, the column title's menu
- // (Rename, colours), a duplicated scene and a captured scene. Writes prefix-checks.txt.
- runSceneShot190ef (args[args.indexOf ("--sceneshot190ef") + 1].unquoted());
- quit();
- return;
- }
- if (args.contains ("--drawshot190ef"))
- {
- // LYNX.exe --drawshot190ef prefix: round 190ef off-screen, in the Clip-launch workflow: Draw Mode in an
- // automation lane, steps at the grid width and an Alt (no grid) freehand stroke drawn through the Playlist's
- // own mouse handlers, and the Options menu with "Draw Mode". Writes prefix-checks.txt.
- runDrawShot190ef (args[args.indexOf ("--drawshot190ef") + 1].unquoted());
- quit();
- return;
- }
- if (args.contains ("--clipenvshot190gi"))
- {
- // LYNX.exe --clipenvshot190gi prefix: round 190gi off-screen: audio clip envelopes on the Playlist (volume and
- // pan lanes, edited through the Playlist's own mouse handlers), the clip menu's LYNX extras (Clip envelope ›,
- // Auto-warp, Quantize audio, run from the menu), warp flags added on the flag strip and moved with Alt + drag,
- // and the Clip-launch Clip View's Envelopes tab (Clip › Gain, Mixer › Track Panning). Writes prefix-checks.txt.
- runClipEnvShot190gi (args[args.indexOf ("--clipenvshot190gi") + 1].unquoted());
- quit();
- return;
- }
- if (args.contains ("--livefactsshot190gx"))
- {
- // LYNX.exe --livefactsshot190gx prefix: round 190gx off-screen: the Clip page's Audio panel in Live's 190gu
- // layout (Beats: Preserve label + chooser, the loop-mode icon chooser beside the Transient Envelope box;
- // Tones / Texture: Grain Size [+ Flux]; Complex [Pro]), the Envelopes tab with a Clip Gain staircase on Live's
- // axis, choosers at the bottom left, and an unwarped clip without the Envelopes tab. Writes prefix-checks.txt.
- runLiveFactsShot190gx (args[args.indexOf ("--livefactsshot190gx") + 1].unquoted());
- quit();
- return;
- }
- if (args.contains ("--warpshot190fm"))
- {
- // LYNX.exe --warpshot190fm prefix: round 190fm off-screen: the Clip page's Audio panel of a grid audio clip in
- // Beats (Preserve, Transient Loop Mode, Envelope), Tones and Texture (Grain Size), Complex (none), and the clip
- // made unique by a mode change while another clip shares its channel (O16). Writes prefix-checks.txt.
- runWarpShot190fm (args[args.indexOf ("--warpshot190fm") + 1].unquoted());
- quit();
- return;
- }
- if (args.contains ("--liveshot190dr"))
- {
- // LYNX.exe --liveshot190dr prefix: round 190dr off-screen, in the Clip-launch workflow: the Session mixer
- // under the clip grid (default sections, Track Options, Volume only, hidden, its View menu), the Clip page's
- // Sample panel of an audio clip (Warp on / off, the Set buttons while it plays, the sample's title) and a
- // device dragged from one track's Device View to another track. Writes prefix-checks.txt.
- runLiveShot190dr (args[args.indexOf ("--liveshot190dr") + 1].unquoted());
- 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 ("--stabilityshot"))
- {
- // LYNX --stabilityshot <folder> (round 190gg): offscreen PNGs of the crash prompt, the plugin window's crash
- // notice, the Plugin manager's "Separate process" column and the monitor's dropout line (no window opens)
- const auto i = args.indexOf ("--stabilityshot");
- runStabilityShot (args[i + 1].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 ("--audio2midi"))
- {
- // LYNX.exe --audio2midi input.wav melody|harmony|drums notes.csv: the clip menu's Convert to MIDI, without the
- // window (round a2m189b's measurements)
- const auto i = args.indexOf ("--audio2midi");
- const auto mode = args[i + 2] == "drums" ? lynx::a2m::Mode::drums : args[i + 2] == "harmony" ? lynx::a2m::Mode::harmony : lynx::a2m::Mode::melody;
- lynx::AudioEngine loader (false);
- const juce::File csv (args[i + 3].unquoted());
- const auto error = lynx::convertFileToMidiCsv (loader, juce::File (args[i + 1].unquoted()), mode, csv);
- csv.getSiblingFile ("audio2midi.txt").replaceWithText (error.isEmpty() ? "result=OK\n" : "result=FAIL " + error + "\n");
- setApplicationReturnValue (error.isEmpty() ? 0 : 1);
- quit();
- return;
- }
- if (args.contains ("--stems") || args.contains ("--stemexport"))
- {
- // LYNX.exe --stems project.(flp|als|lynx) base.wav [--separate]: one WAV per insert that has sound (like
- // "Export stems"), in one render of the song (round 190gj; --separate: one render per insert, as before).
- // LYNX.exe --stemexport project base.ext options.txt [--separate]: what the Export window writes with these
- // options (exportopts::toText lines: stems, sections, the full mix, formats...), the same code.
- // Both write <base>.txt: the files with their peaks, the renders, the wall and CPU time.
- const auto full = args.contains ("--stemexport");
- const auto i = args.indexOf (full ? "--stemexport" : "--stems");
- const auto separate = args.contains ("--separate");
- juce::String error, report;
- int written = 0;
- {
- lynx::AudioEngine loader (false);
- const juce::File input (args[i + 1].unquoted()), base (args[i + 2].unquoted());
- // an .flp or a Live set (.als) opens through the import, as File › Open does (round 182b)
- auto ok = input.hasFileExtension ("flp;als") ? loader.importFlpFile (input, error) : false;
- if (! input.hasFileExtension ("flp;als"))
- if (auto song = lynx::ProjectFile::load (input, error))
- {
- loader.setSong (std::move (*song));
- ok = true;
- }
- const auto& song = loader.getSong();
- lynx::StemPlan plan;
- if (full && ok)
- plan = lynx::planStemExport (song, lynx::exportopts::fromText (juce::File (args[i + 3].unquoted()).loadFileAsString().toStdString()), base);
- else if (ok)
- {
- // every insert a channel goes to, as "<base> - <insert>.wav", 24-bit, 6 s of tail at most
- lynx::ExportSettings settings;
- plan.sets.push_back ({ song, settings.toOptions() });
- for (int t = 1; t < (int) song.mixer.size(); ++t)
- if (std::any_of (song.channels.begin(), song.channels.end(), [t] (const lynx::ChannelDef& c) { return c.mixerTrack == t; }))
- plan.items.push_back ({ juce::String (t), base.getSiblingFile (base.getFileNameWithoutExtension() + " - " + juce::String (t) + ".wav"), 0, t,
- lynx::makeBounceSong (song, t), settings.toOptions() });
- }
- const auto wallStart = juce::Time::getMillisecondCounterHiRes();
- const auto cpuStart = std::clock();
- lynx::StemRunStats stats;
- std::vector<juce::String> lines (plan.items.size());
- auto previous = wallStart; // (one render per file: the time since the file before is its render's)
- written = lynx::runStemExport (
- plan, [] (std::function<void()> f) { f(); }, {}, {}, {},
- [&] (std::size_t k, bool done, float peak) {
- const auto now = juce::Time::getMillisecondCounterHiRes();
- if (done)
- lines[k] = plan.items[k].file.getFileName() + " peak=" + juce::String (peak) + " ms=" + juce::String (now - previous, 0) + "\n";
- previous = now;
- },
- separate, full, &stats);
- const auto wallMs = juce::Time::getMillisecondCounterHiRes() - wallStart;
- const auto cpuMs = 1000.0 * (double) (std::clock() - cpuStart) / (double) CLOCKS_PER_SEC;
- for (const auto& line : lines)
- report << line;
- report << "renders=" << (stats.passes + stats.alone) << " shared=" << stats.passes << " inshared=" << stats.inPass
- << " alone=" << stats.alone << "\n";
- for (const auto& why : stats.why)
- report << "alone: " << why << "\n";
- report << "wall_ms=" << juce::String (wallMs, 0) << " cpu_ms=" << juce::String (cpuMs, 0) << " make_ms=" << juce::String (stats.makeMs, 0)
- << " render_ms=" << juce::String (stats.renderMs, 0) << "\n";
- }
- report << "stems=" << written << "\n";
- juce::File (args[i + 2].unquoted() + ".txt").replaceWithText (report);
- setApplicationReturnValue (written > 0 ? 0 : 1);
- quit();
- return;
- }
- // --export-als <in.lynx|.flp|.als> <folder> [--live11] [--reference] [--scan]: "<folder>/<name> Project/<name>.als" (round 175a)
- if (args.contains ("--export-als"))
- {
- const auto i = args.indexOf ("--export-als");
- runAlsExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--live11"), args.contains ("--reference"));
- return;
- }
- // --gamepadshot <prefix> (round 184a, S16): the game controller's hints overlay and the MIDI settings page with
- // the option on, offscreen, plus the poller fed fake pad states ("<prefix>-gamepad.txt")
- if (args.contains ("--gamepadshot"))
- {
- runGamepadShot (args[args.indexOf ("--gamepadshot") + 1].unquoted());
- return;
- }
- // --export-bundle <in.lynx|.flp|.als> <folder> [--zip] [--no-mixdown] [--shot <prefix>] (round 184a, S9): File ›
- // Export › "For other apps..." without the window; the report goes to "<folder>/export-bundle.txt"
- if (args.contains ("--export-bundle"))
- {
- const auto i = args.indexOf ("--export-bundle");
- runBundleExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--zip"), ! args.contains ("--no-mixdown"),
- args.contains ("--shot") ? args[args.indexOf ("--shot") + 1].unquoted() : juce::String());
- 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();
- // LYNX_PROFILE_MAIN=<file> (round 174f): the message thread sampled every millisecond, 5-second windows
- if (const auto profile = juce::SystemStats::getEnvironmentVariable ("LYNX_PROFILE_MAIN", {}); profile.isNotEmpty())
- lynx::crashguard::startMainProfiler (profile.toStdString());
- startupTrace.mark ("initialise (normal start)");
- // (round 190hd, Windows) how long before the trace's 0 the process was made: the loader (the exe, its DLLs,
- // relocations) and the static initialisers that ran before this file's
- if (const auto created = lynx::crashguard::processStartTime(); created != 0)
- {
- const auto t0 = (std::uint64_t) std::chrono::duration_cast<std::chrono::microseconds> (startupTrace.t0System.time_since_epoch()).count() * 10u
- + 116444736000000000ull; // (FILETIME: 100 ns since 1601)
- if (t0 > created)
- startupTrace.mark ((" (the process was made " + juce::String ((double) (t0 - created) / 10000.0, 1)
- + " ms before this trace's 0: the loader, the DLLs, the first static initialisers)").toRawUTF8());
- }
- prepareGraphicsDevice();
- 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; a path typed in a terminal may be relative
- // (D#92, round 180a: it was ignored, leaving the blank project with no message). A missing file gets "Could not open".
- if (args.size() > 0 && lynx::safety::isFileArgument (args[0].unquoted().toStdString()))
- fileToOpen = juce::File::getCurrentWorkingDirectory().getChildFile (args[0].unquoted());
- // LYNX --no-plugins project.lynx (round 190ap): File › "Open without third-party plugins..." from the command
- // line, for a project a plugin keeps from opening — no hosted plugin is created, each keeps its settings
- if (const auto i = args.indexOf ("--no-plugins"); i >= 0)
- {
- if (i + 1 < args.size() && lynx::safety::isFileArgument (args[i + 1].unquoted().toStdString()))
- fileToOpen = juce::File::getCurrentWorkingDirectory().getChildFile (args[i + 1].unquoted());
- startWithoutPlugins = fileToOpen.hasFileExtension ("lynx");
- }
- // LYNX_TEST_MODE=1 LYNX --open-event-test <ms> <file>: the file arrives the way macOS's Finder delivers it (a Linux
- // or Windows run can exercise that path): 0 ms = at once, before the window exists
- if (lynx::platform::testMode() && args[0] == "--open-event-test" && args.size() > 2)
- {
- const auto file = args[2].unquoted().quoted();
- if (args[1].getIntValue() == 0)
- anotherInstanceStarted (file);
- else
- juce::Timer::callAfterDelay (args[1].getIntValue(), [this, file] { anotherInstanceStarted (file); });
- }
- // 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());
- }
- // round 190go: the ASIO device of the last session is made and opened from now on, while the splash and the
- // window come up (see below)
- lynx::AudioEngine::prewarmAudioDevice();
- // round 190go: the built-in start-up sound is made while the splash and the window come up (pure maths)
- if (startupOptions.sound && lynx::themeui::current().startupSound.empty())
- startupSampleJob = std::async (std::launch::async, [] { return lynx::makeStartupSample(); });
- // Round 190go (start-up faster than FL Studio): the main window is built first, with the engine ready but no
- // audio device open; the device opens after it. An ASIO device of the last session was made and opened ahead,
- // on a worker, while the window was built (AudioEngine::prewarmAudioDevice; the driver itself only ever runs on
- // JUCE's ASIO thread, as COM wants). Play pressed before the device is open starts with it.
- if (! startupOptions.splash)
- {
- startEngine();
- createMainWindow();
- mainWindow->reveal();
- startupTrace.mark ("window revealed");
- // the device (and the start-up sound) once the window's first frame is on screen
- mainWindow->whenPainted ([this] {
- openAudioDevice();
- openMidiDevices();
- startAfterWindow (false);
- });
- return;
- }
- // the splash first; the main window is built behind its card (still: the logo has not started to drop; building
- // it during the drop would stop the animation, both run on the message thread), then the audio device opens
- // (the start-up sound needs it), and the drop starts with its sound. The window shows the moment the logo has
- // landed (round 190go, A4: before, the window was built only after the drop: the drop, then ~0.6 s of build).
- // Round 190hd (Windows): the card draws on a thread of its own, so the main window is built DURING the drop
- // (startOnItsOwnThread below).
- splash = lynx::makeStartupSplash();
- startupTrace.mark ("splash made");
- splash->showOnDesktop();
- startupTrace.mark ("splash on the desktop");
- if (splash->drawsOnItsOwnThread())
- {
- startWithThreadedSplash();
- return;
- }
- // the rest once the card's first frame is on the screen (round 190go: before, a fixed 40 ms), at the latest
- // after 40 ms
- const auto goOn = [this, started = std::make_shared<bool> (false)] {
- if (std::exchange (*started, true) || splash == nullptr) // (once; or quit meanwhile)
- return;
- startEngine();
- if (splash == nullptr) // quit meanwhile
- return;
- createMainWindow();
- if (splash == nullptr || mainWindow == nullptr)
- return;
- if (startupOptions.sound)
- openAudioDevice (false); // (else after the splash: nothing waits for it)
- // one turn of the message loop before the drop: what fell due while the window was built (JUCE's timers,
- // the window's own async work) runs now, on the still card, not in the drop's first frames
- juce::MessageManager::callAsync ([this] { startDrop(); });
- };
- splash->onFirstFrame = goOn;
- juce::Timer::callAfterDelay (40, goOn);
- }
- // Round 190hd (start-up faster than FL Studio, Windows): the card draws on a thread of its own (ui/Splash.cpp), so
- // nothing the message thread does stops the drop. The card shows at once (no Direct2D device is made for it); the
- // engine starts and the audio device opens behind the still card (an ASIO device of the last session was made and
- // opened ahead on its own thread meanwhile), the drop starts with its sound, and the main window is built while
- // the logo drops and shown as soon as it is built, behind the card (the drop and its sound go on above it); the card
- // fades the moment the logo has landed. The card stays for the drop only (the JUCE card's
- // 2.1 s from the process start was there to keep a fast start from flashing; the drop alone is 1.05 s).
- void startWithThreadedSplash()
- {
- splash->onFirstFrame = [this] {
- if (splash != nullptr && startupTrace.on)
- startupTrace.mark ((" splash: first frame on the screen at "
- + juce::String (std::chrono::duration<double, std::milli> (splash->getFirstFrameTime() - startupTrace.t0).count(), 1) + " ms (its own thread)")
- .toRawUTF8());
- };
- juce::MessageManager::callAsync ([this] {
- if (splash == nullptr) // (quit meanwhile)
- return;
- startEngine();
- if (splash == nullptr)
- return;
- if (startupOptions.sound)
- openAudioDevice (false); // (else after the splash: nothing waits for it)
- startDrop();
- // the main window while the logo drops (one more message, so the drop's start is not held by it)
- juce::MessageManager::callAsync ([this] {
- if (splash == nullptr || mainWindow != nullptr || engine == nullptr)
- return;
- createMainWindow();
- // shown as soon as it is built, behind the card: the logo goes on dropping above it and the card fades at
- // the landing as before (LYNX_REVEAL_AT_LANDING=1: the window shows at the landing, as in round 190go)
- if (mainWindow != nullptr && splash != nullptr
- && juce::SystemStats::getEnvironmentVariable ("LYNX_REVEAL_AT_LANDING", {}) != "1")
- {
- mainWindow->reveal();
- windowRevealed = true;
- startupTrace.mark ("window revealed (behind the card, while the logo drops)");
- splash->raise();
- }
- });
- });
- }
- // the logo's drop and the start-up sound together; the window shows the moment the logo has landed
- void startDrop()
- {
- const auto ownThread = splash != nullptr && splash->drawsOnItsOwnThread(); // (the window is built during the drop)
- if (splash == nullptr || (mainWindow == nullptr && ! ownThread) || engine == nullptr)
- return;
- if (startupOptions.sound)
- playStartupSound();
- splash->setStatus (lynx::tr ("Loading the workspace..."));
- splash->startClock();
- // the minimum counts from the process start (the window and the audio device took part of it already); a card
- // on its own thread stays for the drop (round 190hd)
- splashDuration = ownThread ? landingSeconds : lynx::SplashScreen::remainingDuration (startupTrace.seconds());
- splash->setBarDuration (splashDuration);
- splash->whenLanded (splashDuration, [this] {
- if (splash == nullptr || mainWindow == nullptr)
- return;
- if (startupTrace.on)
- startupTrace.mark (("splash: the drop in " + juce::String (splash->getDropFrames()) + " frames, longest gap "
- + juce::String (splash->getLongestDropGapMs(), 1) + " ms"
- + (splash->getLongestDropGapAt() >= 0.0 ? " (at " + juce::String (splash->getLongestDropGapAt(), 3) + " s of its clock; the frame before: "
- + splash->getLongestDropGapDetail() + ")"
- : juce::String()))
- .toRawUTF8());
- if (! std::exchange (windowRevealed, true))
- {
- mainWindow->reveal();
- startupTrace.mark ("window revealed (after the splash)");
- }
- splash->raise();
- const auto deviceOpen = ! engine->isAudioDeviceOpenPending();
- splash->finish ([this, deviceOpen] {
- splash = nullptr;
- // without the start-up sound the device opens now, once the card has faded (the window is up)
- if (! deviceOpen)
- openAudioDevice();
- openMidiDevices();
- if (! deviceOpen)
- startAfterWindow (true);
- });
- if (deviceOpen)
- mainWindow->whenPainted ([this] { startAfterWindow (true); });
- });
- }
- // what follows the window's first frame (the audio device is open): the notice of an unclean end, the start-up
- // project, the probes and the update check; on a first run (with the splash) the setup wizard
- void startAfterWindow (bool offerSetupWizard)
- {
- if (std::exchange (startedAfterWindow, true) || mainWindow == nullptr)
- return;
- // (round 190go) each step after the window is a timed line of the start-up trace
- showUncleanNotice();
- startupTrace.mark ("after the window: unclean-session notice");
- openStartupFile();
- startupTrace.mark ("startup file opened");
- startOpenTimeProbe();
- startUpdateCheck();
- startSupportNote(); // (round 190fq)
- startupTrace.mark ("after the window: probes, update check scheduled");
- juce::MessageManager::callAsync ([] { startupTrace.mark ("first message loop turn"); });
- markSettled(); // (round 190gd)
- // first run: language, audio, plugin folders (FL Studio's included) and a background scan
- if (! offerSetupWizard)
- return;
- if (! lynx::setupWizardDone() && lynx::platform::testMode())
- lynx::platform::testModeLog ("setup wizard");
- else if (! lynx::setupWizardDone())
- {
- mainWindow->showSetupWizard();
- startupTrace.mark ("after the window: setup wizard shown");
- }
- }
- // round 190fq: the start-up support note (ui/SupportLynx.h) counts this start and, from the 10th on, may show its
- // card once at a quiet moment. Only here, on the normal start path (the command-line modes returned earlier); test
- // mode and CI machines neither count nor show it.
- void startSupportNote()
- {
- if (mainWindow == nullptr)
- return;
- const auto env = [] (const char* name) { return juce::SystemStats::getEnvironmentVariable (name, {}).toStdString(); };
- const auto quiet = lynx::supportnote::quietEnvironment (lynx::platform::testMode(), env ("CI"), env ("GITHUB_ACTIONS"), env ("LYNX_NO_SUPPORT_NOTE"));
- if (quiet && lynx::platform::testMode())
- lynx::platform::testModeLog ("support note: not counted (test mode)");
- mainWindow->getContent().startSupportNote (quiet);
- }
- // the start-up trace's last lines: what the first seconds after the window add (lazy work, caches, the first paints)
- static void markSettled()
- {
- if (! startupTrace.on)
- return;
- juce::Timer::callAfterDelay (5000, [] { startupTrace.mark ("5 s after the window"); startupTrace.write(); });
- juce::Timer::callAfterDelay (15000, [] { startupTrace.mark ("15 s after the window"); startupTrace.write(); });
- }
- // Round 190hd (Windows): the Direct3D 11 + Direct2D device (~0.35 s: the graphics driver loads) is made once, on a
- // worker, while the splash card, the engine and the audio device come up, and kept until LYNX closes: a 1 x 1
- // Direct2D image holds JUCE's shared DirectX object (its devices), so the main window finds them made and nothing
- // makes them again (before, every holder going away -- the splash's logo, a temporary one -- could mean a new device
- // at its next use). Other systems: nothing to do.
- void prepareGraphicsDevice()
- {
- #if JUCE_WINDOWS
- if (juce::SystemStats::getEnvironmentVariable ("LYNX_GPU_PREWARM", {}) == "0")
- return;
- graphicsDeviceJob = std::async (std::launch::async, [] {
- const auto from = std::chrono::steady_clock::now();
- juce::Image holder (juce::Image::ARGB, 1, 1, false); // (NativeImageType: Direct2D, the shared device)
- return std::make_pair (holder, std::chrono::duration<double, std::milli> (std::chrono::steady_clock::now() - from).count());
- });
- #endif
- }
- void markGraphicsDevice()
- {
- if (! graphicsDeviceJob.valid() || ! startupTrace.on || std::exchange (graphicsDeviceMarked, true))
- return;
- const auto ready = graphicsDeviceJob.wait_for (std::chrono::seconds (0)) == std::future_status::ready;
- startupTrace.mark (ready ? (" graphics device made on a worker in " + juce::String (graphicsDeviceJob.get().second, 1) + " ms").toRawUTF8()
- : " graphics device: still being made on its worker");
- }
- void startEngine()
- {
- startupTrace.mark ("before the audio engine");
- lynx::BrowserComponent::allowIndexerProcess = true; // (round 190hd: the normal window only)
- // (round 190go) ready to play, no device open yet: see openAudioDevice
- engine = std::make_unique<lynx::AudioEngine> (true, -1, true, true);
- lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
- startupTrace.mark ("audio engine (no device yet)");
- crashEngine = engine.get();
- lynx::crashreporter::watchAudioDevice (engine->getDeviceManager()); // (the session file names the device: crash reports)
- // 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&)
- {
- }
- }
- // The audio device of the last session, then (withSound) the start-up sound on it (once; message thread)
- void openAudioDevice (bool withSound = true)
- {
- if (engine == nullptr || ! engine->isAudioDeviceOpenPending())
- return;
- engine->openAudioDevice();
- if (const auto prewarmed = lynx::asioPrewarmReport(); prewarmed.isNotEmpty() && startupTrace.on)
- startupTrace.mark ((" " + prewarmed).toRawUTF8());
- startupTrace.mark ("audio device opened");
- addDriverFileDeviceType();
- if (withSound)
- playStartupSound();
- }
- void playStartupSound()
- {
- if (startupOptions.sound && ! std::exchange (startupSoundPlayed, true) && engine != nullptr)
- {
- // 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()));
- if (sound == nullptr && startupSampleJob.valid())
- sound = startupSampleJob.get();
- engine->previewSample (sound != nullptr ? sound : lynx::makeStartupSample());
- }
- startupTrace.mark ("startup sound");
- }
- void openMidiDevices()
- {
- if (engine != nullptr)
- engine->openMidiDevices(); // (its own line in the start-up trace: "engine: MIDI inputs")
- }
- 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");
- lynx::remoteui::install ([this] (bool enabled) {
- remoteControl = nullptr;
- if (enabled)
- remoteControl = lynx::RemoteControl::create (*engine, true, [this] {
- const auto title = mainWindow != nullptr ? mainWindow->getName() : juce::String ("Untitled");
- const auto separator = title.indexOf (" - ");
- return separator >= 0 ? title.substring (separator + 3) : title;
- }, [this] {
- const auto file = mainWindow != nullptr ? mainWindow->getContent().getCurrentProjectFile() : juce::File();
- return file == juce::File() ? juce::String() : file.getFullPathName();
- });
- lynx::remoteui::setRuntimeStatus (remoteControl != nullptr && remoteControl->active());
- });
- markGraphicsDevice();
- }
- // 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()
- {
- startupFileHandled = true;
- if (fileToOpen != juce::File() && mainWindow != nullptr)
- {
- if (std::exchange (startWithoutPlugins, false)) // --no-plugins (round 190ap)
- mainWindow->getContent().openNextWithoutPlugins (true);
- mainWindow->openFile (fileToOpen);
- mainWindow->getContent().openNextWithoutPlugins (false); // (a file that did not open leaves nothing behind)
- }
- else if (mainWindow != nullptr && openTimeReport == juce::File())
- mainWindow->getContent().openStartupProject(); // issue #123 (FL's Startup project)
- }
- void shutdown() override
- {
- parityShow.reset(); // (LYNX_PARITYSHOT_SHOW's window, before the engine it shows)
- 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)
- lynx::shutdownAudioToMidi(); // (the same for a conversion to MIDI)
- if (mainWindow != nullptr && mainWindow->isVisible())
- mainWindow->saveState();
- lynx::remoteui::shutdown();
- remoteControl = nullptr; // cancels queued control work before its engine and UI go
- mainWindow = nullptr; // the UI goes before the engine
- graphicsDeviceJob = {}; // (round 190hd: the graphics device's holder, after every window)
- lynx::updater::shutdown(); // (a check or download in flight stops)
- crashEngine = nullptr;
- engine = nullptr;
- // separate-process plugins end on threads of their own (issue #159): a moment for them, never the 10 s a dead
- // child's pipe can take
- lynx::finishSandboxTeardowns (2000);
- // CLAP plugins whose instance another thread deleted while this one was busy: deactivated and destroyed now
- lynx::ClapPluginFormat::finishPendingTeardowns();
- juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
- heartbeat.stopTimer();
- lynx::crashreporter::shutdown(); // (an upload in flight gets a moment, never long)
- lynx::crashguard::stopHangWatch();
- lynx::crashguard::stopMainProfiler();
- 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_PROFILE_DIR=<folder> LYNX --lv2scantest report.txt (Linux, issue #85): the LV2 scan's promise, with real child
- // processes. A new PluginHost per step, as every start of LYNX has. The LV2 folders of the machine are read too.
- void runLv2ScanTest (const juce::String& reportPath)
- {
- juce::String report;
- auto ok = lynx::platform::profileOverride() != juce::File();
- #if JUCE_LINUX
- const auto folder = lynx::platform::profileOverride().getChildFile ("lv2-test");
- const juce::FileSearchPath paths (folder.getFullPathName());
- const auto check = [&] (const juce::String& name, bool passed) {
- report << name << "=" << (passed ? "ok" : "FAILED") << "\n";
- ok = ok && passed;
- };
- const auto install = [&] (const juce::String& name) {
- const auto bundle = folder.getChildFile (name + ".lv2");
- bundle.createDirectory();
- bundle.getChildFile ("manifest.ttl").replaceWithText ("@prefix lv2: <http://lv2plug.in/ns/lv2core#> .\n@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n"
- "<urn:lynx-test:" + name + "> a lv2:Plugin ; lv2:binary <" + name + ".so> ; rdfs:seeAlso <plugin.ttl> .\n");
- bundle.getChildFile ("plugin.ttl").replaceWithText ("@prefix doap: <http://usefulinc.com/ns/doap#> .\n<urn:lynx-test:" + name + "> doap:name \"" + name + "\" .\n");
- };
- auto date = juce::Time::getCurrentTime();
- const auto touch = [&] { // the next date, whatever the file system's date resolution
- date += juce::RelativeTime::seconds (2.0);
- folder.getChildFile ("a.lv2/plugin.ttl").setLastModificationTime (date);
- };
- const auto listed = [] (lynx::PluginHost& host, const juce::String& name) {
- for (const auto& d : host.getKnownPlugins().getTypes())
- if (d.fileOrIdentifier == "urn:lynx-test:" + name)
- return true;
- return false;
- };
- const auto step = [&] (const juce::String& name, int children, const std::function<void (lynx::PluginHost&)>& prepare = {}) {
- lynx::PluginHost host (true);
- if (prepare)
- prepare (host);
- host.scan (paths, {});
- check (name, host.scanChildrenStarted() == children && listed (host, "a"));
- };
- install ("a");
- step ("first_scan_one_child", 1);
- step ("nothing_changed_no_child", 0);
- touch();
- step ("ttl_updated", 1);
- install ("b");
- step ("bundle_installed", 1);
- step ("forget_file", 1, [] (lynx::PluginHost& host) { host.forgetFile ("urn:lynx-test:a"); });
- step ("forget_all", 1, [] (lynx::PluginHost& host) { host.forgetAll(); });
- lynx::platform::settingsFile ("plugins.xml").deleteFile();
- step ("list_lost", 1);
- step ("nothing_changed_again", 0);
- // cancelled while the child works: stopped at once, and nothing is taken for done
- touch();
- setenv ("LYNX_TEST_CRASH", "lv2-batch-hang", 1);
- {
- lynx::PluginHost host (true);
- const auto started = juce::Time::getMillisecondCounter();
- host.scan (paths, [] (float, const juce::String&) { return false; });
- check ("cancel_stops_the_child", host.scanChildrenStarted() == 1 && juce::Time::getMillisecondCounter() - started < 20000);
- }
- unsetenv ("LYNX_TEST_CRASH");
- step ("described_after_cancel", 1);
- // the child dies: plugin by plugin takes over (stopped after two of them: a machine may have hundreds)
- touch();
- setenv ("LYNX_TEST_CRASH", "lv2-batch", 1);
- {
- lynx::PluginHost host (true);
- host.scan (paths, [&host] (float, const juce::String&) { return host.scanChildrenStarted() < 3; });
- check ("crash_falls_back_plugin_by_plugin", host.scanChildrenStarted() == 3);
- auto blamed = false;
- for (const auto& file : host.getKnownPlugins().getBlacklistedFiles())
- blamed = blamed || file.startsWith ("lv2-folders:");
- check ("crash_blacklists_nothing", ! blamed);
- }
- unsetenv ("LYNX_TEST_CRASH");
- step ("described_after_crash", 1);
- // round 190fw: past the first limit, a child that still works is waited for (FL Studio's own VST plugin boots
- // the FL engine), one that sits still is killed as before, and a busy one only up to the cap. Limits are
- // shortened for the test: 2 s first limit, 2 s without work, 8 s cap (real: 30 s, 30 s, 5 min).
- setenv ("LYNX_TEST_SCAN_MS", "2000,2000,8000", 1);
- const auto timed = [&] (const char* fault, const std::function<bool (lynx::PluginHost&)>& progress) {
- touch();
- setenv ("LYNX_TEST_CRASH", fault, 1);
- lynx::PluginHost host (true);
- const auto started = juce::Time::getMillisecondCounter();
- host.scan (paths, [&] (float, const juce::String&) { return ! progress || progress (host); });
- unsetenv ("LYNX_TEST_CRASH");
- const auto took = (int) (juce::Time::getMillisecondCounter() - started);
- report << " " << fault << ": " << took << " ms, children " << host.scanChildrenStarted() << "\n";
- return std::make_pair (took, host.scanChildrenStarted());
- };
- // (after a failed batch, one plugin-by-plugin child and no more: it describes quickly)
- const auto stopAfterBatch = [] (lynx::PluginHost& host) { return host.scanChildrenStarted() < 2; };
- {
- const auto [took, children] = timed ("lv2-batch-busy:5000", {});
- check ("busy_child_is_waited_for", children == 1 && took >= 4500);
- }
- {
- const auto [took, children] = timed ("lv2-batch-hang", stopAfterBatch);
- check ("idle_child_ends_near_the_first_limit", children == 2 && took >= 1900 && took < 9000);
- }
- {
- const auto [took, children] = timed ("lv2-batch-busy:60000", stopAfterBatch);
- check ("busy_child_ends_at_the_cap", children == 2 && took >= 7500 && took < 20000);
- }
- unsetenv ("LYNX_TEST_SCAN_MS");
- step ("described_after_slow_children", 1);
- #endif
- juce::File (reportPath).replaceWithText (report + "result=" + (ok ? "OK" : "FAILED") + "\n");
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- }
- // LYNX.exe --selftest report.txt: renders 2 s without a sound card and writes the result.
- // Exit code 0 = audio came out, 1 = silence.
- // --selftest (round 190ci): two more copies of LYNX end by a fault on purpose (--faulttest), one on a normal stack
- // (the top-level filter) and one on a stack Windows cannot walk (the first-chance hook); each must leave
- // "crash <time>.txt" with the access violation in the folder it is given.
- // Round 190dt (Linux / macOS): a plain fault, and LYNX's own fault inside a guarded plugin call (in its code, and in
- // the C library called from its code), must each leave the crash file with the signal: the plugin guard passes
- // LYNX's own faults on to the crash handler instead of swallowing them ("swallowed.txt" = it did).
- // Round 190gj (P9): the inserts' stems from one render are the files each stem's own render writes, byte for byte
- // (a short song with a bus, a send return, delay compensation, a channel on the Master, an automated insert and a
- // side-chained insert), streamed (24-bit WAV with the full mix) and buffered (normalised float).
- static juce::String stemsSinglePassSelfTest()
- {
- auto s = lynx::Song::makeDefault();
- s.mixer = lynx::Song::defaultMixer (7);
- for (std::size_t c = 0; c < s.channels.size(); ++c)
- s.channels[c].mixerTrack = (int) c + 1;
- auto onMaster = s.channels[2];
- onMaster.mixerTrack = 0;
- onMaster.pan = -0.4f;
- s.channels.push_back (onMaster);
- for (int step : { 1, 5, 9, 13 })
- s.patterns[0].toggleStep ((int) s.channels.size() - 1, step);
- for (int step : { 4, 12 })
- s.patterns[0].toggleStep (3, step); // the snare
- for (int k = 0; k < 4; ++k) // the synth under the kick (its compressor listens to it)
- s.patterns[0].notes.push_back ({ (std::int64_t) k * lynx::ppq, lynx::ppq - 60, 4, 57 + 3 * k, 0.9f });
- s.patterns[0].sortNotes();
- s.mixer[0].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::limiter));
- s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::compressor));
- s.mixer[2].toMaster = false;
- s.mixer[2].sends = { lynx::MixerSend { 6, 1.0f } };
- s.mixer[3].sends = { lynx::MixerSend { 7, 0.5f } };
- s.mixer[3].latencyMs = 3.0f;
- s.mixer[4].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay));
- s.mixer[4].latencyMs = 5.0f;
- s.mixer[4].sends = { lynx::MixerSend { 6, 0.7f } };
- s.mixer[4].masterLevel = 0.8f;
- auto keyed = lynx::makeEffectSlot (lynx::EffectKind::compressor);
- keyed.params[0] = 0.5f; // (−30 dB: the kick's hits pull the synth down)
- keyed.sidechain = 1;
- s.mixer[5].effects.push_back (keyed);
- s.mixer[6].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::distortion));
- s.mixer[7].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::reverb));
- lynx::Automation a;
- a.target = { lynx::AutomationTargetKind::mixerPan, 3 };
- a.points = { { 0, 0.2f, 0.0f }, { 8 * lynx::ppq, 0.9f, 0.0f } };
- s.automations.push_back (a);
- s.playlist.clear();
- for (int bar = 0; bar < 2; ++bar)
- s.playlist.push_back ({ 0, 0, bar * 4 * lynx::ppq, 4 * lynx::ppq, 0 });
- lynx::Clip automationClip;
- automationClip.kind = lynx::ClipKind::automation;
- automationClip.automation = 0;
- automationClip.length = 8 * lynx::ppq;
- automationClip.track = 1;
- s.playlist.push_back (automationClip);
- s.mode = lynx::PlayMode::song;
- const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-stems190gj-" + juce::String (juce::Time::currentTimeMillis()));
- juce::String problems;
- auto run = [&] (lynx::exportopts::Options o, const juce::String& name) {
- o.stems = lynx::exportopts::Stems::mixerTracks;
- o.maxTailSeconds = 3.0;
- const auto alone = dir.getChildFile ("alone"), shared = dir.getChildFile ("shared");
- alone.createDirectory();
- shared.createDirectory();
- const auto ext = juce::String (lynx::exportopts::extension (o.format));
- const auto planAlone = lynx::planStemExport (s, o, alone.getChildFile (name + ext));
- const auto planShared = lynx::planStemExport (s, o, shared.getChildFile (name + ext));
- auto now = [] (std::function<void()> f) { f(); };
- lynx::StemRunStats stats;
- const auto a = lynx::runStemExport (planAlone, now, {}, {}, {}, {}, true);
- const auto b = lynx::runStemExport (planShared, now, {}, {}, {}, {}, false, true, &stats);
- if (a != (int) planAlone.items.size() || b != a)
- problems << name << ": " << a << " / " << b << " files; ";
- // (every insert from the one render, insert 5 with its side-chain too: it stays ducked as in the mix)
- if (stats.passes != 1 || stats.inPass < 6)
- problems << name << ": renders " << stats.passes << " shared, " << stats.inPass << " in it, " << stats.alone << " alone; ";
- for (std::size_t k = 0; k < planShared.items.size() && k < planAlone.items.size(); ++k)
- {
- juce::MemoryBlock x, y;
- planAlone.items[k].file.loadFileAsData (x);
- planShared.items[k].file.loadFileAsData (y);
- if (x.getSize() == 0 || x != y)
- problems << name << ": " << planShared.items[k].file.getFileName() << " differs; ";
- }
- };
- lynx::exportopts::Options streamed;
- streamed.wavBits = 24;
- streamed.stemsIncludeMaster = true;
- run (streamed, "streamed");
- lynx::exportopts::Options buffered;
- buffered.wavBits = 32;
- buffered.normalize = true;
- run (buffered, "buffered");
- dir.deleteRecursively();
- return problems.isEmpty() ? juce::String ("OK") : "ERROR " + problems;
- }
- static juce::String faultReportSelfTest()
- {
- #if (JUCE_WINDOWS && (defined (_M_X64) || defined (__x86_64__))) \
- || ((JUCE_LINUX || JUCE_MAC) && (defined (__x86_64__) || defined (__aarch64__)))
- const auto exe = juce::File::getSpecialLocation (juce::File::currentExecutableFile);
- const auto root = juce::File::getSpecialLocation (juce::File::tempDirectory)
- .getChildFile ("lynx-faulttest-" + juce::String::toHexString (juce::Random::getSystemRandom().nextInt64()));
- juce::StringArray problems;
- #if JUCE_WINDOWS
- const char* const kinds[] = { "plain", "unwalkable" };
- #else
- const char* const kinds[] = { "plain", "guarded", "guarded-libc", "thread", "thread-libc" };
- #endif
- for (const auto* kind : kinds)
- {
- const auto folder = root.getChildFile (kind);
- folder.createDirectory();
- juce::ChildProcess child;
- const auto started = child.start (juce::StringArray { exe.getFullPathName(), "--faulttest", kind, folder.getFullPathName() }, 0);
- if (! started || ! child.waitForProcessToFinish (60000))
- {
- child.kill();
- problems.add (juce::String (kind) + ": " + (started ? "did not end" : "did not start"));
- continue;
- }
- juce::String text;
- for (const auto& file : folder.findChildFiles (juce::File::findFiles, false, "crash *.txt"))
- text = file.loadFileAsString();
- #if JUCE_WINDOWS
- const auto found = text.contains ("0xc0000005");
- #else
- const auto found = text.contains ("segmentation fault") || text.contains ("bus error");
- #endif
- if (folder.getChildFile ("swallowed.txt").existsAsFile())
- problems.add (juce::String (kind) + ": LYNX's own fault was caught as a plugin's ("
- + folder.getChildFile ("swallowed.txt").loadFileAsString() + ")");
- else if (! found)
- problems.add (juce::String (kind) + ": " + (text.isEmpty() ? "no crash file" : "a crash file without the fault")
- + " (exit code 0x" + juce::String::toHexString ((juce::int64) child.getExitCode()) + ")");
- }
- root.deleteRecursively();
- return problems.isEmpty() ? juce::String ("OK") : "ERROR " + problems.joinIntoString ("; ");
- #else
- return "SKIPPED (Windows x64, Linux / macOS x86-64 / ARM64 only)";
- #endif
- }
- 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)
- { // the clip grid (round 181a)
- lynx::launcher::setClip (original, 1, 2, { 0, 0, 0, 1920, 0 });
- auto& slot = *lynx::launcher::settingsAt (*original.clipGrid, 1, 2);
- slot.name = "Clip ação";
- slot.mode = lynx::LaunchMode::toggle;
- slot.quant = lynx::LaunchQuant::eighthTriplet;
- slot.legato = true;
- slot.loop = false;
- original.clipGrid->scenes[0].name = "Intro";
- original.clipGrid->globalQuant = lynx::LaunchQuant::bars2;
- }
- std::uint32_t savedGroove = 0;
- { // round 190bv: the groove pool, a groove on the slot's clip, and that clip copied and the copy moved
- lynx::Groove g;
- g.name = "Balanço";
- g.base = lynx::GrooveBase::eighth;
- g.quantize = 0.25f;
- g.timing = 0.8f;
- g.random = 0.1f;
- g.velocity = -0.5f;
- g.length = 1920;
- g.points = { { 0, 1.0f }, { 560, 0.5f } };
- savedGroove = lynx::groove::add (original.grooves, g);
- original.grooves.amount = 1.2f;
- lynx::groove::setClipGroove (original, 1, 2, savedGroove);
- lynx::session::moveClip (original, 1, 2, 0, 1, true);
- lynx::session::moveClip (original, 0, 1, 2, 0, false);
- original.playlist[0].groove = savedGroove; // round 190fm: a Playlist pattern clip's groove
- }
- 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;
- original.channels[1].cutOthersOnly = original.channels[1].cutAtNoteEnd = true; // FL Studio Mobile's cut rule (round 190fe)
- 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);
- // round 190bw: FL's curve modes of automation points come back from a project, tension whole; a bent point
- // without a mode (a project saved before the modes: [tick, value, tension]) keeps LYNX's older law
- const auto curveModesOk = [&original] {
- auto song = original;
- auto& a = song.automations[0];
- a.points = { { 0, 0.25f, 0.5f, (std::uint8_t) lynx::flcurve::stairs },
- { 960, 1.0f, -0.123456f, (std::uint8_t) lynx::flcurve::smooth },
- { 1920, 0.5f, 0.0f, (std::uint8_t) lynx::flcurve::hold },
- { 2400, 0.75f, 0.7f, lynx::AutomationPoint::legacyCurve },
- { 2880, 0.3f, 0.0f, 0 },
- { 3840, 0.6f, 0.0f, 0 } };
- a.lfo.on = true;
- a.lfo.amp = { { 0, 1.0f, -0.25f, (std::uint8_t) lynx::flcurve::pulse }, { 960, 0.5f, 0.0f, 0 } };
- juce::String e;
- const auto text = lynx::ProjectFile::toJson (song);
- const auto back = lynx::ProjectFile::fromJson (text, e);
- return back && back->automations.size() == 1 && back->automations[0].points == a.points && back->automations[0].lfo.amp == a.lfo.amp
- && back->automations[0].valueAt (700.0) == a.valueAt (700.0) && back->automations[0].valueAt (2600.0) == a.valueAt (2600.0);
- }();
- const auto projectOk = curveModesOk && 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->clipGrid.has_value() && reloaded->clipGrid->globalQuant == lynx::LaunchQuant::bars2
- && reloaded->clipGrid->scenes.size() == 3 && reloaded->clipGrid->scenes[0].name == "Intro"
- && lynx::launcher::clipAt (*reloaded->clipGrid, 1, 2) != nullptr
- && [&reloaded] {
- auto grid = *reloaded->clipGrid;
- const auto* slot = lynx::launcher::settingsAt (grid, 1, 2);
- return slot != nullptr && slot->name == "Clip ação" && slot->mode == lynx::LaunchMode::toggle
- && slot->quant == lynx::LaunchQuant::eighthTriplet && slot->legato && ! slot->loop;
- }()
- && [&reloaded, &original, savedGroove] { // round 190bv
- auto grid = *reloaded->clipGrid;
- const auto* kept = lynx::launcher::settingsAt (grid, 1, 2);
- const auto* moved = lynx::launcher::settingsAt (grid, 2, 0);
- const auto* clip = lynx::launcher::clipAt (grid, 2, 0);
- return reloaded->grooves == original.grooves && reloaded->grooves.grooves.size() == 1
- && reloaded->grooves.amount == 1.2f && reloaded->grooves.grooves[0].name == "Balanço"
- && reloaded->grooves.grooves[0].points.size() == 2 && savedGroove != 0
- && kept != nullptr && kept->groove == savedGroove
- && lynx::launcher::clipAt (grid, 0, 1) == nullptr
- && clip != nullptr && clip->pattern == 0 && clip->length == 1920
- && moved != nullptr && moved->groove == savedGroove && moved->name == "Clip ação"
- && moved->mode == lynx::LaunchMode::toggle && moved->legato && ! moved->loop
- && reloaded->playlist[0].groove == savedGroove && reloaded->playlist[1].groove == 0; // (190fm)
- }()
- && 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->channels[1].cutOthersOnly && reloaded->channels[1].cutAtNoteEnd && ! reloaded->channels[0].cutOthersOnly
- && ! reloaded->channels[0].cutAtNoteEnd
- && 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;
- };
- // round 190bu: a one-knob effect, the chain's Blend and its preset name travel in the project; a project without
- // them reads as before (no goal, Blend 100 %) and writes none of the new keys
- bool fx190buOk = false;
- {
- auto song = lynx::Song::makeDefault();
- const auto plainJson = lynx::ProjectFile::toJson (song);
- const auto* preset = lynx::chains::find ("Whisper Air");
- if (preset != nullptr && song.mixer.size() > 2)
- {
- lynx::chains::apply (song, 1, *preset);
- song.mixer[2].effects.push_back (lynx::goals::make (lynx::goals::room, 0.62f));
- song.mixer[2].effects.push_back (lynx::goals::make (lynx::goals::bass, 0.3f));
- song.mixer[2].chainBlend = 0.4f;
- const auto json = lynx::ProjectFile::toJson (song);
- const auto back = lynx::ProjectFile::fromJson (json, error);
- const auto plainBack = lynx::ProjectFile::fromJson (plainJson, error);
- auto same = back && back->mixer.size() == song.mixer.size();
- for (std::size_t t = 1; same && t <= 2; ++t)
- {
- const auto& a = song.mixer[t];
- const auto& b = back->mixer[t];
- same = a.effects.size() == b.effects.size() && std::abs (a.chainBlend - b.chainBlend) < 1.0e-6f && a.chainPreset == b.chainPreset;
- for (std::size_t i = 0; same && i < a.effects.size(); ++i)
- same = a.effects[i].kind == b.effects[i].kind && a.effects[i].goal == b.effects[i].goal
- && std::abs (a.effects[i].goalAmount - b.effects[i].goalAmount) < 1.0e-6f && a.effects[i].row == b.effects[i].row
- && lynx::goals::active (b.effects[i]) == lynx::goals::active (a.effects[i]);
- }
- fx190buOk = same && lynx::chains::unchanged (*back, 1) && back->mixer[2].chainPreset.empty()
- && ! plainJson.contains ("\"goal\"") && ! plainJson.contains ("chainBlend") && ! plainJson.contains ("chainPreset")
- && json.contains ("\"goalAmount\"") && plainBack && plainBack->mixer[1].chainBlend == 1.0f
- && lynx::ProjectFile::toJson (*back) == json;
- // a user's chain preset file: the slots, Blend and name come back; the strip's level is not part of it
- song.mixer[2].volume = 0.31f;
- const auto file = lynx::ProjectFile::mixerTrackStateToJson (lynx::chains::stateOf (song.mixer[2], "Mine"));
- const auto state = lynx::ProjectFile::mixerTrackStateFromJson (file, error);
- fx190buOk = fx190buOk && state && state->effects.size() == 2 && state->effects[0].goal == lynx::goals::room
- && lynx::goals::active (state->effects[1]) && std::abs (state->chainBlend - 0.4f) < 1.0e-6f && state->chainPreset == "Mine"
- && state->volume == lynx::MixerTrack().volume;
- }
- }
- const auto richOk = fx190buOk && 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();
- // issue #96's per-plugin option: saved only when on; old projects (no field) read as off
- bool hostKeysOk = false;
- {
- auto song = lynx::Song::makeDefault();
- lynx::ChannelDef plugin;
- plugin.instrument = lynx::InstrumentKind::plugin;
- plugin.plugin.id = "x";
- song.channels.push_back (plugin);
- const auto channel = song.channels.size() - 1;
- const auto off = lynx::ProjectFile::toJson (song);
- song.channels[channel].plugin.allowHostKeys = true;
- song.channels[channel].plugin.hostKeysFirst = true;
- song.channels[channel].plugin.pinned = true; // (round 190ao: Pin on top)
- song.channels[channel].plugin.velocityMode = lynx::prefs::pluginVelocityFixed; // (round 190ao: the plugin's own velocity)
- song.channels[channel].plugin.fixedVelocity = 64;
- const auto on = lynx::ProjectFile::toJson (song);
- const auto offBack = lynx::ProjectFile::fromJson (off, error);
- const auto onBack = lynx::ProjectFile::fromJson (on, error);
- hostKeysOk = ! off.contains ("allowHostKeys") && on.contains ("allowHostKeys") && offBack && onBack
- && ! offBack->channels[channel].plugin.allowHostKeys && onBack->channels[channel].plugin.allowHostKeys
- && ! off.contains ("hostKeysFirst") && ! offBack->channels[channel].plugin.hostKeysFirst && onBack->channels[channel].plugin.hostKeysFirst
- && ! off.contains ("pinnedOnTop") && ! offBack->channels[channel].plugin.pinned && onBack->channels[channel].plugin.pinned
- && ! off.contains ("velocityMode") && ! off.contains ("fixedVelocity") && offBack->channels[channel].plugin.velocityMode == 0
- && offBack->channels[channel].plugin.fixedVelocity == lynx::prefs::defaultFixedVelocity
- && onBack->channels[channel].plugin.velocityMode == lynx::prefs::pluginVelocityFixed && onBack->channels[channel].plugin.fixedVelocity == 64;
- }
- // round 190ad: a new project has FL's plugin levels and keeps them through a save; a project saved before
- // (no "pluginLevels") reads as LYNX's own law, and stays so when it opens
- bool pluginLevelsOk = false;
- {
- const auto fresh = lynx::makeNewProject();
- const auto saved = lynx::ProjectFile::toJson (fresh);
- const auto back = lynx::ProjectFile::fromJson (saved, error);
- auto old = lynx::Song::makeDefault(); // (what every earlier version made)
- const auto oldSaved = lynx::ProjectFile::toJson (old);
- const auto oldBack = lynx::ProjectFile::fromJson (oldSaved, error);
- const auto stripped = lynx::ProjectFile::fromJson (saved.replace ("\"pluginLevels\"", "\"pluginLevelsGone\""), error);
- pluginLevelsOk = fresh.flPluginLevels && saved.contains ("\"pluginLevels\"") && back && back->flPluginLevels
- && ! old.flPluginLevels && ! oldSaved.contains ("pluginLevels") && oldBack && ! oldBack->flPluginLevels
- && stripped && ! stripped->flPluginLevels;
- }
- // 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");
- }
- // round 180d: clip fades take FL's S curve; a project saved before that keeps its straight fades, also after another
- // save, and a clip made in it takes the S curve. FL's fade tensions and stretch mode and PITCH survive a save.
- // issue #122: playlist tracks linked to inserts (audio) and channels (instrument) survive save, load and save
- // again byte for byte (they were read before the mixer and fell back to Unassigned)
- bool trackModes122Ok = false;
- {
- auto song = lynx::Song::makeDefault();
- song.playlistTracks.resize (6);
- song.playlistTracks[1].mode = lynx::PlaylistTrackMode::audio;
- song.playlistTracks[1].mixerTrack = 3;
- song.playlistTracks[4].mode = lynx::PlaylistTrackMode::audio;
- song.playlistTracks[4].mixerTrack = (int) song.mixer.size() - 1;
- song.playlistTracks[5].mode = lynx::PlaylistTrackMode::instrument;
- song.playlistTracks[5].channel = 1;
- song.playlistTracks[5].mixerTrack = 2;
- const auto json = lynx::ProjectFile::toJson (song, false);
- const auto loaded = lynx::ProjectFile::fromJson (json, error);
- const auto again = loaded ? lynx::ProjectFile::toJson (*loaded, false) : juce::String();
- trackModes122Ok = loaded && json.contains ("playlistTrackModes") && again == json && loaded->playlistTracks.size() >= 6
- && loaded->playlistTracks[1].mode == lynx::PlaylistTrackMode::audio && loaded->playlistTracks[1].mixerTrack == 3
- && loaded->playlistTracks[4].mode == lynx::PlaylistTrackMode::audio
- && loaded->playlistTracks[4].mixerTrack == (int) song.mixer.size() - 1
- && loaded->playlistTracks[5].mode == lynx::PlaylistTrackMode::instrument && loaded->playlistTracks[5].channel == 1;
- }
- bool clipFades180dOk = false;
- {
- auto song = lynx::Song::makeDefault();
- lynx::Clip faded;
- faded.kind = lynx::ClipKind::audio;
- faded.channel = 0;
- faded.length = lynx::ppq * 8;
- faded.fadeIn = lynx::ppq;
- faded.fadeOutTension = -812.933f;
- faded.fadeOut = lynx::ppq * 2;
- lynx::Clip plainClip = faded;
- plainClip.fadeIn = plainClip.fadeOut = 0;
- plainClip.fadeOutTension = 0.0f;
- plainClip.start = lynx::ppq * 16;
- song.playlist = { faded, plainClip };
- song.channels[0].sampler.flStretchMode = 5;
- song.channels[0].sampler.flStretchPitch = 247;
- const auto json = lynx::ProjectFile::toJson (song);
- const auto current = lynx::ProjectFile::fromJson (json, error);
- const auto oldJson = json.replace ("\"clipFadesPerClip\"", "\"clipFadesOther\"");
- auto old = lynx::ProjectFile::fromJson (oldJson, error);
- auto resaved = old;
- if (resaved)
- {
- auto added = faded;
- added.start = lynx::ppq * 32;
- added.linearFades = 0;
- resaved->playlist.push_back (added);
- resaved = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (*resaved), error);
- }
- clipFades180dOk = current && old && resaved && json.contains ("clipFadesPerClip") && ! oldJson.contains ("clipFadesPerClip")
- && current->playlist.size() == 2 && ! current->playlist[0].linearFades
- && current->playlist[0].fadeOutTension == -812.933f && ! current->playlist[1].linearFades
- && current->channels[0].sampler.flStretchMode == 5 && current->channels[0].sampler.flStretchPitch == 247
- && old->playlist.size() == 2 && old->playlist[0].linearFades && ! old->playlist[1].linearFades
- && resaved->playlist.size() == 3 && resaved->playlist[0].linearFades && ! resaved->playlist[1].linearFades
- && ! resaved->playlist[2].linearFades && resaved->playlist[0].fadeOutTension == -812.933f;
- }
- // 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");
- }
- // FL's pattern clip takeover (issue #158): saved when on; a project saved before it (no key) loads with it off and
- // keeps playing every overlapping clip of a pattern in full; new projects have it on
- bool takeoverOk = false;
- {
- auto song = lynx::Song::makeDefault();
- const auto plain = lynx::ProjectFile::toJson (song);
- song.patternClipTakeover = true;
- const auto json = lynx::ProjectFile::toJson (song);
- const auto back = lynx::ProjectFile::fromJson (json, error);
- const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
- takeoverOk = back && back->patternClipTakeover && json.contains ("patternClipTakeover") && plainBack
- && ! plainBack->patternClipTakeover && ! plain.contains ("patternClipTakeover")
- && lynx::makeNewProject().patternClipTakeover;
- }
- // comping (round 177c): a comp's equal-power crossfades (Clip::fadeCurve) and the crossfade length are saved; a
- // project without them has neither in its file
- bool compOk = false;
- {
- auto song = lynx::Song::makeDefault();
- const auto plain = lynx::ProjectFile::toJson (song);
- lynx::ChannelDef take;
- take.instrument = lynx::InstrumentKind::audioClip;
- take.samplePath = "take.wav";
- song.channels.push_back (take);
- lynx::Clip a;
- a.kind = lynx::ClipKind::audio;
- a.channel = (int) song.channels.size() - 1;
- a.length = lynx::ppq;
- a.fadeOut = 20;
- a.fadeCurve = 2;
- auto b = a;
- b.start = lynx::ppq - 20;
- b.fadeOut = 0;
- b.fadeIn = 20;
- b.fadeCurve = 1;
- // round 180d's FL fade fields (indices 17..20) and the comp curve (index 21) on one clip, all kept
- auto c = a;
- c.start = 4 * lynx::ppq;
- c.fadeIn = 30;
- c.fadeInTension = -0.75f;
- c.fadeOutTension = 0.5f;
- c.linearFades = 2;
- c.flFadeFlags = 0x1234u;
- c.fadeCurve = 3;
- song.playlist = { a, b, c };
- song.compCrossfadeMs = 12.5f;
- song.playlistTracks.resize (2);
- song.playlistTracks[0].compTrack = true;
- song.playlistTracks[1].grouped = true;
- const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
- const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
- const auto* both = back && back->playlist.size() == 3 ? &back->playlist[2] : nullptr;
- compOk = back && back->playlist.size() == 3 && back->playlist[0].fadeCurve == 2 && back->playlist[1].fadeCurve == 1
- && both != nullptr && both->fadeCurve == 3 && both->fadeInTension == -0.75f && both->fadeOutTension == 0.5f
- && both->linearFades == 2 && both->flFadeFlags == 0x1234u && both->fadeIn == 30
- && back->playlist[1].fadeIn == 20 && back->compCrossfadeMs == 12.5f && back->playlistTracks[0].compTrack && ! back->playlistTracks[1].compTrack && plainBack
- && plainBack->compCrossfadeMs == lynx::Song::defaultCompCrossfadeMs && ! plain.contains ("compCrossfadeMs") && ! plain.contains ("playlistCompTracks");
- }
- // 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's pre-fader sends (round 190aq): saved only when one is used, in a list of its own ("preSends") that a
- // version from before ignores (its sends then play post-fader, as FL's)
- bool preSendOk = false;
- {
- auto song = lynx::Song::makeDefault();
- song.setRoute (1, 3, true, 0.5f);
- song.setRoute (1, 4, true);
- song.setRoute (2, 3, true);
- const auto plain = lynx::ProjectFile::toJson (song);
- song.setSendPre (1, 3, true);
- const auto json = lynx::ProjectFile::toJson (song);
- const auto back = lynx::ProjectFile::fromJson (json, error);
- preSendOk = back && back->sendPre (1, 3) && ! back->sendPre (1, 4) && ! back->sendPre (2, 3)
- && std::abs (back->routeLevel (1, 3) - 0.5f) < 1.0e-4f && back->mixer[1].sends == song.mixer[1].sends
- && ! plain.contains ("preSends") && json.contains ("preSends")
- && json.replace ("\"preSends\"", "\"preSendsOld\"") != json;
- // the same file without the list (what an older version reads): the sends are there, post-fader
- if (const auto old = lynx::ProjectFile::fromJson (json.replace ("\"preSends\"", "\"unknownToOldVersions\""), error))
- preSendOk = preSendOk && old->routes (1, 3) && ! old->sendPre (1, 3) && old->mixer[1].sends.size() == 2;
- else
- preSendOk = false;
- }
- // LYNX's "Low latency while recording" (round 190aq): a latency-adding effect on a monitored insert's path is
- // bypassed in the engine only — PDC drops, the slot is marked, the song and the saved project stay as they are —
- // and it is back when the option goes off
- bool lowLatencyOk = false;
- {
- lynx::AudioEngine live (false);
- live.editSong ([] (lynx::Song& s) {
- s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::limiter)); // 1.5 ms look-ahead
- s.mixer[1].inputChannel = 0;
- s.mixer[1].monitor = lynx::InputMonitor::on;
- });
- const auto before = live.getLatencySamples();
- const auto saved = lynx::ProjectFile::toJson (live.getSong());
- const auto idle = live.lowLatencyBypassedCount() == 0; // the option is off: nothing is bypassed
- auto o = live.getRecordOptions();
- o.lowLatencyRecording = true;
- live.setRecordOptions (o);
- const auto during = live.getLatencySamples();
- const auto marked = live.isSlotLowLatencyBypassed (1, 0) && live.lowLatencyBypassedLatency (1, 0) > 0 && live.lowLatencyBypassedCount() >= 1;
- const auto untouched = live.getSong().mixer[1].effects[0].enabled && lynx::ProjectFile::toJson (live.getSong()) == saved;
- // monitoring leaves "On" (nothing armed): the effect returns
- live.editSong ([] (lynx::Song& s) { s.mixer[1].monitor = lynx::InputMonitor::whenArmed; });
- const auto released = live.getLatencySamples() == before && ! live.isSlotLowLatencyBypassed (1, 0);
- live.editSong ([] (lynx::Song& s) { s.mixer[1].monitor = lynx::InputMonitor::on; });
- const auto again = live.getLatencySamples() == during && live.isSlotLowLatencyBypassed (1, 0);
- o.lowLatencyRecording = false;
- live.setRecordOptions (o);
- lowLatencyOk = before > 0 && idle && during < before && marked && untouched && released && again
- && live.getLatencySamples() == before && live.lowLatencyBypassedCount() == 0;
- }
- // The Browser's "Preview in time" (round 190aq): a loop whose name gives its tempo is stretched to the project's
- // and starts on the beat; a one-shot plays as it always did; off, nothing changes
- bool previewInTimeOk = false;
- double previewPrepareMs = 0.0;
- {
- const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-preview");
- dir.deleteRecursively();
- dir.createDirectory();
- auto writeWav = [&dir] (const juce::String& name, int frames, bool loop) {
- const auto wav = dir.getChildFile (name);
- juce::WavAudioFormat format;
- juce::AudioBuffer<float> audio (1, frames);
- for (int i = 0; i < frames; ++i) // a click on every beat of 120 BPM over a tone, or a decaying hit
- audio.setSample (0, i, loop ? (i % 24000 < 400 ? 0.8f : 0.0f) + 0.1f * std::sin (0.02f * (float) i)
- : 0.6f * std::exp (-(float) i / 2000.0f) * std::sin (0.05f * (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 (audio, 0, frames);
- }
- return wav;
- };
- const auto loop = writeWav ("selftest loop 120 bpm.wav", 96000, true); // 4 beats at 120 BPM
- const auto hit = writeWav ("selftest hit.wav", 14400, false); // 0.3 s
- lynx::AudioEngine player (false);
- const auto projectBpm = player.getTransport().bpm.load();
- // off (FL's preview): nothing is prepared, the file plays as it is
- player.previewFile (loop);
- const auto offOk = ! player.getPreviewTiming().pending && ! player.getPreviewTiming().inTime;
- player.setPreviewInTime (true);
- player.previewFile (hit); // a one-shot: as it always played, at once
- const auto hitOk = ! player.getPreviewTiming().pending && ! player.getPreviewTiming().inTime;
- player.previewFile (loop);
- const auto queued = player.getPreviewTiming().pending || std::abs (projectBpm - 120.0) < 0.2;
- player.finishPreviewJobs();
- const auto timing = player.getPreviewTiming();
- previewPrepareMs = player.getLastPreviewPrepareMs();
- const auto wanted = lynx::previewtempo::stretchRatio (120.0, projectBpm);
- const auto stretchedOk = timing.inTime && ! timing.pending && timing.source == lynx::previewtempo::Source::name
- && std::abs (timing.fileBpm - 120.0) < 1.0e-9 && std::abs (timing.ratio - wanted) < 1.0e-12
- && std::abs ((double) timing.frames - 96000.0 * wanted) < 96000.0 * 0.01;
- // the second click on the same file has its stretch ready
- player.previewFile (loop);
- const auto cachedOk = ! player.getPreviewTiming().pending && player.getPreviewTiming().inTime && player.getPreviewTiming().frames == timing.frames;
- player.previewFile ({});
- const auto stoppedOk = ! player.getPreviewTiming().inTime && player.getPreviewInTimeProgress() < 0.0;
- // the start: on the next heard beat while the transport plays (sample exact), at once when it is stopped
- auto firstSample = [] (bool playing, double startTick, int latency) {
- lynx::Transport transport;
- transport.sampleRate.store (48000.0);
- transport.bpm.store (120.0); // 0.04 ticks per sample
- transport.playing.store (playing);
- transport.positionTicks.store (startTick);
- lynx::PreviewPlayer p;
- p.prepareToPlay (48000.0, 512);
- p.setTransport (&transport);
- p.setSyncLatency (latency);
- auto dc = std::make_shared<lynx::SampleData>();
- dc->sampleRate = 48000.0;
- dc->left.assign (48000, 0.5f);
- p.playBrowser (dc, 1.0f, true);
- juce::AudioBuffer<float> block (2, 512);
- juce::MidiBuffer midi;
- for (int done = 0; done < 48000; done += 512)
- {
- p.processBlock (block, midi);
- for (int i = 0; i < 512; ++i)
- if (block.getSample (0, i) != 0.0f)
- return done + i;
- if (playing)
- transport.positionTicks.store (transport.positionTicks.load() + 512 * transport.ticksPerSample());
- }
- return -1;
- };
- const auto beatOk = firstSample (true, 480.0, 0) == 12000 // half a beat to go: 480 ticks / 0.04
- && firstSample (true, 480.0, 100) == 12100 // the song is heard 100 samples late (PDC)
- && firstSample (true, 960.0, 0) == 0 // on a beat: now
- && firstSample (false, 480.0, 0) == 0; // stopped: a free start
- previewInTimeOk = loop.existsAsFile() && hit.existsAsFile() && offOk && hitOk && queued && stretchedOk && cachedOk && stoppedOk && beatOk;
- dir.deleteRecursively();
- }
- // 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();
- // Remote-owned steps still behave as ordinary native history when no RemoteControl instance is enabled.
- // Only API undo/redo refuse device drift; remote reads, staging and publication never hold the audio-device callback lock.
- const auto remoteHistoryResult = []() -> juce::String {
- int checks = 0;
- const auto require = [&] (bool condition, const char* message) {
- ++checks;
- if (! condition) throw std::runtime_error (message);
- };
- try
- {
- for (const auto session : { false, true })
- {
- lynx::AudioEngine history (false);
- lynx::Song initial;
- initial.channels.resize (1);
- initial.channels[0].instrument = lynx::InstrumentKind::synth;
- initial.mixer = lynx::Song::defaultMixer (1);
- initial.bpm = 120.0;
- history.setSong (std::move (initial));
- history.setSessionHistory (session);
- const auto editTempo = [&] (double bpm) {
- require (history.editSongRemoteTransaction ([&] (lynx::Song& s) { s.bpm = bpm; }), "remote tempo edit was not committed");
- };
- const auto refused = [&] (const std::function<void()>& operation) {
- const auto position = history.getHistoryPosition();
- const auto before = lynx::ProjectFile::toJsonExact (history.getSong());
- bool changed = false;
- try { operation(); }
- catch (const lynx::RemoteError& e) { changed = e.code == "changed" && ! e.uncertain; }
- require (changed, "API history did not refuse untracked device changes");
- require (history.getHistoryPosition() == position && lynx::ProjectFile::toJsonExact (history.getSong()) == before,
- "refused API history changed the project or history position");
- };
- const auto withoutDeviceLock = [&] (const std::function<void()>& operation) {
- juce::WaitableEvent locked, release;
- bool timedOut = false;
- std::thread callback ([&] {
- const juce::ScopedLock lock (history.getDeviceManager().getAudioCallbackLock());
- locked.signal();
- timedOut = ! release.wait (3000);
- });
- const auto acquired = locked.wait (3000);
- std::exception_ptr failure;
- try { if (acquired) operation(); }
- catch (...) { failure = std::current_exception(); }
- release.signal();
- callback.join();
- // Check before rethrowing: an expected rejection must not conceal waiting for this lock.
- require (acquired && ! timedOut, "remote read, edit or history publication waited for the audio-device callback lock");
- if (failure) std::rethrow_exception (failure);
- };
- const auto baseline = lynx::ProjectFile::toJsonExact (history.getSong());
- const auto baselineStamp = history.getSongStamp();
- const auto baselinePosition = history.getHistoryPosition();
- const auto unchanged = [&] {
- return history.getSongStamp() == baselineStamp && history.getHistoryPosition() == baselinePosition
- && lynx::ProjectFile::toJsonExact (history.getSong()) == baseline;
- };
- withoutDeviceLock ([&] {
- require (lynx::ProjectFile::toJsonExact (history.snapshotForRemoteControl()) == baseline,
- "remote snapshot changed the project");
- require (history.remoteDeviceStateHash().isNotEmpty(), "remote snapshot did not hash device state");
- });
- require (unchanged(), "remote reads changed the project, revision or history");
- bool staged = false;
- withoutDeviceLock ([&] {
- require (! history.editSongRemoteTransaction ([&] (lynx::Song&) { staged = true; }),
- "remote no-op committed a history step");
- });
- require (staged && unchanged(), "remote no-op did not stage cleanly without changing history");
- bool rejected = false;
- try {
- withoutDeviceLock ([&] {
- history.editSongRemoteTransaction ([] (lynx::Song& next) {
- next.bpm = 999.0;
- throw lynx::RemoteError ("invalid", "selftest stage rejection");
- });
- });
- }
- catch (const lynx::RemoteError& e) { rejected = e.code == "invalid" && ! e.uncertain; }
- require (rejected && unchanged(), "rejected staging changed the project, revision or history");
- for (const auto cancelAfterStage : { false, true })
- {
- int calls = 0;
- staged = false;
- bool cancelledEdit = false;
- try {
- withoutDeviceLock ([&] {
- history.editSongRemoteTransaction ([&] (lynx::Song& next) { staged = true; next.bpm = 999.0; },
- [&] { return ++calls >= (cancelAfterStage ? 2 : 1); });
- });
- }
- catch (const lynx::RemoteError& e) { cancelledEdit = e.code == "failed" && ! e.uncertain; }
- require (cancelledEdit && staged == cancelAfterStage && unchanged(),
- "cancelled edit changed the project, revision or history");
- }
- withoutDeviceLock ([&] { editTempo (130.0); });
- require (history.getSong().bpm == 130.0 && history.getHistoryPosition() == baselinePosition + 1
- && history.getSongStamp() > baselineStamp, "remote commit did not publish one history step");
- history.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.23f; }, false);
- refused ([&] { history.undoRemoteControl(); });
- withoutDeviceLock ([&] { history.undo(); });
- require (history.getHistoryPosition() == 0 && history.getSong().bpm == 120.0 && history.getRemoteHistoryError().isEmpty(),
- "native undo refused device drift while remote control was disabled");
- history.editSong ([] (lynx::Song& s) { s.channels[0].name = "Untracked change"; }, false);
- refused ([&] { history.redoRemoteControl(); });
- withoutDeviceLock ([&] { history.redo(); });
- require (history.getHistoryPosition() == 1 && history.getSong().bpm == 130.0 && history.getRemoteHistoryError().isEmpty(),
- "native redo refused device drift while remote control was disabled");
- withoutDeviceLock ([&] { editTempo (140.0); });
- history.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.42f; }, false);
- withoutDeviceLock ([&] { history.jumpToHistory (0); });
- require (history.getHistoryPosition() == 0 && history.getSong().bpm == 120.0, "native history jump stopped at a remote step");
- withoutDeviceLock ([&] { history.jumpToHistory (2); });
- require (history.getHistoryPosition() == 2 && history.getSong().bpm == 140.0, "native redo jump stopped at a remote step");
- withoutDeviceLock ([&] { history.undoRemoteControl(); });
- require (history.getHistoryPosition() == 1 && history.getSong().bpm == 130.0, "API undo failed with an unchanged device fence");
- withoutDeviceLock ([&] { history.redoRemoteControl(); });
- require (history.getHistoryPosition() == 2 && history.getSong().bpm == 140.0, "API redo failed with an unchanged device fence");
- int cancelledChecks = 0;
- bool cancelled = false;
- try { history.undoRemoteControl ([&] { return ++cancelledChecks >= 2; }); }
- catch (const lynx::RemoteError& e) { cancelled = e.code == "failed" && ! e.uncertain; }
- require (cancelled && history.getHistoryPosition() == 2 && history.getSong().bpm == 140.0,
- "cancelled API history moved a step");
- withoutDeviceLock ([&] { history.undo(); });
- require (history.getHistoryPosition() == 1 && history.getSong().bpm == 130.0 && history.getRemoteHistoryError().isEmpty(),
- "API cancellation leaked into native history");
- }
- return "OK (" + juce::String (checks) + " checks)";
- }
- catch (const std::exception& e) { return "ERROR " + juce::String::fromUTF8 (e.what()); }
- }();
- // Hosted state access and processing share a per-instance lock, including fixed blocks and deferred resets.
- const auto hostedStateLockResult = []() -> juce::String {
- struct Probe final : juce::AudioPluginInstance
- {
- struct Parameter final : juce::HostedAudioProcessorParameter
- {
- explicit Parameter (Probe& p) : owner (p) {}
- float getValue() const override { owner.access (owner.parameterReads); return value.load(); }
- void setValue (float v) override { owner.access (owner.parameterWrites); value.store (v); }
- float getDefaultValue() const override { return 0.0f; }
- juce::String getName (int) const override { return "Value"; }
- juce::String getLabel() const override { return {}; }
- juce::String getParameterID() const override { return "value"; }
- float getValueForText (const juce::String& text) const override { return text.getFloatValue(); }
- Probe& owner;
- std::atomic<float> value { 0.0f };
- };
- Probe() : AudioPluginInstance (BusesProperties().withInput ("Input", juce::AudioChannelSet::stereo(), true)
- .withOutput ("Output", juce::AudioChannelSet::stereo(), true))
- {
- addHostedParameter (std::make_unique<Parameter> (*this));
- }
- const juce::String getName() const override { return "State lock probe"; }
- void fillInPluginDescription (juce::PluginDescription& d) const override { d.name = getName(); }
- void prepareToPlay (double, int) override {}
- void releaseResources() override {}
- void processBlock (juce::AudioBuffer<float>& audio, juce::MidiBuffer&) override { access (blocks); audio.clear(); }
- void reset() override { access (resets, std::this_thread::get_id() == ui); } // (on the UI thread: the export reset)
- double getTailLengthSeconds() const override { return 0.0; }
- bool acceptsMidi() const override { return true; }
- bool producesMidi() const override { return false; }
- bool hasEditor() const override { return false; }
- juce::AudioProcessorEditor* createEditor() override { return nullptr; }
- int getNumPrograms() override { return 1; }
- int getCurrentProgram() override { return 0; }
- void setCurrentProgram (int) override {}
- const juce::String getProgramName (int) override { return {}; }
- void changeProgramName (int, const juce::String&) override {}
- void getStateInformation (juce::MemoryBlock& state) override { access (captures); state.replaceAll ("state", 5); }
- void setStateInformation (const void*, int) override { access (restores, true); }
- // Round 190ha: only a restore and the export reset are exclusive with the audio side. A capture and the
- // UI's parameter changes run beside processing, as on JUCE's own hosts (UI-thread calls never overlap
- // each other here: they run in turn).
- void access (std::atomic<int>& calls, bool exclusive = false)
- {
- ++calls;
- if (exclusive)
- {
- ++exclusiveActive;
- if (active.fetch_add (1) != 0) overlap = true;
- }
- else
- {
- ++active;
- if (exclusiveActive.load() != 0) overlap = true;
- }
- juce::Thread::sleep (1); // widen the concurrent vendor-call window without using real plugins
- --active;
- if (exclusive) --exclusiveActive;
- }
- const std::thread::id ui = std::this_thread::get_id();
- std::atomic<int> active { 0 }, exclusiveActive { 0 }, blocks { 0 }, resets { 0 }, captures { 0 }, restores { 0 };
- std::atomic<int> parameterReads { 0 }, parameterWrites { 0 };
- std::atomic<bool> overlap { false };
- };
- int checks = 0;
- const auto require = [&] (bool condition, const char* message) {
- ++checks;
- if (! condition) throw std::runtime_error (message);
- };
- const auto exercise = [&] (auto& adapter, Probe& probe, const auto& render, const auto& reset) {
- const auto saved = adapter.captureState();
- require (saved.has_value(), "mock hosted state could not be captured");
- juce::WaitableEvent start (true);
- std::thread audio ([&] {
- start.wait();
- for (int i = 0; i < 32; ++i)
- {
- adapter.setParameter (0, i % 2 == 0 ? 0.25f : 0.75f);
- (void) adapter.parameterValue (0);
- reset();
- render();
- }
- });
- const juce::ScopeGuard joinAudio { [&] { if (audio.joinable()) audio.join(); } };
- start.signal();
- bool stateOk = true;
- for (int i = 0; i < 32; ++i)
- {
- stateOk = adapter.captureState().has_value() && stateOk;
- stateOk = adapter.restoreState (*saved) && stateOk;
- adapter.setParameterFromUi (0, i % 2 == 0 ? 0.1f : 0.9f);
- if (i % 8 == 0) adapter.resetForExport();
- }
- audio.join();
- // Contended audio callbacks may all have bypassed while state was held.
- // Exercise a successful callback after release before checking coverage.
- adapter.setParameter (0, 0.5f);
- (void) adapter.parameterValue (0);
- reset();
- render();
- require (stateOk && probe.blocks > 0 && probe.resets > 0 && probe.captures > 0 && probe.restores > 0,
- "mock did not exercise processing, resets and hosted state access");
- require (probe.parameterReads > 0 && probe.parameterWrites > 0,
- "mock did not exercise concurrent hosted parameter access");
- require (! probe.overlap, "hosted processing/reset/parameters overlapped a state restore or the export reset");
- require (! adapter.hasCrashed(), "mock hosted adapter crashed");
- };
- try
- {
- for (const auto fixed : { 0, 64 })
- {
- std::array<float, 128> left {}, right {};
- auto instrument = std::make_unique<Probe>();
- auto* instrumentProbe = instrument.get();
- lynx::PluginInstrument voice (std::move (instrument), 128, fixed);
- exercise (voice, *instrumentProbe, [&] { voice.render (left.data(), right.data(), 128, 1.0f, 1.0f); }, [&] { voice.panic(); });
- auto effect = std::make_unique<Probe>();
- auto* effectProbe = effect.get();
- lynx::PluginEffect fx (std::move (effect), 128, fixed);
- exercise (fx, *effectProbe, [&] { fx.process (left.data(), right.data(), 128, {}, 120.0); }, [&] { fx.transportReset(); });
- }
- return "OK (" + juce::String (checks) + " checks)";
- }
- catch (const std::exception& e) { return "ERROR " + juce::String::fromUTF8 (e.what()); }
- }();
- const auto hostedStateContentionResult = lynx::pluginStateContentionSelfTest();
- // recording from the PC keyboard: a one-beat note lands in the pattern, in a single undo step
- // (Blend on: this checks that the take joins the pattern's notes; a new install starts with Blend off)
- const auto notesBefore = offline.getSong().patterns[0].notes.size();
- {
- auto o = offline.getRecordOptions();
- o.mode = lynx::RecordMode::overdub;
- offline.setRecordOptions (o);
- }
- 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;
- // FL's Tools › Cancel recording (round 187a): the pass's notes go, an edit made before it stays, recording turns
- // off and playback goes on; nothing to redo
- bool cancelRecordOk = false;
- {
- offline.editSong ([] (lynx::Song& s) { s.bpm = 123.0; });
- const auto notesThen = offline.getSong().patterns[0].notes.size();
- offline.setRecording (true);
- offline.play();
- offline.getTransport().positionTicks.store (960.0);
- offline.sendLiveNote (2, 74, 0.9f, true, true);
- offline.getTransport().positionTicks.store (1920.0);
- offline.sendLiveNote (2, 74, 0.0f, false, true);
- offline.sendLiveNote (2, 76, 0.9f, true, true); // (still held when the pass is cancelled)
- const auto cancelled = offline.cancelRecording();
- cancelRecordOk = cancelled && ! offline.isRecording() && offline.getTransport().playing.load()
- && offline.getSong().patterns[0].notes.size() == notesThen && offline.getSong().bpm == 123.0 && ! offline.canRedo()
- && ! offline.cancelRecording(); // (not recording: nothing to cancel)
- offline.sendLiveNote (2, 76, 0.0f, false, false);
- offline.stop();
- }
- // 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();
- }
- // D#92, round 180a: a non-ASCII folder and a dotted name save and load back; an unwritable place says so, and a
- // relative path resolves as the start-up argument does
- bool projectSaveOk = false;
- {
- const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-save180a");
- dir.deleteRecursively();
- const auto folder = dir.getChildFile (juce::String::fromUTF8 ("M\xc3\xbasica nova"));
- folder.createDirectory();
- const auto named = lynx::ProjectFile::withProjectExtension (folder.getChildFile (juce::String::fromUTF8 ("Can\xc3\xa7\xc3\xa3o.v2")));
- auto song = lynx::Song::makeDefault();
- lynx::Note note;
- note.length = 240;
- note.key = 64;
- song.patterns[0].notes.push_back (note);
- juce::String error, blockedError;
- const auto again = lynx::ProjectFile::save (song, named, error) ? lynx::ProjectFile::load (named, error) : std::nullopt;
- const auto blocker = dir.getChildFile ("a file");
- blocker.replaceWithText ("x");
- const auto cwd = juce::File::getCurrentWorkingDirectory();
- folder.setAsCurrentWorkingDirectory();
- const auto relative = juce::File::getCurrentWorkingDirectory().getChildFile (named.getFileName());
- cwd.setAsCurrentWorkingDirectory();
- projectSaveOk = named.getFileName().endsWith (".v2.lynx") && again && again->patterns[0].notes.size() == song.patterns[0].notes.size()
- && relative == named && ! lynx::ProjectFile::save (song, blocker.getChildFile ("x.lynx"), blockedError)
- && blockedError.isNotEmpty() && lynx::ProjectFile::withProjectExtension (named) == named;
- 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.meter()), 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;
- }
- // Round 183c, Racks: (1) a plain Patcher's stored JSON loads and saves back byte for byte and never holds a
- // "rack" key (FL's Patcher is untouched); (2) an Audio Effect Rack slot and an Instrument Rack channel survive save /
- // load with their chains, zones, macros, mappings, variations and compiled cables
- juce::String rackResult = "OK";
- {
- lynx::MixerTrack plain;
- plain.name = "Plain Patcher";
- auto fx = lynx::makeEffectSlot (lynx::EffectKind::patcher);
- lynx::PatchNode a, b;
- a.effect = lynx::makeEffectSlot (lynx::EffectKind::utility);
- a.label = "A";
- a.x = 120.5f;
- b.effect = lynx::makeEffectSlot (lynx::EffectKind::utility);
- b.effect.enabled = false;
- fx.patcher.nodes = { a, b };
- lynx::PatchWire w1, w2, w3, wc;
- w1.to = 0;
- w2.from = 0, w2.to = 1, w2.gain = 0.5f;
- w3.from = 1;
- wc.kind = lynx::PatchWire::Kind::control, wc.from = 0, wc.to = 1, wc.toPort = 0, wc.curve = { 0.0f, 0.25f, 1.0f };
- fx.patcher.wires = { w1, w2, w3, wc };
- lynx::SurfaceControl knob;
- knob.name = "Drive";
- knob.value = 0.25f;
- fx.patcher.surface = { knob };
- lynx::PatchParam pp;
- pp.node = 0, pp.param = 1, pp.name = "Balance";
- fx.patcher.published = { pp };
- plain.effects = { fx };
- const auto first = juce::JSON::toString (lynx::ProjectFile::mixerTrackToVar (plain), true);
- const auto again = juce::JSON::toString (lynx::ProjectFile::mixerTrackToVar (lynx::ProjectFile::mixerTrackFromVar (juce::JSON::parse (first))), true);
- if (first != again || first.contains ("\"rack\"") || first.contains ("rackMixer"))
- rackResult = "ERROR plain Patcher changed";
- auto song = lynx::Song::makeDefault();
- song.mixer.resize (3);
- auto rackSlot = lynx::rack::makeRackSlot (lynx::RackDoc::Kind::audioEffect);
- auto& doc = rackSlot.patcher;
- lynx::PatchNode u;
- u.effect = lynx::makeEffectSlot (lynx::EffectKind::utility);
- const auto n0 = lynx::rack::addDevice (doc, 0, u);
- lynx::rack::addChain (doc, "Wet");
- lynx::rack::addDevice (doc, 1, u);
- doc.rack[0].chains[1].select = { 10, 90, 30, 70 };
- lynx::rack::setChainPan (doc, 1, -0.5f);
- lynx::RackMapping m;
- m.node = n0, m.param = 0, m.min = 0.2f, m.max = 0.9f;
- lynx::rack::map (doc, 0, m);
- lynx::RackMapping v;
- v.target = lynx::RackMapping::Target::chainVolume, v.chain = 1, v.min = 0.0f, v.max = lynx::rack::unityVolume;
- lynx::rack::map (doc, 1, v);
- lynx::rack::setMacro (doc, 0, 64.0f);
- lynx::rack::storeVariation (doc);
- lynx::rack::setMacro (doc, 0, 100.0f);
- lynx::rack::storeVariation (doc);
- doc.rack[0].morphOn = true, doc.rack[0].morphA = 0, doc.rack[0].morphB = 1;
- lynx::rack::setMorph (doc, 0.5f);
- lynx::rack::compile (doc);
- song.mixer[1].effects = { rackSlot };
- lynx::ChannelDef inst;
- inst.name = "Instrument Rack";
- inst.instrument = lynx::InstrumentKind::patcher;
- inst.patcher = lynx::rack::makeRack (lynx::RackDoc::Kind::instrument);
- lynx::PatchNode synth;
- synth.generator = true;
- synth.channel.instrument = lynx::InstrumentKind::synth;
- synth.channel.name = "Synth";
- lynx::rack::addDevice (inst.patcher, 0, synth);
- inst.patcher.rack[0].chains[0].velocity = { 1, 127, 64, 127 };
- lynx::rack::compile (inst.patcher);
- song.channels.push_back (inst);
- const auto json = lynx::ProjectFile::toJson (song);
- const auto back = lynx::ProjectFile::fromJson (json, error);
- // (the devices' parameters are stored to 4 decimals: the documents are compared as stored, the rack exactly)
- const auto loaded = back && back->mixer.size() >= 2 && back->mixer[1].effects.size() == 1;
- const auto& got = loaded ? back->mixer[1].effects[0].patcher : doc;
- if (! loaded)
- rackResult = "ERROR rack slot not loaded";
- else if (got.rack != doc.rack)
- rackResult = "ERROR rack model";
- else if (got.wires != doc.wires)
- rackResult = "ERROR rack cables";
- else if (got.nodes.size() != doc.nodes.size())
- rackResult = "ERROR rack devices";
- else if (back->channels.back().patcher.rack != inst.patcher.rack || back->channels.back().patcher.wires != inst.patcher.wires
- || back->channels.back().patcher.zones != inst.patcher.zones || back->channels.back().patcher.nodes.size() != inst.patcher.nodes.size())
- rackResult = "ERROR instrument rack";
- // the slot's insert as stored, once more: the same text (the stored form is stable)
- else if (const auto once = juce::JSON::toString (lynx::ProjectFile::mixerTrackToVar (back->mixer[1]), true);
- once != juce::JSON::toString (lynx::ProjectFile::mixerTrackToVar (lynx::ProjectFile::mixerTrackFromVar (juce::JSON::parse (once))), true))
- rackResult = "ERROR rack stored form not stable";
- }
- // Round 190ec, Drum Rack: pads (Receive / Play / Choke / Audio To / sends), return chains and the views survive save /
- // load with their compiled zones and cables
- if (rackResult == "OK")
- {
- lynx::Song song;
- song.mixer.resize (2);
- lynx::ChannelDef ch;
- ch.name = "Drums";
- ch.instrument = lynx::InstrumentKind::patcher;
- ch.patcher = lynx::rack::makeDrumRack();
- lynx::PatchNode synth;
- synth.generator = true;
- synth.channel.instrument = lynx::InstrumentKind::synth;
- const auto kick = lynx::rack::addPad (ch.patcher, 36, "Kick", synth);
- const auto hat = lynx::rack::addPad (ch.patcher, 42, "Hat", synth);
- lynx::rack::addPad (ch.patcher, -1, "Every note");
- lynx::rack::addReturn (ch.patcher, "A Verb");
- lynx::rack::setPlay (ch.patcher, kick, 64);
- lynx::rack::setChoke (ch.patcher, hat, 2);
- lynx::rack::setSend (ch.patcher, hat, 0, 0.25f, false);
- lynx::rack::setAudioTo (ch.patcher, kick, 0);
- lynx::rack::rackOf (ch.patcher)->showIO = true;
- lynx::rack::rackOf (ch.patcher)->padScroll = 17;
- song.channels.push_back (ch);
- juce::String error;
- const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
- const auto& got = back && ! back->channels.empty() ? back->channels.back().patcher : lynx::PatcherDoc {};
- if (! back || ! lynx::rack::isDrumRack (got))
- rackResult = "ERROR drum rack not loaded";
- else if (got.rack != ch.patcher.rack)
- rackResult = "ERROR drum rack model";
- else if (got.zones != ch.patcher.zones || got.wires != ch.patcher.wires)
- rackResult = "ERROR drum rack cables";
- }
- // 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;
- // A new Fruity Slicer has no sample and no slices, and FL's is silent then too (round 180c), so it is
- // not one of the engines that must sound here (Linux / macOS CI: "SILENT 1 [Fruity Slicer]", 0.1.25)
- if (kind == lynx::InstrumentKind::fruityslicer && one.channels[0].samplePath.empty())
- continue;
- if (kind == lynx::InstrumentKind::slicex && one.channels[0].samplePath.empty()) // (the same: no sample on its decks yet)
- continue;
- 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;
- }
- // FPC plays its pads' keys; a kit without a sample (FL's "Empty" kit: no FL Studio on this PC) is silent
- // in FL too (round 190q)
- if (kind == lynx::InstrumentKind::fpc)
- {
- const auto pads = lynx::fpcChannelPads (one.channels[0]);
- if (pads.empty())
- continue;
- key = pads.front().key;
- }
- 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();
- // issue #134 (round 190c): the output device, its rate and its buffer changed under a playing project, on
- // stand-in devices (a short run; --devicechangetest plays every instrument and effect)
- const auto deviceChange = lynx::AudioEngine::deviceChangeSelfTest (10, false);
- // round 190gh: export parity (B7) and MIDI device hot-plug (B8)
- const auto exportParity = lynx::AudioEngine::exportParitySelfTest();
- const auto midiHotplug = lynx::AudioEngine::midiHotplugSelfTest();
- // 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 190ap: the Versions panel's list of files, and its labels on disk beside them
- const auto versionsResult = lynx::versionsSelfTest();
- // round 190ap: a project opened with its plugins off creates none of them and saves their settings unchanged
- const auto pluginsOffResult = lynx::pluginsOffSelfTest();
- const auto missingFilesResult = lynx::missingFilesSelfTest(); // issue #165
- // round 190cj: a dancer's own native window stays where the stage put it (it drifted off the screen: JUCE
- // moved a transparent child window by the main window's client offset on every repaint)
- juce::String danceWindowDetail;
- const auto danceWindowResult = lynx::danceWindowSelfTest (&danceWindowDetail);
- // issue #161: a click in a panel (a native child window that takes no focus on a click) of an inactive main
- // window activates it (back from another app, Space played nothing until the Browser was clicked)
- const auto clickActivationResult = lynx::nativechild::clickActivationSelfTest();
- // 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;
- }
- // round 190cg: the loop switch, folded tracks and the tempo lane's range come back from a project; a project
- // without them loads as before (loop on, nothing folded, the whole range)
- juce::String arrange190cgResult = "OK";
- {
- auto song = lynx::Song::makeDefault();
- juce::String why;
- const auto plain = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
- song.loopStart = 960;
- song.loopEnd = 4800;
- song.loopOff = true;
- song.tempoViewLow = 80.0;
- song.tempoViewHigh = 160.0;
- song.playlistTracks.resize (std::max<std::size_t> (song.playlistTracks.size(), 6));
- song.playlistTracks[2].folded = song.playlistTracks[5].folded = true;
- const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
- if (! plain || plain->loopOff || plain->tempoViewLow != 0.0 || plain->tempoViewHigh != 0.0
- || std::any_of (plain->playlistTracks.begin(), plain->playlistTracks.end(), [] (const lynx::PlaylistTrack& t) { return t.folded; }))
- arrange190cgResult = "ERROR defaults " + why;
- else if (! back || ! back->loopOff || back->loopStart != 960 || back->loopEnd != 4800 || back->loopPlays() || back->tempoViewLow != 80.0
- || back->tempoViewHigh != 160.0 || back->playlistTracks.size() < 6 || ! back->playlistTracks[2].folded
- || ! back->playlistTracks[5].folded || back->playlistTracks[3].folded)
- arrange190cgResult = "ERROR round trip " + why;
- }
- // round 190gz (issue #170): "Link Playlist tracks to mixer tracks" comes back from a project with its links; a
- // project without it loads with it off (FL's tracks)
- juce::String trackauto190gzResult = "OK";
- {
- auto song = lynx::Song::makeDefault();
- juce::String why;
- const auto plain = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
- lynx::Clip clip;
- clip.kind = lynx::ClipKind::pattern;
- clip.pattern = 0; // (the default pattern: Kick, Clap and Hat; a second one plays Kick alone)
- song.playlist.push_back (clip);
- auto& kick = song.patterns.emplace_back();
- kick.name = "Kick";
- kick.toggleStep (0, 0);
- clip.pattern = (int) song.patterns.size() - 1;
- clip.track = 1;
- song.playlist.push_back (clip);
- lynx::autolink::setOn (song, true);
- const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
- if (! plain || plain->linkTracksToMixer)
- trackauto190gzResult = "ERROR defaults " + why;
- // (round 190ib: Track 1 holds Kick, Clap and Hat, so they all go through insert 1 and Track 1 is its audio
- // track; Track 2 only repeats Kick and stays unassigned)
- // (a .lynx keeps the tracks up to the last one that differs from a plain track: Track 2 may not be written)
- else if (! back || ! back->linkTracksToMixer || back->playlistTracks.empty() || back->playlistTracks[0].mode != lynx::PlaylistTrackMode::audio
- || back->playlistTracks[0].mixerTrack != 1
- || (back->playlistTracks.size() > 1 && back->playlistTracks[1].mode != lynx::PlaylistTrackMode::unassigned)
- || back->channels[1].mixerTrack != 1 || back->channels[2].mixerTrack != 1)
- {
- trackauto190gzResult = "ERROR round trip " + why;
- if (back && ! back->playlistTracks.empty() && back->channels.size() >= 3)
- trackauto190gzResult << " tracks " << (int) back->playlistTracks.size() << " mode " << (int) back->playlistTracks[0].mode << " insert "
- << back->playlistTracks[0].mixerTrack << " routes " << back->channels[0].mixerTrack << " "
- << back->channels[1].mixerTrack << " " << back->channels[2].mixerTrack;
- }
- }
- // round 190fm: the MIDI Tools generators' settings come back from a project; a project without them loads with
- // Live's defaults (and saves none)
- juce::String midigen190fmResult = "OK";
- {
- auto song = lynx::Song::makeDefault();
- juce::String why;
- const auto plainJson = lynx::ProjectFile::toJson (song);
- const auto plain = lynx::ProjectFile::fromJson (plainJson, why);
- song.midiGenerate.tool = lynx::midigen::Settings::stacks;
- song.midiGenerate.rhythmOptions.pattern = 3;
- song.midiGenerate.seedOptions.voices = 2;
- song.midiGenerate.shapeOptions.levels[4] = 0.25f;
- song.midiGenerate.shapeOptions.preset = lynx::midigen::ShapeOptions::custom;
- song.midiGenerate.stacksOptions.sequence.push_back ({ 4, 3, 67, 1, 1, 0.5f, 2.0f });
- const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
- if (! plain || ! plain->midiGenerate.isDefault() || plainJson.contains ("midiGenerate"))
- midigen190fmResult = "ERROR defaults " + why;
- else if (! back || ! (back->midiGenerate == song.midiGenerate))
- midigen190fmResult = "ERROR round trip " + why;
- }
- // round 190gi: audio clip envelopes come back from a project (an entry two clips share stays shared, an unused one
- // is not written, the lane shown, FL's curve modes); a project without them writes neither "clipEnvelopes" nor a
- // clip field 25 (older projects save byte-identical)
- juce::String clipenv190giResult = "OK";
- {
- auto song = lynx::Song::makeDefault();
- lynx::ChannelDef channel;
- channel.instrument = lynx::InstrumentKind::audioClip;
- channel.samplePath = "clipenv190gi.wav";
- song.channels.push_back (channel);
- lynx::Clip clip;
- clip.kind = lynx::ClipKind::audio;
- clip.channel = (int) song.channels.size() - 1;
- clip.length = lynx::ppq * 4;
- song.playlist.push_back (clip);
- juce::String why;
- const auto plainJson = lynx::ProjectFile::toJson (song);
- lynx::ClipEnvelope e;
- e.volume = { { 0, 1.0f, 0.0f, 0 }, { lynx::ppq * 4, 0.25f, 0.3f, 1 } };
- e.pan = { { 0, 0.5f, 0.0f, 0 }, { lynx::ppq * 2, 0.0f, 0.0f, 0 } };
- e.shown = lynx::clipenv::panLane;
- song.clipEnvelopes.emplace_back(); // (no clip uses it: not written)
- song.clipEnvelopes.push_back (e);
- song.playlist.back().envelope = 1;
- auto twin = song.playlist.back();
- twin.start = lynx::ppq * 8;
- song.playlist.push_back (twin);
- const auto json = lynx::ProjectFile::toJson (song);
- const auto back = lynx::ProjectFile::fromJson (json, why);
- if (plainJson.contains ("clipEnvelopes") || ! json.contains ("clipEnvelopes"))
- clipenv190giResult = "ERROR written " + why;
- else if (! back || back->clipEnvelopes.size() != 1 || ! (back->clipEnvelopes[0] == e))
- clipenv190giResult = "ERROR table " + why;
- else
- {
- int withEnvelope = 0;
- for (const auto& c : back->playlist)
- withEnvelope += c.kind == lynx::ClipKind::audio && c.envelope == 0 ? 1 : 0;
- if (withEnvelope != 2)
- clipenv190giResult = "ERROR clips " + why;
- }
- }
- // round 190gx: Beats' law in the .lynx — a new project's channels are Measured; a project saved before the law
- // (no "beatsLaw190gx" mark, or a nine-number warpModes list) loads Classic; a Classic channel stays Classic
- juce::String beatslaw190gxResult = "OK";
- {
- auto song = lynx::Song::makeDefault();
- lynx::ChannelDef channel;
- channel.instrument = lynx::InstrumentKind::audioClip;
- channel.samplePath = "beatslaw190gx.wav";
- channel.sampler.keepPitch = true;
- channel.sampler.stretchMethod = lynx::StretchMethod::beats;
- song.channels.push_back (channel);
- const auto index = song.channels.size() - 1;
- juce::String why;
- const auto json = lynx::ProjectFile::toJson (song);
- const auto lawOf = [&] (const juce::String& text) {
- const auto back = lynx::ProjectFile::fromJson (text, why);
- return back && back->channels.size() > index ? (int) back->channels[index].sampler.warpModes.beatsLaw : -1;
- };
- auto oldVar = juce::JSON::parse (json); // (the mark removed: a project saved before 190gx)
- if (auto* o = oldVar.getDynamicObject())
- o->removeProperty ("beatsLaw190gx");
- const auto old = juce::JSON::toString (oldVar);
- auto classic = song;
- classic.channels[index].sampler.warpModes.beatsLaw = lynx::WarpModeSettings::beatsLawClassic;
- auto nine = song;
- nine.channels[index].sampler.warpModes.beatsLoop = 0; // (a 190fm project with a changed setting: nine numbers)
- // (the list with its tenth number, the law, removed: what a 190fm build wrote)
- auto nineVar = juce::JSON::parse (lynx::ProjectFile::toJson (nine));
- bool trimmed = false;
- if (auto* channels = nineVar.getProperty ("channels", {}).getArray(); channels != nullptr && (int) index < channels->size())
- if (auto* modes = (*channels)[(int) index].getProperty ("samplerSettings", {}).getProperty ("warpModes", {}).getArray(); modes != nullptr && modes->size() == 10)
- {
- modes->removeLast();
- trimmed = true;
- }
- const auto nineJson = juce::JSON::toString (nineVar);
- if (! json.contains ("beatsLaw190gx") || old.contains ("beatsLaw190gx"))
- beatslaw190gxResult = "ERROR mark";
- else if (lawOf (json) != lynx::WarpModeSettings::beatsLawMeasured)
- beatslaw190gxResult = "ERROR new " + why;
- else if (lawOf (old) != lynx::WarpModeSettings::beatsLawClassic)
- beatslaw190gxResult = "ERROR old " + why;
- else if (lawOf (lynx::ProjectFile::toJson (classic)) != lynx::WarpModeSettings::beatsLawClassic)
- beatslaw190gxResult = "ERROR classic kept " + why;
- else if (! trimmed || lawOf (nineJson) != lynx::WarpModeSettings::beatsLawClassic)
- beatslaw190gxResult = "ERROR nine-number list";
- }
- // round 190he (issue #152): a channel window's Scaling is saved with the channel; the default (125 %) writes
- // nothing, so older projects and untouched channels read as before
- juce::String editorScale190heResult = "OK";
- {
- auto song = lynx::Song::makeDefault();
- song.channels[0].editorScale = 100;
- song.channels[1].editorScale = 0;
- juce::String why;
- const auto json = lynx::ProjectFile::toJson (song);
- const auto back = lynx::ProjectFile::fromJson (json, why);
- auto outOfRange = juce::JSON::parse (json);
- if (auto* chans = outOfRange.getProperty ("channels", {}).getArray(); chans != nullptr && ! chans->isEmpty())
- if (auto* o = (*chans)[0].getDynamicObject())
- o->setProperty ("editorScale", 9000);
- const auto clamped = lynx::ProjectFile::fromJson (juce::JSON::toString (outOfRange), why);
- if (! back || back->channels[0].editorScale != 100 || back->channels[1].editorScale != 0)
- editorScale190heResult = "ERROR round trip " + why;
- else if (json.indexOf ("editorScale") != json.lastIndexOf ("editorScale"))
- editorScale190heResult = "ERROR written for a default channel";
- else if (! clamped || clamped->channels[0].editorScale != lynx::editorscale::maxPercent)
- editorScale190heResult = "ERROR not clamped";
- }
- // round 190he (coordinator's gate): a project saved before 190he (no "sfModBase190he") keeps the old 0.5 centre of
- // a Modulation route on a Soundfont knob; a new song, saved and opened again, centres on the knob
- juce::String sfModBase190heResult = "OK";
- {
- auto song = lynx::Song::makeDefault();
- juce::String why;
- const auto json = lynx::ProjectFile::toJson (song);
- auto oldVar = juce::JSON::parse (json);
- if (auto* o = oldVar.getDynamicObject())
- o->removeProperty ("sfModBase190he");
- const auto back = lynx::ProjectFile::fromJson (json, why);
- const auto old = lynx::ProjectFile::fromJson (juce::JSON::toString (oldVar), why);
- auto resaved = old ? lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (*old), why) : std::optional<lynx::Song> {};
- if (! json.contains ("sfModBase190he") || ! back || ! back->soundfontModBaseReal)
- sfModBase190heResult = "ERROR new song " + why;
- else if (! old || old->soundfontModBaseReal)
- sfModBase190heResult = "ERROR old project " + why;
- else if (! resaved || resaved->soundfontModBaseReal)
- sfModBase190heResult = "ERROR old project saved again";
- }
- // round 190dr: the Session mixer's sections come back from a project (a project without them: Live's defaults);
- // a device dragged to another track and a Warp switch are one undo step each in a real engine
- juce::String livescr190drResult = "OK";
- {
- auto song = lynx::Song::makeDefault();
- lynx::launcher::ensureGrid (song);
- juce::String why;
- const auto plain = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
- song.clipGrid->mixerView.io = false;
- song.clipGrid->mixerView.trackOptions = true;
- const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
- if (! plain || ! plain->clipGrid || ! (plain->clipGrid->mixerView == lynx::SessionMixerView {}))
- livescr190drResult = "ERROR view defaults " + why;
- else if (! back || ! back->clipGrid || back->clipGrid->mixerView.io || ! back->clipGrid->mixerView.trackOptions || ! back->clipGrid->mixerView.shown)
- livescr190drResult = "ERROR view round trip " + why;
- lynx::AudioEngine e (false);
- e.editSong ([] (lynx::Song& s) {
- if (s.mixer.size() < 4)
- s.mixer.resize (4);
- s.mixer[2].effects.clear();
- s.mixer[3].effects.clear();
- for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor })
- {
- lynx::EffectSlot fx;
- fx.kind = kind;
- s.mixer[2].effects.push_back (fx);
- }
- lynx::Automation a;
- a.target = { lynx::AutomationTargetKind::effectMix, 2, 1, 0 };
- s.automations.push_back (a);
- }, false);
- const auto id = e.getSong().mixer[2].effects[1].instance.id;
- const auto automations = e.getSong().automations.size();
- e.editSongStructural ([] (lynx::Song& s) { lynx::detailchain::moveEffectToInsert (s, 2, 1, 3, false); });
- const auto& moved = e.getSong();
- if (livescr190drResult == "OK"
- && (moved.mixer[2].effects.size() != 1 || moved.mixer[3].effects.size() != 1 || moved.mixer[3].effects[0].instance.id != id
- || moved.automations.size() != automations || moved.automations.back().target.index != 3 || moved.automations.back().target.slot != 0))
- livescr190drResult = "ERROR device move";
- e.undo();
- const auto& undone = e.getSong();
- if (livescr190drResult == "OK"
- && (undone.mixer[2].effects.size() != 2 || undone.mixer[3].effects.size() != 0 || undone.mixer[2].effects[1].instance.id != id
- || undone.automations.back().target.index != 2 || undone.automations.back().target.slot != 1))
- livescr190drResult = "ERROR device move undo";
- e.editSong ([] (lynx::Song& s) {
- s.channels.resize (std::max<std::size_t> (s.channels.size(), 1));
- s.channels[0].sampler.stretchBeats = 16.0f;
- lynx::Clip c;
- c.kind = lynx::ClipKind::audio;
- c.channel = 0;
- c.offset = 4 * lynx::ppq;
- c.length = 8 * lynx::ppq;
- lynx::launcher::setClip (s, 0, 0, c);
- }, false);
- e.editSong ([] (lynx::Song& s) { lynx::clipsample::setWarp (s, 0, false, 4.0); });
- const auto* off = e.getSong().clipGrid ? lynx::launcher::clipAt (*e.getSong().clipGrid, 0, 0) : nullptr;
- if (livescr190drResult == "OK" && (e.getSong().channels[0].sampler.stretchBeats != 0.0f || off == nullptr || off->length != (std::int64_t) std::llround (8.0 * lynx::ppq * (4.0 * e.getSong().bpm / 60.0) / 16.0)))
- livescr190drResult = "ERROR warp off";
- e.undo();
- const auto* on = e.getSong().clipGrid ? lynx::launcher::clipAt (*e.getSong().clipGrid, 0, 0) : nullptr;
- if (livescr190drResult == "OK" && (e.getSong().channels[0].sampler.stretchBeats != 16.0f || on == nullptr || on->length != 8 * lynx::ppq))
- livescr190drResult = "ERROR warp undo";
- }
- // round 190ef: the map modes' storage (.lynx round trip of key / MIDI mappings and a link's Min / Max; an older
- // reader keeps the plain link), and in a real engine: a link's range, MIDI Map Mode catching the control instead
- // of moving anything, a slot's MIDI mapping firing on its press and release
- juce::String livewf190efResult = "OK";
- {
- using namespace lynx::remotemap;
- auto song = lynx::Song::makeDefault();
- lynx::launcher::ensureGrid (song);
- const lynx::AutomationTarget vol { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 };
- assignMidi (song, Target::parameter (vol), { 0, 20, -1 });
- assignMidi (song, Target::slot (0, 0), { 0, lynx::linkNoteBase + 36, 2 });
- assignKey (song, Target::sceneLaunch (0), 'S');
- assignKey (song, Target::parameter ({ lynx::AutomationTargetKind::tempo, 0, 0, 0 }), 'T');
- setRange (song, rows (song, Mode::midi)[0], 0.25f, 0.75f);
- setRange (song, rows (song, Mode::key)[1], 0.9f, 0.1f);
- juce::String why;
- const auto json = lynx::ProjectFile::toJson (song);
- const auto back = lynx::ProjectFile::fromJson (json, why);
- if (! back || back->remoteMappings != song.remoteMappings || back->midiLinks != song.midiLinks)
- livewf190efResult = "ERROR round trip " + why;
- auto parsed = juce::JSON::parse (json);
- if (auto* o = parsed.getDynamicObject())
- {
- o->removeProperty ("remoteMappings");
- o->removeProperty ("midiLinkSettings");
- }
- const auto older = lynx::ProjectFile::fromJson (juce::JSON::toString (parsed), why);
- if (livewf190efResult == "OK" && (! older || ! older->remoteMappings.empty() || older->midiLinks.size() != 1 || older->midiLinks[0].max != 1.0f))
- livewf190efResult = "ERROR older reader";
- const auto plain = lynx::ProjectFile::toJson (lynx::Song::makeDefault());
- if (livewf190efResult == "OK" && plain.contains ("remoteMappings"))
- livewf190efResult = "ERROR written without mappings";
- lynx::AudioEngine e (false);
- e.editSong ([vol] (lynx::Song& s) {
- if (s.mixer.size() < 3)
- s.mixer.resize (3);
- lynx::MidiLink l { 20, 0, vol };
- l.min = 0.25f;
- l.max = 0.75f;
- s.midiLinks = { l };
- lynx::launcher::ensureGrid (s);
- assignMidi (s, Target::slot (0, 0), { 0, 21, -1 });
- });
- e.injectControllerForTest (20, 0, 127);
- const auto top = e.currentTargetValue (vol);
- e.injectControllerForTest (20, 0, 0);
- const auto bottom = e.currentTargetValue (vol);
- if (livewf190efResult == "OK" && (std::abs (top - 0.75f) > 0.01f || std::abs (bottom - 0.25f) > 0.01f))
- livewf190efResult = "ERROR range " + juce::String (bottom) + " " + juce::String (top);
- std::vector<Fire> fired;
- e.onRemoteFire = [&fired] (const Fire& f) { fired.push_back (f); };
- e.injectControllerForTest (21, 0, 127);
- e.injectControllerForTest (21, 0, 127); // (still down: no new press)
- e.injectControllerForTest (21, 0, 0);
- if (livewf190efResult == "OK"
- && (fired.size() != 2 || fired[0].edge != Edge::press || fired[1].edge != Edge::release || ! (fired[0].target == Target::slot (0, 0))))
- livewf190efResult = "ERROR slot fire " + juce::String ((int) fired.size());
- e.setMapMode (Mode::midi);
- fired.clear();
- e.injectControllerForTest (20, 0, 127);
- e.injectControllerForTest (21, 0, 127);
- const auto caught = e.takeMapCapture();
- if (livewf190efResult == "OK" && (std::abs (e.currentTargetValue (vol) - 0.25f) > 0.01f || ! fired.empty()))
- livewf190efResult = "ERROR mappings acted in MIDI Map Mode";
- else if (livewf190efResult == "OK" && (! caught || caught->number != 21 || caught->channel != 0 || e.takeMapCapture().has_value()))
- livewf190efResult = "ERROR map capture";
- e.setMapMode (Mode::off);
- e.onRemoteFire = nullptr;
- }
- // round 190em: a scene's time signature denominator (.lynx round trip; an older file without it reads n/4; a
- // launch of a 6 / 8 scene gives the song a 3-beat bar), and Capture MIDI in the clip grid of a real engine: the
- // armed track, the selected scene's slot, the tempo from a phrase played while stopped (8 notes at 148 BPM), the
- // new clip launched and the transport started
- juce::String livewf190emResult = "OK";
- {
- auto song = lynx::Song::makeDefault();
- auto& grid = lynx::launcher::ensureGrid (song);
- grid.scenes.resize (3);
- lynx::session::setSceneSignature (song, 1, 6, 8);
- lynx::session::setSceneTempo (song, 1, 100.0);
- juce::String why;
- const auto json = lynx::ProjectFile::toJson (song);
- const auto back = lynx::ProjectFile::fromJson (json, why);
- if (! back || ! back->clipGrid || back->clipGrid->scenes != song.clipGrid->scenes || back->clipGrid->scenes[1].beatUnit != 8)
- livewf190emResult = "ERROR round trip " + why;
- {
- // a captured clip's blank label (ClipGridSlot::blankName) survives the round trip
- auto withClip = song;
- lynx::Clip c;
- c.pattern = 0;
- c.length = 4 * lynx::ppq;
- if (withClip.patterns.empty())
- withClip.patterns.emplace_back();
- const auto slot = lynx::launcher::setClip (withClip, 0, 0, c);
- if (slot >= 0)
- withClip.clipGrid->slots[(std::size_t) slot].blankName = true;
- const auto again = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (withClip), why);
- const auto* keptClip = again && again->clipGrid ? lynx::launcher::clipAt (*again->clipGrid, 0, 0) : nullptr;
- const auto* kept = keptClip != nullptr ? &again->clipGrid->slots[(std::size_t) keptClip->gridSlot] : nullptr;
- if (livewf190emResult == "OK" && (slot < 0 || kept == nullptr || ! kept->blankName))
- livewf190emResult = "ERROR blank clip name round trip";
- }
- auto parsed = juce::JSON::parse (json);
- if (auto* scenes = parsed.getProperty ("clipGrid", {}).getProperty ("scenes", {}).getArray(); scenes != nullptr && scenes->size() > 1)
- if (auto* o = (*scenes)[1].getDynamicObject())
- o->removeProperty ("beatUnit");
- const auto older = lynx::ProjectFile::fromJson (juce::JSON::toString (parsed), why);
- if (livewf190emResult == "OK" && (! older || ! older->clipGrid || older->clipGrid->scenes.size() < 2 || older->clipGrid->scenes[1].beatUnit != 4
- || older->clipGrid->scenes[1].beatsPerBar != 6))
- livewf190emResult = "ERROR older reader";
- if (livewf190emResult == "OK" && lynx::ProjectFile::toJson (lynx::Song::makeDefault()).contains ("beatUnit"))
- livewf190emResult = "ERROR beatUnit written by default";
- // round 190fg: the song meter's denominator round-trips through .lynx; a file without it reads n/4
- {
- auto six = lynx::Song::makeDefault();
- six.beatsPerBar = 6;
- six.beatUnit = 8;
- const auto text = lynx::ProjectFile::toJson (six);
- juce::String why2;
- const auto back = lynx::ProjectFile::fromJson (text, why2);
- auto json = juce::JSON::parse (text);
- if (auto* o = json.getDynamicObject())
- o->removeProperty ("beatUnit");
- const auto old = lynx::ProjectFile::fromJson (juce::JSON::toString (json), why2);
- if (livewf190emResult == "OK" && (! back || back->beatsPerBar != 6 || back->beatUnit != 8 || ! old || old->beatsPerBar != 6 || old->beatUnit != 4))
- livewf190emResult = "ERROR song meter round trip";
- }
- lynx::AudioEngine e (false);
- e.editSong ([] (lynx::Song& s) {
- s.bpm = 120.0;
- s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 4));
- auto& g = lynx::launcher::ensureGrid (s);
- g.scenes.resize (3);
- lynx::session::setSceneSignature (s, 2, 6, 8);
- lynx::session::setSceneTempo (s, 2, 90.0);
- }, false);
- e.launcherCommand ({ lynx::launcher::Command::Type::launchScene, 0, 2 });
- // (round 190fg: the song takes the scene's 6 / 8 as it is: six eighths a bar, 3 quarters long)
- if (livewf190emResult == "OK" && (e.getSong().beatsPerBar != 6 || e.getSong().beatUnit != 8 || e.getSong().barTicks() != 3 * lynx::ppq
- || e.getSong().bpm != 90.0))
- livewf190emResult = "ERROR scene launch " + juce::String (e.getSong().beatsPerBar) + "/" + juce::String (e.getSong().beatUnit) + " "
- + juce::String (e.getSong().bpm);
- e.stop();
- e.editSong ([] (lynx::Song& s) {
- s.bpm = 120.0;
- s.beatsPerBar = 4;
- s.beatUnit = 4;
- }, false);
- e.setGridTrackArmed (2, true, true);
- const auto now = juce::Time::getMillisecondCounterHiRes();
- const auto beat = 60000.0 / 148.0;
- for (int i = 0; i < 8; ++i)
- {
- const auto at = now - 9.0 * beat + i * beat;
- e.logPlayedNoteForTest (at, 0, 60 + (i % 4) * 2, 0.8f, true);
- e.logPlayedNoteForTest (at + beat * 0.5, 0, 60 + (i % 4) * 2, 0.8f, false);
- }
- int placed = -1;
- bool into = true;
- const auto r = e.captureMidiToSlot (2, 1, placed, into);
- const auto& g = *e.getSong().clipGrid;
- const auto* clip = lynx::launcher::clipAt (g, 2, 1);
- if (livewf190emResult == "OK" && (r.notes != 8 || placed != 1 || into || clip == nullptr || clip->length != 8 * lynx::ppq))
- livewf190emResult = "ERROR capture " + juce::String (r.notes) + " " + juce::String (placed) + (clip == nullptr ? " no clip" : " " + juce::String ((int) clip->length));
- else if (livewf190emResult == "OK" && std::abs (e.getSong().bpm - 148.0) > 0.5)
- livewf190emResult = "ERROR tempo " + juce::String (e.getSong().bpm, 2);
- else if (livewf190emResult == "OK" && ! e.getTransport().playing.load())
- livewf190emResult = "ERROR the capture did not start the transport";
- e.stop();
- }
- const auto mixerBasics = lynx::mixerbasics::run();
- // issue #142: every font has a typeface, and one without does not crash (fonts get theirs through the
- // look and feel, as in the app)
- auto& lookBefore = juce::LookAndFeel::getDefaultLookAndFeel();
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- const auto fontsResult = lynx::theme::fontSelfTest();
- const auto paintCachesResult = lynx::theme::paintCacheSelfTest(); // (round 190gr)
- // round 190bm (0.1.25 showed the Mixer and the Playlist black): their cached pictures shown on native and
- // software targets against straight paints (ui/PictureCheck.h; --picturetest runs more sizes and scales)
- juce::String picturesResult = "OK";
- {
- lynx::AudioEngine pictureEngine (false);
- auto pictureFailures = 0;
- juce::String lines;
- {
- lynx::PlaylistComponent playlist (pictureEngine);
- playlist.setBounds (0, 0, 1200, 700);
- playlist.setVisible (true);
- lines << lynx::ui::picturecheck::run (playlist, "Playlist 1200 x 700", { 1.0f, 1.5f }, pictureFailures, {});
- }
- {
- lynx::MixerComponent mixer (pictureEngine);
- mixer.setBounds (0, 0, 1200, 500);
- mixer.setVisible (true);
- lines << lynx::ui::picturecheck::run (mixer, "Mixer 1200 x 500", { 1.0f, 1.5f }, pictureFailures, {});
- }
- if (pictureFailures > 0 || ! lines.contains (": ok"))
- picturesResult = "ERROR " + lines.trim().replace ("\n", "; ");
- }
- // round 190ci (the 0.1.26 release candidate ended when an FPC channel was added): every built-in generator and
- // effect, its editor built as the Channel Rack / mixer opens it and painted once. The report file names the
- // plugin being opened, so a run that dies there says which one.
- const auto editorsResult = lynx::pluginthumbs::checkEditors ([&reportPath] (const juce::String& key) {
- if (reportPath.isNotEmpty())
- juce::File (reportPath).replaceWithText ("(opening the editor of " + key + ")\n");
- });
- // round 190ci: a fault leaves a crash file, also on a stack Windows cannot walk (that FPC fault left none)
- const auto faultResult = faultReportSelfTest();
- const auto stemsResult = stemsSinglePassSelfTest(); // round 190gj
- juce::LookAndFeel::setDefaultLookAndFeel (&lookBefore);
- const auto ok = editorsResult.startsWith ("OK") && ! faultResult.startsWith ("ERROR") && stemsResult == "OK"
- && mixerBasics == "OK" && fontsResult == "OK" && paintCachesResult.startsWith ("OK") && picturesResult == "OK" && audioOk && projectOk && trackModes122Ok && richOk && hwOutOk && hostKeysOk && pluginLevelsOk && flp168jOk && clipFades180dOk && blocksOk && takeoverOk && compOk && polyOk && latencyOk && preSendOk && lowLatencyOk && previewInTimeOk && substituteOk && patcherOk && rackResult == "OK" && nativesOk && undoOk && projectSaveOk && recordOk && recordUndoOk && cancelRecordOk && midiOk && packageOk
- && sessionResult == "OK" && liveResult.startsWith ("OK")
- && wavpack != "ERROR" && effectsOk && driverPanel == "OK" && deviceChange.startsWith ("OK") && exportParity.startsWith ("OK") && midiHotplug.startsWith ("OK") && metronomeOk && artResult == "OK" && effectParamsResult == "OK"
- && sidechainResult == "OK" && lanesResult == "OK" && arrange190cgResult == "OK" && livescr190drResult == "OK" && livewf190efResult == "OK" && livewf190emResult == "OK" && versionsResult == "OK" && pluginsOffResult == "OK" && missingFilesResult == "OK"
- && midigen190fmResult == "OK" && clipenv190giResult == "OK" && beatslaw190gxResult == "OK" && editorScale190heResult == "OK" && sfModBase190heResult == "OK" && trackauto190gzResult == "OK"
- && remoteHistoryResult.startsWith ("OK") && hostedStateLockResult.startsWith ("OK")
- && hostedStateContentionResult.startsWith ("OK")
- && danceWindowResult == "OK" && clickActivationResult == "OK";
- juce::String report;
- report << "connections=" << offline.getNumGraphConnections() << "\n"
- << "peak=" << peak << "\n"
- << "stems_single_pass=" << stemsResult << "\n"
- << "project=" << (projectOk ? "OK" : "ERROR " + error) << "\n"
- << "playlist_track_modes_roundtrip=" << (trackModes122Ok ? "OK" : "ERROR") << "\n"
- << "project_features=" << (richOk ? "OK" : "ERROR") << "\n"
- << "hardware_outputs=" << (hwOutOk ? "OK" : "ERROR") << "\n"
- << "plugin_host_keys_option=" << (hostKeysOk ? "OK" : "ERROR") << "\n"
- << "plugin_levels_new_project=" << (pluginLevelsOk ? "OK" : "ERROR") << "\n"
- << "flp168j_fields=" << (flp168jOk ? "OK" : "ERROR") << "\n"
- << "clip_fades_180d=" << (clipFades180dOk ? "OK" : "ERROR") << "\n"
- << "pattern_blocks=" << (blocksOk ? "OK" : "ERROR") << "\n"
- << "pattern_clip_takeover=" << (takeoverOk ? "OK" : "ERROR") << "\n"
- << "comp_crossfades=" << (compOk ? "OK" : "ERROR") << "\n"
- << "channel_polyphony=" << (polyOk ? "OK" : "ERROR") << "\n"
- << "track_latency=" << (latencyOk ? "OK" : "ERROR") << "\n"
- << "pre_fader_sends=" << (preSendOk ? "OK" : "ERROR") << "\n"
- << "low_latency_recording=" << (lowLatencyOk ? "OK" : "ERROR") << "\n"
- << "preview_in_time=" << (previewInTimeOk ? "OK" : "ERROR") << " (2 s loop prepared in " << juce::String (previewPrepareMs, 1) << " ms)\n"
- << "plugin_substitutes=" << (substituteOk ? "OK" : "ERROR") << "\n"
- << "patcher=" << (patcherOk ? "OK" : "ERROR") << "\n"
- << "racks=" << rackResult << "\n"
- << "native_engines=" << nativesResult << " (" << nativesMade << " made)\n"
- << "undo=" << (undoOk ? "OK" : "ERROR") << "\n"
- << "mixer_basics=" << mixerBasics << "\n"
- << "remote_history=" << remoteHistoryResult << "\n"
- << "hosted_state_lock=" << hostedStateLockResult << "\n"
- << "hosted_state_contention=" << hostedStateContentionResult << "\n"
- << "fonts=" << fontsResult << "\n"
- << "paint_caches=" << paintCachesResult << "\n"
- << "cached_pictures=" << picturesResult << "\n"
- << "plugin_editors=" << editorsResult << "\n"
- << "fault_report=" << faultResult << "\n"
- << "recording=" << (recordOk && recordUndoOk ? "OK" : "ERROR") << "\n"
- << "cancel_recording=" << (cancelRecordOk ? "OK" : "ERROR") << "\n"
- << "midi=" << (midiOk ? "OK" : "ERROR") << "\n"
- << "package=" << (packageOk ? "OK" : "ERROR") << "\n"
- << "projectSave=" << (projectSaveOk ? "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"
- << "device_change=" << deviceChange << "\n"
- << "export_parity=" << exportParity << "\n"
- << "midi_hotplug=" << midiHotplug << "\n"
- << "plugin_art=" << artResult << "\n"
- << "plugin_sidechain=" << sidechainResult << "\n"
- << "versions_panel=" << versionsResult << "\n"
- << "plugins_off=" << pluginsOffResult << "\n"
- << "missing_files_rows=" << missingFilesResult << "\n"
- << "dance_window=" << danceWindowResult << "\n"
- << "dance_window_detail=" << danceWindowDetail << "\n"
- << "click_activation=" << clickActivationResult << "\n"
- << "lanes_saved=" << lanesResult << "\n"
- << "arrange190cg_saved=" << arrange190cgResult << "\n"
- << "livescr190dr=" << livescr190drResult << "\n"
- << "livewf190ef=" << livewf190efResult << "\n"
- << "livewf190em=" << livewf190emResult << "\n"
- << "midigen190fm_saved=" << midigen190fmResult << "\n"
- << "trackauto190gz_saved=" << trackauto190gzResult << "\n"
- << "clipenv190gi_saved=" << clipenv190giResult << "\n"
- << "beatslaw190gx_saved=" << beatslaw190gxResult << "\n"
- << "editor_scale190he_saved=" << editorScale190heResult << "\n"
- << "sf_mod_base190he=" << sfModBase190heResult << "\n"
- << "metronome=" << metronomeResult << " (FL sounds " << metronomeFlSounds << "/" << lynx::metronome::soundCount
- << ", downbeat peak " << juce::String (metronomeMaster, 4) << ")\n";
- // issue #138 (round 190c): a short note at the very start of the Playlist against the same note at bar 2, through
- // the Export window's path (its own thread while the message loop runs: the report is finished from there)
- if (reportPath.isNotEmpty())
- juce::File (reportPath).replaceWithText (report + "(short_export running)\n");
- lynx::shortexport::run (false, 1, {}, {}, [this, report, ok, reportPath] (juce::String shortExport) {
- const auto all = ok && shortExport.startsWith ("OK");
- const auto text = report + "short_export=" + shortExport + "\nresult=" + (all ? "OK" : "FAILED") + "\n";
- if (reportPath.isNotEmpty())
- juce::File (reportPath).replaceWithText (text);
- setApplicationReturnValue (all ? 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 runPluginOptionsTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& shotsPath)
- {
- struct Test final : juce::Timer
- {
- juce::String reportPath, report;
- juce::File shots;
- std::unique_ptr<lynx::AudioEngine> engine;
- std::unique_ptr<juce::DocumentWindow> mainWindow, other; // LYNX's main window stand-in; another secondary window
- bool instrument = false, ok = true;
- int channelIndex = -1, phase = 0;
- juce::uint32 phaseStart = 0;
- juce::AudioPluginInstance* instance = nullptr;
- std::function<void (bool)> done;
- void step (const juce::String& line)
- {
- report << line << "\n";
- juce::File (reportPath).replaceWithText (report);
- }
- void expect (const juce::String& name, bool value)
- {
- step (name + "=" + juce::String ((int) value));
- ok = ok && value;
- }
- void next (int to)
- {
- phase = to;
- phaseStart = juce::Time::getMillisecondCounter();
- }
- int elapsed() const { return (int) (juce::Time::getMillisecondCounter() - phaseStart); }
- lynx::PluginRef* ref (lynx::Song& song) const
- {
- if (instrument)
- return channelIndex < 0 || channelIndex >= (int) song.channels.size() ? nullptr : &song.channels[(size_t) channelIndex].plugin;
- return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
- }
- const lynx::PluginRef& refNow() const { return *ref (const_cast<lynx::Song&> (engine->getSong())); }
- juce::AudioPluginInstance* find()
- {
- if (instrument)
- {
- if (auto* p = dynamic_cast<lynx::PluginInstrument*> (engine->getChannelInstrument (channelIndex).get()))
- return &p->getInstance();
- }
- else if (auto* p = dynamic_cast<lynx::PluginEffect*> (engine->getEffect (1, 0).get()))
- return &p->getInstance();
- return nullptr;
- }
- void openWindow()
- {
- std::shared_ptr<void> owner = instrument ? std::shared_ptr<void> (engine->getChannelInstrument (channelIndex))
- : std::shared_ptr<void> (engine->getEffect (1, 0));
- lynx::PluginWindows::open (owner, *instance, instance->getName(),
- { engine.get(), [this] (lynx::Song& song) { return ref (song); }, instrument, instrument ? -1 : 1,
- instrument ? -1 : 0, {}, {} });
- }
- void shot (const char* name, bool settingsPage = false)
- {
- if (shots != juce::File() && instance != nullptr)
- step (juce::String ("shot_") + name + "=" + juce::String ((int) lynx::PluginWindows::saveWindowShot (*instance, shots.getChildFile (juce::String (name) + ".png"), settingsPage)));
- }
- // the plugin window is in front of the other secondary window
- bool pluginInFront()
- {
- auto* plug = lynx::PluginWindows::hostWindowHandle (*instance);
- #if JUCE_WINDOWS
- return plug != nullptr && lynx::nativechild::isAbove (plug, other->getWindowHandle());
- #else
- auto& desktop = juce::Desktop::getInstance();
- for (int i = 0; i < desktop.getNumComponents(); ++i)
- if (auto* c = desktop.getComponent (i); c->getWindowHandle() == plug)
- return c->isAlwaysOnTop() || desktop.getComponent (desktop.getNumComponents() - 1) == c;
- return false;
- #endif
- }
- void timerCallback() override
- {
- if (phase == 0) // waiting for the engine to host the plugin
- {
- instance = find();
- if (instance == nullptr)
- {
- if (elapsed() > 20000)
- finish ("not hosted");
- return;
- }
- step ("hosted=" + instance->getName() + " format=" + instance->getPluginDescription().pluginFormatName);
- openWindow();
- next (1);
- return;
- }
- if (phase == 1 && elapsed() >= 800) // Pin on top: off for a new plugin
- {
- expect ("pin_off_by_default", ! lynx::PluginWindows::isPinnedOnTop (*instance) && ! refNow().pinned);
- shot ("pin-off");
- const auto history = engine->getHistoryPosition();
- lynx::PluginWindows::setPinnedOnTop (*instance, true);
- expect ("pin_set", lynx::PluginWindows::isPinnedOnTop (*instance) && refNow().pinned);
- expect ("pin_no_undo_step_project_modified", engine->getHistoryPosition() == history && engine->isModified());
- // another secondary window brought in front of it
- other = std::make_unique<juce::DocumentWindow> ("Another LYNX window", juce::Colours::darkslategrey, juce::DocumentWindow::closeButton);
- other->setUsingNativeTitleBar (true);
- other->setBounds (mainWindow->getX() + 60, mainWindow->getY() + 60, 420, 300);
- other->setVisible (true);
- lynx::keepAboveMainWindow (*other);
- lynx::forceForegroundForTest (*other);
- other->toFront (true);
- next (2);
- return;
- }
- if (phase == 2 && elapsed() >= 1200)
- {
- expect ("pinned_stays_in_front_of_a_clicked_window", pluginInFront());
- shot ("pin-on");
- // closed and opened again: the pin comes back from the project
- lynx::PluginWindows::close (*instance);
- openWindow();
- next (3);
- return;
- }
- if (phase == 3 && elapsed() >= 600)
- {
- expect ("pin_remembered_when_reopened", lynx::PluginWindows::isPinnedOnTop (*instance));
- lynx::PluginWindows::setPinnedOnTop (*instance, false);
- expect ("pin_cleared", ! lynx::PluginWindows::isPinnedOnTop (*instance) && ! refNow().pinned);
- other->toFront (true);
- next (4);
- return;
- }
- if (phase == 4 && elapsed() >= 1000)
- {
- #if JUCE_WINDOWS
- expect ("unpinned_goes_behind_a_clicked_window", ! pluginInFront());
- #endif
- other = nullptr;
- // the wrapper settings page: LYNX's Velocity row in the MIDI group (instruments), default = follow
- expect ("velocity_follows_midi_settings_by_default", refNow().velocityMode == lynx::prefs::pluginVelocityFollow
- && refNow().fixedVelocity == lynx::prefs::defaultFixedVelocity);
- shot ("wrapper-velocity-default", true);
- engine->editSong ([this] (lynx::Song& song) {
- if (auto* r = ref (song))
- {
- r->velocityMode = lynx::prefs::pluginVelocityFixed;
- r->fixedVelocity = 96;
- }
- });
- next (5);
- return;
- }
- if (phase == 5 && elapsed() >= 400)
- {
- expect ("velocity_change_keeps_the_running_plugin", find() == instance);
- shot ("wrapper-velocity-fixed", true);
- engine->undo();
- expect ("velocity_undo", refNow().velocityMode == lynx::prefs::pluginVelocityFollow && find() == instance);
- // the preset menu's "Play a note when a preset loads": off by default, a user setting
- expect ("audition_off_by_default", ! lynx::pluginpresetui::auditionOnLoad());
- lynx::pluginpresetui::setAuditionOnLoad (true);
- expect ("audition_menu_opened", lynx::PluginWindows::showPresetMenu (*instance));
- next (6);
- return;
- }
- if (phase == 6 && elapsed() >= 500) // the menu, as drawn
- {
- auto found = false;
- auto& desktop = juce::Desktop::getInstance();
- for (int c = desktop.getNumComponents(); --c >= 0 && ! found;)
- if (auto* menu = desktop.getComponent (c); dynamic_cast<juce::TopLevelWindow*> (menu) == nullptr && menu->isVisible()
- && menu->getHeight() > 60 && shots != juce::File())
- {
- const auto image = menu->createComponentSnapshot (menu->getLocalBounds(), true, 1.0f);
- juce::FileOutputStream out (shots.getChildFile ("preset-menu-audition.png"));
- found = out.openedOk() && juce::PNGImageFormat().writeImageToStream (image, out);
- }
- step ("shot_preset-menu-audition=" + juce::String ((int) found));
- juce::PopupMenu::dismissAllActiveMenus();
- // a preset loaded while the song is stopped: the note waits a moment, sounds, ends
- const auto asked = engine->auditionPreset (*instance);
- expect ("audition_only_for_channel_instruments", asked == instrument);
- expect ("audition_waits_first", ! instrument || engine->auditionState() == 1);
- next (7);
- return;
- }
- if (phase == 7 && elapsed() >= 300)
- {
- expect ("audition_sounds", ! instrument || engine->auditionState() == 2);
- next (8);
- return;
- }
- if (phase == 8 && elapsed() >= 700)
- {
- expect ("audition_ends", engine->auditionState() == 0);
- engine->getTransport().playing.store (true); // the song plays: no audition
- expect ("no_audition_while_playing", ! engine->auditionPreset (*instance) && engine->auditionState() == 0);
- engine->getTransport().playing.store (false);
- lynx::pluginpresetui::setAuditionOnLoad (false);
- expect ("audition_setting_off_again", ! lynx::pluginpresetui::auditionOnLoad());
- finish ({});
- }
- }
- void finish (const juce::String& failure)
- {
- stopTimer();
- if (failure.isNotEmpty())
- step ("failed=" + failure);
- ok = ok && failure.isEmpty();
- step (ok ? "result=OK" : "result=FAILED");
- lynx::PluginWindows::closeAll();
- done (ok);
- }
- };
- auto* test = new Test();
- test->reportPath = reportPath;
- if (shotsPath.isNotEmpty())
- {
- test->shots = juce::File (shotsPath);
- test->shots.createDirectory();
- }
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- test->done = [this, test] (bool ok) {
- setApplicationReturnValue (ok ? 0 : 1);
- juce::MessageManager::callAsync ([this, test] {
- lynx::setMainWindowForOwnership (nullptr);
- test->other = 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)
- {
- 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;
- test->channelIndex = (int) song.channels.size();
- 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->engine->markSaved();
- test->step ("plugin=" + chosen->name + " instrument=" + juce::String ((int) test->instrument));
- test->next (0);
- test->startTimerHz (20);
- }
- void runReloadTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& shotsPath, bool waitKill)
- {
- struct Test final : juce::Timer
- {
- juce::String reportPath, report;
- juce::File shots;
- std::unique_ptr<lynx::AudioEngine> engine;
- std::unique_ptr<juce::DocumentWindow> mainWindow; // stands for LYNX's main window (window ownership)
- bool instrument = false, waitKill = false, ok = true;
- int channelIndex = -1, phase = 0, round = 0;
- juce::uint32 phaseStart = 0;
- int firstPid = 0, pid = 0, historyBefore = 0;
- bool modifiedBefore = false;
- float captured = -1.0f;
- juce::AudioPluginInstance* instance = nullptr;
- std::vector<lynx::ChannelDef> channelsBefore;
- std::function<void (bool)> done;
- lynx::AudioEngine::HostedSlot where() const { return instrument ? lynx::AudioEngine::HostedSlot { channelIndex, -1, -1 } : lynx::AudioEngine::HostedSlot { -1, 1, 0 }; }
- void step (const juce::String& line)
- {
- report << line << "\n";
- juce::File (reportPath).replaceWithText (report);
- }
- void expect (const juce::String& name, bool value)
- {
- step (name + "=" + juce::String ((int) value));
- ok = ok && value;
- }
- void next (int to)
- {
- phase = to;
- phaseStart = juce::Time::getMillisecondCounter();
- }
- int elapsed() const { return (int) (juce::Time::getMillisecondCounter() - phaseStart); }
- juce::AudioPluginInstance* find()
- {
- if (instrument)
- {
- if (auto* p = dynamic_cast<lynx::PluginInstrument*> (engine->getChannelInstrument (channelIndex).get()))
- return &p->getInstance();
- }
- else if (auto* p = dynamic_cast<lynx::PluginEffect*> (engine->getEffect (1, 0).get()))
- return &p->getInstance();
- return nullptr;
- }
- // a few blocks through the plugin (the offline engine has no audio thread): they carry parameter changes to
- // the plugin's process and its values back
- void pump (int blocks)
- {
- std::vector<float> l (512), r (512);
- lynx::EffectParams none {};
- for (int b = 0; b < blocks; ++b)
- {
- std::fill (l.begin(), l.end(), 0.0f);
- std::fill (r.begin(), r.end(), 0.0f);
- if (instrument)
- {
- if (auto in = engine->getChannelInstrument (channelIndex))
- in->render (l.data(), r.data(), 512, 1.0f, 1.0f);
- }
- else if (auto fx = engine->getEffect (1, 0))
- fx->process (l.data(), r.data(), 512, none, 120.0);
- }
- }
- juce::AudioProcessorParameter* firstParam()
- {
- if (instance != nullptr)
- for (auto* candidate : instance->getParameters())
- if (candidate->isAutomatable() && ! candidate->isMetaParameter() && candidate != instance->getBypassParameter())
- return candidate;
- return nullptr;
- }
- void openWindow()
- {
- std::shared_ptr<void> owner = instrument ? std::shared_ptr<void> (engine->getChannelInstrument (channelIndex))
- : std::shared_ptr<void> (engine->getEffect (1, 0));
- lynx::PluginWindows::WrapperContext context { engine.get(), [this] (lynx::Song& song) -> lynx::PluginRef* {
- if (instrument)
- return channelIndex < 0 || channelIndex >= (int) song.channels.size()
- ? nullptr : &song.channels[(size_t) channelIndex].plugin;
- return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
- }, instrument, instrument ? -1 : 1, instrument ? -1 : 0, {}, {} };
- context.reload = [] {}; // (the test reloads by itself; with it the window shows the notice)
- lynx::PluginWindows::open (owner, *instance, instance->getName(), std::move (context));
- }
- void shot (const char* name, bool settingsPage = false)
- {
- if (shots != juce::File() && instance != nullptr)
- step (juce::String ("shot_") + name + "=" + juce::String ((int) lynx::PluginWindows::saveWindowShot (*instance, shots.getChildFile (juce::String (name) + ".png"), settingsPage)));
- }
- void timerCallback() override
- {
- if (phase == 0) // waiting for the engine to host the plugin
- {
- instance = find();
- if (instance == nullptr)
- {
- if (elapsed() > 20000)
- finish ("not hosted");
- return;
- }
- pid = firstPid = lynx::sandboxedPluginProcessId (*instance);
- step ("hosted=" + instance->getName() + " format=" + instance->getPluginDescription().pluginFormatName + " pid=" + juce::String (pid));
- expect ("separate_process", lynx::isSandboxedPlugin (*instance) && pid != 0);
- expect ("running", ! engine->hostedPluginDown (where()) && engine->downHostedPlugins().empty());
- // a setting that is captured (what a save or a backup does), then one that is not
- if (auto* param = firstParam())
- {
- param->setValue (param->getValue() > 0.5f ? 0.13f : 0.87f);
- pump (4);
- engine->capturePluginStates();
- captured = param->getValue();
- param->setValue (captured > 0.5f ? 0.31f : 0.69f);
- pump (4);
- step ("param=" + param->getName (64) + " captured=" + juce::String (captured, 4) + " then=" + juce::String (param->getValue(), 4));
- }
- else
- {
- engine->capturePluginStates();
- step ("param=none");
- }
- channelsBefore = engine->getSong().channels;
- historyBefore = engine->getHistoryPosition();
- modifiedBefore = engine->isModified();
- if (shots != juce::File())
- openWindow();
- next (1);
- return;
- }
- if (phase == 1 && elapsed() >= 600) // the plugin's process goes
- {
- shot (round == 0 ? "window-running" : "window-reloaded");
- if (waitKill && round == 0)
- {
- juce::File (reportPath + ".pid").replaceWithText (juce::String (pid));
- step ("waiting_for_kill pid=" + juce::String (pid));
- }
- else
- lynx::crashSandboxedPluginForTest (*instance);
- next (2);
- return;
- }
- if (phase == 2) // LYNX notices
- {
- if (! engine->hostedPluginDown (where()))
- {
- pump (1); // (as the audio thread would: a block that gets no answer marks it too)
- if (elapsed() > (waitKill && round == 0 ? 120000 : 10000))
- finish ("the plugin never went down");
- return;
- }
- step ("down_after_ms=" + juce::String (elapsed()));
- const auto down = engine->downHostedPlugins();
- expect ("listed_down", down.size() == 1 && down.front() == where());
- expect ("listed_by_name", engine->downHostedPlugins (nameInSong()).size() == 1 && engine->downHostedPlugins ("no such plugin").empty());
- next (3);
- return;
- }
- if (phase == 3 && elapsed() >= 1500) // nothing reloads by itself
- {
- expect ("still_down_without_asking", engine->hostedPluginDown (where()) && find() == instance
- && lynx::sandboxedPluginProcessId (*instance) == pid);
- shot (round == 0 ? "reload-notice" : "reload-notice-again");
- if (shots != juce::File() && round == 0)
- {
- lynx::PluginWindows::close (*instance);
- lynx::PluginWindows::promptReload (*engine, where(), {});
- next (4);
- return;
- }
- next (5);
- return;
- }
- if (phase == 4 && elapsed() >= 500) // the prompt a click on the channel / slot shows
- {
- auto found = false;
- for (int c = juce::Desktop::getInstance().getNumComponents(); --c >= 0;)
- if (auto* alert = dynamic_cast<juce::AlertWindow*> (juce::Desktop::getInstance().getComponent (c)))
- {
- const auto image = alert->createComponentSnapshot (alert->getLocalBounds(), true, 1.0f);
- juce::FileOutputStream out (shots.getChildFile ("reload-prompt.png"));
- found = out.openedOk() && juce::PNGImageFormat().writeImageToStream (image, out);
- alert->exitModalState (0); // Close: nothing reloads
- break;
- }
- step ("shot_reload-prompt=" + juce::String ((int) found));
- next (45);
- return;
- }
- if (phase == 45 && elapsed() >= 300)
- {
- expect ("still_down_after_close", engine->hostedPluginDown (where()));
- next (5);
- return;
- }
- if (phase == 5) // Reload, as the notice's button / the prompt / the menu item do
- {
- auto* old = instance;
- const auto running = lynx::PluginWindows::reload (*engine, { where() });
- instance = find();
- const auto newPid = instance != nullptr ? lynx::sandboxedPluginProcessId (*instance) : 0;
- expect ("reloaded", running == 1 && instance != nullptr && ! engine->hostedPluginDown (where()) && engine->downHostedPlugins().empty());
- expect ("new_process", newPid != 0 && newPid != pid);
- step ("pid=" + juce::String (newPid) + " same_object=" + juce::String ((int) (instance == old)));
- expect ("old_window_closed", ! lynx::PluginWindows::isOpen (*old) || instance == old);
- pid = newPid;
- if (instance != nullptr)
- {
- pump (4);
- if (auto* param = firstParam(); param != nullptr && captured >= 0.0f)
- {
- step ("param_after_reload=" + juce::String (param->getValue(), 4));
- expect ("state_captured_last", std::abs (param->getValue() - captured) < 0.02f);
- }
- }
- expect ("song_untouched", engine->getSong().channels == channelsBefore);
- expect ("no_undo_step", engine->getHistoryPosition() == historyBefore && engine->isModified() == modifiedBefore);
- if (instance == nullptr)
- {
- finish ("no instance after the reload");
- return;
- }
- if (shots != juce::File())
- openWindow();
- if (round == 0) // once more: a plugin that crashes again waits for the user again
- {
- round = 1;
- next (1);
- return;
- }
- next (6);
- return;
- }
- if (phase == 6 && elapsed() >= 400) // an edit and its undo keep the reloaded plugin
- {
- shot ("window-reloaded-twice");
- auto* before = find();
- engine->editSong ([] (lynx::Song& song) { song.bpm += 1.0f; });
- engine->undo();
- expect ("undo_keeps_the_reloaded_plugin", find() == before && ! engine->hostedPluginDown (where()));
- lynx::PluginWindows::closeAll();
- finish ({});
- }
- }
- std::string nameInSong() const
- {
- const auto& song = engine->getSong();
- return instrument ? song.channels[(size_t) channelIndex].plugin.name : song.mixer[1].effects[0].plugin.name;
- }
- void finish (const juce::String& failure)
- {
- stopTimer();
- if (failure.isNotEmpty())
- step ("failed=" + failure);
- ok = ok && failure.isEmpty();
- step (ok ? "result=OK" : "result=FAILED");
- lynx::PluginWindows::closeAll();
- done (ok);
- }
- };
- lynx::setPluginSandboxAlerts (true); // (the deaths are recorded as in the app; no box: there is no main component)
- auto* test = new Test();
- test->reportPath = reportPath;
- test->waitKill = waitKill;
- if (shotsPath.isNotEmpty())
- {
- test->shots = juce::File (shotsPath);
- test->shots.createDirectory();
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- }
- juce::File (reportPath + ".pid").deleteFile();
- 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);
- if (shotsPath.isNotEmpty())
- {
- 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)
- {
- chosen = type;
- break;
- }
- if (! chosen)
- {
- test->step ("result=FAILED (no plugin)");
- test->done (false);
- return;
- }
- test->instrument = chosen->isInstrument;
- lynx::PluginRef ref;
- ref.separateProcess = true;
- 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;
- test->channelIndex = (int) song.channels.size();
- 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->next (0);
- test->startTimerHz (20);
- }
- 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, dockStep = 0;
- juce::uint32 phaseStartMs = 0; // (phase 1 counts real time: the timer's ticks ran faster than 20 Hz here)
- juce::AudioPluginInstance* instance = nullptr;
- juce::AudioProcessorParameter* checked = nullptr;
- std::unique_ptr<juce::DocumentWindow> mainWindow; // stands for LYNX's main window (window ownership)
- lynx::Workspace* workspace = nullptr; // LYNX_PLUGWIN_DOCK=1: the real main window's desktop (issue #116)
- int channelIndex = -1; // an instrument: its channel (added after the song's own channels)
- int stepMs = 3000; // dock mode: each state held that long (screenshots)
- bool keysDone = false;
- bool dockOk = true;
- std::function<void (bool)> done;
- // LYNX_PLUGWIN_DROP=<sample> (issue #174): a Sample browser window beside the plugin window with that file
- // selected. The report gives the row's and the editor's places on screen with what LYNX sees there (for a
- // real drag by xdotool / SendInput in that time), and, before the plugin is removed, whether the plugin took
- // the file (its saved state names it).
- juce::File dropFile;
- std::unique_ptr<juce::DocumentWindow> dropWindow;
- lynx::BrowserComponent* dropBrowser = nullptr;
- int dropStage = 0;
- juce::uint32 dropReadyMs = 0; // (the Browser may take long to list a big library: the time counts from here)
- void dropTick (int elapsedMs)
- {
- if (dropStage == 0 && elapsedMs >= 1000)
- {
- lynx::externaldrag::install();
- auto content = lynx::BrowserComponent::makeSampleBrowserContent (*engine, [this] (lynx::BrowserComponent& b) { dropBrowser = &b; });
- dropWindow = std::make_unique<juce::DocumentWindow> ("LYNX test sample browser", juce::Colours::darkgrey, 0);
- dropWindow->setContentOwned (content.release(), false);
- dropWindow->setBounds (20, 240, 340, 520);
- dropWindow->setVisible (true);
- if (dropBrowser != nullptr)
- {
- dropBrowser->showFilterForSnapshot (dropFile.getParentDirectory(), lynx::browserview::ContentFilter::all);
- step ("drop_locate=" + juce::String ((int) dropBrowser->locateFile (dropFile)));
- }
- dropStage = 1;
- }
- else if (dropStage == 1 && elapsedMs >= 2500)
- {
- using namespace lynx::externaldrag;
- const auto row = dropBrowser != nullptr ? dropBrowser->selectedRowScreenBounds() : juce::Rectangle<int>();
- const auto from = row.getCentre();
- // (physical pixels too: SendInput / xdotool work in those)
- auto physical = [] (juce::Point<int> p) {
- const auto q = juce::Desktop::getInstance().getDisplays().logicalToPhysical (p);
- return " phys=" + juce::String (q.x) + "," + juce::String (q.y);
- };
- step ("drop_source=" + juce::String (from.x) + "," + juce::String (from.y) + " place=" + placeName (placeAt (from)) + physical (from));
- if (const auto pid = lynx::sandboxedPluginProcessId (*instance); pid != 0)
- step ("drop_target_pid=" + juce::String (pid)); // (its window is the other process's)
- else if (auto* editor = instance->getActiveEditor())
- {
- const auto to = editor->getScreenBounds().getCentre();
- step ("drop_target=" + juce::String (to.x) + "," + juce::String (to.y) + " place=" + placeName (placeAt (to)) + physical (to));
- }
- const auto files = filesOf (juce::String (lynx::BrowserComponent::dragDescription) + "|" + dropFile.getFullPathName(), nullptr);
- step ("drop_files=" + files.joinIntoString (";"));
- dropStage = 2;
- dropReadyMs = juce::Time::getMillisecondCounter();
- }
- }
- void dropResult()
- {
- juce::MemoryBlock state;
- instance->getStateInformation (state);
- const auto name = dropFile.getFileNameWithoutExtension().toStdString();
- auto holds = [&name] (const juce::MemoryBlock& block) {
- const auto* bytes = static_cast<const char*> (block.getData());
- return ! name.empty() && std::search (bytes, bytes + block.getSize(), name.begin(), name.end()) != bytes + block.getSize();
- };
- auto received = holds (state);
- // (JUCE's VST3 host keeps the plugin's own state base64-encoded inside an XML of its own)
- auto xml = juce::AudioProcessor::getXmlFromBinary (state.getData(), (int) state.getSize());
- if (xml == nullptr)
- xml = juce::parseXML (state.toString());
- if (! received && xml != nullptr)
- for (auto* e : xml->getChildIterator())
- {
- juce::MemoryBlock inner;
- if (inner.fromBase64Encoding (e->getAllSubText().trim()) && holds (inner))
- received = true;
- }
- step ("drop_received=" + juce::String ((int) received));
- }
- // issue #116 (with LYNX_DOCKED_PLUGINS=1 and LYNX_PLUGWIN_DOCK=1), FL's f116 sequence for every floating
- // panel: the docked plugin window goes behind a clicked panel and comes back in front when clicked; a
- // panel called by its key comes in front too; Detached reopens it as a window of its own, which stays above
- // every panel clicked (it is owned by the main window).
- const std::array<lynx::workspace::Panel, 4> dockPanels { lynx::workspace::Panel::channelRack, lynx::workspace::Panel::playlist,
- lynx::workspace::Panel::pianoRoll, lynx::workspace::Panel::mixer };
- const int dockSteps = 2 * 4 + 18; // (the last one reports dock_result)
- int danceChannel = -1; // issue #116 slice 4: a dance channel's dancer over the docked plugin
- lynx::MainComponent* ui = nullptr; // dock mode: the real main window's contents
- struct ScaleSpy final : juce::ComponentPeer::ScaleFactorListener
- {
- int calls = 0;
- double last = 0.0;
- void nativeScaleFactorChanged (double s) override { ++calls; last = s; }
- } scaleSpy;
- juce::ComponentPeer* spiedPeer = nullptr;
- void* panelHandle (lynx::workspace::Panel p) const { return workspace->getFrame (p).getWindowHandle(); }
- void dockCheck (int at)
- {
- using lynx::workspace::Panel;
- auto* main = mainWindow->getWindowHandle();
- auto* plug = lynx::PluginWindows::hostWindowHandle (*instance);
- auto expect = [this] (const juce::String& name, bool value) {
- step (name + "=" + juce::String ((int) value));
- dockOk = dockOk && value;
- };
- auto id = [] (Panel p) { return juce::String (lynx::workspace::panelId (p)); };
- if (at == 0)
- {
- expect ("docked", lynx::PluginWindows::isDocked (*instance));
- expect ("plugin_native_child", plug != nullptr && lynx::nativechild::parentOf (plug) == main);
- for (auto p : dockPanels)
- {
- auto* h = panelHandle (p);
- expect (id (p) + "_visible", workspace->isPanelVisible (p));
- expect (id (p) + "_native_child", h != nullptr && h != main && lynx::nativechild::parentOf (h) == main);
- expect ("plugin_above_" + id (p) + "_when_opened", lynx::nativechild::isAbove (plug, h));
- }
- expect ("browser_plain", ! workspace->isNativePanel (Panel::browser));
- }
- if (at < 2 * 4)
- {
- const auto p = dockPanels[at / 2];
- if (at % 2 == 0)
- {
- workspace->activate (p); // a click on the panel
- expect (id (p) + "_above_plugin_after_its_click", lynx::nativechild::isAbove (panelHandle (p), plug));
- // the plugin stays above the panels nobody clicked
- for (auto other : dockPanels)
- if (other != p)
- expect ("plugin_above_" + id (other) + "_after_" + id (p) + "_click", lynx::nativechild::isAbove (plug, panelHandle (other)));
- }
- else
- {
- lynx::PluginWindows::open ({}, *instance, {}); // (open again = a click on the plugin)
- expect ("plugin_above_" + id (p) + "_after_plugin_click", lynx::nativechild::isAbove (plug, panelHandle (p)));
- }
- return;
- }
- if (at == 8)
- {
- // a layout change elsewhere (a panel resized, the Browser shown) keeps the plugin in front; a panel
- // called by its key comes in front of it
- workspace->hide (Panel::browser);
- workspace->show (Panel::browser);
- for (auto p : dockPanels)
- expect ("plugin_above_" + id (p) + "_after_layout_change", lynx::nativechild::isAbove (plug, panelHandle (p)));
- workspace->show (Panel::mixer);
- expect ("mixer_above_plugin_after_show", lynx::nativechild::isAbove (panelHandle (Panel::mixer), plug));
- }
- else if (at == 9)
- {
- // the setup wizard (Options › Setup wizard; first start) in front of the native panels and the plugin
- ui->showSetupWizard();
- }
- else if (at == 10)
- {
- auto* overlay = ui->setupOverlayForTest();
- auto* h = overlay != nullptr ? overlay->getWindowHandle() : nullptr;
- expect ("setup_overlay_native_child", h != nullptr && h != main && lynx::nativechild::parentOf (h) == main);
- expect ("setup_overlay_above_plugin", lynx::nativechild::isAbove (h, plug));
- for (auto p : dockPanels)
- expect ("setup_overlay_above_" + id (p), lynx::nativechild::isAbove (h, panelHandle (p)));
- workspace->activate (Panel::playlist); // (a panel brought in front by code: the overlay stays in front)
- lynx::PluginWindows::open ({}, *instance, {});
- expect ("setup_overlay_stays_in_front", lynx::nativechild::isAbove (h, plug) && lynx::nativechild::isAbove (h, panelHandle (Panel::playlist)));
- }
- else if (at == 11)
- {
- ui->closeSetupWizardForSnapshot();
- expect ("setup_overlay_closed", ui->setupOverlayForTest() == nullptr);
- // drops: JUCE's list of windows in the native stacking order once a drag starts
- workspace->activate (Panel::mixer);
- workspace->hide (Panel::browser);
- workspace->show (Panel::browser);
- lynx::matchWindowOrderToScreen();
- auto children = lynx::nativechild::attachedChildren (main);
- auto& desktop = juce::Desktop::getInstance();
- int last = -1;
- bool ordered = children.size() >= 5;
- for (auto* c : children)
- if (c->isVisible())
- {
- int at2 = -1;
- for (int k = 0; k < desktop.getNumComponents(); ++k)
- if (desktop.getComponent (k) == c)
- at2 = k;
- ordered = ordered && at2 > last;
- last = at2;
- }
- expect ("drop_order_matches_screen", ordered);
- }
- else if (at == 12)
- {
- // the main window's scale changes (a display with another scale): every native child placed again in
- // physical pixels, the docked editor's window told (JUCE tells child windows nothing by itself)
- for (int i = 0; i < juce::ComponentPeer::getNumPeers(); ++i)
- if (auto* peer = juce::ComponentPeer::getPeer (i); peer != nullptr && peer->getNativeHandle() == plug)
- spiedPeer = peer;
- if (spiedPeer != nullptr)
- spiedPeer->addScaleFactorListener (&scaleSpy);
- lynx::nativechild::notifyScaleListenersForTest (*mainWindow);
- juce::Desktop::getInstance().setGlobalScaleFactor (1.25f); // and LYNX's own UI zoom
- }
- else if (at == 13)
- {
- bool placed = true;
- for (auto* c : lynx::nativechild::attachedChildren (main))
- placed = placed && (! c->isVisible() || lynx::nativechild::placedPhysically (*c));
- expect ("native_children_placed_at_125", placed);
- expect ("docked_editor_told_the_scale", scaleSpy.calls > 0 && spiedPeer != nullptr
- && std::abs (scaleSpy.last - spiedPeer->getPlatformScaleFactor()) < 0.001);
- if (spiedPeer != nullptr && juce::ComponentPeer::isValidPeer (spiedPeer))
- spiedPeer->removeScaleFactorListener (&scaleSpy);
- juce::Desktop::getInstance().setGlobalScaleFactor (1.0f);
- lynx::PluginWindows::setDetached (*instance, true);
- }
- else if (at == 14)
- {
- expect ("detached_reopened", lynx::PluginWindows::isOpen (*instance) && ! lynx::PluginWindows::isDocked (*instance));
- expect ("detached_owned_by_main", plug != nullptr && lynx::nativechild::ownerOf (plug) == main);
- expect ("detached_saved", find() == instance && engineRef() != nullptr && engineRef()->detached);
- for (auto p : dockPanels)
- workspace->activate (p);
- }
- else if (at == 15)
- {
- // (an owned top-level window: above the main window and so above all its child windows)
- expect ("detached_stays_above_clicked_panels", plug != nullptr && lynx::nativechild::ownerOf (plug) == main
- && lynx::nativechild::parentOf (plug) != main && lynx::PluginWindows::isOpen (*instance));
- lynx::PluginWindows::setDetached (*instance, false);
- }
- else if (at == 16)
- {
- // issue #116 slice 4: a Fruity Dance dancer standing on the docked plugin window, in front of it
- auto* stage = dynamic_cast<lynx::DanceStage*> (ui->danceStageForTest());
- juce::Rectangle<int> over;
- for (auto* c : lynx::nativechild::attachedChildren (main))
- if (c->getWindowHandle() == plug)
- over = ui->getLocalArea (nullptr, c->getScreenBounds());
- expect ("dance_stage", stage != nullptr && ! over.isEmpty());
- lynx::dance::Settings s;
- s.move = lynx::dance::held; // (a still pose: the pixels tested below stay where they are)
- s.x = over.getCentreX();
- s.y = over.getCentreY() + 70;
- const auto state = lynx::dance::toState (s);
- engine->editSongStructural ([this, state] (lynx::Song& song) {
- lynx::ChannelDef c;
- c.name = "Fruity Dance";
- c.instrument = lynx::InstrumentKind::fruitydance;
- c.pluginState = state;
- danceChannel = (int) song.channels.size();
- song.channels.push_back (c);
- });
- engine->dispatchPendingMessages();
- if (stage != nullptr)
- stage->update();
- }
- else if (at == 17)
- {
- auto* stage = dynamic_cast<lynx::DanceStage*> (ui->danceStageForTest());
- auto* w = stage != nullptr ? stage->windowOf (danceChannel) : nullptr;
- auto* h = w != nullptr ? w->getWindowHandle() : nullptr;
- expect ("dancer_window_native_child", h != nullptr && h != main && lynx::nativechild::parentOf (h) == main);
- expect ("dancer_window_layered", lynx::nativechild::isLayered (h));
- expect ("dancer_above_plugin", lynx::nativechild::isAbove (h, plug));
- for (auto p : dockPanels)
- expect ("dancer_above_" + id (p), lynx::nativechild::isAbove (h, panelHandle (p)));
- // panels and the plugin brought in front (clicks, keys): the dancer stays in front of them
- workspace->activate (Panel::mixer);
- workspace->show (Panel::pianoRoll);
- lynx::PluginWindows::open ({}, *instance, {});
- expect ("dancer_stays_in_front", lynx::nativechild::isAbove (h, plug) && lynx::nativechild::isAbove (h, panelHandle (Panel::mixer))
- && lynx::nativechild::isAbove (h, panelHandle (Panel::pianoRoll)));
- // the mouse: the dancer's body takes it, its window's transparent pixels let it through
- if (w != nullptr)
- {
- const auto picture = w->createComponentSnapshot (w->getLocalBounds(), true, 1.0f);
- const auto body = stage->bodyOf (danceChannel) - (w->getScreenPosition() - stage->getScreenPosition());
- juce::Point<int> solid { -1, -1 }, clear { -1, -1 };
- for (int y = body.getCentreY() - 10; y < body.getBottom() && solid.x < 0; ++y)
- for (int x = body.getX(); x < body.getRight() && solid.x < 0; ++x)
- if (picture.getBounds().contains (x, y) && picture.getPixelAt (x, y).getAlpha() == 255)
- solid = { x, y };
- for (int y = 0; y < picture.getHeight() && clear.x < 0; y += 2)
- for (int x = 0; x < picture.getWidth() && clear.x < 0; x += 2)
- if (picture.getPixelAt (x, y).getAlpha() == 0 && ! body.expanded (8).contains (x, y))
- clear = { x, y };
- step ("dancer_window=" + w->getBounds().toString() + " solid=" + solid.toString() + " clear=" + clear.toString());
- auto* atSolid = lynx::nativechild::windowAt (*w, solid);
- auto* atClear = lynx::nativechild::windowAt (*w, clear);
- expect ("dancer_takes_its_body_clicks", solid.x >= 0 && atSolid == h);
- expect ("dancer_lets_clicks_through", clear.x >= 0 && atClear != nullptr && atClear != h);
- expect ("stage_leaves_the_mouse", ! stage->hitTest (stage->bodyOf (danceChannel).getCentreX(), stage->bodyOf (danceChannel).getCentreY()));
- }
- }
- else if (at == 18)
- {
- // no dance channel: no dancer window (nothing drawn, no cost)
- auto* stage = dynamic_cast<lynx::DanceStage*> (ui->danceStageForTest());
- engine->editSongStructural ([this] (lynx::Song& song) {
- if (danceChannel >= 0 && danceChannel < (int) song.channels.size())
- song.channels.erase (song.channels.begin() + danceChannel);
- });
- engine->dispatchPendingMessages();
- if (stage != nullptr)
- stage->update();
- expect ("dancer_window_gone", stage != nullptr && stage->windowCount() == 0);
- }
- else if (at == 19 || at == 20)
- {
- // round 190ev (issue #152, "flickering windows"): on Windows a docked panel no longer fades by its
- // window's alpha (each fade switched its drawing surface twice and the panel flashed); it shows and
- // hides at once, as FL's docked windows. Elsewhere round 190i's fade stays.
- auto& frame = workspace->getFrame (Panel::mixer);
- if (at == 19)
- {
- workspace->show (Panel::mixer);
- expect ("mixer_above_plugin_when_shown", lynx::nativechild::isAbove (panelHandle (Panel::mixer), plug));
- workspace->hide (Panel::mixer);
- expect ("mixer_hides_at_once", ! frame.isVisible() && workspace->nativeFadeDirection (Panel::mixer) == 0
- && frame.getAlpha() == 1.0f && ! lynx::nativechild::isLayered (frame.getWindowHandle()));
- }
- else
- {
- workspace->show (Panel::mixer);
- expect ("mixer_shows_at_once", frame.isVisible() && frame.getAlpha() == 1.0f && workspace->nativeFadeDirection (Panel::mixer) == 0
- && ! lynx::nativechild::isLayered (frame.getWindowHandle())
- && lynx::nativechild::isAbove (panelHandle (Panel::mixer), plug));
- }
- }
- else if (at >= 21 && at <= 23)
- {
- // round 190ev (issue #152, "the Channel rack almost never comes to the front"): LYNX's own editor
- // windows (here a channel's settings) are docked like FL's plugin windows, so a click on the rack
- // brings the rack in front of them and a click on one brings it back; a click inside a docked
- // plugin's own view (a native window JUCE never hears of) brings that plugin window in front.
- auto docked = [] {
- auto& desktop = juce::Desktop::getInstance();
- for (int i = 0; i < desktop.getNumComponents(); ++i)
- if (auto* c = desktop.getComponent (i); c != nullptr && c->isVisible() && (bool) c->getProperties()["lynxDockedWindow"])
- return c;
- return (juce::Component*) nullptr;
- };
- auto* rack = panelHandle (Panel::channelRack);
- if (at == 21)
- {
- lynx::openChannelSettings (*engine, 0);
- auto* ed = docked();
- auto* h = ed != nullptr ? ed->getWindowHandle() : nullptr;
- expect ("editor_docked", h != nullptr && lynx::nativechild::parentOf (h) == main && lynx::nativechild::ownerOf (h) == nullptr);
- expect ("editor_above_rack_when_opened", h != nullptr && lynx::nativechild::isAbove (h, rack));
- workspace->activate (Panel::channelRack); // a click on the rack
- expect ("rack_above_editor_after_its_click", h != nullptr && lynx::nativechild::isAbove (rack, h));
- // a real click (a message to the editor's own window) on its title bar, at a point where the editor
- // can be seen. Round 190fc (0.1.27 RC M1): JUCE takes a button-down only where the system says its
- // window is the one under the point (HWNDComponentPeer::contains asks WindowFromPoint), so the old
- // fixed point (60, 8) was dropped whenever the rack, raised just above, covered it there: the
- // check read 0 while real clicks (on what can be seen) raise the editor.
- if (h != nullptr && ed != nullptr)
- {
- juce::Point<int> at (-1, -1);
- for (int x = 30; x < ed->getWidth() - 40 && at.x < 0; x += 12)
- if (lynx::nativechild::windowAt (*ed, { x, 8 }) == h)
- at = { x, 8 };
- step (juce::String ("editor_title_visible_at=") + juce::String (at.x));
- if (at.x >= 0)
- {
- const auto scale = ed->getPeer() != nullptr ? ed->getPeer()->getPlatformScaleFactor() * (double) ed->getDesktopScaleFactor() : 1.0;
- lynx::nativechild::postClickForTest (h, (at.toDouble() * scale).roundToInt());
- }
- }
- }
- else if (at == 22)
- {
- auto* ed = docked();
- auto* h = ed != nullptr ? ed->getWindowHandle() : nullptr;
- expect ("editor_above_rack_after_its_click", h != nullptr && lynx::nativechild::isAbove (h, rack));
- workspace->activate (Panel::channelRack);
- expect ("rack_above_plugin_after_its_click", lynx::nativechild::isAbove (rack, plug));
- auto* view = lynx::nativechild::innermostChild (plug);
- step (juce::String ("plugin_view_window=") + (view != nullptr ? "1" : "0"));
- if (view != nullptr) // a click in the plugin's own view, near its top-left corner
- lynx::nativechild::postClickForTest (view, { 2, 2 });
- }
- else
- {
- if (lynx::nativechild::innermostChild (plug) != nullptr)
- expect ("plugin_above_rack_after_click_in_its_view", lynx::nativechild::isAbove (plug, rack));
- lynx::closeChannelSettings();
- // FL's Tools > Macros > Switch all plugin editors to > Detached (round 190i)
- lynx::PluginWindows::setAllDetached (*engine, true);
- }
- }
- else if (at == 24)
- {
- expect ("macro_detached_the_open_editor", lynx::PluginWindows::isOpen (*instance) && ! lynx::PluginWindows::isDocked (*instance)
- && plug != nullptr && lynx::nativechild::ownerOf (plug) == main);
- expect ("macro_detached_saved", find() == instance && engineRef() != nullptr && engineRef()->detached);
- lynx::PluginWindows::setAllDetached (*engine, false); // ... > Attached
- }
- else
- {
- expect ("docked_again", lynx::PluginWindows::isDocked (*instance) && engineRef() != nullptr && ! engineRef()->detached);
- step (juce::String ("dock_result=") + (dockOk ? "OK" : "FAILED"));
- }
- }
- const lynx::PluginRef* engineRef() const
- {
- const auto& song = engine->getSong();
- if (instrument)
- return channelIndex < 0 || channelIndex >= (int) song.channels.size() ? nullptr : &song.channels[(size_t) channelIndex].plugin;
- return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
- }
- 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 (channelIndex).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 (channelIndex))
- : 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 channelIndex < 0 || channelIndex >= (int) song.channels.size()
- ? nullptr : &song.channels[(size_t) channelIndex].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;
- phaseStartMs = juce::Time::getMillisecondCounter();
- return;
- }
- if (phase == 1 && ticks >= 30 && ! keysDone && juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_KEYS", {}).isNotEmpty() && instance->getActiveEditor() != nullptr)
- keysDone = ! lynx::pluginKeysTestTick (*instance->getActiveEditor(),
- [this] (bool on) {
- engine->editSong ([this, on] (lynx::Song& song) {
- (instrument ? song.channels[(size_t) channelIndex].plugin : song.mixer[1].effects[0].plugin).hostKeysFirst = on;
- });
- },
- [this] (const juce::String& line) { step (line); });
- const auto elapsedMs = (int) (juce::Time::getMillisecondCounter() - phaseStartMs);
- if (phase == 1 && ticks == 20 && checked != nullptr)
- step ("param_after_1s=" + juce::String (checked->getValue(), 4));
- // (3 s apart: time for screenshots of each state)
- if (phase == 1 && workspace != nullptr && dockStep < dockSteps && elapsedMs >= (dockStep + 1) * stepMs)
- dockCheck (dockStep++);
- if (phase == 1 && dropFile.existsAsFile())
- dropTick (elapsedMs);
- // (with LYNX_PLUGWIN_DROP: `seconds` after the drop places were reported, time for the drag)
- const auto dropDone = ! dropFile.existsAsFile()
- || (dropStage == 2 && (int) (juce::Time::getMillisecondCounter() - dropReadyMs) >= seconds * 1000);
- if (phase == 1 && elapsedMs >= seconds * 1000 && dropDone && (workspace == nullptr || dockStep >= dockSteps)) // remove the plugin from the song
- {
- if (dropFile.existsAsFile())
- dropResult();
- engine->editSong ([this] (lynx::Song& song) {
- if (instrument)
- {
- if (channelIndex >= 0 && channelIndex < (int) song.channels.size())
- song.channels.erase (song.channels.begin() + channelIndex);
- }
- 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 || ! dockOk ? "result=FAILED" : "result=OK");
- stopTimer();
- lynx::PluginWindows::closeAll();
- done (! open && dockOk);
- }
- }
- };
- auto* test = new Test();
- test->reportPath = reportPath;
- test->seconds = seconds;
- if (const auto drop = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_DROP", {}); drop.isNotEmpty())
- test->dropFile = juce::File (drop);
- test->done = [this, test] (bool ok) {
- setApplicationReturnValue (ok ? 0 : 1);
- juce::MessageManager::callAsync ([this, test] {
- lynx::setMainWindowForOwnership (nullptr);
- lynx::PluginWindows::setDockWorkspace (nullptr);
- test->dropWindow = nullptr; // (its Browser before the engine)
- test->workspace = nullptr;
- test->mainWindow = nullptr; // (dock mode: the main component with it, before the engine)
- 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);
- if (juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_DOCK", {}) == "1" && lynx::nativechild::dockingEnabled())
- {
- // the real main window's contents (it docks plugin windows in its own desktop), so the panels are real
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- auto* ui = new lynx::MainComponent (*test->engine, false);
- test->mainWindow->setUsingNativeTitleBar (true);
- test->mainWindow->setContentOwned (ui, false);
- test->mainWindow->setBounds (20, 20, 1500, 900);
- test->workspace = &ui->workspaceForTest();
- test->ui = ui;
- if (const auto ms = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_STEP_MS", {}).getIntValue(); ms > 0)
- test->stepMs = ms;
- }
- test->mainWindow->setVisible (true);
- lynx::setMainWindowForOwnership (test->mainWindow.get());
- if (test->workspace != nullptr)
- {
- using lynx::workspace::Panel;
- for (auto p : { Panel::playlist, Panel::mixer, Panel::pianoRoll, Panel::channelRack })
- test->workspace->show (p);
- test->step ("dock_test=2 rack_visible=" + juce::String ((int) test->workspace->isPanelVisible (Panel::channelRack)));
- }
- 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.separateProcess = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_SEPARATE", {}) == "1"; // (issue #96's other-process check)
- 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;
- test->channelIndex = (int) song.channels.size();
- 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 runFocusTest (const juce::String& reportPath)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- struct FocusTest 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;
- 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;
- }
- juce::ComponentPeer* mainPeer() const { return main != nullptr ? main->getPeer() : nullptr; }
- bool focusInMain() const
- {
- auto* f = juce::Component::getCurrentlyFocusedComponent();
- return f != nullptr && main->isParentOf (f);
- }
- // a click (press and release) at the middle of the panel's content, through the native window it is in
- static void click (juce::Component& frame, bool right)
- {
- auto* peer = frame.getPeer();
- if (peer == nullptr)
- return;
- const auto at = peer->getComponent().getLocalPoint (&frame, frame.getLocalBounds().getCentre().toFloat());
- const auto button = right ? juce::ModifierKeys::rightButtonModifier : juce::ModifierKeys::leftButtonModifier;
- const auto now = juce::Time::currentTimeMillis();
- peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, at, juce::ModifierKeys (button), 1.0f, 0.0f, now);
- peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, at, juce::ModifierKeys(), 1.0f, 0.0f, now + 40);
- }
- bool space()
- {
- auto* peer = mainPeer(); // (the system sends the key to the window with the focus: the main one)
- return peer != nullptr && peer->handleKeyPress (juce::KeyPress (juce::KeyPress::spaceKey, juce::ModifierKeys(), ' '));
- }
- juce::TextEditor* firstField (juce::Component& c)
- {
- if (auto* t = dynamic_cast<juce::TextEditor*> (&c); t != nullptr && t->isShowing() && t->getWantsKeyboardFocus())
- return t;
- for (auto* child : c.getChildren())
- if (auto* t = firstField (*child))
- return t;
- return nullptr;
- }
- // the user tabs away and comes back with a click in `panel`
- void backWithClickIn (lynx::workspace::Panel panel, bool right)
- {
- auto& frame = ui->workspaceForTest().getFrame (panel);
- const auto name = juce::String (lynx::workspace::panelId (panel)) + (right ? " (right click)" : "");
- auto* peer = mainPeer();
- line (name + ": native child window=" + juce::String ((int) lynx::nativechild::isAttached (frame)));
- check (name + ": the main window has the keys before", ui->hasKeyboardFocus (true));
- peer->handleFocusLoss(); // (another app is in front: the main window lost the system focus)
- check (name + ": nothing in LYNX has the keys while it is in the background", ! focusInMain());
- // the cause: JUCE answers the system's "activate?" from the panel's own component, which takes no focus on a click
- line (name + ": JUCE's answer alone would activate the window=" + juce::String ((int) frame.getMouseClickGrabsKeyboardFocus()));
- const auto activates = lynx::nativechild::clickActivatesWindow (frame, false);
- check (name + ": a click in it activates the inactive main window", activates);
- #if JUCE_WINDOWS
- if (lynx::nativechild::isAttached (frame))
- check (name + ": its native window answers WM_MOUSEACTIVATE with MA_ACTIVATE",
- lynx::nativechild::mouseActivateAnswerForTest (frame, true) == 1 /* MA_ACTIVATE */);
- #endif
- if (activates)
- peer->handleFocusGain(); // (the system activates the main window and gives it the focus)
- click (frame, right);
- }
- void spacePlays (lynx::workspace::Panel panel, bool right)
- {
- const auto name = juce::String (lynx::workspace::panelId (panel)) + (right ? " (right click)" : "");
- check (name + ": the main window has the keys after the click", ui->hasKeyboardFocus (true));
- auto& transport = engine->getTransport();
- if (transport.playing.load())
- engine->stop();
- const auto used = space();
- check (name + ": Space starts playback", used && transport.playing.load());
- engine->stop();
- }
- void timerCallback() override
- {
- using lynx::workspace::Panel;
- auto& ws = ui->workspaceForTest();
- switch (stepIndex++)
- {
- case 0:
- line ("docking=" + juce::String ((int) lynx::nativechild::dockingEnabled()));
- ws.show (Panel::playlist);
- ws.show (Panel::pianoRoll);
- ui->grabKeyboardFocus();
- break;
- case 1: backWithClickIn (Panel::playlist, false); break;
- case 2: spacePlays (Panel::playlist, false); ui->grabKeyboardFocus(); break;
- case 3: backWithClickIn (Panel::pianoRoll, false); break;
- case 4: spacePlays (Panel::pianoRoll, false); ui->grabKeyboardFocus(); break;
- case 5: backWithClickIn (Panel::playlist, true); break;
- case 6:
- juce::PopupMenu::dismissAllActiveMenus(); // (the right click's menu)
- spacePlays (Panel::playlist, true);
- break;
- case 7:
- {
- // a text field (the Browser's search box) keeps the keys through a switch to another app and back:
- // nothing in LYNX takes them from it (no periodic grab); inside the active window the click's
- // activation answer is unchanged, and a click in the Playlist ends the typing as before (issue #9,
- // as FL ends typing in its search field)
- auto* field = firstField (*ui);
- line ("text field found=" + juce::String ((int) (field != nullptr)));
- if (field != nullptr)
- {
- auto& frame = ws.getFrame (Panel::playlist);
- field->grabKeyboardFocus();
- check ("the text field has the keys", field->hasKeyboardFocus (false));
- mainPeer()->handleFocusLoss();
- mainPeer()->handleFocusGain(); // (back with Alt+Tab, or a click that activates the window)
- check ("the text field gets the keys back with the window", field->hasKeyboardFocus (false));
- check ("active window: a click in a panel does not activate it again", ! lynx::nativechild::clickActivatesWindow (frame, true));
- click (frame, false);
- check ("a click in the Playlist ends the typing: the main window has the keys", ui->hasKeyboardFocus (true) && ! field->hasKeyboardFocus (false));
- }
- line (ok ? "result=OK" : "result=FAILED");
- stopTimer();
- done();
- break;
- }
- default:
- break;
- }
- }
- };
- auto* test = new FocusTest();
- test->reportPath = reportPath;
- startFocusTestWindow (*test);
- test->startTimer (600);
- }
- // --simplekeytest (round 190fc, 0.1.27 RC H2): in the Simple layout Space often did nothing after a click in the
- // window (the dock, a track header, the grid, the Lyrics button) or after a demo opened from Welcome › Start from. The
- // main window in the Simple layout; each step clicks as the system would (through the native window under the point)
- // and presses Space where the system sends it (the native window of the component with the focus): playback must
- // start, except while a text field the user clicked into has the keys (it types). Shows a window (Windows: GUI lock).
- void runSimpleKeyTest (const juce::String& reportPath)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- struct KeyTest final : juce::Timer
- {
- juce::String reportPath, report;
- bool ok = true;
- int stepIndex = 0, instrumentTrack = 0;
- std::unique_ptr<lynx::AudioEngine> engine;
- lynx::MainComponent* ui = nullptr;
- std::unique_ptr<juce::DocumentWindow> main;
- 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;
- }
- static juce::String describe (juce::Component* c)
- {
- if (c == nullptr)
- return "nothing";
- juce::String path;
- for (auto* p = c; p != nullptr && path.length() < 160; p = p->getParentComponent())
- {
- auto name = p->getComponentID().isNotEmpty() ? p->getComponentID() : p->getName();
- if (name.isEmpty())
- name = juce::String (typeid (*p).name()).fromLastOccurrenceOf ("::", false, false).substring (0, 28);
- path << (path.isEmpty() ? "" : " < ") << name;
- }
- return path;
- }
- // the first showing component with this ID in the main window or a native child window of it
- juce::Component* find (const juce::String& id)
- {
- std::function<juce::Component* (juce::Component&)> in = [&] (juce::Component& root) -> juce::Component* {
- if (root.getComponentID() == id && root.isShowing())
- return &root;
- for (auto* c : root.getChildren())
- if (auto* f = in (*c))
- return f;
- return nullptr;
- };
- if (auto* f = in (*main))
- return f;
- if (auto* peer = main->getPeer())
- for (auto* attached : lynx::nativechild::attachedChildren (peer->getNativeHandle()))
- if (auto* f = in (*attached))
- return f;
- return nullptr;
- }
- // a click (press and release) at `local` in `c`, through the native window it is in
- juce::String lastHit;
- void click (juce::Component& c, juce::Point<int> local)
- {
- auto* peer = c.getPeer();
- if (peer == nullptr)
- return;
- const auto at = peer->getComponent().getLocalPoint (&c, local.toFloat());
- lastHit = describe (peer->getComponent().getComponentAt (at.roundToInt()));
- line (" click at " + local.toString() + " in " + describe (&c).upToFirstOccurrenceOf (" < ", false, false) + " -> " + lastHit);
- const auto now = juce::Time::currentTimeMillis();
- peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, at, juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier), 1.0f, 0.0f, now);
- peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, at, juce::ModifierKeys(), 1.0f, 0.0f, now + 40);
- }
- void click (juce::Component& c) { click (c, c.getLocalBounds().getCentre()); }
- // Space where the system sends it: the native window of the focused component (else the main one)
- bool space()
- {
- // Windows: posted to the window with the system's focus, as a real key goes (the system's own routing)
- if (lynx::nativechild::pressSpaceForTest (main->getWindowHandle()))
- return true;
- auto* focused = juce::Component::getCurrentlyFocusedComponent();
- auto* peer = focused != nullptr && focused->getPeer() != nullptr ? focused->getPeer() : main->getPeer();
- return peer != nullptr && peer->handleKeyPress (juce::KeyPress (juce::KeyPress::spaceKey, juce::ModifierKeys(), ' '));
- }
- void spacePlays (const juce::String& after)
- {
- line (" keys at: " + describe (juce::Component::getCurrentlyFocusedComponent()));
- auto& transport = engine->getTransport();
- if (transport.playing.load())
- engine->stop();
- space();
- check ("Space plays after " + after, transport.playing.load());
- engine->stop();
- }
- void timerCallback() override
- {
- auto* simple = ui->getSimpleWorkflowForSnapshot();
- auto& playlist = ui->getPlaylistForSnapshot();
- switch (stepIndex++)
- {
- case 0:
- ui->setLayoutStyle (lynx::layoutstyle::Style::simple);
- ui->grabKeyboardFocus();
- break;
- case 1:
- check ("the Simple workflow is up", simple != nullptr);
- if (simple == nullptr)
- return finish();
- spacePlays ("the layout came up");
- simple->showWelcome();
- break;
- case 2:
- if (auto* demo = find ("tour.welcome.demo"))
- click (*demo); // Welcome › Open a demo song: the Start from list
- else
- check ("Welcome > Open a demo song found", false);
- break;
- case 3:
- {
- if (! simple->isStartFromShowing()) // (X11: a child window just mapped may miss the first click)
- if (auto* demo = find ("tour.welcome.demo"))
- {
- line (" the first click was not taken: once more");
- click (*demo);
- }
- check ("Start from is up", simple->isStartFromShowing());
- if (auto* start = dynamic_cast<lynx::StartFromPanel*> (simple->startFromForSnapshot()))
- check ("a demo song opens from it", start->openForSnapshot (1));
- break;
- }
- case 4:
- check ("Start from closed with the demo open", ! simple->isStartFromShowing() && ! engine->getSong().playlist.empty());
- spacePlays ("a demo opened from Welcome > Start from");
- instrumentTrack = [] (const lynx::Song& song) { // the first Instrument track (the dock's Keyboard and Editor tabs are for it)
- for (int t = 0; t < (int) song.playlistTracks.size(); ++t)
- if (lynx::simpletracks::kindOf (song, t) == lynx::simpletracks::Kind::instrument)
- return t;
- return 0;
- } (engine->getSong());
- line ("instrument track: " + juce::String (instrumentTrack));
- playlist.selectTrack (instrumentTrack);
- simple->trackSelected (instrumentTrack);
- break;
- case 5:
- if (auto* dock = simple->dockForSnapshot(); dock != nullptr && dock->isShowing())
- {
- click (*dock, { dock->getWidth() - 6, dock->getHeight() - 6 }); // (its empty corner)
- spacePlays ("a click in the dock");
- }
- else
- check ("the dock shows", false);
- break;
- case 6:
- if (auto* tab = find ("simple.dock.keyboard"))
- {
- click (*tab);
- spacePlays ("a click on a dock tab (Keyboard)");
- }
- if (auto* tab = find ("simple.dock.editor"))
- {
- click (*tab);
- spacePlays ("a click on a dock tab (Editor)");
- }
- break;
- case 7:
- if (auto* lyrics = find ("simple.lyrics"))
- {
- click (*lyrics);
- spacePlays ("a click on the Lyrics button");
- }
- else
- check ("the Lyrics button found", false);
- break;
- case 8:
- {
- const auto lane = playlist.trackRowForSnapshot (instrumentTrack).withTrimmedLeft (playlist.headerWidth);
- click (playlist, { juce::jmax (4, playlist.headerWidth / 2), lane.getCentreY() });
- spacePlays ("a click on a track header");
- click (playlist, lane.getCentre() + juce::Point<int> (40, 0));
- spacePlays ("a click in the Playlist grid");
- break;
- }
- case 9:
- {
- // a text field the user clicks into keeps its typing keys; a click outside gives Space back
- // a dock knob clicked keeps the arrow keys, and Space still plays from it
- for (auto tab : { lynx::SimpleDock::Tab::effects, lynx::SimpleDock::Tab::instrument })
- {
- juce::Component* knob = nullptr;
- std::function<void (juce::Component&)> seek = [&] (juce::Component& c) {
- if (knob == nullptr && c.isShowing() && (bool) c.getProperties().getWithDefault ("lynxClickKeepsKeys", false))
- knob = &c;
- for (auto* child : c.getChildren())
- seek (*child);
- };
- if (auto* dock = simple->dockForSnapshot())
- {
- dock->setTab (tab);
- seek (*dock);
- }
- if (knob != nullptr)
- {
- click (*knob);
- spacePlays ("a click on a dock knob");
- break;
- }
- }
- if (auto* dock = simple->dockForSnapshot())
- dock->setTab (lynx::SimpleDock::Tab::instrument);
- juce::TextEditor* field = nullptr;
- std::function<void (juce::Component&)> look = [&] (juce::Component& c) {
- if (auto* t = dynamic_cast<juce::TextEditor*> (&c); t != nullptr && t->isShowing() && field == nullptr)
- field = t;
- for (auto* child : c.getChildren())
- look (*child);
- };
- if (auto* dock = simple->dockForSnapshot())
- look (*dock);
- line ("text field in the dock found=" + juce::String ((int) (field != nullptr)));
- if (field != nullptr)
- {
- click (*field);
- const auto before = field->getText();
- space();
- check ("Space types into the text field the user clicked", field->getText() != before && ! engine->getTransport().playing.load());
- engine->stop();
- field->clear();
- const auto lane = playlist.trackRowForSnapshot (instrumentTrack).withTrimmedLeft (playlist.headerWidth);
- click (playlist, lane.getCentre() + juce::Point<int> (60, 0));
- spacePlays ("a click in the grid after typing");
- }
- // H1: the first-song tour's card in front of the native panels, taking no keys (started on the demo
- // as it is: Help's question about a new project is a dialog)
- if (auto* tour = simple->tourForSnapshot())
- tour->start();
- break;
- }
- case 10:
- {
- auto* tour = simple->tourForSnapshot();
- auto* card = tour != nullptr ? tour->cardForSnapshot() : nullptr;
- check ("the tour runs", tour != nullptr && tour->isRunning() && card != nullptr && card->isVisible());
- if (card == nullptr)
- return finish();
- auto& frame = ui->workspaceForTest().getFrame (lynx::workspace::Panel::playlist);
- const auto native = lynx::nativechild::dockingEnabled() && lynx::nativechild::isAttached (frame);
- line ("playlist native child window=" + juce::String ((int) native) + ", tour card native child window="
- + juce::String ((int) lynx::nativechild::isAttached (*card)));
- if (native)
- {
- check ("the tour card is a native child window of the main window (not under the panels)", lynx::nativechild::isAttached (*card));
- #if JUCE_WINDOWS
- check ("the tour card is above the Playlist's native window", lynx::nativechild::isAbove (card->getWindowHandle(), frame.getWindowHandle()));
- juce::Component* layer = nullptr;
- for (auto* c : lynx::nativechild::attachedChildren (main->getPeer()->getNativeHandle()))
- if (c != nullptr && c->getComponentID() == "tour.layer")
- layer = c;
- check ("the ring's layer is above the Playlist too", layer != nullptr && lynx::nativechild::isAbove (layer->getWindowHandle(), frame.getWindowHandle()));
- check ("the ring's layer lets clicks through to the Playlist",
- layer != nullptr && lynx::nativechild::windowAt (*layer, layer->getLocalBounds().getCentre()) != layer->getWindowHandle());
- #endif
- }
- check ("the tour card took no keys", ! card->hasKeyboardFocus (true));
- spacePlays ("the tour came up");
- if (auto* next = card->findChildWithID ("tour.next"); next != nullptr && next->isShowing())
- {
- click (*next);
- check ("a click on the card took no keys", ! card->hasKeyboardFocus (true));
- spacePlays ("a click on the tour card");
- }
- finish();
- break;
- }
- default:
- break;
- }
- }
- void finish()
- {
- line (ok ? "result=OK" : "result=FAILED");
- stopTimer();
- done();
- }
- };
- auto* test = new KeyTest();
- test->reportPath = reportPath;
- startFocusTestWindow (*test);
- // Windows: kept above other apps' windows for its few seconds (JUCE takes a button-down only where the system finds
- // its window under the point, and the test clicks through LYNX's own peers, not the system's input)
- #if JUCE_WINDOWS
- test->main->setAlwaysOnTop (true); // (Linux: JUCE makes the X11 window again for it; the private X server has no other windows)
- #endif
- test->startTimer (700);
- }
- template <typename Test>
- void startFocusTestWindow (Test& t)
- {
- auto* test = &t;
- test->engine = std::make_unique<lynx::AudioEngine> (false);
- test->main = std::make_unique<juce::DocumentWindow> ("LYNX focus 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());
- test->done = [this, test] {
- setApplicationReturnValue (test->ok ? 0 : 1);
- juce::MessageManager::callAsync ([this, test] {
- lynx::setMainWindowForOwnership (nullptr);
- test->main = nullptr;
- delete test;
- quit();
- });
- };
- }
- 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.
- // Round 190fw: an instrument plugin file on channel 5 of an offline engine (Image-Line's "FL Studio VSTi", which
- // runs FL Studio inside it). Without a project: four chords at 137 BPM, rendered (notes.wav), the plugin's state
- // saved in <folder>/vstitest.lynx. With a project (one saved by LYNX with the plugin on a channel, e.g. after its
- // window was used): that project. Then: the project loaded back from the file renders the same (reload.wav) and
- // gives the same state back; the project's own notes removed, rendered at 100 and 150 BPM (tempo-100/150.wav), the
- // onsets of what the plugin plays by itself must follow the host tempo; and the outputs the plugin offers.
- void runVstiTest (const juce::String& pluginPath, const juce::String& folderPath, const juce::String& projectPath)
- {
- juce::String report;
- auto ok = true;
- const juce::File folder (folderPath);
- folder.createDirectory();
- const auto check = [&] (const juce::String& name, bool passed) {
- report << name << "=" << (passed ? "OK" : "FAILED") << "\n";
- ok = ok && passed;
- };
- struct Take
- {
- float peak = 0.0f;
- std::vector<float> left;
- };
- // renders `song` with the plugin file known to the engine's host; `wav` (in the folder) gets the audio
- const auto render = [&] (const lynx::Song& song, double seconds, const juce::String& wav, std::function<void (lynx::AudioEngine&)> after = {}) {
- Take take;
- lynx::AudioEngine engine (false);
- engine.getPluginHost().addPluginFile (juce::File (pluginPath));
- engine.setSong (song);
- const auto file = folder.getChildFile (wav);
- file.deleteFile();
- std::unique_ptr<juce::AudioFormatWriter> writer;
- if (auto stream = file.createOutputStream())
- {
- juce::WavAudioFormat format;
- writer.reset (format.createWriterFor (stream.get(), 48000.0, 2, 24, {}, 0));
- if (writer != nullptr)
- stream.release();
- }
- lynx::AudioEngine::RenderOptions o;
- o.seconds = seconds;
- o.sampleRate = 48000.0;
- o.output = writer.get();
- o.capture = [&take] (const float* l, const float*, int n) { take.left.insert (take.left.end(), l, l + n); };
- take.peak = engine.renderOffline (o);
- writer.reset();
- if (after)
- after (engine);
- return take;
- };
- // the channel that holds the plugin
- const auto pluginChannel = [&] (const lynx::Song& song) {
- for (std::size_t c = 0; c < song.channels.size(); ++c)
- if (song.channels[c].instrument == lynx::InstrumentKind::plugin
- && juce::String (song.channels[c].plugin.name).containsIgnoreCase (juce::File (pluginPath).getFileNameWithoutExtension().upToFirstOccurrenceOf (" (", false, false)))
- return (int) c;
- return -1;
- };
- lynx::Song song;
- const auto saved = folder.getChildFile ("vstitest.lynx");
- if (projectPath.isEmpty())
- {
- lynx::AudioEngine scanner (false);
- report << "plugins_in_file=" << scanner.getPluginHost().addPluginFile (juce::File (pluginPath)) << "\n";
- std::optional<juce::PluginDescription> type;
- for (const auto& t : scanner.getPluginHost().getKnownPlugins().getTypes())
- if (t.isInstrument && juce::File (t.fileOrIdentifier) == juce::File (pluginPath))
- type = t;
- check ("instrument_found", type.has_value());
- if (! type)
- {
- juce::File (folder.getChildFile ("report.txt")).replaceWithText (report + "result=FAILED\n");
- setApplicationReturnValue (1);
- quit();
- return;
- }
- report << "plugin=" << type->name << " (" << type->manufacturerName << ") outputs=" << type->numOutputChannels << "\n";
- song = lynx::Song::makeDefault();
- song.bpm = 137.0;
- auto& c = song.channels[4];
- c.instrument = lynx::InstrumentKind::plugin;
- c.plugin = {};
- c.plugin.id = type->createIdentifierString().toStdString();
- c.plugin.name = type->name.toStdString();
- c.name = type->name.toStdString();
- c.volume = 1.0f;
- for (std::size_t k = 0; k < song.channels.size(); ++k)
- song.channels[k].muted = k != 4;
- song.patterns[0].notes.clear();
- for (int beat = 0; beat < 8; ++beat) // a chord per beat, two bars
- for (int key : { 60, 64, 67 })
- song.patterns[0].notes.push_back ({ (std::int64_t) beat * lynx::ppq, lynx::ppq / 2, 4, key + (beat / 4) * 5, 0.9f });
- song.patterns[0].sortNotes();
- const auto notes = render (song, 4.0, "notes.wav", [&song] (lynx::AudioEngine& engine) {
- engine.capturePluginStates();
- song = engine.getSong();
- });
- report << "notes_peak=" << notes.peak << "\n";
- check ("notes_play", notes.peak > 0.001f && notes.peak < 10.0f);
- juce::String error;
- check ("project_saved", lynx::ProjectFile::save (song, saved, error));
- }
- else
- {
- juce::String error;
- const auto loaded = lynx::ProjectFile::load (juce::File (projectPath), error);
- check ("project_loaded", loaded.has_value());
- if (loaded)
- song = *loaded;
- juce::File (projectPath).copyFileTo (saved);
- }
- const auto channel = pluginChannel (song);
- check ("plugin_channel", channel >= 0);
- if (channel >= 0)
- {
- const auto& plugin = song.channels[(std::size_t) channel].plugin;
- juce::MemoryBlock state;
- state.fromBase64Encoding (juce::String (plugin.state));
- report << "channel=" << channel + 1 << " state_bytes=" << (int) state.getSize() << "\n";
- check ("state_saved", state.getSize() > 0);
- // the project read back from the file: the same sound, and the same state handed back
- juce::String error;
- const auto again = lynx::ProjectFile::load (saved, error);
- check ("project_reloaded", again.has_value());
- if (again)
- {
- std::string stateBack;
- const auto first = render (*again, 4.0, "reload-a.wav");
- const auto second = render (*again, 4.0, "reload-b.wav", [&] (lynx::AudioEngine& engine) {
- engine.capturePluginStates();
- stateBack = engine.getSong().channels[(std::size_t) channel].plugin.state;
- });
- // two loads of the same project: the same audio (sample for sample, or within -60 dB for a plugin
- // with free-running modulation)
- double energy = 0.0, difference = 0.0;
- const auto n = std::min (first.left.size(), second.left.size());
- for (std::size_t k = 0; k < n; ++k)
- {
- energy += (double) first.left[k] * first.left[k];
- difference += ((double) first.left[k] - second.left[k]) * ((double) first.left[k] - second.left[k]);
- }
- const auto ratioDb = energy > 0.0 ? 10.0 * std::log10 (std::max (difference, 1e-30) / energy) : 0.0;
- report << "reload_peak=" << first.peak << " reload_difference_db=" << juce::String (ratioDb, 1) << "\n";
- check ("reload_plays", first.peak > 0.001f);
- check ("reload_same_sound", energy > 0.0 && ratioDb < -60.0);
- juce::MemoryBlock back;
- back.fromBase64Encoding (juce::String (stateBack));
- report << "state_back_bytes=" << (int) back.getSize() << " identical=" << (int) (back == state) << "\n";
- check ("state_handed_back", back.getSize() > 0);
- }
- // the host tempo: what the plugin plays by itself (FL Studio's own patterns inside FL Studio VSTi) at two
- // tempos, without the project's notes
- auto self = song;
- for (std::size_t k = 0; k < self.channels.size(); ++k)
- self.channels[k].muted = (int) k != channel;
- for (auto& pattern : self.patterns)
- pattern.notes.erase (std::remove_if (pattern.notes.begin(), pattern.notes.end(), [channel] (const lynx::Note& n) { return n.channel == channel; }),
- pattern.notes.end());
- const auto onsets = [] (const std::vector<float>& x) {
- // envelope rises over a threshold (10 ms hold-off of 60 ms): the times in seconds
- std::vector<double> at;
- float peak = 0.0f;
- for (const auto v : x)
- peak = std::max (peak, std::abs (v));
- const auto threshold = peak * 0.3f;
- auto quietFor = 1 << 30;
- for (std::size_t k = 0; k < x.size(); ++k)
- {
- const auto loud = std::abs (x[k]) >= threshold;
- if (loud && quietFor >= 48000 * 60 / 1000)
- at.push_back ((double) k / 48000.0);
- quietFor = loud ? 0 : quietFor + 1;
- }
- return at;
- };
- const auto medianGap = [] (const std::vector<double>& at) {
- std::vector<double> gaps;
- for (std::size_t k = 1; k < at.size(); ++k)
- gaps.push_back (at[k] - at[k - 1]);
- if (gaps.empty())
- return 0.0;
- std::sort (gaps.begin(), gaps.end());
- return gaps[gaps.size() / 2];
- };
- self.bpm = 100.0;
- const auto slow = render (self, 6.0, "tempo-100.wav");
- self.bpm = 150.0;
- const auto fast = render (self, 6.0, "tempo-150.wav");
- const auto gapSlow = medianGap (onsets (slow.left)), gapFast = medianGap (onsets (fast.left));
- report << "self_peak_100=" << slow.peak << " self_peak_150=" << fast.peak << " onsets_100=" << (int) onsets (slow.left).size()
- << " onsets_150=" << (int) onsets (fast.left).size() << " gap_100=" << juce::String (gapSlow, 4) << " gap_150="
- << juce::String (gapFast, 4) << "\n";
- if (slow.peak > 0.001f && gapFast > 0.0)
- {
- report << "tempo_ratio=" << juce::String (gapSlow / gapFast, 3) << " (expected 1.5)\n";
- check ("follows_host_tempo", std::abs (gapSlow / gapFast - 1.5) < 0.05);
- }
- else
- report << "tempo: the plugin plays nothing by itself in this project\n";
- // the outputs it offers (FL Studio VSTi (Multi): FL's mixer tracks as separate outputs)
- lynx::AudioEngine engine (false);
- engine.getPluginHost().addPluginFile (juce::File (pluginPath));
- engine.setSong (song);
- engine.renderOffline (0.2, 48000.0);
- if (auto instrument = std::dynamic_pointer_cast<lynx::PluginInstrument> (engine.getChannelInstrument (channel)))
- {
- report << "outputs=" << (int) instrument->outputs().size() << ":";
- for (const auto& o : instrument->outputs())
- report << " [" << o.name << "]";
- report << "\n";
- check ("outputs_listed", ! instrument->outputs().empty());
- }
- else
- check ("instrument_loaded", false);
- }
- report << "plugin_crashes=" << lynx::pluginCrashCount() << "\n";
- report << "result=" << (ok ? "OK" : "FAILED") << "\n";
- folder.getChildFile ("report.txt").replaceWithText (report);
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- }
- 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();
- }
- // Round 190gg (B4): --crashguardtest plugin report.txt thread | ui. "thread": the plugin's own thread faults in its 40th
- // block (Linux / macOS): that thread is parked, LYNX switches the plugin off (as the main window's timer does) and goes
- // on; the other inserts play; Reload brings it back. "ui": the calls the UI makes into a plugin, under the guard: a
- // preset load that crashes (the Plugin window's preset menu path) and making the editor (PluginWindows::open, the CLAP
- // test plugin's "editor-create": a display is needed, e.g. Xvfb); each switches the plugin off, LYNX goes on.
- void runCrashGuardThreadOrUiTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& mode)
- {
- juce::String report;
- bool ok = true;
- const auto expect = [&] (const char* name, bool value) {
- report << name << "=" << (value ? 1 : 0) << "\n";
- ok = ok && value;
- };
- const auto setEnv = [] (const char* name, const char* value) {
- #if JUCE_WINDOWS
- _putenv_s (name, value);
- #else
- setenv (name, value, 1);
- #endif
- };
- const auto render = [] (lynx::AudioEngine& engine, double seconds, float* peak) {
- lynx::AudioEngine::RenderOptions o;
- o.seconds = seconds;
- o.sampleRate = 48000.0;
- o.pluginWarmUp = false;
- if (peak != nullptr)
- o.capture = [peak] (const float* l, const float* r, int n) {
- for (int k = 0; k < n; ++k)
- *peak = std::max (*peak, std::max (std::abs (l[k]), std::abs (r[k])));
- };
- return engine.renderOffline (o);
- };
- report << "mode=" << mode << "\nthread_guard=" << (lynx::crashguard::pluginThreadFaultsCaught() ? "on" : "off") << "\n";
- setEnv ("LYNX_TEST_CRASH", mode == "thread" ? "thread" : "");
- setEnv ("LYNX_TEST_CRASH_AFTER", "40");
- const auto tmp = juce::File::getSpecialLocation (juce::File::tempDirectory)
- .getChildFile ("lynx-crashguardtest-" + juce::String::toHexString (juce::Random::getSystemRandom().nextInt64()));
- tmp.createDirectory();
- {
- lynx::AudioEngine offline (false);
- auto& host = offline.getPluginHost();
- host.addPluginFile (juce::File (pluginPath));
- juce::PluginDescription effect;
- bool found = false;
- for (const auto& type : host.getKnownPlugins().getTypes())
- if (! found && ! type.isInstrument && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
- {
- effect = type;
- found = true;
- }
- expect ("plugin_found", found);
- auto song = lynx::Song::makeDefault();
- lynx::EffectSlot slot;
- slot.kind = lynx::EffectKind::plugin;
- slot.plugin.id = effect.createIdentifierString().toStdString();
- slot.plugin.name = effect.name.toStdString();
- song.mixer[1].effects.push_back (slot);
- offline.setSong (song);
- const lynx::AudioEngine::HostedSlot where { -1, 1, 0 };
- render (offline, 0.05, nullptr);
- offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.85f; }, false);
- render (offline, 0.05, nullptr);
- auto* first = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (1, 0).get());
- expect ("plugin_loaded", first != nullptr);
- const auto crashesBefore = lynx::pluginCrashCount();
- if (mode == "thread")
- {
- const auto faultsBefore = lynx::crashguard::pluginThreadFaultCount();
- float peak = 0.0f;
- render (offline, 3.0, &peak); // (the plugin starts its faulting thread in its 40th block)
- for (int i = 0; i < 200 && lynx::crashguard::pluginThreadFaultCount() == faultsBefore; ++i)
- juce::Thread::sleep (10);
- const auto faults = lynx::crashguard::pluginThreadFaults();
- expect ("thread_fault_parked", lynx::crashguard::pluginThreadFaultCount() == faultsBefore + 1 && ! faults.empty());
- if (! faults.empty())
- report << "thread_fault=" << faults.back().where << " (" << lynx::crashguard::describe (faults.back().code) << ")\n";
- expect ("not_yet_counted_as_a_call_crash", lynx::pluginCrashCount() == crashesBefore);
- // what the main window's timer does
- // (every instance of that module: the engine may hold more than the slot's, e.g. the offline render's)
- if (first != nullptr)
- report << "slot_file=" << first->getInstance().getPluginDescription().fileOrIdentifier << "\n";
- const auto switched = lynx::switchOffPluginsOfThreadFaults();
- report << "switched_off=" << switched << "\n";
- expect ("plugin_switched_off", switched >= 1 && first != nullptr && first->hasCrashed() && lynx::pluginCrashCount() == crashesBefore + switched);
- expect ("only_once", lynx::switchOffPluginsOfThreadFaults() == 0);
- const auto down = offline.downHostedPlugins();
- expect ("slot_down", down.size() == 1 && down[0] == where);
- float after = 0.0f;
- render (offline, 1.0, &after);
- report << "peak_after=" << after << "\n";
- expect ("audio_after_fault", after > 0.01f);
- offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.0f; }, false);
- float others = 0.0f;
- render (offline, 1.0, &others);
- expect ("other_inserts_play", others > 0.01f);
- offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.85f; }, false);
- const auto running = offline.reloadHostedPlugins (down);
- auto* again = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (1, 0).get());
- float reloaded = 0.0f;
- render (offline, 1.0, &reloaded);
- expect ("reloaded_plays", running == 1 && again != nullptr && again != first && ! again->hasCrashed() && reloaded > 0.01f);
- }
- else
- {
- // a preset that crashes the plugin (the preset menu's load), saved first from the running plugin
- auto& instance = first->getInstance();
- const auto preset = tmp.getChildFile ("crash.lynxpreset");
- juce::String error;
- expect ("preset_saved", lynx::pluginpresetui::save (instance, preset, "crash", error) && preset.existsAsFile());
- setEnv ("LYNX_TEST_CRASH", "state");
- const auto loaded = lynx::pluginpresetui::load (instance, preset, error);
- setEnv ("LYNX_TEST_CRASH", "");
- report << "preset_error=" << error << "\n";
- expect ("preset_crash_caught", ! loaded && lynx::pluginCrashCount() == crashesBefore + 1 && first->hasCrashed());
- expect ("preset_plugin_down", offline.hostedPluginDown (where) && lynx::pluginInstanceDown (instance));
- expect ("not_called_again", ! lynx::callPluginFromUi (instance, "test", [] {}) && lynx::pluginCrashCount() == crashesBefore + 1);
- float after = 0.0f;
- render (offline, 1.0, &after);
- expect ("audio_after_preset_crash", after > 0.01f);
- // Reload; then its editor crashes as it is made (PluginWindows::open): no window, the plugin is down
- setEnv ("LYNX_TEST_CRASH", "editor-create");
- const auto running = offline.reloadHostedPlugins (offline.downHostedPlugins());
- auto held = offline.getEffect (1, 0);
- auto* again = dynamic_cast<lynx::PluginEffect*> (held.get());
- expect ("reloaded", running == 1 && again != nullptr && again != first && ! again->hasCrashed());
- if (again != nullptr)
- {
- lynx::PluginWindows::open (held, again->getInstance(), "crash test", {});
- expect ("editor_crash_caught", lynx::pluginCrashCount() == crashesBefore + 2 && again->hasCrashed());
- expect ("no_window", ! lynx::PluginWindows::isOpen (again->getInstance()));
- float editorAfter = 0.0f;
- render (offline, 1.0, &editorAfter);
- expect ("audio_after_editor_crash", editorAfter > 0.01f);
- }
- setEnv ("LYNX_TEST_CRASH", "");
- }
- }
- setEnv ("LYNX_TEST_CRASH", "");
- // LYNX's own faults (also on its own threads) stay crashes (child processes; the selftest runs the same)
- const auto own = faultReportSelfTest();
- report << "own_faults=" << own << "\n";
- ok = ok && ! own.startsWith ("ERROR");
- for (const auto& c : lynx::pluginCrashes())
- report << " crashed: " << c.plugin << " (" << lynx::crashguard::describe (c.code) << ")\n";
- tmp.deleteRecursively();
- report << "result=" << (ok ? "OK" : "FAILED") << "\n";
- juce::File (reportPath).replaceWithText (report);
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- }
- // LYNX --crashguardtest plugin report.txt [process|memcpy] (round 190dt): see the dispatch in initialise().
- void runCrashGuardTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& mode)
- {
- if (mode == "thread" || mode == "ui")
- {
- runCrashGuardThreadOrUiTest (pluginPath, reportPath, mode);
- return;
- }
- juce::String report;
- bool ok = true;
- const auto expect = [&] (const char* name, bool value) {
- report << name << "=" << (value ? 1 : 0) << "\n";
- ok = ok && value;
- };
- const auto setEnv = [] (const char* name, const char* value) {
- #if JUCE_WINDOWS
- _putenv_s (name, value);
- #else
- setenv (name, value, 1);
- #endif
- };
- // renders without the plugin warm-up (its silent blocks would count towards the crash)
- const auto render = [] (lynx::AudioEngine& engine, double seconds, const std::function<void (const float*, const float*, int)>& capture) {
- lynx::AudioEngine::RenderOptions o;
- o.seconds = seconds;
- o.sampleRate = 48000.0;
- o.pluginWarmUp = false;
- o.capture = capture;
- return engine.renderOffline (o);
- };
- const auto peakOf = [] (float& peak) {
- return [&peak] (const float* l, const float* r, int n) {
- for (int k = 0; k < n; ++k)
- peak = std::max (peak, std::max (std::abs (l[k]), std::abs (r[k])));
- };
- };
- report << "guard=" << (lynx::crashguard::pluginFaultsCaught() ? "on" : "off") << "\nmode=" << mode << "\n";
- setEnv ("LYNX_TEST_CRASH", mode == "memcpy" ? "memcpy" : "process");
- setEnv ("LYNX_TEST_CRASH_AFTER", "40");
- const auto tmp = juce::File::getSpecialLocation (juce::File::tempDirectory)
- .getChildFile ("lynx-crashguardtest-" + juce::String::toHexString (juce::Random::getSystemRandom().nextInt64()));
- tmp.createDirectory();
- std::optional<lynx::Song> saved;
- std::string savedState;
- {
- lynx::AudioEngine offline (false);
- auto& host = offline.getPluginHost();
- host.addPluginFile (juce::File (pluginPath));
- juce::PluginDescription effect;
- bool found = false;
- for (const auto& type : host.getKnownPlugins().getTypes())
- if (! found && ! type.isInstrument && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
- {
- effect = type;
- found = true;
- }
- expect ("plugin_found", found);
- // the plugin on insert 1 (the kick's); the clap and the hat play on inserts 2 and 3
- auto song = lynx::Song::makeDefault();
- lynx::EffectSlot slot;
- slot.kind = lynx::EffectKind::plugin;
- slot.plugin.id = effect.createIdentifierString().toStdString();
- slot.plugin.name = effect.name.toStdString();
- song.mixer[1].effects.push_back (slot);
- offline.setSong (song);
- const lynx::AudioEngine::HostedSlot where { -1, 1, 0 };
- // the rack is published at the engine's rate and an offline render runs at its own (48 kHz) without publishing:
- // one edit after a first render puts the rack (and the plugin) at the render's rate, so later edits keep it
- render (offline, 0.05, {}); // (a few blocks, far from the 40th)
- offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.85f; }, false);
- render (offline, 0.05, {});
- auto* first = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (1, 0).get());
- expect ("plugin_loaded", first != nullptr);
- offline.capturePluginStates();
- savedState = offline.getSong().mixer[1].effects[0].plugin.state;
- expect ("state_captured", ! savedState.empty());
- // the crash: 3 s, the plugin faults in its 40th block
- const auto crashesBefore = lynx::pluginCrashCount();
- juce::int64 position = 0, crashAt = -1;
- float peakAfter = 0.0f;
- const auto afterPeak = peakOf (peakAfter);
- const auto peak = render (offline, 3.0, [&] (const float* l, const float* r, int n) {
- if (crashAt < 0 && lynx::pluginCrashCount() != crashesBefore)
- crashAt = position;
- else if (crashAt >= 0)
- afterPeak (l, r, n);
- position += n;
- });
- report << "peak=" << peak << "\ncrash_at_sample=" << crashAt << "\npeak_after_crash=" << peakAfter << "\n";
- const auto crashes = lynx::pluginCrashes();
- expect ("crash_caught", lynx::pluginCrashCount() == crashesBefore + 1 && ! crashes.empty() && ! crashes.back().onLoad);
- if (! crashes.empty())
- report << "crash=" << crashes.back().plugin << " (" << lynx::crashguard::describe (crashes.back().code) << ")\n";
- expect ("slot_marked_crashed", first != nullptr && offline.getEffect (1, 0).get() == first && first->hasCrashed());
- const auto down = offline.downHostedPlugins();
- expect ("slot_down", down.size() == 1 && down[0] == where);
- expect ("audio_after_crash", crashAt >= 0 && peakAfter > 0.01f);
- // the other inserts: with the kick (through the crashed slot) silent, the clap and the hat still play
- offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.0f; }, false);
- float othersPeak = 0.0f;
- render (offline, 1.0, peakOf (othersPeak));
- report << "other_inserts_peak=" << othersPeak << "\n";
- expect ("other_inserts_play", othersPeak > 0.01f);
- expect ("nothing_reloads_by_itself", offline.hostedPluginDown (where) && offline.getEffect (1, 0).get() == first);
- offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.85f; }, false);
- // the project saves with the settings the plugin had before it crashed, and opens again
- offline.capturePluginStates();
- expect ("state_kept", offline.getSong().mixer[1].effects[0].plugin.state == savedState);
- const auto file = tmp.getChildFile ("crashed.lynx");
- juce::String error;
- expect ("project_saved", lynx::ProjectFile::save (offline.getSong(), file, error) && file.existsAsFile());
- saved = lynx::ProjectFile::load (file, error);
- expect ("project_reopens", saved.has_value() && saved->mixer.size() > 1 && saved->mixer[1].effects.size() == 1
- && saved->mixer[1].effects[0].plugin.state == savedState);
- // Reload (the prompt's button, round 190ao): a new instance; the module's block count is past 40 now
- const auto running = offline.reloadHostedPlugins (down);
- auto* again = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (1, 0).get());
- expect ("reloaded", running == 1 && again != nullptr && again != first && ! again->hasCrashed());
- float reloadedPeak = 0.0f;
- render (offline, 1.0, peakOf (reloadedPeak));
- report << "reloaded_peak=" << reloadedPeak << "\n";
- expect ("reloaded_plays", reloadedPeak > 0.01f && lynx::pluginCrashCount() == crashesBefore + 1 && again != nullptr && ! again->hasCrashed());
- }
- // the saved project opens again with the plugin crashing on its saved settings: left out, the rest plays, the
- // settings stay in the project
- setEnv ("LYNX_TEST_CRASH", "state");
- if (saved.has_value())
- {
- lynx::AudioEngine reopened (false);
- reopened.getPluginHost().addPluginFile (juce::File (pluginPath));
- const auto before = lynx::pluginCrashCount();
- reopened.setSong (*saved);
- float reopenedPeak = 0.0f;
- render (reopened, 1.0, peakOf (reopenedPeak));
- const auto crashes = lynx::pluginCrashes();
- report << "reopened_peak=" << reopenedPeak << "\n";
- if (reopened.getPluginHost().getLoadFailures().size() > 0)
- report << "load_failures=" << reopened.getPluginHost().getLoadFailures().joinIntoString (" | ") << "\n";
- expect ("state_crash_caught", lynx::pluginCrashCount() == before + 1 && ! crashes.empty() && crashes.back().onLoad);
- expect ("state_crash_left_out", dynamic_cast<lynx::PluginEffect*> (reopened.getEffect (1, 0).get()) == nullptr);
- expect ("state_crash_project_plays", reopenedPeak > 0.01f);
- reopened.capturePluginStates();
- expect ("state_crash_settings_kept", reopened.getSong().mixer[1].effects.size() == 1
- && reopened.getSong().mixer[1].effects[0].plugin.state == savedState);
- }
- setEnv ("LYNX_TEST_CRASH", "");
- // LYNX's own faults inside a guarded call stay crashes (child processes; the selftest runs the same)
- const auto own = faultReportSelfTest();
- report << "own_faults=" << own << "\n";
- ok = ok && ! own.startsWith ("ERROR");
- report << "plugin_crashes=" << lynx::pluginCrashCount() << "\n";
- for (const auto& c : lynx::pluginCrashes())
- report << " crashed: " << c.plugin << " (" << lynx::crashguard::describe (c.code) << (c.onLoad ? ", loading its state" : "") << ")\n";
- tmp.deleteRecursively();
- report << "result=" << (ok ? "OK" : "FAILED") << "\n";
- juce::File (reportPath).replaceWithText (report);
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- }
- // LYNX.exe --mpetest "LYNX Test MPE.clap" report.txt (tools/testplugin/lynx_test_mpe.c, issue #108): a hosted CLAP
- // instrument with the wrapper's MPE switch on gets each note on its own member channel, its fine pitch / Mod X /
- // Mod Y as tuning / brightness / pressure note expressions before the note on, and a sounding note's expression
- // on that note's channel alone. The plugin writes down what it received; no window, no audio device.
- void runMpeTest (const juce::String& pluginPath, const juce::String& reportPath)
- {
- const auto log = juce::File (reportPath).getSiblingFile (juce::File (reportPath).getFileNameWithoutExtension() + "-plugin.txt");
- log.deleteFile();
- #if JUCE_WINDOWS
- _putenv_s ("LYNX_TEST_MPE_REPORT", log.getFullPathName().toRawUTF8());
- #else
- setenv ("LYNX_TEST_MPE_REPORT", log.getFullPathName().toRawUTF8(), 1);
- #endif
- juce::String report;
- auto failures = 0;
- {
- lynx::AudioEngine engine (false);
- auto& host = engine.getPluginHost();
- 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;
- lynx::PluginRef ref;
- if (clap)
- {
- ref.id = clap->createIdentifierString().toStdString();
- ref.name = clap->name.toStdString();
- }
- ref.mpe = true;
- juce::String error;
- auto instrument = clap ? host.makeInstrument (ref, 48000.0, &error) : nullptr;
- report << "instrument_loaded=" << (instrument != nullptr ? "yes" : "no") << (error.isNotEmpty() ? " (" + error + ")" : juce::String()) << "\n";
- if (instrument != nullptr)
- {
- std::vector<float> l (256), r (256);
- auto block = [&] { instrument->render (l.data(), r.data(), 256, 1.0f, 1.0f); };
- block(); // (the zone's setup)
- instrument->setNextNoteFinePitch (30.0f); // +30 cents
- instrument->setNextNoteModulation (0.75f, 1.0f); // timbre 0.75, full pressure
- instrument->noteOn (60, 0.8f);
- instrument->noteOn (64, 0.5f); // a second note: its own channel, centre values
- block();
- instrument->noteExpression (60, (int) lynx::vfx::Prop::pitch, 200.0f, 0.0f);
- instrument->noteExpression (64, (int) lynx::vfx::Prop::modX, 0.25f, 0.0f);
- instrument->noteExpression (60, (int) lynx::vfx::Prop::modY, 0.75f, 0.0f);
- block();
- instrument->noteOff (60);
- instrument->noteOff (64);
- block();
- }
- else
- ++failures;
- } // (the plugin writes its log as it is destroyed)
- struct Line
- {
- juce::String kind;
- int a = 0, b = 0, c = 0, d = 0;
- };
- std::vector<Line> lines;
- for (const auto& text : juce::StringArray::fromLines (log.loadFileAsString()))
- {
- const auto t = juce::StringArray::fromTokens (text, " ", "");
- if (t.size() >= 3)
- lines.push_back ({ t[0], t[1].getIntValue(), t[2].getIntValue(), t.size() > 3 ? t[3].getIntValue() : 0, t.size() > 4 ? t[4].getIntValue() : 0 });
- }
- report << "plugin_events=" << (int) lines.size() << "\n";
- // the first line at or after `from` that matches (−1 = none); `value` within `tolerance` (thousandths)
- auto find = [&lines] (const juce::String& kind, int a, int b, int value, int tolerance, int from = 0) {
- for (auto i = (std::size_t) from; i < lines.size(); ++i)
- {
- const auto& x = lines[i];
- const auto v = kind == "expr" ? x.d : x.c;
- if (x.kind == kind && x.a == a && x.b == b && std::abs (v - value) <= tolerance)
- return (int) i;
- }
- return -1;
- };
- auto check = [&] (const char* what, bool ok) {
- report << what << "=" << (ok ? "ok" : "FAILED") << "\n";
- failures += ok ? 0 : 1;
- };
- // (CLAP expression ids: 2 tuning in semitones, 5 brightness, 6 pressure; channels 0-based: the first member = 1)
- const auto on60 = find ("on", 1, 60, 800, 5), on64 = find ("on", 2, 64, 500, 5);
- check ("zone_setup_sent", find ("midi", 176, 6, 15, 0) >= 0 && find ("midi", 177, 6, 48, 0) >= 0);
- check ("notes_on_their_own_channels", on60 >= 0 && on64 > on60);
- const auto tune = find ("expr", 2, 1, 300, 3), bright = find ("expr", 5, 1, 756, 4), press = find ("expr", 6, 1, 1000, 1);
- check ("expression_before_the_note_on", tune >= 0 && bright >= 0 && press >= 0 && tune < on60 && bright < on60 && press < on60);
- check ("second_note_starts_centred", find ("expr", 2, 2, 0, 1) >= 0 && find ("expr", 5, 2, 504, 4) >= 0 && find ("expr", 6, 2, 0, 1) >= 0);
- const auto later = std::max (on60, on64) + 1;
- check ("sounding_note_expression", later > 0 && find ("expr", 2, 1, 2000, 3, later) >= 0 && find ("expr", 5, 2, 252, 4, later) >= 0
- && find ("expr", 6, 1, 504, 4, later) >= 0);
- check ("other_note_untouched", later > 0 && find ("expr", 2, 2, 2000, 3, later) < 0 && find ("expr", 6, 2, 504, 4, later) < 0);
- check ("notes_off_on_their_channels", find ("off", 1, 60, 0, 100000) >= 0 && find ("off", 2, 64, 0, 100000) >= 0);
- auto expressionAsMidi = false; // (a CLAP-dialect plugin gets no raw bend / pressure / CC 74 on a member channel)
- for (const auto& x : lines)
- if (x.kind == "midi" && (x.a & 0x0f) != 0 && ((x.a & 0xf0) == 0xe0 || (x.a & 0xf0) == 0xd0 || ((x.a & 0xf0) == 0xb0 && x.b == 74)))
- expressionAsMidi = true;
- check ("no_duplicate_midi_expression", ! expressionAsMidi);
- report << "--- plugin log ---\n" << log.loadFileAsString() << "result=" << (failures == 0 ? "OK" : "FAILED") << "\n";
- juce::File (reportPath).replaceWithText (report);
- setApplicationReturnValue (failures == 0 ? 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] () mutable {
- 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)
- // The engine has replaced this instance (made for 48 kHz) by then, so this is its last reference: it is
- // deleted here, on the export's thread, and its deactivate / destroy go to the message thread, which this
- // waits for. That has to happen before `done`: once the message thread sees it, it blocks in join() until
- // this thread ends, and an instance deleted after that waited 10 s for it and then deactivated the plugin
- // right here, off the main thread (the plugin aborts: about 1 run in 40 under load, round 190au).
- effect.reset();
- 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 --vst3noteidtest "LYNX Test Synth.vst3" report.txt (round 190fg, cmake/LynxPatchJuce.cmake fix 26): the VST3
- // test synth (tools/testplugin/lynx_test_synth_vst3.cpp: voices kept by noteId, its log the ids it got) plays two
- // overlapping pairs of one key on one channel: FIFO (A 0-4, B 2-6 beats, key 60) and LIFO (C 8-14, D 10-12, key 64).
- // Each note off must carry its own note on's id (FL: each note ends its own voice, round 190ej): the inner note D's
- // end ends D. A second render with the tag hook off shows fix 14 alone (the oldest id: D's end carries C's id).
- void runVst3NoteIdTest (const juce::String& pluginPath, const juce::String& reportPath)
- {
- juce::String report;
- bool ok = false;
- const auto logBase = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-noteid-" + juce::String (juce::Time::currentTimeMillis()));
- // (read by each new instance)
- #if JUCE_WINDOWS
- _putenv_s ("LYNX_TEST_SYNTH_LOG", logBase.getFullPathName().toRawUTF8());
- #else
- setenv ("LYNX_TEST_SYNTH_LOG", logBase.getFullPathName().toRawUTF8(), 1);
- #endif
- struct E
- {
- bool on = false;
- int key = 0, id = -1;
- };
- // (the lines each render added: a running instance keeps its log file open, so the files stay until the end)
- std::map<juce::String, int> linesRead;
- const auto readLog = [&logBase, &linesRead] {
- std::vector<E> events;
- for (const auto& f : logBase.getParentDirectory().findChildFiles (juce::File::findFiles, false, logBase.getFileName() + ".*"))
- {
- juce::StringArray lines;
- f.readLines (lines);
- auto& done = linesRead[f.getFullPathName()];
- for (int i = done; i < lines.size(); ++i)
- {
- const auto p = juce::StringArray::fromTokens (lines[i], " ", {});
- if (p.size() >= 5 && p[0].startsWith ("E"))
- events.push_back ({ p[1] == "on", p[2].getIntValue(), p[4].getIntValue() });
- }
- done = lines.size() - (lines.isEmpty() || lines[lines.size() - 1].isNotEmpty() ? 0 : 1);
- }
- return events;
- };
- {
- lynx::AudioEngine offline (false);
- auto& host = offline.getPluginHost();
- report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
- std::optional<juce::PluginDescription> vst3;
- for (const auto& type : host.getKnownPlugins().getTypes())
- if (type.pluginFormatName == "VST3" && type.isInstrument)
- vst3 = type;
- const auto render = [&] (bool tags) {
- auto song = lynx::Song::makeDefault();
- song.bpm = 120.0;
- auto& c = song.channels[0];
- c.instrument = lynx::InstrumentKind::plugin;
- c.plugin.id = vst3->createIdentifierString().toStdString();
- c.plugin.name = vst3->name.toStdString();
- for (std::size_t k = 1; k < song.channels.size(); ++k)
- song.channels[k].muted = true;
- auto& notes = song.patterns[0].notes;
- notes.clear();
- const auto beat = (std::int64_t) lynx::ppq;
- notes.push_back ({ 0, 4 * beat, 0, 60, 0.8f }); // A
- notes.push_back ({ 2 * beat, 4 * beat, 0, 60, 0.8f }); // B
- notes.push_back ({ 8 * beat, 6 * beat, 0, 64, 0.8f }); // C
- notes.push_back ({ 10 * beat, 2 * beat, 0, 64, 0.8f }); // D (inside C)
- song.patterns[0].sortNotes();
- song.patterns[0].lengthTicks = 16 * beat;
- offline.setSong (song);
- offline.dispatchPendingMessages();
- if (! tags)
- juce::lynxNoteTagHook = nullptr; // (fix 14 alone: the oldest sounding id; the next instance sets it again)
- offline.renderOffline (7.9, 48000.0); // (C ends at 7 s; the 8 s pattern does not loop yet)
- return readLog();
- };
- const auto check = [&report] (const char* name, const std::vector<E>& events, bool expectOwn) {
- // ons and offs of each key in the order the plugin got them
- std::map<int, std::vector<int>> ons, offs;
- for (const auto& e : events)
- (e.on ? ons : offs)[e.key].push_back (e.id);
- const auto& a = ons[60]; const auto& o60 = offs[60];
- const auto& c = ons[64]; const auto& o64 = offs[64];
- report << name << ": key 60 ons";
- for (auto id : a) report << " " << id;
- report << " offs";
- for (auto id : o60) report << " " << id;
- report << "; key 64 ons";
- for (auto id : c) report << " " << id;
- report << " offs";
- for (auto id : o64) report << " " << id;
- report << "\n";
- if (a.size() != 2 || o60.size() != 2 || c.size() != 2 || o64.size() != 2 || a[0] < 0 || c[0] < 0)
- return false;
- const auto fifo = o60[0] == a[0] && o60[1] == a[1]; // A ends first: A's id either way
- // LIFO: D (c[1]) ends first; its own id with the tags, C's (the oldest) without
- const auto lifo = expectOwn ? (o64[0] == c[1] && o64[1] == c[0]) : (o64[0] == c[0] && o64[1] == c[1]);
- return fifo && lifo;
- };
- if (vst3)
- {
- report << "plugin=" << vst3->name << "\n";
- const auto withTags = render (true);
- const auto okTags = check ("with_tags", withTags, true);
- const auto withoutTags = render (false);
- const auto okBefore = check ("fix14_only", withoutTags, false);
- report << "own_ids=" << (okTags ? "yes" : "NO") << " fix14_only_oldest=" << (okBefore ? "yes" : "NO") << "\n";
- ok = okTags && okBefore;
- }
- }
- if (ok) // (a failure leaves the logs for a look: their path is in the report)
- for (const auto& f : logBase.getParentDirectory().findChildFiles (juce::File::findFiles, false, logBase.getFileName() + ".*"))
- f.deleteFile();
- else
- report << "synth_logs=" << logBase.getFullPathName() << ".*\n";
- #if JUCE_WINDOWS
- _putenv_s ("LYNX_TEST_SYNTH_LOG", "");
- #else
- unsetenv ("LYNX_TEST_SYNTH_LOG");
- #endif
- report << "result=" << (ok ? "OK" : "FAILED") << "\n";
- juce::File (reportPath).replaceWithText (report);
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- }
- // Round 181c: a wrapper MIDI option changed on a running plugin must act like the same option on a new one. For each
- // option: a control engine whose plugin is created with the option set (proves the test can see it), then an engine
- // whose plugin is already running when the option changes through editSong, as the wrapper page does it. What the
- // plugin received comes from the test plugin's own log. The running instance must also stay the same one.
- void runWrapperMidiTest (const juce::String& pluginPath, const juce::String& reportPath)
- {
- juce::String report;
- auto ok = true;
- const juce::File logFile (juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_VST2_MIDILOG", {}));
- struct Event { juce::String instance; int status, data1, data2; };
- auto take = [&] {
- std::vector<Event> out;
- juce::StringArray lines;
- logFile.readLines (lines);
- for (const auto& line : lines)
- {
- const auto p = juce::StringArray::fromTokens (line, " ", {});
- if (p.size() == 4)
- out.push_back ({ p[0], p[1].getIntValue(), p[2].getIntValue(), p[3].getIntValue() });
- }
- logFile.deleteFile();
- return out;
- };
- auto count = [] (const std::vector<Event>& events, int status, int data1, int data2) {
- int n = 0;
- for (const auto& e : events)
- n += (e.status & 0xF0) == status && (data1 < 0 || e.data1 == data1) && (data2 < 0 || e.data2 == data2) ? 1 : 0;
- return n;
- };
- struct Option
- {
- const char* name;
- std::function<void (lynx::PluginRef&)> before, change;
- std::function<juce::String (const std::vector<Event>&)> seen;
- };
- const Option options[] = {
- { "Send note release velocity off", {}, [] (lynx::PluginRef& r) { r.releaseVelocity = false; },
- [&] (const std::vector<Event>& e) { return "offs_with_release_32=" + juce::String (count (e, 0x80, 69, 32)) + " offs_at_0=" + juce::String (count (e, 0x80, 69, 0)); } },
- { "Send pitch bend range on", {}, [] (lynx::PluginRef& r) { r.sendBendRange = true; },
- [&] (const std::vector<Event>& e) { return "rpn_range_12=" + juce::String (count (e, 0xB0, 6, 12)); } },
- { "Pitch bend range 24", [] (lynx::PluginRef& r) { r.sendBendRange = true; }, [] (lynx::PluginRef& r) { r.bendRange = 24; },
- [&] (const std::vector<Event>& e) { return "rpn_range_24=" + juce::String (count (e, 0xB0, 6, 24)); } },
- { "Send MOD X as polyphonic aftertouch on", {}, [] (lynx::PluginRef& r) { r.modXAftertouch = true; },
- [&] (const std::vector<Event>& e) { return "aftertouch=" + juce::String (count (e, 0xA0, 69, -1)); } },
- { "Send All Notes Off when playback stops off", {}, [] (lynx::PluginRef& r) { r.allNotesOffOnStop = false; },
- [&] (const std::vector<Event>& e) { return "cc123=" + juce::String (count (e, 0xB0, 123, -1)); } },
- };
- // each phase has its own engine: an engine keeps the running instance across setSong, so one engine would
- // carry the control's plugin into the "before" phase
- lynx::AudioEngine scanner (false);
- auto& host = scanner.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;
- if (! vst2 || logFile.getFullPathName().isEmpty())
- ok = false;
- else
- for (const auto& option : options)
- {
- auto makeSong = [&] (bool changed) {
- auto song = lynx::Song::makeDefault();
- auto& channel = song.channels[0];
- channel.instrument = lynx::InstrumentKind::plugin;
- channel.plugin = {};
- channel.plugin.id = vst2->createIdentifierString().toStdString();
- channel.plugin.name = vst2->name.toStdString();
- if (option.before)
- option.before (channel.plugin);
- if (changed)
- option.change (channel.plugin);
- song.patterns[0].notes.clear();
- lynx::Note note;
- note.start = 0;
- note.length = lynx::ppq;
- note.channel = 0;
- note.key = 69;
- note.velocity = 1.0f;
- note.release = 0.25f; // 32 of 127
- note.modX = 0.75f;
- song.patterns[0].notes.push_back (note);
- for (std::size_t c = 1; c < song.channels.size(); ++c)
- song.channels[c].muted = true;
- return song;
- };
- // a block of the song, then a note held across "playback stopped", as the options act on either
- auto play = [&] (lynx::AudioEngine& engine) {
- logFile.deleteFile();
- engine.renderOffline (1.0, 48000.0);
- if (auto instrument = engine.getChannelInstrument (0))
- {
- instrument->noteOn (60, 1.0f);
- instrument->transportStopped();
- }
- engine.renderOffline (0.1, 48000.0);
- return take();
- };
- auto newEngine = [&] {
- auto engine = std::make_unique<lynx::AudioEngine> (false);
- engine->getPluginHost().addPluginFile (juce::File (pluginPath));
- return engine;
- };
- std::vector<Event> control;
- {
- auto engine = newEngine();
- engine->setSong (makeSong (true));
- control = play (*engine);
- }
- auto engine = newEngine();
- engine->setSong (makeSong (false));
- const auto before = play (*engine);
- const auto instrumentBefore = engine->getChannelInstrument (0).get();
- engine->capturePluginStates(); // as the wrapper page does
- engine->editSong ([&] (lynx::Song& song) { option.change (song.channels[0].plugin); });
- const auto after = play (*engine);
- const auto sameInstance = engine->getChannelInstrument (0).get() == instrumentBefore;
- // the counts differ between phases (how many blocks the note spans, how many instances the phase made):
- // what matters is whether each kind of event is there at all
- auto shape = [] (const juce::String& seen) {
- juce::String out;
- for (const auto& token : juce::StringArray::fromTokens (seen, " ", {}))
- out << token.upToFirstOccurrenceOf ("=", false, false) << (token.fromFirstOccurrenceOf ("=", false, false).getIntValue() > 0 ? "=yes " : "=no ");
- return out;
- };
- auto instances = [] (const std::vector<Event>& events) {
- std::set<juce::String> made;
- for (const auto& e : events)
- made.insert (e.instance);
- return (int) made.size();
- };
- const auto a = option.seen (control) + " instances=" + juce::String (instances (control)),
- b = option.seen (before) + " instances=" + juce::String (instances (before)),
- c = option.seen (after) + " instances=" + juce::String (instances (after));
- const auto visible = shape (option.seen (control)) != shape (option.seen (before));
- const auto works = shape (option.seen (after)) == shape (option.seen (control));
- report << option.name << ": control " << a << " | before " << b << " | after the change " << c << " | same_instance=" << (int) sameInstance
- << " | test_sees_the_option=" << (int) visible << " | " << (! visible ? "NOT PROVEN" : works ? "acts on the plugin" : "DEAD until re-created") << "\n";
- ok = ok && visible && works;
- }
- report << "result=" << (ok ? "OK" : "FAILED") << "\n";
- juce::File (reportPath).replaceWithText (report);
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- }
- // LYNX.exe --wrappershot "LYNX Test Drums.dll" <folder> (round 188d): the wrapper's Processing tab drawn offscreen
- // (no window, no focus) for the FL | LYNX review: wrap-default.png (a fresh plugin), wrap-automap.png (Auto map
- // outputs, output 3 off: FL's shot b23), wrap-settings.png. Scale 1.5 (FL's shots are at 150 %).
- void runWrapperShot (const juce::String& pluginPath, const juce::String& folderPath)
- {
- const juce::File folder (folderPath);
- folder.createDirectory();
- auto ok = false;
- lynx::AudioEngine engine (false);
- engine.getPluginHost().addPluginFile (juce::File (pluginPath));
- std::optional<juce::PluginDescription> vst2;
- for (const auto& type : engine.getPluginHost().getKnownPlugins().getTypes())
- if (type.pluginFormatName == "VST" && juce::File (type.fileOrIdentifier) == juce::File (pluginPath))
- vst2 = type; // (the profile may know other test plugins)
- if (vst2 && ! vst2->isInstrument)
- {
- // an effect (round 188d): on insert 1, with insert 2 routed there as a sidechain (FL's k65 / k78 shots):
- // wrap-fx-default.png, wrap-fx-automap.png (Auto map inputs and outputs)
- auto song = lynx::Song::makeDefault();
- if (song.mixer.size() < 4)
- song.mixer.resize (4);
- auto slot = lynx::makeEffectSlot (lynx::EffectKind::plugin);
- slot.plugin.id = vst2->createIdentifierString().toStdString();
- slot.plugin.name = vst2->name.toStdString();
- song.mixer[1].effects = { slot };
- lynx::mixerops::sidechainTo (song, 2, 1);
- engine.setSong (song);
- engine.renderOffline (0.05, 48000.0);
- if (auto fx = std::dynamic_pointer_cast<lynx::PluginEffect> (engine.getEffect (1, 0)))
- {
- auto find = [] (lynx::Song& s) -> lynx::PluginRef* {
- return s.mixer.size() < 2 || s.mixer[1].effects.empty() ? nullptr : &s.mixer[1].effects[0].plugin;
- };
- auto save = [&] (const char* name) {
- const auto image = lynx::wrapperSettingsSnapshot (engine, find, fx->getInstance(), false, 1, 1.5f, 1, 0);
- juce::FileOutputStream out (folder.getChildFile (name));
- out.setPosition (0);
- out.truncate();
- return out.openedOk() && juce::PNGImageFormat().writeImageToStream (image, out);
- };
- ok = save ("wrap-fx-default.png");
- engine.editSong ([] (lynx::Song& s) {
- lynx::autoMapOutputs (s.mixer[1].effects[0].plugin.inputs, 2);
- lynx::autoMapOutputs (s.mixer[1].effects[0].plugin.outputs, 2);
- s.mixer[1].effects[0].sidechain = lynx::mixerops::sidechainIndexSource (s, 1, 1);
- });
- ok = ok && save ("wrap-fx-automap.png") && engine.getSong().mixer[1].effects[0].sidechain == 2;
- }
- }
- else if (vst2)
- {
- auto song = lynx::Song::makeDefault();
- auto& channel = song.channels[0];
- channel.instrument = lynx::InstrumentKind::plugin;
- channel.plugin = {};
- channel.plugin.id = vst2->createIdentifierString().toStdString();
- channel.plugin.name = vst2->name.toStdString();
- channel.mixerTrack = 5;
- engine.setSong (song);
- engine.renderOffline (0.05, 48000.0); // (the plugin is hosted by then)
- if (auto instrument = std::dynamic_pointer_cast<lynx::PluginInstrument> (engine.getChannelInstrument (0)))
- {
- auto find = [] (lynx::Song& s) -> lynx::PluginRef* { return s.channels.empty() ? nullptr : &s.channels[0].plugin; };
- auto save = [&] (const char* name, int tab) {
- const auto image = lynx::wrapperSettingsSnapshot (engine, find, instrument->getInstance(), true, tab, 1.5f);
- juce::FileOutputStream out (folder.getChildFile (name));
- out.setPosition (0);
- out.truncate();
- return out.openedOk() && juce::PNGImageFormat().writeImageToStream (image, out);
- };
- ok = save ("wrap-default.png", 1) && save ("wrap-settings.png", 0);
- engine.editSong ([] (lynx::Song& s) {
- lynx::autoMapOutputs (s.channels[0].plugin.outputs, 8);
- s.channels[0].plugin.outputs.resize (8);
- s.channels[0].plugin.outputs[2].active = 0;
- s.channels[0].plugin.processInactive = false; // (as an LED click does, FL's b23)
- });
- ok = ok && save ("wrap-automap.png", 1);
- }
- }
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- }
- // LYNX.exe --multiouttest "LYNX Test Drums.dll" report.txt (round 188d, issue #114): a multi-output VST2
- // (tools/testplugin/lynx_test_drums_vst2.c: key 36 = output 1 at 110 Hz, key 37 = output 2 at 220 Hz) on a
- // channel routed to insert 1; the wrapper's Processing › Connections as FL plays them [EXEC fl188d]: every output
- // on the channel's insert by default, an offset to another insert, an inactive output silent, the channel's
- // volume on all of them. Measured on the master with insert 1 muted or not.
- void runMultiOutTest (const juce::String& pluginPath, const juce::String& reportPath)
- {
- juce::String report;
- auto ok = true;
- lynx::AudioEngine scanner (false);
- report << "plugins_in_file=" << scanner.getPluginHost().addPluginFile (juce::File (pluginPath)) << "\n";
- std::optional<juce::PluginDescription> vst2;
- for (const auto& type : scanner.getPluginHost().getKnownPlugins().getTypes())
- if (type.pluginFormatName == "VST" && juce::File (type.fileOrIdentifier) == juce::File (pluginPath))
- vst2 = type; // (the profile may know other test plugins)
- struct Case
- {
- const char* name;
- std::vector<lynx::PluginOutputRoute> routes;
- bool muteInsert1;
- float volume;
- bool kick, snare; // expected on the master
- };
- const Case cases[] = {
- { "defaults", {}, false, -1.0f, true, true },
- { "defaults, insert 1 muted", {}, true, -1.0f, false, false },
- { "auto map, insert 1 muted", { { 0, 1 }, { 1, 1 } }, true, -1.0f, false, true },
- { "auto map", { { 0, 1 }, { 1, 1 } }, false, -1.0f, true, true },
- { "output 2 inactive", { { 0, 1 }, { 1, 0 } }, false, -1.0f, true, false },
- { "output 1 inactive", { { 0, 0 } }, false, -1.0f, false, true },
- { "auto map, channel volume 0", { { 0, 1 }, { 1, 1 } }, false, 0.0f, false, false },
- { "output 2 inactive, Process inactive inputs and outputs on", { { 0, 1 }, { 1, 0 } }, false, -1.0f, true, true },
- };
- auto tone = [] (const std::vector<float>& x, double hz) {
- // Goertzel magnitude over the buffer (normalised to a sine's amplitude)
- const auto w = 2.0 * juce::MathConstants<double>::pi * hz / 48000.0;
- double s1 = 0.0, s2 = 0.0;
- for (const auto v : x)
- {
- const auto s0 = v + 2.0 * std::cos (w) * s1 - s2;
- s2 = s1;
- s1 = s0;
- }
- return std::sqrt (s1 * s1 + s2 * s2 - 2.0 * std::cos (w) * s1 * s2) * 2.0 / (double) std::max<std::size_t> (1, x.size());
- };
- if (! vst2)
- ok = false;
- else
- for (const auto& c : cases)
- {
- lynx::AudioEngine engine (false);
- engine.getPluginHost().addPluginFile (juce::File (pluginPath));
- auto song = lynx::Song::makeDefault();
- auto& channel = song.channels[0];
- channel.instrument = lynx::InstrumentKind::plugin;
- channel.plugin = {};
- channel.plugin.id = vst2->createIdentifierString().toStdString();
- channel.plugin.name = vst2->name.toStdString();
- channel.plugin.outputs = c.routes;
- // (FL's "Process inactive inputs and outputs" plays an inactive output: off but for the case named so)
- channel.plugin.processInactive = juce::String (c.name).contains ("Process inactive");
- channel.mixerTrack = 1;
- if (c.volume >= 0.0f)
- channel.volume = c.volume;
- for (std::size_t k = 1; k < song.channels.size(); ++k)
- song.channels[k].muted = true;
- if (song.mixer.size() < 4)
- song.mixer.resize (4);
- song.mixer[1].muted = c.muteInsert1;
- song.patterns[0].notes.clear();
- for (const auto key : { 36, 37 })
- {
- lynx::Note note;
- note.start = 0;
- note.length = lynx::ppq;
- note.channel = 0;
- note.key = key;
- note.velocity = 1.0f;
- song.patterns[0].notes.push_back (note);
- }
- engine.setSong (song);
- std::vector<float> master;
- lynx::AudioEngine::RenderOptions options;
- options.seconds = 0.25;
- options.sampleRate = 48000.0;
- options.capture = [&master] (const float* l, const float*, int n) { master.insert (master.end(), l, l + n); };
- engine.renderOffline (options);
- const auto kick = tone (master, 110.0), snare = tone (master, 220.0);
- const auto pass = (kick > 0.01) == c.kick && (snare > 0.01) == c.snare;
- report << c.name << ": kick_110Hz=" << juce::String (kick, 4) << " snare_220Hz=" << juce::String (snare, 4) << " expected kick="
- << (int) c.kick << " snare=" << (int) c.snare << (pass ? " OK" : " FAILED") << "\n";
- ok = ok && pass;
- if (auto instrument = std::dynamic_pointer_cast<lynx::PluginInstrument> (engine.getChannelInstrument (0)))
- if (&c == &cases[0])
- {
- report << "outputs=" << (int) instrument->outputs().size();
- for (const auto& o : instrument->outputs())
- report << " [" << o.name << " ch" << o.channel << "x" << o.channels << "]";
- report << "\n";
- ok = ok && instrument->outputs().size() == 8 && instrument->outputs()[1].name == "Snare";
- }
- }
- // round 189j: "LYNX Test SC.dll" next to it (tools/testplugin/lynx_test_sc_vst2.c) as an effect on insert 1
- const auto sc = juce::File (pluginPath).getSiblingFile ("LYNX Test SC.dll");
- if (sc.existsAsFile())
- ok = runEffectConnectionsTest (sc, report) && ok;
- report << "result=" << (ok ? "OK" : "FAILED") << "\n";
- juce::File (reportPath).replaceWithText (report);
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- }
- // Round 189j: a hosted effect's Processing › Connections against FL 2026's own renders of the same projects
- // [EXEC fxconn189j: FL /R renders of LYNX's .flp exports, docs/analise/REA_rodada189j.md]. Insert 1: a 440 Hz
- // sampler and "LYNX Test SC" (output 1 = input 1, output 2 = input 2); inserts 2 (1000 Hz) and 3 (1500 Hz) routed
- // to insert 1 at level 0 only; insert 4 a 2500 Hz reference on the Master; insert 1 routed to the Master and at
- // level 0 to inserts 5 (panned left) and 6 (right). Each tone's level per side, in dB from the reference's, must be
- // FL's within 0.5 dB (absent: 50 dB under it).
- bool runEffectConnectionsTest (const juce::File& scFile, juce::String& report)
- {
- lynx::AudioEngine scanner (false);
- scanner.getPluginHost().addPluginFile (scFile);
- std::optional<juce::PluginDescription> sc;
- for (const auto& type : scanner.getPluginHost().getKnownPlugins().getTypes())
- if (type.pluginFormatName == "VST" && juce::File (type.fileOrIdentifier) == scFile)
- sc = type;
- report << "effect_plugin=" << (sc ? sc->name : juce::String ("not found")) << "\n";
- if (! sc)
- return false;
- const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-fxconn189j");
- dir.createDirectory();
- const double tones[] = { 440.0, 1000.0, 1500.0, 2500.0 };
- for (const auto hz : tones)
- {
- const auto wav = dir.getChildFile ("sine" + juce::String ((int) hz) + ".wav");
- if (wav.existsAsFile())
- continue;
- juce::AudioBuffer<float> sine (1, 44100 * 3);
- for (int i = 0; i < sine.getNumSamples(); ++i)
- sine.setSample (0, i, 0.25f * (float) std::sin (2.0 * juce::MathConstants<double>::pi * hz * i / 44100.0));
- juce::WavAudioFormat format;
- std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
- if (auto* w = format.createWriterFor (out.get(), 44100.0, 1, 16, {}, 0))
- {
- out.release();
- std::unique_ptr<juce::AudioFormatWriter> writer (w);
- writer->writeFromAudioSampleBuffer (sine, 0, sine.getNumSamples());
- }
- }
- using Route = lynx::PluginOutputRoute;
- constexpr float none = -999.0f;
- struct Case
- {
- const char* name;
- std::vector<Route> inputs, outputs;
- int tweak; // 1 no Master route, 2 insert 1 fader at 0.4, 3 Process inactive off, 4 Master route level 0, 5 route
- // to 7 too, 6 insert 2 fader at 0.4, 7 insert 2 muted, 8 insert 2 panned left
- float level[3][2]; // 440 / 1000 / 1500 Hz, left / right: dB from the reference, FL's
- };
- const Route d { 0, 1 };
- const Case cases[] = {
- { "e00 FL defaults", { d, d }, {}, 0, { { 6.1f, 6.1f }, { none, none }, { none, none } } },
- { "e01 input 1 at 1", { { 1, 1 } }, {}, 0, { { 0, 0 }, { 0, 0 }, { none, none } } },
- { "e02 input 1 at 2", { { 2, 1 } }, {}, 0, { { 0, 0 }, { none, none }, { 0, 0 } } },
- { "e03 input 2 at 1", { d, { 1, 1 } }, {}, 0, { { 0, 0 }, { 0, 0 }, { none, none } } },
- { "e04 output 2 at 1 (Master)", { d, { 1, 1 } }, { d, { 1, 1 } }, 0, { { 0, 0 }, { 0, 0 }, { none, none } } },
- { "e05 output 2 at 2 (insert 5)", { d, { 1, 1 } }, { d, { 2, 1 } }, 0, { { 0, 0 }, { 3.0f, none }, { none, none } } },
- { "e06 output 1 at 1", {}, { { 1, 1 } }, 0, { { 6.1f, 6.1f }, { none, none }, { none, none } } },
- { "e07 output 2 at 5 (past the list)", { d, { 1, 1 } }, { d, { 5, 1 } }, 0, { { 0, 0 }, { none, 3.0f }, { none, none } } },
- { "e08 inputs 1 and 2 at 1", { { 1, 1 }, { 1, 1 } }, {}, 0, { { none, none }, { 6.1f, 6.1f }, { none, none } } },
- { "e09 output 2 inactive", { d, { 1, 1 } }, { d, { 0, 0 } }, 0, { { 0, 0 }, { 0, 0 }, { none, none } } },
- { "e10 input 1 at 5 (past the list)", { { 5, 1 } }, {}, 0, { { 6.1f, 6.1f }, { none, none }, { none, none } } },
- { "e11 output 2 at 3 (insert 6)", { d, { 1, 1 } }, { d, { 3, 1 } }, 0, { { 0, 0 }, { none, 3.0f }, { none, none } } },
- { "e13 no Master route, output 2 at 1", { d, { 1, 1 } }, { d, { 1, 1 } }, 1, { { none, none }, { 3.0f, none }, { none, none } } },
- { "e14 insert 1 fader 0.4, output 2 at 1", { d, { 1, 1 } }, { d, { 1, 1 } }, 2, { { -12.7f, -12.7f }, { 0, 0 }, { none, none } } },
- { "e15 input 2 inactive", { d, { 1, 0 } }, { d, d }, 3, { { 0, 0 }, { none, none }, { none, none } } },
- { "e16 output 2 inactive", { d, { 1, 1 } }, { d, { 0, 0 } }, 3, { { 0, 0 }, { none, none }, { none, none } } },
- { "e18 route to 7 too, output 2 at 3", { d, { 1, 1 } }, { d, { 3, 1 } }, 5, { { 0, 0 }, { none, 3.0f }, { none, none } } },
- { "e19 Master route at 0, output 2 at 1", { d, { 1, 1 } }, { d, { 1, 1 } }, 4, { { none, none }, { 0, 0 }, { none, none } } },
- { "e22 input 1 at 1 inactive", { { 1, 0 } }, {}, 3, { { 0, 0 }, { none, none }, { none, none } } },
- { "e23 output 2 at -1, insert 1 fader 0.4", { d, { 1, 1 } }, { d, { -1, 1 } }, 2, { { -12.7f, -12.7f }, { 0, 0 }, { none, none } } },
- { "e24 input 1 at 1, insert 2 fader 0.4", { { 1, 1 } }, {}, 6, { { 0, 0 }, { -12.7f, -12.7f }, { none, none } } },
- { "e25 input 1 at 1, insert 2 muted", { { 1, 1 } }, {}, 7, { { 0, 0 }, { none, none }, { none, none } } },
- { "e26 input 1 at 1, insert 2 panned left", { { 1, 1 } }, {}, 8, { { 0, 0 }, { 3.0f, none }, { none, none } } },
- };
- auto goertzel = [] (const std::vector<float>& x, double hz) {
- const auto w = 2.0 * juce::MathConstants<double>::pi * hz / 44100.0;
- double s1 = 0.0, s2 = 0.0;
- for (const auto v : x)
- {
- const auto s0 = v + 2.0 * std::cos (w) * s1 - s2;
- s2 = s1;
- s1 = s0;
- }
- const auto a = std::sqrt (juce::jmax (0.0, s1 * s1 + s2 * s2 - 2.0 * std::cos (w) * s1 * s2)) * 2.0 / (double) std::max<std::size_t> (1, x.size());
- return a > 1e-7 ? 20.0 * std::log10 (a) : -140.0;
- };
- auto ok = true;
- for (const auto& c : cases)
- {
- lynx::AudioEngine engine (false);
- engine.getPluginHost().addPluginFile (scFile);
- auto song = lynx::Song::makeDefault();
- song.bpm = 120.0;
- song.channels.clear();
- song.automations.clear();
- for (auto& p : song.patterns)
- p.notes.clear();
- for (int k = 0; k < 4; ++k)
- {
- lynx::ChannelDef ch;
- ch.name = "S" + std::to_string ((int) tones[k]);
- ch.instrument = lynx::InstrumentKind::sampler;
- ch.samplePath = dir.getChildFile ("sine" + juce::String ((int) tones[k]) + ".wav").getFullPathName().toStdString();
- ch.mixerTrack = k + 1;
- song.channels.push_back (ch);
- lynx::Note note;
- note.start = 0;
- note.length = 8 * lynx::ppq;
- note.channel = k;
- note.key = 60;
- note.velocity = 0.78f;
- song.patterns[0].notes.push_back (note);
- }
- if (song.mixer.size() < 10)
- song.mixer.resize (10);
- for (auto& t : song.mixer)
- {
- t.effects.clear();
- t.sends.clear();
- t.toMaster = true;
- }
- lynx::EffectSlot fx;
- fx.kind = lynx::EffectKind::plugin;
- fx.plugin.id = sc->createIdentifierString().toStdString();
- fx.plugin.name = sc->name.toStdString();
- fx.plugin.inputs = c.inputs;
- fx.plugin.outputs = c.outputs;
- fx.plugin.processInactive = c.tweak != 3;
- auto& one = song.mixer[1];
- one.effects.push_back (fx);
- one.sends = { { 5, 0.0f }, { 6, 0.0f } };
- for (const int t : { 2, 3 })
- {
- song.mixer[(std::size_t) t].toMaster = false;
- song.mixer[(std::size_t) t].sends = { { 1, 0.0f } };
- }
- song.mixer[5].pan = -1.0f;
- song.mixer[6].pan = 1.0f;
- one.toMaster = c.tweak != 1;
- if (c.tweak == 2)
- one.volume = 0.4f;
- if (c.tweak == 4)
- one.masterLevel = 0.0f;
- if (c.tweak == 6)
- song.mixer[2].volume = 0.4f;
- song.mixer[2].muted = c.tweak == 7;
- song.mixer[2].pan = c.tweak == 8 ? -1.0f : 0.0f;
- if (c.tweak == 5)
- {
- one.sends = { { 7, 0.0f }, { 5, 0.0f }, { 6, 0.0f } };
- song.mixer[7].pan = 0.5f;
- }
- // (input 2's index sets the slot's side input source, as the Connections page and the import do)
- if (c.inputs.size() > 1 && c.inputs[1].offset > 0)
- one.effects[0].sidechain = lynx::mixerops::sidechainIndexSource (song, 1, c.inputs[1].offset);
- engine.setSong (song);
- std::vector<float> left, right;
- lynx::AudioEngine::RenderOptions options;
- options.seconds = 1.2;
- options.sampleRate = 44100.0;
- options.capture = [&] (const float* l, const float* r, int n) {
- left.insert (left.end(), l, l + n);
- right.insert (right.end(), r, r + n);
- };
- engine.renderOffline (options);
- const auto from = (std::size_t) 22050, to = (std::size_t) 44100;
- if (right.size() < to)
- {
- report << c.name << ": rendered " << (int) right.size() << " samples FAILED\n";
- ok = false;
- continue;
- }
- const std::vector<float> l (left.begin() + (std::ptrdiff_t) from, left.begin() + (std::ptrdiff_t) to);
- const std::vector<float> r (right.begin() + (std::ptrdiff_t) from, right.begin() + (std::ptrdiff_t) to);
- const auto ref = 0.5 * (goertzel (l, 2500.0) + goertzel (r, 2500.0));
- auto pass = ref > -60.0;
- report << c.name << ": ref=" << juce::String (ref, 1);
- for (int k = 0; k < 3; ++k)
- for (int side = 0; side < 2; ++side)
- {
- const auto got = goertzel (side == 0 ? l : r, tones[k]) - ref;
- const auto want = c.level[k][side];
- const auto good = want == none ? got < -50.0 : std::abs (got - want) < 0.5;
- pass = pass && good;
- report << " " << (int) tones[k] << (side == 0 ? "L" : "R") << "=" << (got < -50.0 ? juce::String ("-") : juce::String (got, 1))
- << (good ? "" : "(FL " + (want == none ? juce::String ("-") : juce::String (want, 1)) + ")");
- }
- report << (pass ? " OK" : " FAILED") << "\n";
- ok = ok && pass;
- }
- return ok;
- }
- // 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 runDemoSongs (const juce::String& folderPath)
- {
- const juce::File folder (folderPath);
- folder.createDirectory();
- bool ok = true;
- for (int d = 1; d < lynx::demos::count; ++d)
- {
- juce::String error;
- ok = lynx::ProjectFile::save (lynx::demos::make (d), folder.getChildFile (lynx::demos::fileName (d)), error) && ok;
- }
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- }
- void runShowcase (const juce::String& outputPath, int currentPattern)
- {
- const auto song = lynx::makeShowcaseSong (currentPattern);
- juce::String error;
- const auto ok = lynx::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);
- }
- }
- }
- void release()
- {
- instrument.reset();
- effect.reset();
- }
- 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;
- // issue #159: freeing the crashed plugin doesn't wait on its pipe (JUCE waited up to 10 s there for
- // the gone child, on the message thread when the rack freed it); its teardown ends on its own
- const auto freeStart = juce::Time::getMillisecondCounterHiRes();
- voice2.release();
- const auto freeMs = juce::Time::getMillisecondCounterHiRes() - freeStart;
- const auto endedAll = lynx::finishSandboxTeardowns (15000);
- report << "crashed_free_ms=" << freeMs << " teardown_done=" << (endedAll ? 1 : 0) << "\n";
- crashOk = crashOk && freeMs < 250.0 && endedAll;
- }
- 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();
- }
- // --timertest (round 174f): a view's polling timer follows the view and its parents, and survives a minimised window
- void runTimerTest (const juce::File& report)
- {
- struct Ticks final : juce::Timer
- {
- void timerCallback() override {}
- } timer;
- juce::Component top, parent, view;
- parent.addChildComponent (view);
- top.addChildComponent (parent);
- top.setSize (320, 200);
- lynx::ui::TimerWhileShowing watch (view, timer, 30);
- juce::String text;
- auto failures = 0;
- auto expect = [&] (const char* step, bool running) {
- const auto ok = timer.isTimerRunning() == running;
- failures += ok ? 0 : 1;
- text << step << ": timer " << (timer.isTimerRunning() ? "running" : "stopped") << (ok ? "" : " FAIL") << "\n";
- };
- expect ("never shown", false);
- view.setVisible (true);
- parent.setVisible (true);
- expect ("view and parent visible, not on the desktop", false);
- top.addToDesktop (juce::ComponentPeer::windowHasTitleBar);
- top.setVisible (true);
- expect ("window shown", true);
- parent.setVisible (false);
- expect ("parent hidden", false);
- parent.setVisible (true);
- expect ("parent shown", true);
- view.setVisible (false);
- expect ("view hidden", false);
- top.getPeer()->setMinimised (true);
- view.setVisible (true);
- expect ("view shown while minimised", true);
- top.getPeer()->setMinimised (false);
- expect ("window restored", true);
- top.setVisible (false);
- expect ("window hidden", false);
- top.setVisible (true);
- expect ("window shown again", true);
- top.removeFromDesktop();
- text << "failures: " << failures << "\nresult=" << (failures == 0 ? "OK" : "FAIL") << "\n";
- report.replaceWithText (text);
- setApplicationReturnValue (failures == 0 ? 0 : 1);
- quit();
- }
- // --cachetest (round 174f): PlaylistComponent::cacheSelfTest on the project, the Playlist off screen at 1466 x 930
- void runCacheTest (const juce::File& project, const juce::File& report)
- {
- engine = std::make_unique<lynx::AudioEngine>();
- juce::String error;
- auto ok = false;
- 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;
- }
- juce::String text = "project: " + project.getFullPathName() + "\n";
- if (ok)
- {
- auto playlist = std::make_unique<lynx::PlaylistComponent> (*engine);
- playlist->setBounds (0, 0, 1466, 930);
- playlist->setVisible (true);
- text << playlist->cacheSelfTest ([] { lynx::ui::WaveformCache::getInstance()->waitUntilIdle (60000); }, report.getParentDirectory());
- }
- else
- text << "result=ERROR " << error << "\n";
- report.replaceWithText (text);
- setApplicationReturnValue (ok && text.contains ("result=OK") ? 0 : 1);
- quit();
- }
- // --picturetest (round 190bm): ui/PictureCheck.h on the Playlist and the Mixer, at a window's usual size, at a 4K
- // screen's, and wider than a GPU bitmap can be (16384 px)
- void runPictureTest (const juce::File& report, const juce::File& project)
- {
- engine = std::make_unique<lynx::AudioEngine>();
- juce::String error, text;
- if (project != juce::File())
- {
- auto ok = false;
- 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;
- }
- text << "project: " << project.getFullPathName() << (ok ? "" : " (not loaded: " + error + ")") << "\n";
- }
- #if JUCE_WINDOWS
- text << "native image: " << juce::NativeImageType().create (juce::Image::RGB, 8, 8, true)->createType()->getTypeID()
- << " (software = " << juce::SoftwareImageType().getTypeID() << ")\n";
- #endif
- auto failures = 0;
- struct Size
- {
- int width, height;
- std::vector<float> scales;
- };
- const auto folder = report.getParentDirectory();
- for (const auto& size : { Size { 1466, 930, { 1.0f, 1.5f, 2.0f, 3.0f } }, Size { 3840, 2040, { 1.0f, 2.0f } }, Size { 17000, 700, { 1.0f } } })
- {
- const auto label = [&size] (const char* name) { return juce::String (name) + " " + juce::String (size.width) + " x " + juce::String (size.height); };
- {
- auto playlist = std::make_unique<lynx::PlaylistComponent> (*engine);
- playlist->setBounds (0, 0, size.width, size.height);
- playlist->setVisible (true);
- {
- juce::Image warm (juce::Image::RGB, 64, 64, true); // (one paint asks for the waveforms, then they are waited for)
- juce::Graphics g (warm);
- playlist->paintEntireComponent (g, true);
- }
- lynx::ui::WaveformCache::getInstance()->waitUntilIdle (60000);
- text << lynx::ui::picturecheck::run (*playlist, label ("Playlist"), size.scales, failures, folder);
- }
- {
- auto mixer = std::make_unique<lynx::MixerComponent> (*engine);
- mixer->setBounds (0, 0, size.width, juce::jmin (size.height, 700));
- mixer->setVisible (true);
- text << lynx::ui::picturecheck::run (*mixer, label ("Mixer"), size.scales, failures, folder);
- }
- }
- text << "failures: " << failures << "\nresult=" << (failures == 0 ? "OK" : "FAIL") << "\n";
- report.replaceWithText (text);
- setApplicationReturnValue (failures == 0 ? 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)
- {
- if (const auto profile = juce::SystemStats::getEnvironmentVariable ("LYNX_PROFILE_MAIN", {}); profile.isNotEmpty())
- lynx::crashguard::startMainProfiler (profile.toStdString()); // (stopped in shutdown)
- 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();
- // LYNX_UIPERF_SIZE=WxH, LYNX_UIPERF_SCALE=<percent> (round 179a): a large window, a HiDPI desktop's scale
- if (const auto scale = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_SCALE", {}).getIntValue(); scale > 0)
- juce::Desktop::getInstance().setGlobalScaleFactor ((float) scale / 100.0f);
- if (const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_SIZE", {}), "x", ""); size.size() == 2)
- mainWindow->setBounds (0, 0, size[0].getIntValue(), size[1].getIntValue());
- juce::String error;
- auto ok = false;
- const auto loadStart = juce::Time::getMillisecondCounterHiRes();
- if (project.hasFileExtension ("flp;als;flm")) // (round 190gr: a Live set, its Session clips in the grid)
- 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 paintedPixels = 0.0; // round 190ge: the dirty area of those frames, summed (overdraw / repaint storms)
- 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();
- paintedPixels = 0.0;
- 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()
- << ", painted " << juce::String (wall > 0.0 ? paintedPixels / wall / 1000.0 : 0.0, 2) << " Mpx/s"
- << "\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);
- r->paintedPixels += (double) area.getWidth() * (double) area.getHeight();
- }
- 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 });
- // round 177a: only the meters move, so the strips' picture must stay valid, also with a folded group's tab and VCA
- // strips on screen (their levels are drawn over the picture, like the inserts' meters)
- run->steps.push_back ({ "mixer meters over the picture, playing", [this, ui] {
- ui->selectTabForSnapshot (3);
- engine->getTransport().songMode = false;
- engine->rewind();
- engine->play();
- ui->getMixerForSnapshot().getStripsForSnapshot().cacheCountersForPerf();
- }, {}, 6000, [this, ui, report] {
- const auto [spoiled, refills] = ui->getMixerForSnapshot().getStripsForSnapshot().cacheCountersForPerf();
- if (juce::FileOutputStream out (report.withFileExtension ("png")); out.openedOk())
- {
- out.setPosition (0);
- out.truncate();
- juce::PNGImageFormat().writeImageToStream (mainWindow->createComponentSnapshot (mainWindow->getLocalBounds()), out);
- }
- return juce::String (" mixer picture: spoiled ") + juce::String (spoiled) + " times, drawn again " + juce::String (refills) + " times\n";
- } });
- 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 });
- // round 174f: Ctrl+wheel zoom, a notch every third frame (~20 a second), three in then three out, as dupmon drives it
- run->steps.push_back ({ "playlist zoom (Ctrl+wheel)", {},
- [wheelAt, ui] (int f) {
- if (f % 3 == 0)
- wheelAt (ui->getPlaylistForSnapshot(), 0.0f, (f / 9) % 2 == 0 ? 0.15f : -0.15f, juce::ModifierKeys (juce::ModifierKeys::ctrlModifier));
- }, 120 });
- run->steps.push_back ({ "playlist after the zoom (settles)", {}, {}, 500 });
- 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 });
- // round 190ge: the other main views while the pattern plays, then every view with the transport stopped and
- // nothing moving (an idle view should paint nothing: its frames and painted area are the repaint storms), then
- // the Clip-launch grid playing
- auto playPattern = [this] {
- engine->getTransport().songMode = false;
- engine->rewind();
- engine->play();
- };
- run->steps.push_back ({ "piano roll maximised, pattern playing", [ui, playPattern] { ui->selectTabForSnapshot (1); playPattern(); }, {}, 3000 });
- run->steps.push_back ({ "channel rack maximised, pattern playing", [ui, playPattern] { ui->selectTabForSnapshot (0); playPattern(); }, {}, 3000 });
- const char* idleViews[] { "channel rack", "piano roll", "playlist", "mixer" };
- for (int view = 0; view < 4; ++view)
- run->steps.push_back ({ juce::String ("idle: ") + idleViews[view] + ", stopped", [this, ui, view] { engine->stop(); ui->selectTabForSnapshot (view); }, {}, 3000 });
- run->steps.push_back ({ "idle: desktop, stopped", [this, ui] { engine->stop(); ui->showDesktopForSnapshot (false); }, {}, 3000 });
- run->steps.push_back ({ "clip grid, song playing", [this, ui] {
- ui->selectTabForSnapshot (2);
- ui->setClipLaunchWorkflow (true);
- ui->setClipGridView (lynx::PlaylistArea::GridView::grid);
- engine->getTransport().songMode = true;
- engine->rewind();
- engine->play();
- }, {}, 3000 });
- // round 190gr: the grid's clips launched (every scene that has clips, one after the other: the playing cells'
- // progress bars move, the launches blink until their grid point)
- run->steps.push_back ({ "clip grid, clips launched", [this] {
- engine->getTransport().songMode = true;
- if (const auto& grid = engine->getSong().clipGrid)
- for (int scene = 0; scene < juce::jmin (8, (int) grid->scenes.size()); ++scene)
- engine->launcherCommand ({ lynx::launcher::Command::Type::launchScene, 0, scene });
- }, {}, 3000, [this] {
- int playing = 0;
- if (const auto* state = engine->launcherState())
- for (const auto& t : state->tracks)
- playing += t.playing.load() >= 0 ? 1 : 0;
- engine->launcherCommand ({ lynx::launcher::Command::Type::stopAll });
- return " tracks playing a clip: " + juce::String (playing) + "\n";
- } });
- run->steps.push_back ({ "idle: clip grid, stopped", [this] { engine->stop(); }, {}, 3000, [ui] { ui->setClipLaunchWorkflow (false); return juce::String(); } });
- // LYNX_UIPERF_ONLY=text: only the steps whose name has that text
- if (const auto only = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_ONLY", {}); only.isNotEmpty())
- run->steps.erase (std::remove_if (run->steps.begin(), run->steps.end(), [&only] (const auto& s) { return ! juce::String (s.name).contains (only); }), run->steps.end());
- // 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)
- // --rtstress --backuptest N (round 177d): while the project plays, a device's MIDI clock (10/s) and active sensing
- // (3/s) arrive, and the project counts as changed. N > 0 also forces a backup every N seconds on top of the timed ones.
- // The report tells how many backups were written, when, and what the MIDI counters did.
- struct BackupTest final : juce::Timer
- {
- lynx::AudioEngine* engine = nullptr;
- lynx::MainComponent* ui = nullptr;
- double everyMs = 0.0, startMs = 0.0, lastForcedMs = 0.0, longestCallMs = 0.0;
- int ticks = 0, forced = 0;
- std::uint64_t seenOver = 0, seenNear = 0;
- juce::String misses; // each callback over (or near) its deadline: how long after the last forced backup
- void timerCallback() override
- {
- engine->injectMidiInput (juce::MidiMessage (0xf8));
- if (++ticks % 3 == 0)
- engine->injectMidiInput (juce::MidiMessage (0xfe));
- const auto now = juce::Time::getMillisecondCounterHiRes();
- const auto s = engine->getRtStats().snapshot();
- if (s.overBudget != seenOver || s.nearBudget != seenNear)
- {
- misses << " +" << juce::String ((now - lastForcedMs) / 1000.0, 1) << " s after the last forced backup (or the start): over +"
- << (juce::int64) (s.overBudget - seenOver) << ", near +" << (juce::int64) (s.nearBudget - seenNear) << "\n";
- seenOver = s.overBudget;
- seenNear = s.nearBudget;
- }
- if (everyMs > 0.0 && now - lastForcedMs >= everyMs)
- {
- lastForcedMs = now;
- ++forced;
- ui->backupNowForTest();
- longestCallMs = juce::jmax (longestCallMs, juce::Time::getMillisecondCounterHiRes() - now);
- }
- }
- };
- std::unique_ptr<BackupTest> backupTest;
- void startBackupTest()
- {
- const auto& cli = juce::JUCEApplication::getCommandLineParameterArray();
- const auto at = cli.indexOf ("--backuptest");
- auto* ui = mainWindow != nullptr ? dynamic_cast<lynx::MainComponent*> (mainWindow->getContentComponent()) : nullptr;
- if (at < 0 || ui == nullptr)
- return;
- backupTest = std::make_unique<BackupTest>();
- backupTest->engine = engine.get();
- backupTest->ui = ui;
- backupTest->everyMs = cli[at + 1].getDoubleValue() * 1000.0;
- backupTest->startMs = backupTest->lastForcedMs = juce::Time::getMillisecondCounterHiRes();
- // (the project counts as changed, so a backup has something to write; the Master's fader is down, so a long run
- // makes no sound: everything else is processed as usual)
- engine->editSong ([] (lynx::Song& s) {
- if (! s.mixer.empty())
- s.mixer[0].volume = 0.0f;
- });
- backupTest->startTimer (100);
- }
- juce::String finishBackupTest()
- {
- if (backupTest == nullptr)
- return {};
- backupTest->stopTimer();
- juce::String text;
- const auto played = engine->getMidiPlayed();
- text << " backup test: MIDI light count " << (int) engine->getMidiActivity() << ", played count " << (int) played << " (clock and active sensing only)\n";
- text << " backup test: " << backupTest->forced << " forced, longest forced call on the message thread "
- << juce::String (backupTest->longestCallMs, 1) << " ms\n";
- if (backupTest->misses.isNotEmpty())
- text << " backup test: callbacks over or near the deadline (seen within 100 ms):\n" << backupTest->misses;
- auto files = lynx::autosaveFolder().findChildFiles (juce::File::findFiles, false, "*.lynx");
- text << " backup test: " << files.size() << " file(s) in the backup folder:\n";
- for (const auto& f : files)
- text << " " << juce::String ((f.getLastModificationTime().toMilliseconds() - juce::Time::getCurrentTime().toMilliseconds()) / 1000) << " s before the end: "
- << f.getFileName() << " (" << f.getSize() << " bytes)\n";
- engine->injectMidiInput (juce::MidiMessage::noteOn (1, 60, (juce::uint8) 1));
- engine->injectMidiInput (juce::MidiMessage::noteOff (1, 60));
- text << " backup test: after a played note, played count " << (int) engine->getMidiPlayed() << "\n";
- backupTest.reset();
- return text;
- }
- 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();
- startBackupTest();
- juce::Timer::callAfterDelay ((int) (seconds * 1000.0), [this, project, report, seconds, loadMs, recordTo] {
- if (engine == nullptr)
- return;
- const auto backupReport = finishBackupTest();
- 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 << backupReport;
- // --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.mode = lynx::RecordMode::overdub;
- 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.mode = lynx::RecordMode::overdub;
- 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.
- // --slicexedittest (round 190aj): see the command line above
- void runSlicexEditTest (const juce::File& project, const juce::File& script, const juce::File& report, const juce::String& prefix)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- juce::StringArray lines;
- {
- lynx::AudioEngine offline (false);
- lynx::MainComponent ui (offline, false);
- ui.setSize (1280, 720);
- ui.openFile (project);
- offline.dispatchPendingMessages();
- int channel = -1;
- for (int c = 0; c < (int) offline.getSong().channels.size() && channel < 0; ++c)
- if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::slicex)
- channel = c;
- if (channel < 0)
- lines.add ("no Slicex channel in " + project.getFullPathName());
- else
- {
- auto panel = lynx::makeChannelSettingsPanel (offline, channel);
- juce::Component frame;
- frame.setSize (panel->getWidth(), panel->getHeight());
- frame.setOpaque (true);
- frame.addAndMakeVisible (*panel);
- panel->setTopLeftPosition (0, 0);
- offline.dispatchPendingMessages();
- juce::StringArray commands;
- script.readLines (commands);
- for (const auto& raw : commands)
- {
- const auto command = raw.trim();
- if (command.isEmpty() || command.startsWith ("#"))
- {
- lines.add (command);
- continue;
- }
- if (command.startsWith ("shot "))
- {
- frame.setSize (panel->getWidth(), panel->getHeight()); // (round 190hg: the display modes resize the editor)
- 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 + command.fromFirstOccurrenceOf (" ", false, false).trim() + ".png");
- file.deleteFile();
- juce::PNGImageFormat png;
- if (auto out = file.createOutputStream())
- png.writeImageToStream (image, *out);
- lines.add (command + " -> " + file.getFileName());
- continue;
- }
- const auto result = lynx::slicexEditorTest (*panel, command);
- offline.dispatchPendingMessages();
- lines.add (command + " -> " + result);
- }
- }
- }
- report.replaceWithText (lines.joinIntoString ("\n") + "\nresult=DONE\n");
- juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
- quit();
- }
- // --slicexkeytest (round 190ac): see the command line above
- void runSlicexKeyTest (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 ("slicexkey", "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); };
- // the deck's sample: 1 s at 48 kHz, four regions (cue points) of 0.25 s, each a steady tone of its own (200 Hz
- // × region number), so the region a key played can be read from the output
- constexpr int rate = 48000, regionFrames = rate / 4;
- const auto wavFile = report.getSiblingFile ("slicexkey-deck.wav");
- {
- juce::MemoryOutputStream w;
- auto chunk = [&w] (const char* id, const juce::MemoryBlock& body) {
- w.write (id, 4);
- w.writeInt ((int) body.getSize());
- w.write (body.getData(), body.getSize());
- };
- juce::MemoryOutputStream fmt, data, cue;
- fmt.writeShort (1);
- fmt.writeShort (1);
- fmt.writeInt (rate);
- fmt.writeInt (rate * 2);
- fmt.writeShort (2);
- fmt.writeShort (16);
- for (int i = 0; i < 4 * regionFrames; ++i)
- data.writeShort ((short) std::lround (12000.0 * std::sin (juce::MathConstants<double>::twoPi * 200.0 * (double) (i / regionFrames + 1) * (double) i / rate)));
- cue.writeInt (4);
- for (int k = 0; k < 4; ++k)
- {
- cue.writeInt (k + 1);
- cue.writeInt (k * regionFrames);
- cue.write ("data", 4);
- cue.writeInt (0);
- cue.writeInt (0);
- cue.writeInt (k * regionFrames);
- }
- juce::MemoryOutputStream riff;
- riff.write ("WAVE", 4);
- w.reset();
- chunk ("fmt ", fmt.getMemoryBlock());
- chunk ("data", data.getMemoryBlock());
- chunk ("cue ", cue.getMemoryBlock());
- riff.write (w.getData(), w.getDataSize());
- juce::MemoryOutputStream file;
- file.write ("RIFF", 4);
- file.writeInt ((int) riff.getDataSize());
- file.write (riff.getData(), riff.getDataSize());
- wavFile.replaceWithData (file.getData(), file.getDataSize());
- }
- lynx::Song song;
- song.bpm = 120.0;
- song.mixer = lynx::Song::defaultMixer (2);
- song.channels.resize (1);
- auto& channel = song.channels[0];
- channel.instrument = lynx::InstrumentKind::slicex;
- channel.mixerTrack = 1;
- channel.samplePath = wavFile.getFullPathName().toStdString();
- {
- auto state = lynx::slicex::fresh();
- lynx::slicex::setDeckFile (state, 0, channel.samplePath, 4);
- lynx::slicex::setDeckBeats (state, 0, 0.0, 2.0);
- channel.pluginState = lynx::slicex::write (state);
- }
- song.patterns.emplace_back();
- engine->setSong (song);
- auto& callback = engine->deviceCallback();
- callback.audioDeviceAboutToStart (device.get());
- step ("song=one Slicex channel, deck A = 4 regions of 0.25 s (200 / 400 / 600 / 800 Hz), 48 kHz, blocks of 512; keys as the editor's keyboard sends them");
- juce::Timer::callAfterDelay (2000, [this, device, step] {
- if (engine == nullptr)
- return;
- auto& cb = engine->deviceCallback();
- auto pump = [&cb] (int blocks) {
- std::vector<float> l (512), r (512), out;
- float* outs[] = { l.data(), r.data() };
- juce::AudioIODeviceCallbackContext context;
- for (int k = 0; k < blocks; ++k)
- {
- cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context);
- out.insert (out.end(), l.begin(), l.end());
- }
- 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));
- };
- // the tone's frequency from its rising zero crossings over a stretch
- auto hertz = [] (const std::vector<float>& x, int from, int count) {
- int crossings = 0, first = -1, last = -1;
- for (int i = from + 1; i < from + count && i < (int) x.size(); ++i)
- if (x[(std::size_t) i - 1] < 0.0f && x[(std::size_t) i] >= 0.0f)
- {
- first = first < 0 ? i : first;
- last = i;
- ++crossings;
- }
- return crossings > 1 ? 48000.0 * (double) (crossings - 1) / (double) (last - first) : 0.0;
- };
- bool ok = true;
- auto check = [&ok, step] (bool good, const juce::String& what) {
- ok = ok && good;
- step ((good ? "ok " : "FAIL ") + what);
- };
- const auto idle = pump (20);
- engine->getMeters().takePeak (1, 0);
- check (rms (idle, 0, (int) idle.size()) < 1.0e-6, "idle: rms " + juce::String (rms (idle, 0, (int) idle.size()), 9));
- // 4 regions map to keys 60…63 (FL's automatic map); the editor's click: velocity 100 / 128
- engine->sendLiveNote (0, 60, 0.78125f, true);
- const auto first = pump (16); // 8192 frames = 171 ms, inside region 1 (250 ms)
- const auto meter = engine->getMeters().takePeak (1, 0);
- check (rms (first, 1024, 6000) > 0.01, "key 60 down: rms " + juce::String (rms (first, 1024, 6000), 6) + ", " + juce::String (hertz (first, 1024, 6000), 1) + " Hz");
- check (std::abs (hertz (first, 1024, 6000) - 200.0) < 4.0, "key 60 plays region 1 (200 Hz)");
- check (meter > 0.01f, "mixer track 1 meter peak " + juce::String (meter, 6));
- engine->sendLiveNote (0, 60, 0.0f, false);
- const auto tail = pump (60);
- check (rms (tail, (int) tail.size() - 4096, 4096) < 1.0e-5, "key 60 up: the end is silent, rms " + juce::String (rms (tail, (int) tail.size() - 4096, 4096), 9));
- engine->sendLiveNote (0, 62, 0.78125f, true);
- const auto third = pump (16);
- check (rms (third, 1024, 6000) > 0.01 && std::abs (hertz (third, 1024, 6000) - 600.0) < 8.0,
- "key 62 plays region 3 (600 Hz): rms " + juce::String (rms (third, 1024, 6000), 6) + ", " + juce::String (hertz (third, 1024, 6000), 1) + " Hz");
- engine->sendLiveNote (0, 62, 0.0f, false);
- engine->sendLiveNote (0, 72, 0.78125f, true); // a key without a region
- const auto none = pump (60);
- check (rms (none, (int) none.size() - 4096, 4096) < 1.0e-5, "key 72 (no region): silent, rms " + juce::String (rms (none, (int) none.size() - 4096, 4096), 9));
- engine->sendLiveNote (0, 72, 0.0f, false);
- step (ok ? "result=OK" : "result=FAILED");
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- });
- }
- // --renderaheadtest (round 190gq): see the command line above
- void runRenderAheadTest (const juce::File& report, const juce::StringArray& projects, int block, double seconds)
- {
- struct StandIn final : juce::AudioIODevice
- {
- explicit StandIn (int b) : juce::AudioIODevice ("renderahead", "test"), block (b) {}
- const int block;
- 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 { block }; }
- int getDefaultBufferSize() override { return block; }
- 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 block; }
- 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; }
- };
- struct Scenario
- {
- juce::String name;
- juce::File file; // a project, or none: the showcase song
- int mode = 0; // 0 Song mode from the start, 1 a loop region, 2 Pattern mode
- };
- auto scenarios = std::make_shared<std::vector<Scenario>>();
- scenarios->push_back ({ "showcase, Song mode", {}, 0 });
- scenarios->push_back ({ "showcase, a loop region wrapping mid-block", {}, 1 });
- scenarios->push_back ({ "showcase, Pattern mode", {}, 2 });
- for (const auto& p : projects)
- scenarios->push_back ({ juce::File (p).getFileName(), juce::File (p), 0 });
- auto text = std::make_shared<juce::String>();
- auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
- step ("render-ahead test: blocks of " + juce::String (block) + " at 48 kHz, " + juce::String (seconds, 1) + " s per run");
- auto outputs = std::make_shared<std::vector<std::vector<float>>>();
- auto ok = std::make_shared<bool> (true);
- auto run = std::make_shared<std::function<void (std::size_t, int)>>();
- *run = [this, scenarios, step, outputs, ok, run, block, seconds, report] (std::size_t index, int pass) {
- if (index >= scenarios->size())
- {
- lynx::renderAheadOption().store (true);
- step (juce::String ("result=") + (*ok ? "OK" : "FAIL"));
- setApplicationReturnValue (*ok ? 0 : 1);
- engine.reset();
- quit();
- return;
- }
- const auto& sc = (*scenarios)[index];
- lynx::renderAheadOption().store (pass == 1);
- engine = std::make_unique<lynx::AudioEngine>();
- engine->getDeviceManager().closeAudioDevice(); // the engine's callback is driven by hand below
- engine->setRenderAheadAlways (true); // (the showcase song is light: the app would leave it real-time)
- juce::String error;
- auto loaded = true;
- if (sc.file == juce::File())
- {
- auto song = lynx::makeShowcaseSong (0);
- if (sc.mode == 1)
- {
- song.loopStart = 4 * lynx::ppq * song.beatsPerBar + 37; // (not on a block boundary)
- song.loopEnd = 6 * lynx::ppq * song.beatsPerBar + 211;
- song.loopOff = false;
- }
- if (sc.mode == 2)
- song.mode = lynx::PlayMode::pattern;
- engine->setSong (std::move (song));
- }
- else if (sc.file.hasFileExtension ("flp"))
- loaded = engine->importFlpFile (sc.file, error);
- else if (auto song = lynx::ProjectFile::load (sc.file, error))
- engine->setSong (std::move (*song));
- else
- loaded = false;
- if (! loaded)
- {
- step ("FAIL " + sc.name + ": " + error);
- *ok = false;
- (*run) (index + 1, 0);
- return;
- }
- auto device = std::make_shared<StandIn> (block);
- engine->deviceCallback().audioDeviceAboutToStart (device.get());
- // the graph is (re)built on the message thread: the run starts once it has settled
- juce::Timer::callAfterDelay (1500, [this, scenarios, step, outputs, ok, run, block, seconds, index, pass, device] {
- if (engine == nullptr)
- return;
- const auto& sc = (*scenarios)[index];
- auto& cb = engine->deviceCallback();
- std::vector<float> l ((std::size_t) block), r ((std::size_t) block), out;
- float* outs[] = { l.data(), r.data() };
- juce::AudioIODeviceCallbackContext context;
- engine->stop();
- engine->seek (0.0);
- cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, block, context); // (the seek, stopped)
- engine->play();
- const auto blocks = (int) (seconds * 48000.0 / block);
- const auto t0 = juce::Time::getMillisecondCounterHiRes();
- for (int k = 0; k < blocks; ++k)
- {
- cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, block, context);
- out.insert (out.end(), l.begin(), l.end());
- out.insert (out.end(), r.begin(), r.end());
- // (about the device's pace at the start of each second, so the render-ahead thread gets ahead)
- if (k % (48000 / block) < 48000 / block / 2)
- std::this_thread::sleep_for (std::chrono::microseconds ((int) (block * 1.0e6 / 48000.0 * 0.6)));
- }
- const auto ms = juce::Time::getMillisecondCounterHiRes() - t0;
- engine->stop();
- cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, block, context);
- const auto* st = engine->renderAheadStats();
- auto n = [] (const std::atomic<std::uint64_t>& v) { return (juce::int64) v.load(); };
- juce::String line = sc.name + (pass == 1 ? ", render ahead on: " : ", render ahead off: ") + juce::String (ms / 1000.0, 1) + " s";
- if (st != nullptr && pass == 1)
- line << "; blocks " << n (st->blocks) << ", from the ring " << n (st->fromRing) << ", waited " << n (st->waited) << ", in the callback "
- << n (st->inline_) << ", dropped " << n (st->flushes) << ", drained " << n (st->drains) << ", started " << n (st->engagements)
- << ", boundary mismatches " << n (st->splitMismatches) << "; ahead " << st->aheadChannels.load() << " channels / "
- << st->aheadTracks.load() << " inserts, boundary " << st->boundary.load() << ", window " << st->window.load();
- step (" " + line);
- if (pass == 0)
- {
- outputs->assign (1, std::move (out));
- (*run) (index, 1);
- return;
- }
- const auto& off = outputs->front();
- std::size_t first = off.size() == out.size() ? off.size() : 0;
- for (std::size_t s = 0; s < std::min (off.size(), out.size()); ++s)
- if (std::memcmp (&off[s], &out[s], sizeof (float)) != 0)
- {
- first = s;
- break;
- }
- const auto same = off.size() == out.size() && first == off.size();
- const auto clean = st != nullptr && st->flushes.load() == 0 && st->splitMismatches.load() == 0 && st->engagements.load() >= 1
- && st->fromRing.load() > st->blocks.load() / 4;
- *ok = *ok && same && clean;
- step (juce::String (same && clean ? "ok " : "FAIL ") + sc.name + ": " + (same ? "bit-identical" : "differs from sample " + juce::String ((juce::int64) first / 2 % block) + " of block " + juce::String ((juce::int64) first / 2 / block))
- + (clean ? "" : ", render-ahead counters off (see above)"));
- (*run) (index + 1, 0);
- });
- };
- (*run) (0, 0);
- }
- 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;
- // (round 177c: LYNX_RECTEST_BLEND_OFF=1: Blend off; LYNX_RECTEST_LAST_PASS=1: "only the last pass plays")
- o.mode = juce::SystemStats::getEnvironmentVariable ("LYNX_RECTEST_BLEND_OFF", {}) == "1" ? lynx::RecordMode::replace
- : lynx::RecordMode::overdub;
- o.lastLoopPassPlays = juce::SystemStats::getEnvironmentVariable ("LYNX_RECTEST_LAST_PASS", {}) == "1";
- 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;
- }
- report.getSiblingFile (report.getFileNameWithoutExtension() + "-project.lynx").replaceWithText (lynx::ProjectFile::toJson (engine->getSong()));
- 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;flm;songtmpl"))
- 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|als) 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 runAlsExport (const juce::String& inputPath, const juce::String& folderPath, bool live11, bool reference)
- {
- juce::String error;
- juce::StringArray notes;
- juce::File als;
- {
- lynx::AudioEngine loader (false);
- const juce::File input (inputPath);
- bool ok = false;
- // --scan: the targeted plugin scan an open runs first (child processes), so the set's plugins load
- if (juce::JUCEApplication::getCommandLineParameterArray().contains ("--scan") && input.hasFileExtension ("flp;als;flm;songtmpl"))
- {
- juce::MemoryBlock data;
- if (input.loadFileAsData (data))
- {
- const std::vector<std::uint8_t> bytes (static_cast<const std::uint8_t*> (data.getData()),
- static_cast<const std::uint8_t*> (data.getData()) + data.getSize());
- try
- {
- const auto uses = input.hasFileExtension ("als") ? lynx::alsForeignPlugins (bytes)
- : lynx::flpForeignPlugins (flp::parseProject ({ bytes.data(), bytes.size() }));
- loader.getPluginHost().scanFiles (loader.getPluginHost().filesToScanFor (uses), {});
- }
- catch (const std::exception&)
- {
- }
- }
- }
- if (input.hasFileExtension ("flp;als;flm;songtmpl"))
- ok = loader.importFlpFile (input, error);
- else if (auto song = lynx::ProjectFile::load (input, error))
- {
- loader.setSong (std::move (*song));
- ok = true;
- }
- if (ok)
- {
- loader.capturePluginStates();
- const juce::File folder (folderPath);
- folder.createDirectory();
- als = lynx::writeAlsProject (loader.getSong(), &loader.getPluginHost(), live11 ? lynx::AlsVersion::live11 : lynx::AlsVersion::live12, ! reference, folder,
- input.getFileNameWithoutExtension(), notes, error);
- }
- }
- juce::String report;
- report << (als != juce::File() ? "ok " + als.getFullPathName() : "error=" + error) << "\n" << notes.joinIntoString ("\n") << "\n";
- juce::File (folderPath).getChildFile ("export-als.txt").replaceWithText (report);
- setApplicationReturnValue (als != juce::File() ? 0 : 1);
- quit();
- }
- // --versionsshot <prefix> (round 190ap): everything the round adds, offscreen (no window on the desktop):
- // -versions.png / -versions-unsaved.png the Versions panel (a project with versions, backups and labels; a new one)
- // -menu-file.png / -menu-file-pluginsoff.png the File menu, and as it is while the plugins are off
- // -pluginsoff-window.png / -pluginsoff-mixer.png a project opened without its third-party plugins (the tags)
- // -pluginsoff-panel.png / -pluginsoff-panel-one.png the list, all off, then after "Switch on" for one
- // -export-default.png / -export.png the Export window as it opens, and with the additions in use
- bool runLinkShot (const juce::String& prefix)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- juce::StringArray report;
- bool allOk = true;
- const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
- report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
- allOk = allOk && ok;
- };
- const auto shoot = [&prefix] (juce::Component& c, const char* name) {
- savePng (c.createComponentSnapshot (c.getLocalBounds()), prefix + "-" + name + ".png");
- };
- using lynx::AutomationTarget;
- using lynx::AutomationTargetKind;
- using lynx::MidiLink;
- lynx::AudioEngine engine (false);
- const AutomationTarget volume { AutomationTargetKind::channelVolume, 0 }, pan { AutomationTargetKind::channelPan, 0 },
- insert { AutomationTargetKind::mixerVolume, 1 };
- // ---- the window as it opens on a control with no link (FL's defaults)
- {
- auto panel = lynx::makeRemoteControlPanel (engine, { volume }, false);
- shoot (*panel, "remote-default");
- check ("default_state", lynx::remoteControlPanelState (*panel).startsWith ("-1|1|-1|Input|"), lynx::remoteControlPanelState (*panel));
- // Auto detect: the controller that sends next fills the fields
- engine.injectControllerForTest (74, 2, 100, 5);
- lynx::remoteControlPanelPoll (*panel);
- check ("auto_detect", lynx::remoteControlPanelState (*panel).startsWith ("5|3|74|"), lynx::remoteControlPanelState (*panel));
- // a formula preset, smoothing; Accept writes the link
- lynx::remoteControlPanelSetController (*panel, -1, 1, 7);
- lynx::remoteControlPanelSetFormula (*panel, "Tension(Input,10)");
- lynx::remoteControlPanelSetSmoothing (*panel, true, 469);
- shoot (*panel, "remote-formula-smoothing");
- lynx::remoteControlPanelPress (*panel, 2);
- const auto& links = engine.getSong().midiLinks;
- check ("accept_writes_link", links.size() == 1 && links[0].cc == 7 && links[0].channel == 0 && links[0].port == -1
- && links[0].formula == "Tension(Input,10)" && links[0].smooth && links[0].target == volume);
- }
- // ---- a broken formula: the message, the red text
- {
- auto panel = lynx::makeRemoteControlPanel (engine, { volume }, false);
- lynx::remoteControlPanelSetFormula (*panel, "Min(Input*2,");
- shoot (*panel, "remote-formula-error");
- check ("formula_error_shown", ! lynx::remoteControlPanelState (*panel).contains ("Compiled ok."), lynx::remoteControlPanelState (*panel));
- }
- // ---- the engine: formula, port, conflicts, omni
- {
- engine.editSong ([&] (lynx::Song& s) {
- s.midiLinks.clear();
- MidiLink inverted { 20, 0, volume };
- inverted.formula = "1-Input";
- MidiLink ported { 21, 0, pan };
- ported.port = 3;
- s.midiLinks = { inverted, ported };
- });
- engine.injectControllerForTest (20, 0, 127);
- check ("formula_inverts", std::abs (engine.currentTargetValue (volume)) < 0.01f, juce::String (engine.currentTargetValue (volume)));
- engine.injectControllerForTest (20, 0, 0);
- check ("formula_inverts_back", std::abs (engine.currentTargetValue (volume) - 1.0f) < 0.01f, juce::String (engine.currentTargetValue (volume)));
- const auto panBefore = engine.currentTargetValue (pan);
- engine.injectControllerForTest (21, 0, 127); // no port: not this link's device
- check ("port_must_match", std::abs (engine.currentTargetValue (pan) - panBefore) < 0.001f);
- engine.injectControllerForTest (21, 0, 127, 3);
- check ("port_matches", std::abs (engine.currentTargetValue (pan) - 1.0f) < 0.01f, juce::String (engine.currentTargetValue (pan)));
- // the window on a control whose controller another control uses: Remove conflicts in red; Accept removes it
- auto panel = lynx::makeRemoteControlPanel (engine, { insert }, false);
- lynx::remoteControlPanelSetController (*panel, -1, 1, 20);
- shoot (*panel, "remote-conflict");
- check ("conflict_counted", lynx::remoteControlPanelState (*panel).contains ("|1|"), lynx::remoteControlPanelState (*panel));
- lynx::remoteControlPanelPress (*panel, 2);
- const auto& links = engine.getSong().midiLinks;
- check ("conflict_removed", links.size() == 2
- && std::none_of (links.begin(), links.end(), [&] (const MidiLink& l) { return l.target == volume; })
- && std::any_of (links.begin(), links.end(), [&] (const MidiLink& l) { return l.target == insert && l.cc == 20; }));
- engine.undo();
- check ("accept_is_one_undo_step", engine.getSong().midiLinks.size() == 2 && engine.getSong().midiLinks[0].target == volume);
- }
- // ---- an existing link opened again: "Link 1" / "New link"
- {
- auto panel = lynx::makeRemoteControlPanel (engine, { volume }, false);
- shoot (*panel, "remote-existing-link");
- check ("existing_link_loaded", lynx::remoteControlPanelState (*panel).startsWith ("-1|1|20|1-Input|"), lynx::remoteControlPanelState (*panel));
- // Reset, then Accept: a link without a controller is removed
- lynx::remoteControlPanelPress (*panel, 0);
- check ("reset_state", lynx::remoteControlPanelState (*panel).startsWith ("-1|1|-1|Input|"), lynx::remoteControlPanelState (*panel));
- lynx::remoteControlPanelPress (*panel, 2);
- const auto& links = engine.getSong().midiLinks;
- check ("reset_accept_unlinks", std::none_of (links.begin(), links.end(), [&] (const MidiLink& l) { return l.target == volume; }));
- }
- // ---- several controls ("Link to controllers..."): Accept and Skip step through them
- {
- auto panel = lynx::makeRemoteControlPanel (engine, { volume, pan, insert }, false, [] {});
- shoot (*panel, "remote-multilink");
- const auto parameter = [&panel] { return juce::StringArray::fromTokens (lynx::remoteControlPanelState (*panel), "|", "")[6]; };
- const auto first = parameter();
- check ("multilink_caption_and_skip", first.startsWith ("1/3") && first.contains (lynx::tr ("Channel volume"))
- && lynx::remoteControlPanelState (*panel).contains ("S|omni"),
- lynx::remoteControlPanelState (*panel));
- lynx::remoteControlPanelSetController (*panel, -1, 1, 30);
- lynx::remoteControlPanelPress (*panel, 2); // Accept: volume linked, on to pan
- const auto second = parameter();
- lynx::remoteControlPanelPress (*panel, 1); // Skip: pan untouched, on to the insert
- const auto third = parameter();
- const auto beforeLast = lynx::remoteControlPanelFinished (*panel);
- lynx::remoteControlPanelPress (*panel, 1); // Skip on the last one: done
- const auto closed = ! beforeLast && lynx::remoteControlPanelFinished (*panel);
- const auto& links = engine.getSong().midiLinks;
- check ("multilink_steps", first != second && second != third && closed
- && std::any_of (links.begin(), links.end(), [&] (const MidiLink& l) { return l.target == volume && l.cc == 30; }),
- first + " > " + second + " > " + third);
- }
- // ---- Global link settings
- {
- auto panel = lynx::makeRemoteControlPanel (engine, { volume }, true);
- shoot (*panel, "global-default");
- lynx::remoteControlPanelSetController (*panel, 2, 1, 11);
- lynx::remoteControlPanelSetFormula (*panel, "Input*0.5");
- lynx::remoteControlPanelPress (*panel, 2);
- const auto global = engine.globalLinkOf (volume);
- check ("global_link_written", global && global->cc == 11 && global->port == 2 && global->formula == "Input*0.5");
- const auto text = engine.getMidiPrefs().toText();
- const auto back = lynx::prefs::MidiPrefs::fromText (text);
- check ("global_link_settings_round_trip", back.globalLinks == engine.getMidiPrefs().globalLinks && text.find ("linkset=2|0|469|Input*0.5") != std::string::npos);
- auto again = lynx::makeRemoteControlPanel (engine, { volume }, true);
- shoot (*again, "global-existing-link");
- engine.setGlobalLink (volume, std::nullopt);
- check ("global_link_removed", ! engine.globalLinkOf (volume));
- }
- // ---- the project file: links with settings come back; a project of an older version loads the same
- {
- lynx::Song song = engine.getSong();
- MidiLink plain { 7, -1, volume };
- MidiLink rich { 74, 2, pan };
- rich.port = 4;
- rich.formula = "Min(Input*1.1,0.5)+Max(Input*1.1,0.6)-0.6";
- rich.smooth = true;
- rich.smoothing = -300;
- rich.omni = true;
- song.midiLinks = { plain, rich };
- juce::String error;
- const auto json = lynx::ProjectFile::toJson (song);
- const auto back = lynx::ProjectFile::fromJson (json, error);
- check ("project_round_trip", back && back->midiLinks == song.midiLinks, error);
- // without settings the file holds only the list older versions wrote
- song.midiLinks = { plain };
- const auto plainJson = lynx::ProjectFile::toJson (song);
- check ("plain_links_write_the_old_form", ! plainJson.contains ("midiLinkSettings") && plainJson.contains ("midiLinks"));
- const auto plainBack = lynx::ProjectFile::fromJson (plainJson, error);
- check ("old_project_loads_the_same", plainBack && plainBack->midiLinks.size() == 1 && plainBack->midiLinks[0] == plain
- && ! plainBack->midiLinks[0].hasSettings());
- // what an older version does with a new file: it reads "midiLinks" alone, so the links stay (plain)
- auto parsed = juce::JSON::parse (json);
- if (auto* o = parsed.getDynamicObject())
- o->removeProperty ("midiLinkSettings");
- const auto stripped = lynx::ProjectFile::fromJson (juce::JSON::toString (parsed), error);
- check ("older_version_keeps_the_links", stripped && stripped->midiLinks.size() == 2 && stripped->midiLinks[1].cc == 74
- && ! stripped->midiLinks[1].hasSettings());
- }
- // ---- round 190cs: FL's live answers (live check 190cq) and the note / button link modes
- {
- const auto state = [] (juce::Component& p) { return lynx::remoteControlPanelState (p); };
- engine.editSong ([] (lynx::Song& s) { s.midiLinks.clear(); });
- // the layout FL shows: no assignment list without a link, no Skip outside Multilink, no internal
- // controller group without a controller in the project; the parameter caption in FL's words
- auto fresh = lynx::makeRemoteControlPanel (engine, { volume }, false);
- shoot (*fresh, "cs-remote-default");
- check ("cs_layout_without_link", state (*fresh).contains ("|" + lynx::tr ("Channel volume") + "|") && state (*fresh).contains ("|shown=POC|"), state (*fresh));
- // Omni: enabled on a mixer track's volume (FL: "Insert 1 - Volume"), greyed on the tempo
- auto onInsert = lynx::makeRemoteControlPanel (engine, { insert }, false);
- auto onTempo = lynx::makeRemoteControlPanel (engine, { AutomationTarget { AutomationTargetKind::tempo, 0 } }, false);
- shoot (*onInsert, "cs-remote-omni-insert");
- check ("cs_omni_mixer_track", state (*onInsert).contains ("|omni=on|") && state (*onTempo).contains ("|omni=off|"),
- state (*onInsert) + " / " + state (*onTempo));
- // the formula compiles on Enter only; FL's messages and colours
- lynx::remoteControlPanelSetFormula (*fresh, "1-Input^2", false);
- check ("cs_no_compile_while_typing", state (*fresh).contains ("|" + lynx::tr ("(default 1:1 mapping)") + "|"), state (*fresh));
- lynx::remoteControlPanelSetFormula (*fresh, "-Input^2");
- shoot (*fresh, "cs-remote-compiled");
- check ("cs_compiled_on_enter", state (*fresh).contains ("|" + lynx::tr ("Compiled ok.") + "|"), state (*fresh));
- const std::pair<const char*, const char*> errors[] { { "Input*", "Syntax error: function or operand" },
- { "foo(Input)", "Invalid identifier: foo" },
- { "Sin(Input", "Unequal brackets" },
- { "Input 2", "input two space limited" } };
- for (const auto& [text, expected] : errors)
- {
- lynx::remoteControlPanelSetFormula (*fresh, text);
- check ("cs_fl_error_text", state (*fresh).contains (expected), state (*fresh));
- }
- lynx::remoteControlPanelSetFormula (*fresh, "foo(Input)");
- shoot (*fresh, "cs-remote-error");
- // Accept with that formula: the link is made, the formula is not kept (FL reopens it as "Input")
- lynx::remoteControlPanelSetController (*fresh, -1, 1, 7);
- lynx::remoteControlPanelPress (*fresh, 2);
- check ("cs_bad_formula_accept_is_input", engine.getSong().midiLinks.size() == 1 && engine.getSong().midiLinks[0].cc == 7
- && engine.getSong().midiLinks[0].formula.empty());
- auto reopened = lynx::makeRemoteControlPanel (engine, { volume }, false);
- shoot (*reopened, "cs-remote-reopened");
- check ("cs_reopened_shows_input_and_link_list", state (*reopened).startsWith ("-1|1|7|Input|" + lynx::tr ("(default 1:1 mapping)") + "|")
- && state (*reopened).contains ("|shown=PAOC|"),
- state (*reopened));
- // the internal controller group appears with a controller in the project, with "Record automation"
- engine.editSong ([] (lynx::Song& s) {
- lynx::EffectSlot peak;
- peak.kind = lynx::EffectKind::peakController;
- s.mixer[0].effects.push_back (peak);
- });
- auto withController = lynx::makeRemoteControlPanel (engine, { volume }, false);
- lynx::remoteControlPanelSetInternal (*withController, 1, true);
- shoot (*withController, "cs-remote-internal");
- check ("cs_internal_group_shown", state (*withController).contains ("|shown=PAIOC|") && state (*withController).startsWith ("-1|1|-1|"),
- state (*withController));
- lynx::remoteControlPanelPress (*withController, 2);
- const auto& autos = engine.getSong().automations;
- check ("cs_record_automation_kept", std::any_of (autos.begin(), autos.end(), [&] (const lynx::Automation& a) {
- return a.isLive() && a.target == volume && a.recordLive;
- }));
- engine.editSong ([] (lynx::Song& s) {
- s.mixer[0].effects.pop_back();
- s.automations.clear();
- s.midiLinks.clear();
- });
- // the global window: no parameter list, Omni, Remove conflicts or Skip; Mode is there
- auto globalPanel = lynx::makeRemoteControlPanel (engine, { volume }, true);
- shoot (*globalPanel, "cs-global-default");
- check ("cs_global_layout", state (*globalPanel).contains ("|shown=|"), state (*globalPanel));
- // a key link in each Mode: note 60 = FL's controller number 256 + 60
- const auto key = lynx::linkNoteBase + 60;
- auto modePanel = lynx::makeRemoteControlPanel (engine, { volume }, false);
- lynx::remoteControlPanelSetController (*modePanel, -1, 1, key);
- lynx::remoteControlPanelSetMode (*modePanel, 2);
- shoot (*modePanel, "cs-remote-note-latch");
- lynx::remoteControlPanelPress (*modePanel, 2);
- check ("cs_note_link_written", engine.getSong().midiLinks.size() == 1 && engine.getSong().midiLinks[0].cc == key
- && engine.getSong().midiLinks[0].mode == 2);
- const auto play = [&engine, key, volume] (int velocity) {
- engine.injectControllerForTest (key, 0, velocity);
- return engine.currentTargetValue (volume);
- };
- const auto setMode = [&engine] (int mode) {
- engine.editSong ([mode] (lynx::Song& s) { s.midiLinks[0].mode = mode; });
- engine.editSong ([] (lynx::Song& s) { s.setTargetValue ({ AutomationTargetKind::channelVolume, 0 }, 0.25f); });
- };
- setMode (2); // Latch: press switches, release does nothing
- const auto l1 = play (100), l1off = play (0), l2 = play (90), l2off = play (0);
- check ("cs_mode_latch", std::abs (l1 - 1.0f) < 1e-4f && std::abs (l1off - 1.0f) < 1e-4f && l2 < 1e-4f && l2off < 1e-4f,
- juce::String (l1) + " " + juce::String (l1off) + " " + juce::String (l2) + " " + juce::String (l2off));
- setMode (1); // Hold: the velocity while held, back to 0 on release
- const auto h1 = play (100), h1off = play (0);
- check ("cs_mode_hold", std::abs (h1 - 100.0f / 127.0f) < 1e-4f && h1off < 1e-4f, juce::String (h1) + " " + juce::String (h1off));
- setMode (0); // Default: as Hold for a key
- const auto d1 = play (64), d1off = play (0);
- check ("cs_mode_default", std::abs (d1 - 64.0f / 127.0f) < 1e-4f && d1off < 1e-4f, juce::String (d1) + " " + juce::String (d1off));
- setMode (3); // Inc: each press adds 1/128
- const auto i1 = play (100), i1off = play (0), i2 = play (20);
- check ("cs_mode_inc", std::abs (i1 - (0.25f + 1.0f / 128.0f)) < 1e-4f && std::abs (i1off - i1) < 1e-6f
- && std::abs (i2 - (0.25f + 2.0f / 128.0f)) < 1e-4f,
- juce::String (i1) + " " + juce::String (i2));
- setMode (4); // Stay: the velocity, kept after the release
- const auto s1 = play (100), s1off = play (0);
- check ("cs_mode_stay", std::abs (s1 - 100.0f / 127.0f) < 1e-4f && std::abs (s1off - s1) < 1e-6f, juce::String (s1) + " " + juce::String (s1off));
- // the project file keeps the key link and its mode; an older reader skips it
- lynx::Song song = engine.getSong();
- song.midiLinks[0].mode = 2;
- MidiLink cc7 { 7, 0, pan };
- cc7.mode = 4;
- song.midiLinks.insert (song.midiLinks.begin(), cc7);
- juce::String error;
- const auto json = lynx::ProjectFile::toJson (song);
- const auto back = lynx::ProjectFile::fromJson (json, error);
- check ("cs_note_link_round_trip", back && back->midiLinks == song.midiLinks && json.contains ("midiNoteLinks"), error);
- auto parsed = juce::JSON::parse (json);
- if (auto* o = parsed.getDynamicObject())
- {
- o->removeProperty ("midiNoteLinks");
- o->removeProperty ("midiLinkSettings");
- }
- const auto older = lynx::ProjectFile::fromJson (juce::JSON::toString (parsed), error);
- check ("cs_older_reader_keeps_cc_links_only", older && older->midiLinks.size() == 1 && older->midiLinks[0].cc == 7);
- // "Record automation" of an internal-controller link, saved only when on
- lynx::Automation live;
- live.target = volume;
- live.source.track = 0;
- live.recordLive = true;
- song.automations = { live };
- const auto withLive = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
- live.recordLive = false;
- song.automations = { live };
- check ("cs_record_automation_round_trip", withLive && withLive->automations.size() == 1 && withLive->automations[0].recordLive
- && ! lynx::ProjectFile::toJson (song).contains ("recordLive"));
- engine.editSong ([] (lynx::Song& s) { s.midiLinks.clear(); });
- }
- // ---- menus: the control menu, the formula presets, the controller list, the Multilink items
- {
- juce::PopupMenu control;
- lynx::addAutomationItem (control, engine, volume, true);
- engine.setMultilink (true);
- engine.noteTweaked (volume);
- engine.noteTweaked (pan);
- juce::PopupMenu multilink;
- lynx::addMultilinkControlsItems (multilink, engine);
- check ("multilink_queue", engine.multilinkTargets().size() == 2);
- engine.setMultilink (false);
- saveMenus (juce::StringArray { "Control menu", "Formula presets", "Multilink" },
- std::vector<juce::PopupMenu> { control, lynx::remoteControlFormulaMenu ([] (const juce::String&) {}), multilink },
- prefix + "-menus.png");
- saveMenus (juce::StringArray { "Ctrl menu" }, std::vector<juce::PopupMenu> { lynx::remoteControlControllerMenu ([] (int) {}) },
- prefix + "-ctrl-menu.png");
- // the Mode list as its box pops it up (round 190cs)
- juce::PopupMenu modes;
- for (const char* m : { "Default", "Hold", "Latch", "Inc", "Stay" })
- modes.addItem (lynx::tr (m), true, juce::String (m) == "Default", [] {});
- saveMenus (juce::StringArray { "Mode" }, std::vector<juce::PopupMenu> { modes }, prefix + "-mode-menu.png");
- }
- // ---- Settings > MIDI: the input's Port box, the link list with a link's settings
- {
- engine.editSong ([&] (lynx::Song& s) {
- MidiLink l { 74, 2, pan };
- l.port = 4;
- l.formula = "1-Input";
- l.smooth = true;
- s.midiLinks = { MidiLink { 7, 0, volume }, l };
- });
- auto page = lynx::makeMidiPage (engine, {}, false);
- page->setSize (760, 900);
- shoot (*page, "settings-midi");
- }
- juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
- return allOk;
- }
- // A stand-in hosted plugin for the shot route: three parameters, its state = their values
- struct FlCtlShotPlugin final : juce::AudioPluginInstance
- {
- FlCtlShotPlugin()
- {
- for (const char* n : { "Cutoff", "Resonance", "Drive" })
- addHostedParameter (std::make_unique<juce::AudioParameterFloat> (juce::ParameterID (n, 1), n, 0.0f, 1.0f, 0.5f));
- }
- const juce::String getName() const override { return "Shot plugin"; }
- void prepareToPlay (double, int) override {}
- void releaseResources() override {}
- void processBlock (juce::AudioBuffer<float>&, juce::MidiBuffer&) override {}
- double getTailLengthSeconds() const override { return 0.0; }
- bool acceptsMidi() const override { return false; }
- bool producesMidi() const override { return false; }
- juce::AudioProcessorEditor* createEditor() override { return nullptr; }
- bool hasEditor() const override { return false; }
- int getNumPrograms() override { return 1; }
- int getCurrentProgram() override { return 0; }
- void setCurrentProgram (int) override {}
- const juce::String getProgramName (int) override { return {}; }
- void changeProgramName (int, const juce::String&) override {}
- void getStateInformation (juce::MemoryBlock& b) override
- {
- for (auto* p : getParameters())
- {
- const float v = static_cast<juce::AudioParameterFloat*> (p)->get();
- b.append (&v, sizeof (float));
- }
- }
- void setStateInformation (const void* data, int size) override
- {
- const auto& list = getParameters();
- for (int i = 0; i < list.size() && (i + 1) * (int) sizeof (float) <= size; ++i)
- *static_cast<juce::AudioParameterFloat*> (list[i]) = static_cast<const float*> (data)[i];
- }
- void fillInPluginDescription (juce::PluginDescription& d) const override
- {
- d.name = getName();
- d.pluginFormatName = "Shot";
- d.fileOrIdentifier = "shot";
- }
- };
- static juce::File writeShotSample (const juce::File& file, double hz)
- {
- juce::AudioBuffer<float> buffer (1, 22050);
- for (int i = 0; i < buffer.getNumSamples(); ++i)
- buffer.setSample (0, i, (float) (std::sin (juce::MathConstants<double>::twoPi * hz * i / 44100.0) * std::exp (-i / 6000.0)));
- file.deleteFile();
- juce::WavAudioFormat wav;
- if (auto out = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (file.createOutputStream().release(), 44100.0, 1, 16, {}, 0)))
- out->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
- return file;
- }
- static bool clickMenuItem (const juce::PopupMenu& menu, const juce::String& text)
- {
- for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
- if (it.getItem().text == text && it.getItem().isEnabled && it.getItem().action != nullptr)
- {
- it.getItem().action();
- return true;
- }
- return false;
- }
- // --samplerpageshot <prefix> (round 190dh): FL's Sampler page offscreen — the page as FL's shot (dock188a) shows it,
- // the legacy effects, a small window, a zoomed waveform — and its laws turned as a user would; prefix-checks.txt
- bool runSamplerPageShot (const juce::String& prefix)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- juce::StringArray report;
- bool allOk = true;
- const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
- report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
- allOk = allOk && ok;
- };
- const auto shoot = [&prefix] (juce::Component& c, const char* name) {
- savePng (c.createComponentSnapshot (c.getLocalBounds()), prefix + "-" + name + ".png");
- };
- lynx::AudioEngine engine (false);
- const auto folder = juce::File (prefix).getParentDirectory().getChildFile ("sampler-samples");
- folder.createDirectory();
- // an 808-like kick, 1 s (FL's shot: "Basic 808 Kick.wav")
- const auto kick = folder.getChildFile ("Basic 808 Kick.wav");
- {
- juce::AudioBuffer<float> buffer (1, 44100);
- double phase = 0.0;
- for (int i = 0; i < buffer.getNumSamples(); ++i)
- {
- const auto t = i / 44100.0;
- phase += juce::MathConstants<double>::twoPi * (48.0 + 90.0 * std::exp (-t * 30.0)) / 44100.0;
- buffer.setSample (0, i, (float) (0.9 * std::sin (phase) * std::exp (-t * 3.2)));
- }
- kick.deleteFile();
- juce::WavAudioFormat wav;
- if (auto out = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (kick.createOutputStream().release(), 44100.0, 1, 16, {}, 0)))
- out->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
- }
- engine.editSong ([&] (lynx::Song& s) {
- if (s.channels.empty())
- s.channels.resize (1);
- lynx::audioclips::loadSampleInto (s.channels[0], kick.getFullPathName().toStdString(), "808 Kick");
- // FL's shot: Resample and Load regions on, Use loop points on, declicking "Out only (no bleeding)"
- s.channels[0].sampler.resampleOnLoad = true;
- });
- const auto sampler = [&engine] { return engine.getSong().channels[0].sampler; };
- auto frame = lynx::makeChannelFrame (engine, 0, 0);
- frame->setSize (frame->getWidth() > 0 ? frame->getWidth() : 700, frame->getHeight() > 0 ? frame->getHeight() : 720);
- frame->createComponentSnapshot (frame->getLocalBounds()); // (starts the waveform's analysis)
- lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
- shoot (*frame, "sampler-page");
- report.add ("page size " + juce::String (frame->getWidth()) + "x" + juce::String (frame->getHeight()));
- // ---- the laws, turned on the page
- auto& f = *frame;
- lynx::samplerPageTurn (f, "pingPong", 1.0);
- check ("ping_pong", sampler().precompute.pingPong);
- lynx::samplerPageTurn (f, "pingPong", 0.0);
- lynx::samplerPageTurn (f, "loopStart", 5000.0);
- check ("loop_start", sampler().loopStart == 5000 && sampler().loopEnd == 5001, juce::String (sampler().loopStart) + "/" + juce::String (sampler().loopEnd));
- lynx::samplerPageTurn (f, "loopEnd", 15000.0);
- check ("loop_end", sampler().loopStart == 5000 && sampler().loopEnd == 15000);
- lynx::samplerPageTurn (f, "loopStart", 20000.0, true); // Shift: the loop moves
- check ("loop_shift_moves", sampler().loopStart == 20000 && sampler().loopEnd == 30000, juce::String (sampler().loopStart) + "/" + juce::String (sampler().loopEnd));
- check ("keep_on_disk_greyed_with_loop", lynx::samplerPageQuery (f, "keepOnDisk") == "0");
- lynx::samplerPageTurn (f, "useLoops", 0.0);
- check ("keep_on_disk_back", lynx::samplerPageQuery (f, "keepOnDisk") == "1" && ! sampler().useLoopPoints);
- check ("not_cut_yet", ! lynx::channelCutsItself (engine.getSong().channels[0]));
- lynx::samplerPageTurn (f, "useLoops", 1.0);
- check ("use_loops_cuts_itself", sampler().useLoopPoints && lynx::channelCutsItself (engine.getSong().channels[0]));
- engine.editSong ([] (lynx::Song& s) {
- lynx::setChannelCutsItself (s.channels[0], 0, false);
- s.channels[0].sampler.useLoopPoints = false;
- });
- lynx::samplerPageTurn (f, "crossfade", 300.0); // (Use loop points off: the crossfade switches it on)
- check ("crossfade_switches_loops_on", sampler().precompute.crossfade == 300 && sampler().useLoopPoints);
- lynx::samplerPageTurn (f, "crossfade", 0.0);
- lynx::samplerPageTurn (f, "pitch", 300.0); // (Resample: FL switches to Auto)
- check ("pitch_resample_to_auto", sampler().keepPitch && sampler().flStretchMode == 5 && sampler().flStretchPitch == 300
- && lynx::samplerPageQuery (f, "mode") == lynx::tr ("General"),
- lynx::samplerPageQuery (f, "mode") + " " + juce::String (sampler().pitch));
- lynx::samplerPageTurn (f, "pitch", 0.0);
- lynx::samplerPageTurn (f, "mode", 1.0); // Resample
- check ("mode_resample", ! sampler().keepPitch && std::abs (sampler().pitch) < 1.0e-4f);
- lynx::samplerPageTurn (f, "time", 4.0);
- lynx::samplerPageTurn (f, "mul", 10000.0);
- check ("time_mul", std::abs (sampler().stretchBeats - 8.0f) < 1.0e-3f && sampler().stretchMul == 10000, juce::String (sampler().stretchBeats));
- lynx::samplerPageTurn (f, "mul", 0.0);
- lynx::samplerPageTurn (f, "time", 0.0);
- lynx::samplerPageTurn (f, "length", 0.5);
- lynx::samplerPageTurn (f, "smpStart", 0.5);
- check ("smp_start_keeps_length", std::abs (sampler().regionStart - 0.5f) < 1.0e-3f && std::abs (sampler().regionEnd - 0.75f) < 1.0e-3f,
- juce::String (sampler().regionStart) + "-" + juce::String (sampler().regionEnd));
- lynx::samplerPageTurn (f, "smpStart", 0.0);
- lynx::samplerPageTurn (f, "length", 1.0);
- lynx::samplerPageTurn (f, "declick", 4.0);
- check ("declick_mode", sampler().declickMode == 4);
- lynx::samplerPageTurn (f, "declick", 0.0);
- // ---- the .lynx keeps what the page set
- {
- lynx::samplerPageTurn (f, "mul", -5000.0);
- lynx::samplerPageTurn (f, "keepOnDisk", 1.0);
- juce::String error;
- const auto json = lynx::ProjectFile::toJson (engine.getSong(), false);
- const auto back = lynx::ProjectFile::fromJson (json, error);
- check ("lynx_round_trip", back.has_value() && back->channels[0].sampler == engine.getSong().channels[0].sampler, error);
- lynx::samplerPageTurn (f, "mul", 0.0);
- lynx::samplerPageTurn (f, "keepOnDisk", 0.0);
- }
- // ---- shots: FL's state again (loop points from the file: none), the legacy panel, a zoom, a small window
- engine.editSong ([] (lynx::Song& s) {
- auto& ch = s.channels[0];
- ch.sampler.loopStart = ch.sampler.loopEnd = -1;
- ch.sampler.useLoopPoints = true;
- ch.sampler.precompute = {};
- });
- lynx::samplerPageTurn (f, "show", 0.0); // (no control: the page shows the channel again)
- frame->createComponentSnapshot (frame->getLocalBounds());
- shoot (*frame, "sampler-page-fl-state");
- lynx::samplerPageTurn (f, "legacy", 1.0);
- check ("legacy_panel", lynx::samplerPageQuery (f, "legacy") == "1");
- shoot (*frame, "sampler-page-legacy");
- lynx::samplerPageTurn (f, "legacy", 0.0);
- lynx::samplerPageTurn (f, "zoom", 0.25);
- check ("zoom_scroll", lynx::samplerPageQuery (f, "scroll") == "0.250", lynx::samplerPageQuery (f, "scroll"));
- shoot (*frame, "sampler-page-zoom");
- lynx::samplerPageTurn (f, "zoom", 1.0);
- frame->setSize (520, 470);
- frame->createComponentSnapshot (frame->getLocalBounds());
- shoot (*frame, "sampler-page-small");
- report.add (juce::String ("result=") + (allOk ? "OK" : "FAIL"));
- juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\n");
- return allOk;
- }
- bool runFlCtlShot (const juce::String& prefix)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- juce::StringArray report;
- bool allOk = true;
- const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
- report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
- allOk = allOk && ok;
- };
- const auto shoot = [&prefix] (juce::Component& c, const char* name) {
- savePng (c.createComponentSnapshot (c.getLocalBounds()), prefix + "-" + name + ".png");
- };
- using lynx::AutomationTarget;
- using lynx::AutomationTargetKind;
- lynx::AudioEngine engine (false);
- engine.editSong ([] (lynx::Song& s) {
- if (s.channels.size() < 3)
- s.channels.resize (3);
- if (s.patterns.empty())
- s.patterns.resize (1);
- s.currentPattern = 0;
- });
- const AutomationTarget volume { AutomationTargetKind::channelVolume, 0 }, pan { AutomationTargetKind::channelPan, 0 };
- // ---- FL's multilink menu: on with two queued controls, off with the last tweaked parameters
- {
- engine.setMultilink (true);
- engine.noteTweaked (volume);
- engine.noteTweaked (pan);
- auto on = lynx::multilinkButtonMenu (engine);
- juce::PopupMenu::MenuItemIterator first (on);
- first.next();
- check ("ml_caption_on", first.getItem().isSectionHeader && first.getItem().text == lynx::tr ("{0} parameters selected", { "2" }), first.getItem().text);
- // Init pattern: the values at the pattern's start; ends multilink
- const auto v0 = engine.currentTargetValue (volume);
- lynx::runMultilinkAction (engine, lynx::mlmenu::Action::initPattern, engine.multilinkTargets(), 0);
- const auto& lanes = engine.getSong().patterns[0].events;
- check ("ml_init_pattern", lanes.size() == 2 && ! lanes[0].events.empty() && lanes[0].events[0].tick == 0
- && std::abs (lanes[0].events[0].value - v0) < 1.0e-6f && ! engine.isMultilinkOn());
- // Randomize keeps multilink on; Humanize moves at most an eighth
- engine.setMultilink (true);
- engine.noteTweaked (volume);
- engine.noteTweaked (pan);
- lynx::runMultilinkAction (engine, lynx::mlmenu::Action::randomize, engine.multilinkTargets(), 1234);
- check ("ml_randomize_keeps_queue", engine.isMultilinkOn() && engine.multilinkTargets().size() == 2);
- const auto before = engine.currentTargetValue (volume);
- lynx::runMultilinkAction (engine, lynx::mlmenu::Action::humanize, engine.multilinkTargets(), 99);
- check ("ml_humanize_small", std::abs (engine.currentTargetValue (volume) - before) <= 0.1251f && engine.isMultilinkOn(),
- juce::String (before) + " -> " + juce::String (engine.currentTargetValue (volume)));
- lynx::runMultilinkAction (engine, lynx::mlmenu::Action::initSong, engine.multilinkTargets(), 0);
- check ("ml_init_song", engine.getSong().findInitialValue (volume) >= 0 && ! engine.isMultilinkOn());
- // off: the last two tweaked parameters, no Cancel
- auto off = lynx::multilinkButtonMenu (engine);
- bool hasCancel = false;
- for (juce::PopupMenu::MenuItemIterator it (off); it.next();)
- hasCancel = hasCancel || it.getItem().text == lynx::tr ("Cancel");
- juce::PopupMenu::MenuItemIterator offFirst (off);
- offFirst.next();
- check ("ml_off_caption", offFirst.getItem().text == lynx::tr ("Last 2 tweaked parameters") && ! hasCancel, offFirst.getItem().text);
- // LYNX's own one-step items stay, after FL's items below a line (greyed while multilink is off)
- juce::String last;
- bool lineBefore = false, prevLine = false;
- for (juce::PopupMenu::MenuItemIterator it (on); it.next();)
- {
- if (it.getItem().text == lynx::tr ("Link to controller"))
- lineBefore = prevLine;
- prevLine = it.getItem().isSeparator;
- last = it.getItem().text;
- }
- check ("ml_lynx_items_after_fl", lineBefore && last == lynx::tr ("Override global links"), last);
- saveMenus (juce::StringArray { "Multilink on (2 queued)", "Multilink off" }, std::vector<juce::PopupMenu> { on, off },
- prefix + "-multilink-menu.png");
- }
- // ---- the plugin menu's spare state and Parameters > Link all parameters...
- {
- FlCtlShotPlugin plugin;
- juce::PopupMenu menu;
- lynx::addPluginWrapperItems (menu, engine, plugin, { AutomationTargetKind::channelParam, 1, 0, 0 });
- saveMenus (juce::StringArray { "Plugin menu: spare state and parameters" }, std::vector<juce::PopupMenu> { menu }, prefix + "-plugin-menu.png");
- const auto targets = lynx::allPluginParameterTargets (plugin, { AutomationTargetKind::channelParam, 1, 0, 0 });
- check ("link_all_parameters", targets.size() == 3 && targets[2].param == 2 && targets[2].index == 1);
- auto* cutoff = static_cast<juce::AudioParameterFloat*> (plugin.getParameters()[0]);
- *cutoff = 0.2f;
- check ("spare_store", clickMenuItem (menu, lynx::tr ("Store in spare state")));
- *cutoff = 0.9f;
- juce::PopupMenu again;
- lynx::addPluginWrapperItems (again, engine, plugin, { AutomationTargetKind::channelParam, 1, 0, 0 });
- check ("spare_flip", clickMenuItem (again, lynx::tr ("Flip with spare state")) && std::abs (cutoff->get() - 0.2f) < 1.0e-6f, juce::String (cutoff->get()));
- check ("spare_flip_back", clickMenuItem (again, lynx::tr ("Flip with spare state")) && std::abs (cutoff->get() - 0.9f) < 1.0e-6f, juce::String (cutoff->get()));
- lynx::sparestate::shared().forget (&plugin);
- }
- // ---- the sampler's File row: Load (history menu, wheel), Locate, Remove
- {
- const auto folder = juce::File (prefix).getParentDirectory().getChildFile ("flctl-samples");
- folder.createDirectory();
- const auto a = writeShotSample (folder.getChildFile ("Kick 1.wav"), 60.0), b = writeShotSample (folder.getChildFile ("Snare 2.wav"), 200.0),
- c = writeShotSample (folder.getChildFile ("Hat 3.wav"), 900.0);
- lynx::samplehistory::list().clear();
- engine.editSong ([&] (lynx::Song& s) {
- for (const auto& f : { c, b, a }) // (each load goes into the history, newest first)
- lynx::audioclips::loadSampleInto (s.channels[1], f.getFullPathName().toStdString(), f.getFileNameWithoutExtension().toStdString());
- });
- check ("history_order", lynx::samplehistory::list().size() == 3 && lynx::samplehistory::list().front() == a.getFullPathName().toStdString());
- juce::File located;
- lynx::locateInBrowserHandler() = [&located] (const juce::File& f) { located = f; };
- auto frame = lynx::makeChannelFrame (engine, 1, 0);
- frame->setSize (frame->getWidth() > 0 ? frame->getWidth() : 600, frame->getHeight() > 0 ? frame->getHeight() : 820);
- frame->createComponentSnapshot (frame->getLocalBounds()); // (starts the waveform's analysis)
- lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
- shoot (*frame, "sampler-file-row");
- const auto history = lynx::samplerHistoryMenu (*frame);
- check ("history_menu", history.has_value() && history->getNumItems() == 4); // (caption + three samples)
- if (history)
- saveMenus (juce::StringArray { "Load: Sample history" }, std::vector<juce::PopupMenu> { *history }, prefix + "-sample-history.png");
- lynx::samplerFileRowPress (*frame, 0); // wheel down: the next (older) sample
- check ("wheel_down", engine.getSong().channels[1].samplePath == b.getFullPathName().toStdString(), juce::String (engine.getSong().channels[1].samplePath));
- lynx::samplerFileRowPress (*frame, 1); // wheel up: back
- check ("wheel_up", engine.getSong().channels[1].samplePath == a.getFullPathName().toStdString());
- lynx::samplerFileRowPress (*frame, 2);
- check ("locate", located == a, located.getFullPathName());
- lynx::samplerFileRowPress (*frame, 3);
- check ("remove", engine.getSong().channels[1].samplePath.empty());
- engine.undo();
- check ("remove_undo", engine.getSong().channels[1].samplePath == a.getFullPathName().toStdString());
- lynx::locateInBrowserHandler() = nullptr;
- }
- // ---- a sampler running FL's voice: FL's Envelope / instrument page with the tensions, the predelay and presets
- {
- engine.editSong ([] (lynx::Song& s) {
- auto& ch = s.channels[2];
- ch.instrument = lynx::InstrumentKind::sampler;
- ch.name = "FL sampler";
- const auto snap = lynx::flvp::defaultSnapshot();
- ch.sampler.flChannel.assign (90, 0);
- std::memcpy (ch.sampler.flChannel.data(), snap.data(), 85 * 4);
- std::memcpy (&ch.sampler.flChannel[85], snap.data() + 0x15c, 4);
- std::memcpy (&ch.sampler.flChannel[86], snap.data() + 0x160, 4);
- std::memcpy (&ch.sampler.flChannel[87], snap.data() + 0x168, 4);
- ch.sampler.flChannel[88] = 96;
- ch.sampler.flChannel[89] = 0;
- auto& vol = ch.sampler.flChannel; // the volume envelope on, bent
- vol[17 + 1] = -1;
- vol[17 + 2] = 4000; // predelay
- vol[17 + 14] = -70; // attack tension
- vol[17 + 15] = 60; // decay tension
- vol[17 + 16] = -40; // release tension
- });
- auto frame = lynx::makeChannelFrame (engine, 2, 1);
- frame->setSize (frame->getWidth() > 0 ? frame->getWidth() : 600, frame->getHeight() > 0 ? frame->getHeight() : 560);
- shoot (*frame, "sampler-fl-envelope");
- check ("fl_page_shown", lynx::flVoicePresetsMenu (*frame).has_value());
- lynx::flVoicePresetFolder().deleteRecursively();
- check ("preset_save", lynx::flVoiceSavePreset (*frame, "Bent volume")
- && lynx::flVoicePresetFolder().getChildFile ("Bent volume.CHENV").getSize() == 68);
- if (const auto menu = lynx::flVoicePresetsMenu (*frame))
- saveMenus (juce::StringArray { "Channel envelope presets" }, std::vector<juce::PopupMenu> { *menu }, prefix + "-envelope-presets.png");
- // the preset into the pitch target: its record becomes the saved one
- lynx::showFlVoiceTarget (*frame, lynx::flvoice::pitch);
- const auto loaded = lynx::flVoiceLoadPreset (*frame, lynx::flVoicePresetFolder().getChildFile ("Bent volume.CHENV"));
- const auto& fl = engine.getSong().channels[2].sampler.flChannel;
- check ("preset_load", loaded && fl.size() == 90 && fl[68 + 2] == 4000 && fl[68 + 14] == -70 && fl[68 + 16] == -40 && fl[88] == 96);
- engine.undo();
- check ("preset_load_undo", engine.getSong().channels[2].sampler.flChannel[68 + 14] != -70);
- }
- juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
- return allOk;
- }
- // --flplshot (round 190dx): see the dispatch above
- bool runHdrShot190ft (const juce::String& prefix)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- juce::StringArray report;
- bool allOk = true;
- const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
- report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
- allOk = allOk && ok;
- };
- const auto list = [] (const std::vector<int>& v) {
- juce::StringArray out;
- for (auto i : v)
- out.add (juce::String (i));
- return out.joinIntoString (",");
- };
- lynx::AudioEngine engine (false);
- lynx::MainComponent ui (engine, false);
- ui.setSize (1600, 900);
- {
- auto song = lynx::Song::makeDefault();
- song.playlist.clear();
- for (int t = 0; t < 6; ++t)
- {
- if ((int) song.playlistTracks.size() <= t)
- song.playlistTracks.resize ((std::size_t) t + 1);
- song.playlistTracks[(std::size_t) t].name = juce::String ("Track " + juce::String (t + 1)).toStdString();
- for (int k = 0; k < 2; ++k)
- {
- lynx::Clip c;
- c.kind = lynx::ClipKind::pattern;
- c.pattern = 0;
- c.track = t;
- c.start = (std::int64_t) (k * 4 + t % 3) * lynx::ppq;
- c.length = 2 * lynx::ppq;
- song.playlist.push_back (c);
- }
- }
- if (song.mixer.size() < 4)
- song.mixer.resize (4);
- song.playlistTracks[2].mode = lynx::PlaylistTrackMode::audio; // an audio track linked to mixer track 3
- song.playlistTracks[2].mixerTrack = 3;
- song.playlistTracks[2].name = "Vox";
- engine.setSong (std::move (song));
- }
- engine.dispatchPendingMessages();
- ui.selectTabForSnapshot (2);
- engine.dispatchPendingMessages();
- auto& pl = ui.getPlaylistForSnapshot();
- pl.setSize (juce::jmax (pl.getWidth(), 900), juce::jmax (pl.getHeight(), 600));
- auto source = juce::Desktop::getInstance().getMainMouseSource();
- const auto now = juce::Time::getCurrentTime();
- const juce::ModifierKeys left (juce::ModifierKeys::leftButtonModifier);
- const int ctrl = juce::ModifierKeys::commandModifier; // (FL's Ctrl: Cmd on a Mac)
- const int shift = juce::ModifierKeys::shiftModifier;
- const int alt = juce::ModifierKeys::altModifier;
- const auto event = [&] (juce::Component& c, juce::Point<int> p, juce::ModifierKeys mods, juce::Point<int> down, int clicks, bool dragged) {
- return juce::MouseEvent (source, p.toFloat(), mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, &c, &c, now, down.toFloat(), now, clicks, dragged);
- };
- // a press (and release) at p with the modifiers; `to`: a drag there before the release
- const auto press = [&] (juce::Component& c, juce::Point<int> p, juce::ModifierKeys mods, std::optional<juce::Point<int>> to = {}, int clicks = 1) {
- const auto down = mods.withFlags (juce::ModifierKeys::leftButtonModifier);
- c.mouseMove (event (c, p, mods, p, 1, false));
- c.mouseDown (event (c, p, down, p, clicks, false));
- if (to)
- c.mouseDrag (event (c, *to, down, p, clicks, true));
- c.mouseUp (event (c, to ? *to : p, mods, p, clicks, to.has_value()));
- };
- const auto headerPoint = [&] (int track) { const auto r = pl.trackRowForSnapshot (track); return juce::Point<int> (40, r.getY() + juce::jmin (10, r.getHeight() / 3)); };
- const auto bandPoint = [&] (int track) { const auto r = pl.trackRowForSnapshot (track); return juce::Point<int> (40, r.getBottom() - 2); };
- const auto clipsOn = [&] (const std::vector<int>& tracks) {
- std::vector<int> out;
- const auto& song = engine.getSong();
- for (int i = 0; i < (int) song.playlist.size(); ++i)
- if (std::find (tracks.begin(), tracks.end(), song.playlist[(std::size_t) i].track) != tracks.end())
- out.push_back (i);
- return out;
- };
- const auto sortedClips = [&] { auto v = pl.getSelectedClips(); std::sort (v.begin(), v.end()); return v; };
- const auto headerShot = [&] (const juce::String& name, int rows) {
- const auto bottom = pl.trackRowForSnapshot (rows).getY();
- savePng (pl.createComponentSnapshot ({ 0, 0, juce::jmin (pl.getWidth(), 760), juce::jmin (pl.getHeight(), bottom + 12) }), prefix + name);
- };
- // ---- 1. selection (AUTracksPanelMouseDown / FUN_012e83e0)
- press (pl, headerPoint (1), {});
- check ("click_selects_alone", pl.selectedTracksForSnapshot() == std::vector<int> { 1 }, list (pl.selectedTracksForSnapshot()));
- pl.selectClipsForSnapshot ({});
- // LYNX extra (issue #163): Ctrl+click adds / removes one track, its clips follow
- press (pl, headerPoint (3), ctrl);
- check ("ctrl_click_adds_lynx", pl.selectedTracksForSnapshot() == std::vector<int> { 1, 3 } && sortedClips() == clipsOn ({ 3 }),
- list (pl.selectedTracksForSnapshot()) + " clips " + list (sortedClips()));
- press (pl, headerPoint (5), ctrl);
- press (pl, headerPoint (1), ctrl);
- check ("ctrl_click_removes_lynx", pl.selectedTracksForSnapshot() == std::vector<int> { 3, 5 } && sortedClips() == clipsOn ({ 3, 5 }),
- list (pl.selectedTracksForSnapshot()) + " clips " + list (sortedClips()));
- // FL's own toggle: Ctrl+Shift+click (its clips are added)
- press (pl, headerPoint (1), ctrl | shift);
- check ("ctrl_shift_click_adds", pl.selectedTracksForSnapshot() == std::vector<int> { 1, 3, 5 }, list (pl.selectedTracksForSnapshot()));
- check ("ctrl_shift_click_adds_clips", sortedClips() == clipsOn ({ 1, 3, 5 }), list (sortedClips()));
- press (pl, headerPoint (3), ctrl | shift);
- check ("ctrl_shift_click_removes", pl.selectedTracksForSnapshot() == std::vector<int> { 1, 5 }, list (pl.selectedTracksForSnapshot()));
- press (pl, headerPoint (3), ctrl | shift);
- check ("ctrl_shift_click_adds_again", pl.selectedTracksForSnapshot() == std::vector<int> { 1, 3, 5 }, list (pl.selectedTracksForSnapshot()));
- pl.selectClipsForSnapshot ({});
- headerShot ("-ctrl-multiselect.png", 6);
- press (pl, headerPoint (0), ctrl, headerPoint (2));
- check ("ctrl_drag_range_with_clips", pl.selectedTracksForSnapshot() == std::vector<int> { 0, 1, 2 } && sortedClips() == clipsOn ({ 0, 1, 2 }),
- list (pl.selectedTracksForSnapshot()) + " clips " + list (sortedClips()));
- press (pl, headerPoint (1), shift); // LYNX's own Shift+click range (from the last clicked track, 0)
- check ("lynx_shift_range_kept", pl.selectedTracksForSnapshot() == std::vector<int> { 0, 1 }, list (pl.selectedTracksForSnapshot()));
- {
- int linked = -1;
- auto old = pl.onLinkedMixerTrack;
- pl.onLinkedMixerTrack = [&linked] (int insert) { linked = insert; };
- press (pl, headerPoint (2), {});
- check ("audio_track_click_links_mixer_track", linked == 3, juce::String (linked));
- pl.onLinkedMixerTrack = old;
- }
- // ---- 2. the resize band (FUN_00ea93a0, AUTracksPanelMouseMove)
- const auto heightOf = [&] (int t) { return pl.trackRowForSnapshot (t).getHeight(); };
- const auto& tracks = [&]() -> const std::vector<lynx::PlaylistTrack>& { return engine.getSong().playlistTracks; };
- press (pl, headerPoint (4), {}); // (track 4 alone selected)
- {
- const auto start = bandPoint (4);
- press (pl, start, {}, start + juce::Point<int> (0, 41));
- check ("drag_resizes", tracks()[4].height == 88 && heightOf (4) == 88, juce::String (tracks()[4].height) + " / " + juce::String (heightOf (4))); // (190gw: from FL's 48 px row)
- headerShot ("-resized.png", 6);
- const auto again = bandPoint (4);
- press (pl, again, {}, again + juce::Point<int> (0, -100)); // (above the row's top, but less than 32 px)
- check ("drag_stops_at_16", heightOf (4) == 16, juce::String (heightOf (4)));
- press (pl, bandPoint (4), alt);
- check ("alt_click_resets", tracks()[4].height == 0 && tracks()[4].lockedHeight == -1 && heightOf (4) == 48, juce::String (heightOf (4)));
- press (pl, bandPoint (4), {}, {}, 2); // the second press of a double click
- check ("double_click_locks_small", tracks()[4].lockedHeight == 1 && heightOf (4) == 16, juce::String (tracks()[4].lockedHeight));
- press (pl, bandPoint (4), {});
- check ("click_on_locked_band_unlocks", tracks()[4].lockedHeight == -1 && heightOf (4) == 48, juce::String (tracks()[4].lockedHeight));
- const auto top = pl.trackRowForSnapshot (4).getY();
- const auto b = bandPoint (4);
- press (pl, b, {}, juce::Point<int> (b.x, top - 40));
- check ("drag_past_the_top_groups", tracks()[4].grouped && tracks()[4].height == 0, juce::String ((int) tracks()[4].grouped));
- const auto b2 = bandPoint (4);
- press (pl, b2, {}, juce::Point<int> (b2.x, pl.trackRowForSnapshot (4).getY() - 40));
- check ("again_ungroups", ! tracks()[4].grouped, juce::String ((int) tracks()[4].grouped));
- }
- {
- // every selected track: the same height, from the first one's top to the mouse
- press (pl, headerPoint (1), {});
- press (pl, headerPoint (2), ctrl | shift);
- press (pl, headerPoint (3), ctrl | shift);
- const auto top = pl.trackRowForSnapshot (1).getY();
- const auto b = bandPoint (2);
- press (pl, b, {}, juce::Point<int> (b.x, top + 2 * 50));
- check ("selected_tracks_share_the_height", tracks()[1].height == 50 && tracks()[2].height == 50 && tracks()[3].height == 50,
- juce::String (tracks()[1].height) + "," + juce::String (tracks()[2].height) + "," + juce::String (tracks()[3].height));
- headerShot ("-selected-resized.png", 6);
- }
- // ---- 3. saved: .lynx round trip and the .flp size factor
- {
- engine.editSong ([] (lynx::Song& s) { s.playlistTracks[5].height = 300; s.playlistTracks[0].lockedHeight = 60; });
- const auto json = lynx::ProjectFile::toJson (engine.getSong());
- juce::String error;
- const auto back = lynx::ProjectFile::fromJson (json, error);
- check ("lynx_round_trip", back && back->playlistTracks.size() > 5 && back->playlistTracks[5].height == 300 && back->playlistTracks[1].height == 50
- && back->playlistTracks[0].lockedHeight == 60, error);
- lynx::flpexport::Options options;
- lynx::flpexport::Report flpReport;
- const auto project = flp::parseProject (lynx::flpexport::exportFlp (engine.getSong(), options, flpReport));
- float size5 = -1.0f, size1 = -1.0f;
- for (const auto& arrangement : project.arrangements)
- for (const auto& t : arrangement.tracks)
- {
- if (t.index == 5) size5 = t.heightScale;
- if (t.index == 1) size1 = t.heightScale;
- }
- check ("flp_size_factor", std::abs (size5 - lynx::polish::flSizeForHeight (300, 48)) < 1.0e-4f && std::abs (size1 - lynx::polish::flSizeForHeight (50, 48)) < 1.0e-4f,
- juce::String (size5) + " " + juce::String (size1));
- }
- // ---- 4. the mixer strips (round 170b's FL rules): Ctrl+click alone, Ctrl+Shift+click adds / removes
- {
- ui.selectTabForSnapshot (3);
- engine.editSong ([] (lynx::Song& s) { if (s.mixer.size() < 9) s.mixer.resize (9); });
- engine.dispatchPendingMessages();
- auto& mixer = ui.getMixerForSnapshot();
- mixer.setSize (1400, 640);
- auto& strips = mixer.getStripsForSnapshot();
- strips.setSize (juce::jmax (strips.getWidth(), 1300), juce::jmax (strips.getHeight(), 560));
- const auto at = [&] (int t) { return juce::Point<int> (strips.stripLeft (t) + 8, strips.getHeight() / 2 + 40); };
- press (strips, at (2), {});
- check ("mixer_click_alone", strips.getSelection() == std::vector<int> { 2 }, list (strips.getSelection()));
- // LYNX extra (issue #163): Ctrl+click adds / removes one insert
- press (strips, at (4), ctrl);
- press (strips, at (6), ctrl);
- check ("mixer_ctrl_click_adds_lynx", strips.getSelection() == std::vector<int> { 2, 4, 6 }, list (strips.getSelection()));
- press (strips, at (4), ctrl);
- check ("mixer_ctrl_click_removes_lynx", strips.getSelection() == std::vector<int> { 2, 6 }, list (strips.getSelection()));
- // FL: Ctrl+Shift+click adds / removes too
- press (strips, at (5), ctrl | shift);
- check ("mixer_ctrl_shift_click_adds", strips.getSelection() == std::vector<int> { 2, 5, 6 }, list (strips.getSelection()));
- savePng (mixer.createComponentSnapshot ({ 0, 0, juce::jmin (mixer.getWidth(), 900), mixer.getHeight() }), prefix + "-mixer-ctrl-multiselect.png");
- // FL: Ctrl+drag across the strips = the range from the press, alone
- press (strips, at (3), ctrl, at (4));
- check ("mixer_ctrl_drag_range", strips.getSelection() == std::vector<int> { 3, 4 }, list (strips.getSelection()));
- }
- // ---- 5. round 190gw (live check 190gu B1): FL's default row, the left lock strip, the right selection strip
- {
- ui.selectTabForSnapshot (2);
- auto song = lynx::Song::makeDefault();
- song.playlist.clear();
- song.playlistTracks.assign (6, {});
- for (int t = 0; t < 6; ++t)
- song.playlistTracks[(std::size_t) t].name = juce::String ("Track " + juce::String (t + 1)).toStdString();
- engine.setSong (std::move (song));
- engine.dispatchPendingMessages();
- pl.setSize (juce::jmax (pl.getWidth(), 900), juce::jmax (pl.getHeight(), 600));
- check ("gw_default_row_48", heightOf (0) == 48 && heightOf (5) == 48, juce::String (heightOf (0)));
- const auto rowMid = [&] (int t) { const auto r = pl.trackRowForSnapshot (t); return r.getY() + r.getHeight() / 2 - 4; };
- const auto stripX = lynx::PlaylistComponent::flHeaderWidth - 4;
- // the left strip (x < 10): the row flips to the smallest size and back; nothing selects
- press (pl, { 2, rowMid (2) }, {});
- check ("gw_left_strip_smallest", heightOf (2) == 16 && tracks()[2].lockedHeight == 1, juce::String (heightOf (2)));
- press (pl, { 2, rowMid (2) }, {});
- check ("gw_left_strip_back", heightOf (2) == 48 && tracks()[2].lockedHeight == -1, juce::String (heightOf (2)));
- // the right strip: click = alone, Shift+click toggles, right-click toggles with no menu
- press (pl, { stripX, rowMid (0) }, {});
- check ("gw_strip_click_alone", pl.selectedTracksForSnapshot() == std::vector<int> { 0 }, list (pl.selectedTracksForSnapshot()));
- press (pl, { stripX, rowMid (1) }, shift);
- check ("gw_strip_shift_click_adds", pl.selectedTracksForSnapshot() == std::vector<int> { 0, 1 }, list (pl.selectedTracksForSnapshot()));
- headerShot ("-gw-strip-two-selected.png", 6);
- press (pl, { stripX, rowMid (0) }, shift);
- check ("gw_strip_shift_click_removes", pl.selectedTracksForSnapshot() == std::vector<int> { 1 }, list (pl.selectedTracksForSnapshot()));
- {
- const juce::Point<int> p { stripX, rowMid (4) };
- const juce::ModifierKeys right (juce::ModifierKeys::rightButtonModifier);
- pl.mouseDown (event (pl, p, right, p, 1, false));
- pl.mouseUp (event (pl, p, {}, p, 1, false));
- }
- check ("gw_strip_right_click_adds", pl.selectedTracksForSnapshot() == std::vector<int> { 1, 4 }, list (pl.selectedTracksForSnapshot()));
- // a drag down the strip: the tracks crossed join (FUN_012e8740)
- press (pl, { stripX, rowMid (0) }, {}, juce::Point<int> (stripX, rowMid (4)));
- check ("gw_strip_drag_range", pl.selectedTracksForSnapshot() == std::vector<int> { 0, 1, 2, 3, 4 }, list (pl.selectedTracksForSnapshot()));
- headerShot ("-gw-strip-range.png", 6);
- // a double click: the track alone <-> every track
- press (pl, { stripX, rowMid (2) }, {});
- press (pl, { stripX, rowMid (2) }, {}, {}, 2);
- check ("gw_strip_double_click_all", (int) pl.selectedTracksForSnapshot().size() == pl.numTracksForSnapshot(), list (pl.selectedTracksForSnapshot()));
- press (pl, { stripX, rowMid (1) }, {});
- // .lynx: the new default row is saved; a project from before (no key) keeps LYNX's old 38 px row
- juce::String error;
- const auto json = lynx::ProjectFile::toJson (engine.getSong());
- const auto back = lynx::ProjectFile::fromJson (json, error);
- check ("gw_lynx_row_saved", back && back->playlistRowHeight == 48, error);
- auto parsed = juce::JSON::parse (json);
- if (auto* o = parsed.getDynamicObject())
- o->removeProperty ("playlistRowHeight");
- const auto old = lynx::ProjectFile::fromJson (juce::JSON::toString (parsed), error);
- check ("gw_old_lynx_keeps_38", old && old->playlistRowHeight == 38, error);
- engine.setSong (*old);
- engine.dispatchPendingMessages();
- check ("gw_old_lynx_rows_38", heightOf (0) == 38, juce::String (heightOf (0)));
- // an automation clip with two target links (Crossfade with) comes back with its links and formulas
- auto linked = lynx::Song::makeDefault();
- linked.channels.resize (2);
- lynx::Automation a;
- a.links = { { { lynx::AutomationTargetKind::channelAdjust, 0, 0, lynx::leveladjust::volume }, lynx::clipops::crossfadeOutFormula },
- { { lynx::AutomationTargetKind::channelAdjust, 1, 0, lynx::leveladjust::volume }, lynx::clipops::crossfadeInFormula } };
- a.target = a.links[0].target;
- a.points = { { 0, 1.0f, 0.0f }, { 384, 0.0f, 0.0f } };
- linked.automations.push_back (a);
- const auto linkedBack = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (linked), error);
- check ("gw_lynx_links_round_trip", linkedBack && linkedBack->automations.size() == linked.automations.size()
- && linkedBack->automations.back().links == a.links && linkedBack->automations.back().target == a.target, error);
- // Sampler › Open in new Fruity Slicer / Slicex channel: named after the sample, " #n" when taken
- const auto wav = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-190gw").getChildFile ("Basic 808 Clap.wav");
- wav.getParentDirectory().createDirectory();
- {
- juce::AudioBuffer<float> b (1, 4410);
- for (int i = 0; i < b.getNumSamples(); ++i)
- b.setSample (0, i, 0.5f * std::sin ((float) i * 0.2f) * (1.0f - (float) i / (float) b.getNumSamples()));
- wav.deleteFile();
- juce::WavAudioFormat format;
- std::unique_ptr<juce::OutputStream> out (wav.createOutputStream());
- if (auto* w = format.createWriterFor (out.get(), 44100.0, 1, 16, {}, 0))
- {
- out.release();
- std::unique_ptr<juce::AudioFormatWriter> writer (w);
- writer->writeFromAudioSampleBuffer (b, 0, b.getNumSamples());
- }
- }
- engine.editSong ([] (lynx::Song& s) {
- s.channels.resize (1);
- s.channels[0] = {};
- s.channels[0].name = "Basic 808 Clap";
- });
- engine.dispatchPendingMessages();
- if (lynx::openInNewChannelHandler())
- {
- lynx::openInNewChannelHandler() (wav, lynx::InstrumentKind::fruityslicer);
- lynx::openInNewChannelHandler() (wav, lynx::InstrumentKind::slicex);
- }
- engine.dispatchPendingMessages();
- const auto& ch = engine.getSong().channels;
- check ("gw_open_in_new_named_after_sample", ch.size() >= 3 && ch[1].name == "Basic 808 Clap #2" && ch[2].name == "Basic 808 Clap #3"
- && ch[1].instrument == lynx::InstrumentKind::fruityslicer && ch[2].instrument == lynx::InstrumentKind::slicex,
- ch.size() >= 3 ? juce::String::fromUTF8 (ch[1].name.c_str()) + " | " + juce::String::fromUTF8 (ch[2].name.c_str()) : juce::String ((int) ch.size()));
- wav.getParentDirectory().deleteRecursively();
- // the mixer's two boxes (live check 190gu B4): "Insert multiple..." asks "Number of tracks to add" (1),
- // "Add multiple..." "Enter the number of mixer tracks to add" (10)
- for (const auto adding : { false, true })
- {
- auto box = lynx::MixerStrips::makeInsertMultipleBox (adding);
- const auto text = box->getTextEditorContents ("count");
- check (adding ? "gw_add_multiple_box" : "gw_insert_multiple_box", text == (adding ? "10" : "1"), text);
- if (box->getWidth() > 0 && box->getHeight() > 0)
- savePng (box->createComponentSnapshot (box->getLocalBounds()), prefix + (adding ? "-gw-add-multiple-box.png" : "-gw-insert-multiple-box.png"));
- }
- }
- juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
- return allOk;
- }
- // --userfixshot190ib (round 190ib): see the dispatch above
- bool runUserFixShot190ib (const juce::String& prefix)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- juce::StringArray report;
- bool allOk = true;
- const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
- report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
- allOk = allOk && ok;
- };
- lynx::AudioEngine engine (false);
- lynx::MainComponent ui (engine, false);
- ui.setSize (1600, 900);
- engine.dispatchPendingMessages();
- // ---- #182: a real JUCE popup menu inside a host component, keys sent to its window as the keyboard would
- juce::Component host;
- host.setSize (560, 900);
- const auto typeInto = [&host] (const juce::String& text) {
- auto* menuWindow = host.getNumChildComponents() > 0 ? host.getChildComponent (host.getNumChildComponents() - 1) : nullptr;
- for (auto c : text)
- if (menuWindow != nullptr)
- menuWindow->keyPressed (juce::KeyPress ((int) juce::CharacterFunctions::toLowerCase (c), 0, c));
- return menuWindow != nullptr;
- };
- const auto shotMenu = [&host, &prefix] (const juce::String& name) {
- savePng (host.createComponentSnapshot (host.getLocalBounds()), prefix + name);
- };
- {
- auto& pl = ui.getPlaylistForSnapshot();
- pl.editMenu().showMenuAsync (juce::PopupMenu::Options().withParentComponent (&host).withTargetScreenArea ({ 8, 8, 1, 1 }));
- check ("menu_shown", host.getNumChildComponents() > 0, juce::String (host.getNumChildComponents()));
- shotMenu ("-menu-0.png");
- typeInto ("d");
- shotMenu ("-menu-d.png"); // the first item starting with D
- typeInto ("d");
- shotMenu ("-menu-dd.png"); // D again: the next one
- juce::Time::waitForMillisecondCounter (juce::Time::getMillisecondCounter() + 1100); // (a pause: a new prefix)
- typeInto ("drop a");
- shotMenu ("-menu-drop-a.png"); // "Drop audio on track headers"
- juce::PopupMenu::dismissAllActiveMenus();
- }
- {
- auto& pr = ui.getPianoRollForSnapshot();
- pr.moreMenuForSnapshot().showMenuAsync (juce::PopupMenu::Options().withParentComponent (&host).withTargetScreenArea ({ 8, 8, 1, 1 }));
- juce::Time::waitForMillisecondCounter (juce::Time::getMillisecondCounter() + 1100);
- typeInto ("preview");
- shotMenu ("-pianoroll-preview.png"); // #183's item, reached by typing its name
- juce::PopupMenu::dismissAllActiveMenus();
- check ("preview_while_playing_off_by_default", ! lynx::PianoRollComponent::previewWhilePlaying);
- }
- // ---- #181: Ctrl+, (Cmd+, on macOS) through the main window's key handling opens Settings, again closes it
- const auto ctrlComma = juce::KeyPress (',', juce::ModifierKeys::commandModifier, ',');
- check ("settings_closed_first", lynx::shownSettingsPage() < 0);
- ui.keyPressed (ctrlComma);
- check ("ctrl_comma_opens_settings", lynx::shownSettingsPage() == (int) lynx::SettingsPage::general, juce::String (lynx::shownSettingsPage()));
- ui.keyPressed (ctrlComma);
- check ("ctrl_comma_again_closes_it", lynx::shownSettingsPage() < 0, juce::String (lynx::shownSettingsPage()));
- juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
- return allOk;
- }
- // --trackautoshot190gz (round 190gz): see the dispatch above
- bool runTrackAutoShot190gz (const juce::String& prefix)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- juce::StringArray report;
- bool allOk = true;
- const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
- report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
- allOk = allOk && ok;
- };
- lynx::AudioEngine engine (false);
- lynx::MainComponent ui (engine, false);
- ui.setSize (1600, 900);
- {
- // a small song in FL's shape: Kick and Synth patterns, a drum loop, a vocal on its prepared insert, a mixed beat
- using namespace lynx;
- auto song = Song::makeDefault();
- song.playlist.clear();
- song.patterns.clear();
- for (auto& c : song.channels)
- c.mixerTrack = 0; // (FL's new channels play on the Master)
- song.channels[4].mixerTrack = 9; // the Synth on a bus the user made
- song.mixer[9].name = "Synth bus";
- const auto audio = [&song] (const char* name, int mixer) {
- ChannelDef c;
- c.name = name;
- c.instrument = InstrumentKind::audioClip;
- c.samplePath = std::string ("/shots/") + name + ".wav";
- c.mixerTrack = mixer;
- song.channels.push_back (c);
- return (int) song.channels.size() - 1;
- };
- const auto loop = audio ("Drum loop", 0);
- const auto vox = audio ("Lead vocal", 12);
- song.mixer[12].name = "Vox chain";
- song.mixer[12].colour = 0xFF3C8DD8;
- song.mixer[12].effects.push_back (makeEffectSlot (EffectKind::parametricEq));
- const auto pattern = [&song] (const char* name, std::vector<int> channels, std::uint32_t colour) {
- auto& p = song.patterns.emplace_back();
- p.name = name;
- p.colour = colour;
- for (const auto c : channels)
- for (int step : { 0, 4, 8, 12 })
- p.toggleStep (c, step);
- return (int) song.patterns.size() - 1;
- };
- const auto kick = pattern ("Kick", { 0 }, 0xFFD85A3C);
- const auto lead = pattern ("Lead", { 4 }, 0xFF8A5CD8);
- const auto beat = pattern ("Beat", { 1, 2, 3 }, 0xFF5CB85C);
- const auto clip = [&song] (int track, ClipKind kind, int source, int bar, int bars) {
- Clip c;
- c.kind = kind;
- c.track = track;
- c.start = (std::int64_t) bar * 4 * ppq;
- c.length = (std::int64_t) bars * 4 * ppq;
- (kind == ClipKind::pattern ? c.pattern : c.channel) = source;
- song.playlist.push_back (c);
- };
- for (int bar = 0; bar < 8; bar += 2)
- {
- clip (0, ClipKind::pattern, kick, bar, 2);
- clip (2, ClipKind::pattern, beat, bar, 2);
- }
- clip (1, ClipKind::audio, loop, 0, 8);
- clip (3, ClipKind::pattern, lead, 2, 4);
- clip (4, ClipKind::audio, vox, 4, 4);
- clip (6, ClipKind::pattern, kick, 4, 2); // (round 190ib: Track 7 only repeats Track 1's Kick)
- song.playlistTracks.resize (8);
- engine.setSong (std::move (song));
- }
- engine.dispatchPendingMessages();
- ui.selectTabForSnapshot (2);
- engine.dispatchPendingMessages();
- auto& pl = ui.getPlaylistForSnapshot();
- pl.setSize (juce::jmax (pl.getWidth(), 1000), juce::jmax (pl.getHeight(), 640));
- pl.setViewForSnapshot (120.0, 1, 0);
- const auto shotRows = [&] (const juce::String& name, int rows) {
- const auto bottom = pl.trackRowForSnapshot (rows).getY();
- savePng (pl.createComponentSnapshot ({ 0, 0, juce::jmin (pl.getWidth(), 820), juce::jmin (pl.getHeight(), bottom + 12) }), prefix + name);
- };
- const auto& song = [&]() -> const lynx::Song& { return engine.getSong(); };
- const auto mode = [&] (int t) { return t < (int) song().playlistTracks.size() ? song().playlistTracks[(std::size_t) t].mode : lynx::PlaylistTrackMode::unassigned; };
- const auto mixerOf = [&] (int t) { return t < (int) song().playlistTracks.size() ? song().playlistTracks[(std::size_t) t].mixerTrack : -1; };
- // ---- 1. FL's default: tracks and inserts apart, FL's narrow headers
- check ("off_by_default", ! song().linkTracksToMixer && pl.headerWidthForSnapshot() == lynx::PlaylistComponent::flHeaderWidth,
- juce::String (pl.headerWidthForSnapshot()));
- shotRows ("-off.png", 7);
- // ---- 2. the switch (Playlist › Edit, Track mode, Settings › Project): it lists what it changes and asks (round
- // 190ib: inserts move, channels are routed), then it is one undo step
- lynx::autolink::Report plan;
- bool asked = false;
- lynx::PlaylistComponent::answerLinkConfirmation = [&] (const lynx::autolink::Report& r) {
- plan = r;
- asked = true;
- return true;
- };
- {
- const auto text = lynx::PlaylistComponent::describeLinkPlan (song(), lynx::autolink::planOn (song()));
- juce::AlertWindow box (lynx::tr ("Link Playlist tracks to mixer tracks"), text, juce::MessageBoxIconType::QuestionIcon);
- box.addButton (lynx::tr ("Link"), 1);
- box.addButton (lynx::tr ("Cancel"), 0);
- box.sendLookAndFeelChange();
- savePng (lynx::shot::snapshot (box), prefix + "-confirm.png");
- }
- pl.runAction ("playlist.linkTracks");
- engine.dispatchPendingMessages();
- const auto moved = [&plan] (int from, int to) {
- return std::any_of (plan.changes.begin(), plan.changes.end(), [=] (const lynx::autolink::Change& c) {
- return c.kind == lynx::autolink::Change::Kind::moveInsert && c.from == from && c.to == to;
- });
- };
- check ("asked_first_with_the_moves", asked && moved (9, 4) && moved (12, 5) && plan.repeats.size() == 1 && ! plan.changesSound(),
- juce::String ((int) plan.changes.size()));
- check ("switch_on", song().linkTracksToMixer && pl.headerWidthForSnapshot() == lynx::PlaylistComponent::linkedHeaderWidth,
- juce::String (pl.headerWidthForSnapshot()));
- check ("kick_instrument_track_insert_1", mode (0) == lynx::PlaylistTrackMode::instrument && mixerOf (0) == 1 && song().channels[0].mixerTrack == 1,
- juce::String (mixerOf (0)));
- check ("loop_audio_track_insert_2", mode (1) == lynx::PlaylistTrackMode::audio && mixerOf (1) == 2 && song().mixer[2].name == "Drum loop",
- juce::String (mixerOf (1)));
- // (round 190ib: Track N = insert N for every track with content of its own)
- check ("beat_track_insert_3", mode (2) == lynx::PlaylistTrackMode::audio && mixerOf (2) == 3 && song().channels[1].mixerTrack == 3
- && song().channels[2].mixerTrack == 3 && song().channels[3].mixerTrack == 3,
- juce::String (mixerOf (2)));
- check ("synth_bus_moves_to_insert_4", mode (3) == lynx::PlaylistTrackMode::instrument && song().channels[4].mixerTrack == 4
- && song().mixer[4].name == "Synth bus" && song().playlistTracks[3].name == "Synth bus",
- juce::String (song().channels[4].mixerTrack));
- check ("vocal_chain_moves_to_insert_5", mode (4) == lynx::PlaylistTrackMode::audio && mixerOf (4) == 5 && song().mixer[5].effects.size() == 1
- && song().mixer[5].name == "Vox chain",
- juce::String (mixerOf (4)));
- check ("empty_and_repeat_tracks_stay", mode (5) == lynx::PlaylistTrackMode::unassigned && mode (6) == lynx::PlaylistTrackMode::unassigned
- && lynx::autolink::repeatedTracks (song())[6] == 0);
- shotRows ("-on.png", 7);
- // one undo step: Undo brings FL's tracks back, Redo the links
- engine.undo();
- engine.dispatchPendingMessages();
- check ("undo_switch_on", ! song().linkTracksToMixer && mode (0) == lynx::PlaylistTrackMode::unassigned && mode (1) == lynx::PlaylistTrackMode::unassigned
- && song().channels[0].mixerTrack == 0 && pl.headerWidthForSnapshot() == lynx::PlaylistComponent::flHeaderWidth);
- engine.redo();
- engine.dispatchPendingMessages();
- check ("redo_switch_on", song().linkTracksToMixer && mixerOf (1) == 2 && pl.headerWidthForSnapshot() == lynx::PlaylistComponent::linkedHeaderWidth);
- auto source = juce::Desktop::getInstance().getMainMouseSource();
- const auto now = juce::Time::getCurrentTime();
- const int ctrl = juce::ModifierKeys::commandModifier;
- const auto event = [&] (juce::Point<int> p, juce::ModifierKeys mods, juce::Point<int> down, int clicks, bool dragged) {
- return juce::MouseEvent (source, p.toFloat(), mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, &pl, &pl, now, down.toFloat(), now, clicks, dragged);
- };
- const auto press = [&] (juce::Point<int> p, juce::ModifierKeys mods, std::optional<juce::Point<int>> to = {}) {
- const auto down = mods.withFlags (juce::ModifierKeys::leftButtonModifier);
- pl.mouseMove (event (p, mods, p, 1, false));
- pl.mouseDown (event (p, down, p, 1, false));
- if (to)
- pl.mouseDrag (event (*to, down, p, 1, true));
- pl.mouseUp (event (to ? *to : p, mods, p, 1, to.has_value()));
- engine.flushLevels();
- engine.dispatchPendingMessages();
- };
- const auto doubleClick = [&] (juce::Point<int> p) {
- const auto down = juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier);
- pl.mouseDown (event (p, down, p, 2, false));
- pl.mouseDoubleClick (event (p, down, p, 2, false));
- pl.mouseUp (event (p, {}, p, 2, false));
- engine.flushLevels();
- engine.dispatchPendingMessages();
- };
- // the controls are found where they are drawn: M right of the plate, S left of it, the volume bar and the pan knob
- // under them (the same geometry the header paints with)
- const auto row = [&] (int t) { return pl.trackRowForSnapshot (t); };
- const int w = pl.headerWidthForSnapshot();
- const auto mAt = [&] (int t) { const auto r = row (t); return juce::Point<int> (w - 13 - 9, r.getY() + 11); }; // (meter column 9 px)
- const auto sAt = [&] (int t) { return mAt (t) - juce::Point<int> (20, 0); };
- const auto volumeAt = [&] (int t, float fraction) {
- const auto r = row (t);
- const auto left = 8, width = w - 9 - 2 - 32;
- return juce::Point<int> (left + juce::roundToInt (fraction * (float) width), r.getY() + 26);
- };
- const auto panAt = [&] (int t) { const auto r = row (t); return juce::Point<int> (w - 9 - 6 - 7, r.getY() + 26); };
- const auto& insert2 = [&]() -> const lynx::MixerTrack& { return song().mixer[2]; };
- // ---- 3. the linked headers' controls act on the track's mixer track
- press (mAt (1), {});
- check ("m_mutes_the_insert", insert2().muted, juce::String ((int) insert2().muted));
- press (mAt (1), {});
- check ("m_again_unmutes", ! insert2().muted);
- press (sAt (1), {});
- check ("s_solos_the_insert", insert2().solo);
- press (sAt (1), {});
- press (volumeAt (1, 0.25f), {});
- check ("volume_click_sets_the_level", std::abs (insert2().volume - 0.25f) < 0.03f, juce::String (insert2().volume, 3));
- press (volumeAt (1, 0.25f), {}, volumeAt (1, 0.5f));
- check ("volume_drag", std::abs (insert2().volume - 0.5f) < 0.03f, juce::String (insert2().volume, 3));
- doubleClick (volumeAt (1, 0.5f));
- check ("volume_double_click_0_db", insert2().volume == lynx::unityFader, juce::String (insert2().volume, 3));
- press (panAt (1), {}, panAt (1) - juce::Point<int> (0, 40));
- check ("pan_drag_up", std::abs (insert2().pan - 0.5f) < 0.02f, juce::String (insert2().pan, 3));
- shotRows ("-controls.png", 7);
- doubleClick (panAt (1));
- check ("pan_double_click_centre", insert2().pan == 0.0f, juce::String (insert2().pan, 3));
- // an instrument track's header acts on its channel's insert (Synth: insert 4 since round 190ib)
- press (volumeAt (3, 0.4f), {});
- check ("instrument_track_volume_on_its_insert", std::abs (song().mixer[4].volume - 0.4f) < 0.03f, juce::String (song().mixer[4].volume, 3));
- engine.editSong ([] (lynx::Song& s) { s.mixer[4].volume = lynx::unityFader; });
- // FL's track mute and solo stay on the Playlist track: Ctrl+click on M solos it, a muted track lights M and the
- // first click unmutes it
- press (mAt (1), ctrl);
- check ("ctrl_m_solos_the_playlist_track", song().isTrackMuted (0) && ! song().isTrackMuted (1) && ! insert2().solo);
- press (mAt (1), ctrl);
- engine.editSong ([] (lynx::Song& s) {
- for (auto& t : s.playlistTracks)
- t.muted = false;
- s.playlistTracks[1].muted = true;
- });
- press (mAt (1), {});
- check ("m_unmutes_a_muted_playlist_track_first", ! song().isTrackMuted (1) && ! insert2().muted);
- // a track that only repeats another keeps FL's LED (Track 7, Track 1's Kick): a click mutes the Playlist track
- press (juce::Point<int> (w - 9 - 11, row (6).getCentreY()), {});
- check ("unlinked_led_is_fl", song().isTrackMuted (6));
- engine.editSong ([] (lynx::Song& s) { s.playlistTracks[6].muted = false; });
- // round 190ib: a linked track and its insert keep one name, whichever is renamed
- engine.editSong ([] (lynx::Song& s) { s.mixer[3].name = "Drums"; });
- check ("insert_rename_renames_the_track", song().playlistTracks[2].name == "Drums");
- engine.editSong ([] (lynx::Song& s) { s.playlistTracks[2].name = "Beat"; });
- check ("track_rename_renames_the_insert", song().mixer[3].name == "Beat");
- // ---- 4. new content follows: a sample on empty Track 6 makes it an audio track (insert 6)
- engine.editSong ([] (lynx::Song& s) {
- lynx::ChannelDef c;
- c.name = "Guitar";
- c.instrument = lynx::InstrumentKind::audioClip;
- c.samplePath = "/shots/Guitar.wav";
- s.channels.push_back (c);
- lynx::Clip clip;
- clip.kind = lynx::ClipKind::audio;
- clip.channel = (int) s.channels.size() - 1;
- clip.track = 5;
- clip.start = 4 * 4 * lynx::ppq;
- clip.length = 4 * 4 * lynx::ppq;
- s.playlist.push_back (clip);
- });
- check ("new_sample_links_its_track", mode (5) == lynx::PlaylistTrackMode::audio && mixerOf (5) == 6 && song().channels.back().mixerTrack == 6,
- juce::String (mixerOf (5)));
- engine.undo();
- check ("undo_takes_the_clip_and_the_link", mode (5) == lynx::PlaylistTrackMode::unassigned && song().channels.back().name != "Guitar");
- // ---- 5. row heights (round 190ft): short rows keep M / S; from 34 px the volume and pan; tall rows the input
- const auto heights = [&] (std::vector<std::pair<int, int>> rows) {
- engine.editSong ([rows] (lynx::Song& s) {
- for (const auto& [t, h] : rows)
- s.playlistTracks[(std::size_t) t].height = h;
- });
- engine.dispatchPendingMessages();
- };
- heights ({ { 0, 16 }, { 1, 24 }, { 4, 80 } });
- shotRows ("-heights.png", 7);
- {
- const auto r = row (1);
- const auto before = insert2().volume;
- press (juce::Point<int> (20, r.getY() + 12), {}); // (no volume bar on a 24 px row: the press selects)
- check ("short_row_has_no_volume_bar", insert2().volume == before && pl.selectedTracksForSnapshot() == std::vector<int> { 1 });
- press (juce::Point<int> (w - 22, r.getY() + 12), {});
- check ("short_row_m_still_works", insert2().muted);
- press (juce::Point<int> (w - 22, r.getY() + 12), {});
- }
- heights ({ { 0, 0 }, { 1, 0 }, { 4, 0 } });
- // ---- 6. saved: .lynx keeps the switch; the links themselves are FL track modes
- {
- juce::String error;
- const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song()), error);
- check ("lynx_round_trip", back && back->linkTracksToMixer && back->playlistTracks.size() > 4 && back->playlistTracks[1].mixerTrack == 2
- && back->playlistTracks[0].mode == lynx::PlaylistTrackMode::instrument, error);
- auto plain = song();
- plain.linkTracksToMixer = false;
- const auto json = lynx::ProjectFile::toJson (plain);
- check ("off_not_saved", ! json.contains ("linkTracksToMixer"));
- }
- // ---- 7. off: FL's headers again (the links stay)
- lynx::PlaylistComponent::answerLinkConfirmation = nullptr;
- pl.runAction ("playlist.linkTracks");
- engine.dispatchPendingMessages();
- check ("switch_off_fl_headers", ! song().linkTracksToMixer && pl.headerWidthForSnapshot() == lynx::PlaylistComponent::flHeaderWidth
- && mode (1) == lynx::PlaylistTrackMode::audio);
- shotRows ("-off-after.png", 7);
- // ---- 8. Settings › Project's switches
- {
- auto panel = lynx::makeSettingsPanel (engine, lynx::SettingsPage::project);
- panel->setSize (760, 720);
- savePng (lynx::shot::snapshot (*panel), prefix + "-settings-project.png");
- }
- juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
- return allOk;
- }
- bool runFlPlShot (const juce::String& prefix)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- juce::StringArray report;
- bool allOk = true;
- const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
- report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
- allOk = allOk && ok;
- };
- const auto plain = [] (juce::String t) {
- // (without the shortcut column and the mnemonic: the mark, or the " (K)" a translation without the letter gets)
- t = t.upToFirstOccurrenceOf ("\t", false, false);
- if (const auto at = t.indexOf (juce::String (" (") + juce::String::charToString (1)); at >= 0)
- t = t.substring (0, at);
- return t.removeCharacters (juce::String ("&_") + juce::String::charToString (1));
- };
- const auto findSub = [&plain] (const juce::PopupMenu& menu, const juce::String& text) -> const juce::PopupMenu* {
- for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
- if (it.getItem().subMenu != nullptr && plain (it.getItem().text) == plain (text))
- return it.getItem().subMenu.get();
- return nullptr;
- };
- const auto texts = [&plain] (const juce::PopupMenu& menu, int count) {
- juce::StringArray out;
- for (juce::PopupMenu::MenuItemIterator it (menu); it.next() && out.size() < count;)
- out.add (it.getItem().isSeparator ? juce::String ("-") : it.getItem().isSectionHeader ? "[" + plain (it.getItem().text) + "]" : plain (it.getItem().text));
- return out;
- };
- const auto modelTexts = [] (const std::vector<lynx::fltrackmenus::Entry>& model) {
- juce::StringArray out;
- for (const auto& e : model)
- if (e.kind != lynx::fltrackmenus::Entry::Kind::list)
- out.add (e.kind == lynx::fltrackmenus::Entry::Kind::separator ? juce::String ("-")
- : e.kind == lynx::fltrackmenus::Entry::Kind::caption ? "[" + lynx::tr (e.text) + "]"
- : lynx::tr (e.text));
- return out;
- };
- const auto click = [&plain] (const juce::PopupMenu& menu, const juce::String& text) {
- for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
- if (plain (it.getItem().text) == plain (text) && it.getItem().isEnabled && it.getItem().action != nullptr)
- {
- it.getItem().action();
- return true;
- }
- return false;
- };
- lynx::AudioEngine engine (false);
- lynx::MainComponent ui (engine, false);
- ui.setSize (1600, 900);
- int vox = -1;
- {
- auto song = lynx::Song::makeDefault();
- song.channels.push_back ({});
- song.channels.back().name = "Vox";
- song.channels.back().instrument = lynx::InstrumentKind::audioClip;
- song.channels.back().volume = 0.6f;
- song.channels.back().samplePath = writeShotSample (juce::File (prefix + "-vox.wav"), 330.0).getFullPathName().toStdString();
- vox = (int) song.channels.size() - 1;
- lynx::Clip c;
- c.kind = lynx::ClipKind::audio;
- c.channel = vox;
- c.track = 3;
- c.start = 4 * lynx::ppq;
- c.length = 2 * lynx::ppq;
- song.playlist.push_back (c);
- engine.setSong (std::move (song));
- }
- engine.dispatchPendingMessages();
- auto& playlist = ui.getPlaylistForSnapshot();
- // ---- 1. the audio clip menu: Preview first, Automate › Panning / Volume
- {
- const auto menu = playlist.getClipMenuForSnapshot (0);
- juce::PopupMenu::MenuItemIterator it (menu);
- it.next(); // (the "Audio clip" title band)
- it.next();
- check ("clip_menu_preview_first", plain (it.getItem().text) == lynx::tr ("Preview"), it.getItem().text);
- const auto* automate = findSub (menu, lynx::tr ("Automate"));
- check ("clip_menu_automate", automate != nullptr && texts (*automate, 9) == modelTexts (lynx::fltrackmenus::automate()),
- automate != nullptr ? texts (*automate, 9).joinIntoString ("|") : juce::String ("missing"));
- saveMenus (juce::StringArray { "Audio clip menu", "Automate" }, std::vector<juce::PopupMenu> { menu, automate != nullptr ? *automate : juce::PopupMenu() },
- prefix + "-clip-menu.png");
- const auto before = engine.getSong().automations.size();
- check ("automate_volume_runs", automate != nullptr && click (*automate, lynx::tr ("Volume")));
- const auto& song = engine.getSong();
- // (round 190dz: the Levels adjustment's volume multiplier, neutral = 0.5 of its 0…200 % travel)
- const auto ok = song.automations.size() == before + 1 && song.automations.back().target.kind == lynx::AutomationTargetKind::channelAdjust
- && song.automations.back().target.param == lynx::leveladjust::volume
- && song.automations.back().target.index == vox && song.automations.back().points.size() == 2
- && song.automations.back().points[1].tick == 2 * lynx::ppq && std::abs (song.automations.back().points[0].value - 0.5f) < 1.0e-6f;
- const auto* clip = ok ? &song.playlist.back() : nullptr;
- check ("automate_volume_clip", ok && clip->kind == lynx::ClipKind::automation && clip->track == 3 && clip->start == 4 * lynx::ppq
- && clip->length == 2 * lynx::ppq,
- ok ? juce::String::fromUTF8 (song.automations.back().name.c_str()) : juce::String());
- engine.undo();
- check ("automate_undo", engine.getSong().automations.size() == before);
- // Preview: the clip's own audio (FL plays it through its channel); LYNX renders it for the preview output
- const auto rendered = engine.renderClipAudio (0);
- check ("preview_renders_the_clip", ! rendered.left.empty(), juce::String ((int) rendered.left.size()) + " frames");
- }
- // ---- 2. the Playlist's "+": its menu, a right click's audio track, the corner
- {
- const auto menu = playlist.getAddTrackMenuForSnapshot();
- check ("add_menu_head", texts (menu, 5) == modelTexts (lynx::fltrackmenus::addTrack()), texts (menu, 5).joinIntoString ("|"));
- saveMenus (juce::StringArray { "Playlist +" }, std::vector<juce::PopupMenu> { menu }, prefix + "-add-track-menu.png");
- ui.selectTabForSnapshot (2);
- engine.dispatchPendingMessages();
- auto* button = playlist.getAddTrackButtonForSnapshot();
- check ("add_button_in_corner", button != nullptr && button->isVisible() && button->getX() == 7 && button->getWidth() == 21 && button->getHeight() == 18
- && button->getBottom() <= lynx::PlaylistComponent::headerHeight);
- savePng (playlist.createComponentSnapshot (juce::Rectangle<int> (0, 0, juce::jmin (560, playlist.getWidth()), juce::jmin (260, playlist.getHeight()))),
- prefix + "-playlist-corner.png");
- const auto track = playlist.addAudioTrackNow();
- const auto& song = engine.getSong();
- check ("add_audio_track", track == 0 && song.playlistTracks.size() > 0 && song.playlistTracks[0].mode == lynx::PlaylistTrackMode::audio
- && song.playlistTracks[0].mixerTrack > 0,
- juce::String (track));
- engine.undo();
- }
- // ---- 3. Track mode › Instrument track ›
- {
- const auto menu = playlist.getTrackMenuForSnapshot (5);
- const auto* modes = findSub (menu, lynx::tr ("Track mode"));
- const auto* instrument = modes != nullptr ? findSub (*modes, lynx::tr ("Instrument track")) : nullptr;
- check ("instrument_track_head", instrument != nullptr && texts (*instrument, 4) == modelTexts (lynx::fltrackmenus::instrumentTrack()),
- instrument != nullptr ? texts (*instrument, 4).joinIntoString ("|") : juce::String ("missing"));
- const auto* existing = instrument != nullptr ? findSub (*instrument, lynx::tr ("Use existing channel")) : nullptr;
- check ("use_existing_lists_generators", existing != nullptr && existing->getNumItems() == 5, existing != nullptr ? juce::String (existing->getNumItems()) : juce::String());
- std::vector<juce::PopupMenu> menus { modes != nullptr ? *modes : juce::PopupMenu(), instrument != nullptr ? *instrument : juce::PopupMenu(),
- existing != nullptr ? *existing : juce::PopupMenu() };
- saveMenus (juce::StringArray { "Track mode", "Instrument track", "Use existing channel" }, menus, prefix + "-instrument-track-menu.png");
- lynx::ChannelDef synth;
- synth.name = "Lead";
- synth.instrument = lynx::InstrumentKind::synth;
- const auto channels = engine.getSong().channels.size();
- int made = -1;
- engine.editSong ([&] (lynx::Song& s) { made = lynx::trackmodes::addInstrumentTrack (s, synth, 5); });
- check ("instrument_track_new_channel", made == (int) channels && engine.getSong().playlistTracks.size() > 5
- && engine.getSong().playlistTracks[5].channel == made);
- engine.undo();
- }
- // ---- 4. the Channel rack menu: Assign to new instrument track / Unassign
- {
- auto& rack = ui.getRackForSnapshot();
- const auto menu = rack.getChannelMenuForSnapshot (1);
- saveMenus (juce::StringArray { "Channel menu" }, std::vector<juce::PopupMenu> { menu }, prefix + "-channel-menu.png");
- check ("assign_runs", click (menu, lynx::tr ("Assign to new instrument track")));
- const auto tracks = lynx::trackmodes::instrumentTracksOf (engine.getSong(), 1);
- check ("assign_first_free_track", tracks == std::vector<int> { 0 }, juce::String (tracks.empty() ? -1 : tracks.front()));
- const auto again = rack.getChannelMenuForSnapshot (1);
- check ("unassign_offered", click (again, lynx::tr ("Unassign from instrument track")) && lynx::trackmodes::instrumentTracksOf (engine.getSong(), 1).empty());
- bool greyed = false;
- const auto voxMenu = rack.getChannelMenuForSnapshot (vox);
- for (juce::PopupMenu::MenuItemIterator it (voxMenu); it.next();)
- if (plain (it.getItem().text) == plain (lynx::tr ("Assign to new instrument track")))
- greyed = ! it.getItem().isEnabled;
- check ("assign_greyed_for_audio_clip_channel", greyed);
- }
- // ---- 5. Tools › One-click audio recording
- std::fprintf (stderr, "flplshot: tools\n");
- {
- const auto names = ui.getMenuNamesForSnapshot();
- const auto tools = ui.getMenuForSnapshot (names.indexOf (lynx::tr ("Tools")));
- const auto* oneClick = findSub (tools, lynx::tr ("One-click audio recording"));
- check ("one_click_submenu", oneClick != nullptr && texts (*oneClick, 3) == modelTexts (lynx::fltrackmenus::oneClickRecording()),
- oneClick != nullptr ? texts (*oneClick, 3).joinIntoString ("|") : juce::String ("missing"));
- saveMenus (juce::StringArray { "Tools", "One-click audio recording" }, std::vector<juce::PopupMenu> { tools, oneClick != nullptr ? *oneClick : juce::PopupMenu() },
- prefix + "-tools-one-click.png");
- const auto plan = lynx::oneclick::plan (engine.getSong(), {}, 2, lynx::oneclick::Into::playlist);
- check ("one_click_plan", plan.insert == 2 && plan.armInsert && plan.askInput && plan.songMode);
- }
- // ---- 6. Mixer › Disk recording › Latency compensation
- {
- auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
- const auto menu = strips.buildMenu (1);
- const auto* disk = findSub (menu, lynx::tr ("Disk recording"));
- int after = -1, at = -1, i = 0;
- bool ticked = false;
- if (disk != nullptr)
- for (juce::PopupMenu::MenuItemIterator it (*disk); it.next(); ++i)
- {
- if (plain (it.getItem().text) == plain (lynx::tr ("Auto-create audio clip (the rendered files go on the Playlist)")))
- after = i;
- if (plain (it.getItem().text) == plain (lynx::tr ("Latency compensation")))
- {
- at = i;
- ticked = it.getItem().isTicked;
- }
- }
- check ("latency_comp_item", disk != nullptr && after >= 0 && at == after + 1 && ticked && engine.getRecordOptions().latencyCompensation,
- juce::String (after) + " " + juce::String (at));
- saveMenus (juce::StringArray { "Disk recording" }, std::vector<juce::PopupMenu> { disk != nullptr ? *disk : juce::PopupMenu() },
- prefix + "-disk-recording.png");
- check ("latency_comp_toggles", disk != nullptr && click (*disk, lynx::tr ("Latency compensation")) && ! engine.getRecordOptions().latencyCompensation);
- }
- juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
- return allOk;
- }
- // --flclipshot (round 190dz): see the dispatch above
- // a menu as JUCE lays it out with explicit column breaks (PopupMenu::addColumnBreak): the columns side by side on
- // one menu background; custom items (the title band) are painted by their own component
- static juce::Image columnMenuImage (const juce::PopupMenu& menu)
- {
- auto& lf = juce::LookAndFeel::getDefaultLookAndFeel();
- const auto border = lf.getPopupMenuBorderSize();
- struct Row
- {
- const juce::PopupMenu::Item* item;
- int height;
- };
- std::vector<std::vector<Row>> columns (1);
- std::vector<int> widths (1, 160);
- for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
- {
- const auto& item = it.getItem();
- int w = 0, h = 0;
- if (item.customComponent != nullptr)
- item.customComponent->getIdealSize (w, h);
- else
- {
- lf.getIdealPopupMenuItemSize (item.text.upToFirstOccurrenceOf ("\t", false, false), item.isSeparator, item.isSectionHeader ? -1 : 0, w, h);
- if (item.isSectionHeader)
- h += h / 2; // as JUCE does
- if (item.text.containsChar ('\t'))
- w += 90;
- }
- columns.back().push_back ({ &item, h });
- widths.back() = juce::jmax (widths.back(), w + 10);
- if (item.shouldBreakAfter)
- {
- columns.emplace_back();
- widths.push_back (160);
- }
- }
- int width = 0, height = 0;
- for (std::size_t c = 0; c < columns.size(); ++c)
- {
- width += widths[c];
- int h = 2 * border;
- for (const auto& row : columns[c])
- h += row.height;
- height = juce::jmax (height, h);
- }
- auto image = lynx::shot::canvas (width, height);
- juce::Graphics g (image);
- lynx::shot::logical (g);
- lf.drawPopupMenuBackground (g, width, height);
- int x = 0;
- for (std::size_t c = 0; c < columns.size(); ++c)
- {
- int y = border;
- for (const auto& row : columns[c])
- {
- const auto& item = *row.item;
- const juce::Rectangle<int> r (x, y, widths[c], row.height);
- if (item.customComponent != nullptr)
- {
- juce::Graphics::ScopedSaveState state (g);
- g.setOrigin (r.getPosition());
- item.customComponent->setSize (r.getWidth(), r.getHeight());
- item.customComponent->paintEntireComponent (g, false);
- }
- else if (item.isSectionHeader)
- lf.drawPopupMenuSectionHeader (g, r, item.text);
- else
- {
- juce::Graphics::ScopedSaveState state (g);
- g.setOrigin (r.getPosition());
- lf.drawPopupMenuItem (g, r.withPosition (0, 0), item.isSeparator, item.isEnabled, false, item.isTicked, item.subMenu != nullptr,
- item.text.upToFirstOccurrenceOf ("\t", false, false), item.text.fromFirstOccurrenceOf ("\t", false, false),
- item.image.get(), nullptr);
- }
- y += row.height;
- }
- x += widths[c];
- if (c + 1 < columns.size()) // (JUCE's column separator)
- {
- g.setColour (lf.findColour (juce::PopupMenu::textColourId).withAlpha (0.15f));
- g.fillRect (x - 1, border, 1, height - 2 * border);
- }
- }
- return image;
- }
- // --genpresetshot (round 190fs): see the dispatch above
- bool runGenPresetShot (const juce::String& prefix)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- juce::StringArray report;
- bool allOk = true;
- const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
- report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
- allOk = allOk && ok;
- };
- const auto shoot = [&prefix] (juce::Component& c, const char* name) {
- savePng (c.createComponentSnapshot (c.getLocalBounds()), prefix + "-" + name + ".png");
- };
- const auto plain = [] (juce::String t) { return t.upToFirstOccurrenceOf ("\t", false, false).removeCharacters ("&"); };
- const auto texts = [&plain] (const juce::PopupMenu& menu) {
- juce::StringArray out;
- for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
- out.add (it.getItem().isSeparator ? juce::String ("-") : it.getItem().isSectionHeader ? "[" + plain (it.getItem().text) + "]" : plain (it.getItem().text));
- return out;
- };
- const auto click = [&plain] (const juce::PopupMenu& menu, const juce::String& text) {
- for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
- if (plain (it.getItem().text) == plain (text) && it.getItem().isEnabled && it.getItem().action != nullptr)
- {
- it.getItem().action();
- return true;
- }
- return false;
- };
- const auto sameSound = [] (const lynx::ChannelDef& a, const lynx::ChannelDef& b) { return lynx::genpresets::sameSound (a, b); };
- lynx::AudioEngine engine (false);
- const auto& fl = lynx::flStudioAccess();
- auto dx = lynx::natives::makeChannel (lynx::InstrumentKind::dx10, fl);
- auto osc = lynx::natives::makeChannel (lynx::InstrumentKind::threeosc, fl);
- check ("channels_made", dx.has_value() && osc.has_value());
- if (! dx || ! osc)
- {
- juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\n");
- return false;
- }
- engine.editSong ([&] (lynx::Song& s) {
- s.channels.clear();
- s.channels.push_back (*dx);
- s.channels.back().mixerTrack = 1;
- s.channels.push_back (*osc);
- s.channels.back().mixerTrack = 2;
- lynx::ChannelDef synth;
- synth.instrument = lynx::InstrumentKind::synth;
- synth.name = "Synth";
- synth.mixerTrack = 3;
- s.channels.push_back (synth);
- });
- const auto channel = [&engine] (int i) { return engine.getSong().channels[(std::size_t) i]; };
- // ---- 1. Fruity DX10: the preset box before and after "Save preset..."
- {
- auto frame = lynx::makeChannelFrame (engine, 0, 0);
- frame->setSize (juce::jmax (500, frame->getWidth()), juce::jmax (300, frame->getHeight()));
- auto menu = lynx::channelPresetMenu (*frame);
- check ("dx10_menu", menu.has_value());
- const auto before = menu ? texts (*menu) : juce::StringArray();
- check ("dx10_menu_has_save", before.contains (lynx::tr ("Save preset...")) && before.contains (lynx::tr ("Show the presets folder"))
- && ! before.contains ("[" + lynx::tr ("Your presets") + "]"), before.joinIntoString ("|"));
- if (menu)
- saveMenus (juce::StringArray { "Fruity DX10 presets" }, std::vector<juce::PopupMenu> { *menu }, prefix + "-dx10-menu-before.png");
- // a sound of its own: the bank's 4th preset, then a knob moved (a sound no factory preset has)
- const auto mine = [&] {
- auto c = channel (0);
- if (auto b = lynx::banks::withPreset (c, 3))
- c = *b;
- if (! c.pluginState.empty())
- c.pluginState[c.pluginState.size() / 2] ^= 0x5a;
- return c;
- }();
- engine.editSong ([&] (lynx::Song& s) { s.channels[0] = mine; });
- check ("dx10_saved", lynx::channelPresetSave (*frame, "My FM Bell"));
- const auto file = lynx::genpresetui::folderFor (lynx::InstrumentKind::dx10).getChildFile ("My FM Bell.lynxpreset");
- check ("dx10_file", file.existsAsFile() && lynx::genpresetui::isPresetFile (file), file.getFullPathName());
- check ("dx10_box_shows_it", lynx::channelPresetName (*frame) == "My FM Bell", lynx::channelPresetName (*frame));
- menu = lynx::channelPresetMenu (*frame);
- const auto after = menu ? texts (*menu) : juce::StringArray();
- check ("dx10_menu_your_presets", after.contains ("[" + lynx::tr ("Your presets") + "]") && after.contains ("My FM Bell")
- && after.contains (lynx::tr ("Delete preset \"{0}\"", { "My FM Bell" })), after.joinIntoString ("|"));
- if (menu)
- saveMenus (juce::StringArray { "Fruity DX10 presets" }, std::vector<juce::PopupMenu> { *menu }, prefix + "-dx10-menu.png");
- shoot (*frame, "dx10-window");
- // another sound, then the user's preset from the menu: the saved sound back, one undo step, project changed
- if (auto other = lynx::banks::withPreset (channel (0), 0))
- engine.editSong ([&] (lynx::Song& s) { s.channels[0] = *other; });
- check ("dx10_other_sound", ! sameSound (channel (0), mine));
- engine.markSaved();
- menu = lynx::channelPresetMenu (*frame);
- check ("dx10_load_click", menu.has_value() && click (*menu, "My FM Bell"));
- check ("dx10_loaded_identical", sameSound (channel (0), mine) && channel (0).pluginState == mine.pluginState);
- check ("dx10_loaded_name_and_insert", channel (0).name == "My FM Bell" && channel (0).mixerTrack == 1,
- juce::String::fromUTF8 (channel (0).name.c_str()));
- check ("dx10_project_changed", engine.isModified());
- engine.undo();
- check ("dx10_one_undo_step", ! sameSound (channel (0), mine));
- engine.redo();
- check ("dx10_redo", sameSound (channel (0), mine));
- // the Browser: a new channel with the preset's generator, sound and name
- juce::String error;
- const auto count = engine.getSong().channels.size();
- check ("browser_new_channel", lynx::genpresetui::addChannel (engine, file, error) && engine.getSong().channels.size() == count + 1, error);
- const auto added = engine.getSong().channels.back();
- check ("browser_channel_sound", added.instrument == lynx::InstrumentKind::dx10 && sameSound (added, mine) && added.name == "My FM Bell");
- engine.undo();
- check ("browser_channel_undo", engine.getSong().channels.size() == count);
- }
- // ---- 2. 3x Osc: save, the menu, delete
- {
- auto frame = lynx::makeChannelFrame (engine, 1, 0);
- frame->setSize (juce::jmax (500, frame->getWidth()), juce::jmax (300, frame->getHeight()));
- check ("3xosc_saved", lynx::channelPresetSave (*frame, "Wide Saw Lead") && lynx::channelPresetSave (*frame, "Sub Bass"));
- auto menu = lynx::channelPresetMenu (*frame);
- const auto items = menu ? texts (*menu) : juce::StringArray();
- check ("3xosc_menu", items.contains ("Wide Saw Lead") && items.contains ("Sub Bass") && items.contains (lynx::tr ("Save preset...")),
- items.joinIntoString ("|"));
- if (menu)
- saveMenus (juce::StringArray { "3x Osc presets" }, std::vector<juce::PopupMenu> { *menu }, prefix + "-3xosc-menu.png");
- shoot (*frame, "3xosc-window");
- check ("3xosc_delete", menu.has_value() && click (*menu, lynx::tr ("Delete preset \"{0}\"", { "Sub Bass" })));
- check ("3xosc_deleted", lynx::genpresetui::userPresets (lynx::InstrumentKind::threeosc).size() == 1
- && ! lynx::genpresetui::folderFor (lynx::InstrumentKind::threeosc).getChildFile ("Sub Bass.lynxpreset").exists());
- menu = lynx::channelPresetMenu (*frame);
- const auto left = menu ? texts (*menu) : juce::StringArray();
- check ("3xosc_menu_after_delete", left.contains ("Wide Saw Lead") && ! left.contains ("Sub Bass"), left.joinIntoString ("|"));
- }
- // ---- 3. LYNX's synth: its "Presets..." box
- {
- engine.editSong ([] (lynx::Song& s) { s.channels[2].synth.cutoff = 777.0f; });
- auto frame = lynx::makeChannelFrame (engine, 2, 0);
- frame->setSize (juce::jmax (500, frame->getWidth()), juce::jmax (300, frame->getHeight()));
- check ("synth_saved", lynx::channelPresetSave (*frame, "Dark Pad"));
- const auto menu = lynx::channelPresetMenu (*frame);
- const auto items = menu ? texts (*menu) : juce::StringArray();
- check ("synth_menu", items.contains ("Dark Pad") && items.contains (lynx::tr ("Save preset...")) && items.contains (lynx::tr ("Show the presets folder")),
- items.joinIntoString ("|"));
- if (menu)
- saveMenus (juce::StringArray { "Synth presets" }, std::vector<juce::PopupMenu> { *menu }, prefix + "-synth-menu.png");
- const auto saved = lynx::genpresetui::read (lynx::genpresetui::folderFor (lynx::InstrumentKind::synth).getChildFile ("Dark Pad.lynxpreset"));
- check ("synth_file", saved.has_value() && saved->sound.synth.cutoff == 777.0f);
- }
- // ---- 4. the name box (the hosted plugins' and the effects' "Save preset" box)
- {
- auto box = lynx::genpresetui::makeNameBox ("My FM Bell");
- box->setSize (juce::jmax (360, box->getWidth()), juce::jmax (150, box->getHeight()));
- shoot (*box, "save-name-box");
- check ("name_box", box->getTextEditorContents ("name") == "My FM Bell");
- }
- juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\n");
- return allOk;
- }
- // --flfixshot (round 190ey): see the dispatch above
- bool runFlFixShot (const juce::String& prefix)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- juce::StringArray report;
- bool allOk = true;
- const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
- report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
- allOk = allOk && ok;
- };
- const auto shoot = [&prefix] (juce::Component& c, const char* name) {
- savePng (c.createComponentSnapshot (c.getLocalBounds()), prefix + "-" + name + ".png");
- };
- const auto plain = [] (juce::String t) {
- t = t.upToFirstOccurrenceOf ("\t", false, false);
- if (const auto at = t.indexOf (juce::String (" (") + juce::String::charToString (1)); at >= 0)
- t = t.substring (0, at);
- return t.removeCharacters (juce::String ("&_") + juce::String::charToString (1));
- };
- const auto texts = [&plain] (const juce::PopupMenu& menu) {
- juce::StringArray out;
- for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
- out.add (it.getItem().isSeparator ? juce::String ("-") : it.getItem().isSectionHeader ? "[" + plain (it.getItem().text) + "]" : plain (it.getItem().text));
- return out;
- };
- const auto findSub = [&plain] (const juce::PopupMenu& menu, const juce::String& text) -> const juce::PopupMenu* {
- for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
- if (it.getItem().subMenu != nullptr && plain (it.getItem().text) == plain (text))
- return it.getItem().subMenu.get();
- return nullptr;
- };
- const auto click = [&plain] (const juce::PopupMenu& menu, const juce::String& text) {
- for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
- if (plain (it.getItem().text) == plain (text) && it.getItem().isEnabled && it.getItem().action != nullptr)
- {
- it.getItem().action();
- return true;
- }
- return false;
- };
- const auto folder = juce::File (prefix).getParentDirectory().getChildFile ("flfix-samples");
- folder.createDirectory();
- const auto writeWav = [] (const juce::File& file, double rate, int frames, double hz) {
- juce::AudioBuffer<float> buffer (1, frames);
- for (int i = 0; i < frames; ++i)
- buffer.setSample (0, i, (float) (0.8 * std::sin (juce::MathConstants<double>::twoPi * hz * i / rate) * std::exp (-i / (rate * 0.12))));
- file.deleteFile();
- juce::WavAudioFormat wav;
- if (auto out = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (file.createOutputStream().release(), rate, 1, 16, {}, 0)))
- out->writeFromAudioSampleBuffer (buffer, 0, frames);
- return file;
- };
- // ---- 1. the Sampler page (SMP-1 / 4 / 5 / 7, CTL-4)
- {
- lynx::AudioEngine engine (false);
- const auto clap = writeWav (folder.getChildFile ("Basic 808 Clap.wav"), 44100.0, 11600, 180.0);
- const auto loop48 = writeWav (folder.getChildFile ("Loop 48k.wav"), 48000.0, 48000, 220.0);
- engine.editSong ([&] (lynx::Song& s) {
- if (s.channels.empty())
- s.channels.resize (1);
- lynx::audioclips::loadSampleInto (s.channels[0], clap.getFullPathName().toStdString(), "808 Clap");
- });
- const auto sampler = [&engine] { return engine.getSong().channels[0].sampler; };
- auto frame = lynx::makeChannelFrame (engine, 0, 0);
- frame->setSize (frame->getWidth() > 0 ? frame->getWidth() : 700, frame->getHeight() > 0 ? frame->getHeight() : 720);
- frame->createComponentSnapshot (frame->getLocalBounds());
- lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
- auto& f = *frame;
- lynx::samplerPageTurn (f, "show", 0.0);
- const auto rate = engine.getTransport().sampleRate.load();
- check ("resample_greyed_at_project_rate", lynx::samplerPageQuery (f, "resample") == (std::abs (rate - 44100.0) < 0.5 ? "0" : "1"), juce::String (rate));
- check ("load_regions_greyed_without_regions", lynx::samplerPageQuery (f, "loadRegions") == "0");
- check ("load_markers_greyed_without_markers", lynx::samplerPageQuery (f, "loadMarkers") == "0");
- check ("bit_depth_16", lynx::samplerPageQuery (f, "corner") == "16", lynx::samplerPageQuery (f, "corner"));
- check ("wave_hint_summary", lynx::samplerPageQuery (f, "waveHint").startsWith ("44100Hz, 16Bit int mono, 0:263"), lynx::samplerPageQuery (f, "waveHint"));
- shoot (f, "sampler-44k");
- // SMP-5: MUL's text
- lynx::samplerPageTurn (f, "mul", 800.0);
- check ("mul_text", lynx::samplerPageQuery (f, "mulText") == "105.70%", lynx::samplerPageQuery (f, "mulText"));
- lynx::samplerPageTurn (f, "mul", 0.0);
- // SMP-4: CROSSFADE on a loopless sample: Use loop points on, the loop = the whole sample, the box reads 32
- engine.editSong ([] (lynx::Song& s) { s.channels[0].sampler.useLoopPoints = false; });
- lynx::samplerPageTurn (f, "crossfade", 120.0);
- check ("crossfade_loops_whole_sample", sampler().useLoopPoints && sampler().loopStart == 0 && sampler().loopEnd == 11599,
- juce::String (sampler().loopStart) + ".." + juce::String (sampler().loopEnd));
- check ("bit_depth_32_precomputed", lynx::samplerPageQuery (f, "corner") == "32", lynx::samplerPageQuery (f, "corner"));
- frame->createComponentSnapshot (frame->getLocalBounds());
- lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
- shoot (f, "sampler-crossfade-red-loop");
- lynx::samplerPageTurn (f, "crossfade", 0.0);
- // SMP-3: a loop set with END alone, drawn red (FL: 0..276)
- engine.editSong ([] (lynx::Song& s) {
- s.channels[0].sampler.loopStart = 0;
- s.channels[0].sampler.loopEnd = 2400;
- });
- lynx::samplerPageTurn (f, "show", 0.0);
- shoot (f, "sampler-end-loop-red");
- // round 190gw (live check 190gu B3): the waveform menu's Spectrum view / Multichannel waveform view, on a stereo
- // clap-like noise burst (left and right differ) with no loop, as FL's shot
- {
- const auto noisy = folder.getChildFile ("Noise Clap.wav");
- juce::AudioBuffer<float> b (2, 44100);
- juce::Random random (190);
- for (int i = 0; i < b.getNumSamples(); ++i)
- for (int c = 0; c < 2; ++c)
- b.setSample (c, i, (float) ((random.nextFloat() * 2.0f - 1.0f) * 0.9 * std::exp (-i / (44100.0 * (c == 0 ? 0.10 : 0.18)))
- * (i > 1500 * c ? 1.0 : 0.15)));
- noisy.deleteFile();
- juce::WavAudioFormat wav;
- if (auto out = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (noisy.createOutputStream().release(), 44100.0, 2, 16, {}, 0)))
- out->writeFromAudioSampleBuffer (b, 0, b.getNumSamples());
- const auto before = engine.getSong().channels[0];
- engine.editSong ([&] (lynx::Song& s) {
- s.channels[0].samplePath = noisy.getFullPathName().toStdString();
- s.channels[0].sampler.loopStart = s.channels[0].sampler.loopEnd = -1;
- s.channels[0].sampler.useLoopPoints = false;
- });
- lynx::samplerPageTurn (f, "show", 0.0);
- frame->createComponentSnapshot (frame->getLocalBounds()); // (starts the new file's waveform)
- lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
- lynx::samplerpage::waveViews().spectrum = true;
- lynx::samplerPageTurn (f, "show", 0.0);
- shoot (f, "sampler-spectrum-view");
- lynx::samplerpage::waveViews() = { false, true };
- lynx::samplerPageTurn (f, "show", 0.0);
- shoot (f, "sampler-multichannel-view");
- lynx::samplerpage::waveViews() = {};
- engine.editSong ([&before] (lynx::Song& s) { s.channels[0] = before; });
- lynx::samplerPageTurn (f, "show", 0.0);
- frame->createComponentSnapshot (frame->getLocalBounds());
- lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
- }
- // SMP-7: the waveform menu
- const auto waveMenu = lynx::samplerWaveMenu (f);
- juce::StringArray expected { lynx::tr ("Reload"), lynx::tr ("Save as..."), lynx::tr ("Locate file"), lynx::tr ("Copy audio to clipboard"),
- lynx::tr ("Paste audio from clipboard"), "-", lynx::tr ("Edit in audio editor"),
- lynx::tr ("Edit in pitch corrector"), lynx::tr ("Edit in time warper"), "-", // (round 190gw)
- lynx::tr ("Open in new sampler channel"), lynx::tr ("Open in new Fruity Granulizer channel"),
- lynx::tr ("Open in new Fruity Slicer channel"), lynx::tr ("Open in new Slicex channel"), "-", // (round 190gk)
- lynx::tr ("Detect tempo") };
- if (lynx::fileProperties) // (round 190gk: Windows only)
- expected.add (lynx::tr ("Get properties"));
- expected.addArray (juce::StringArray { "-", lynx::tr ("Spectrum view"), lynx::tr ("Multichannel waveform view") }); // (round 190gw)
- check ("wave_menu_items", waveMenu.has_value() && texts (*waveMenu) == expected, waveMenu.has_value() ? texts (*waveMenu).joinIntoString ("|") : juce::String ("none"));
- if (waveMenu.has_value())
- saveMenus (juce::StringArray { "Sampler waveform" }, std::vector<juce::PopupMenu> { *waveMenu }, prefix + "-wave-menu.png");
- check ("copy_audio_to_clipboard", waveMenu.has_value() && click (*waveMenu, lynx::tr ("Copy audio to clipboard"))
- && lynx::audioclipboard::editor().frames() == 11600);
- // SMP-1: a 48 kHz sample in this project: Resample enabled
- lynx::samplerPageTurn (f, "show", 0.0);
- engine.editSong ([&] (lynx::Song& s) { s.channels[0].samplePath = loop48.getFullPathName().toStdString(); });
- lynx::samplerPageTurn (f, "show", 0.0);
- check ("resample_enabled_48k", lynx::samplerPageQuery (f, "resample") == (std::abs (rate - 48000.0) < 0.5 ? "0" : "1"), juce::String (rate));
- frame->createComponentSnapshot (frame->getLocalBounds()); // (starts the new file's waveform)
- lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
- shoot (f, "sampler-48k");
- // CTL-4: Remove sample renames the channel "Sampler"
- lynx::samplerFileRowPress (f, 3);
- check ("remove_sample_renames", engine.getSong().channels[0].name == "Sampler" && engine.getSong().channels[0].samplePath.empty(),
- juce::String::fromUTF8 (engine.getSong().channels[0].name.c_str()));
- lynx::samplerPageTurn (f, "show", 0.0);
- check ("no_sample_content_greyed", lynx::samplerPageQuery (f, "keepOnDisk") == "0" && lynx::samplerPageQuery (f, "resample") == "0");
- shoot (f, "sampler-removed");
- }
- // ---- 2. the Multilink button's menu with multilink off (CTL-1)
- lynx::AudioEngine engine (false);
- lynx::MainComponent ui (engine, false);
- ui.setSize (1600, 900);
- {
- using lynx::AutomationTarget;
- using lynx::AutomationTargetKind;
- engine.editSong ([] (lynx::Song& s) {
- if (s.channels.empty())
- s.channels.resize (1);
- s.channels[0].name = "808 Kick";
- });
- engine.setMultilink (false);
- engine.noteTweaked ({ AutomationTargetKind::channelVolume, 0 });
- engine.noteTweaked ({ AutomationTargetKind::channelPan, 0 });
- const auto menu = ui.getMultilinkMenuForSnapshot();
- juce::PopupMenu::MenuItemIterator first (menu);
- first.next();
- const auto caption = first.getItem().text;
- bool columnBreak = false, lynxLines = false;
- juce::String rightCaption;
- for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
- {
- if (columnBreak && rightCaption.isEmpty() && it.getItem().isSectionHeader)
- rightCaption = it.getItem().text;
- columnBreak = columnBreak || it.getItem().shouldBreakAfter;
- lynxLines = lynxLines || it.getItem().text == lynx::tr ("Link to controller");
- }
- check ("ml_off_left_column_named", first.getItem().isSectionHeader && caption == lynx::describeAutomationTarget (engine, { AutomationTargetKind::channelPan, 0 }), caption);
- check ("ml_off_two_columns", columnBreak && rightCaption == lynx::tr ("Last 2 tweaked parameters"), rightCaption);
- check ("ml_off_no_lynx_greyed_lines", ! lynxLines);
- savePng (columnMenuImage (menu), prefix + "-multilink-off-menu.png");
- }
- // ---- 3. the Playlist (PL-1 / 2 / 3 / 6 / 7 / 8)
- auto& playlist = ui.getPlaylistForSnapshot();
- {
- auto song = lynx::Song::makeDefault();
- lynx::ChannelDef bass;
- bass.name = "Amount Too - Bass";
- bass.instrument = lynx::InstrumentKind::audioClip;
- bass.samplePath = writeWav (folder.getChildFile ("bass.wav"), 44100.0, 88200, 82.0).getFullPathName().toStdString();
- bass.misc.levels.volume = 1.468f;
- song.channels.push_back (bass);
- lynx::Clip c;
- c.kind = lynx::ClipKind::audio;
- c.channel = (int) song.channels.size() - 1;
- c.track = 3;
- c.start = 4 * lynx::ppq;
- c.length = 2 * lynx::ppq;
- song.playlist.push_back (c);
- engine.setSong (std::move (song));
- }
- engine.dispatchPendingMessages();
- const auto clipIndex = (int) engine.getSong().playlist.size() - 1;
- {
- const auto menu = playlist.getClipMenuForSnapshot (clipIndex);
- const auto* automate = findSub (menu, lynx::tr ("Automate"));
- check ("automate_volume_runs", automate != nullptr && click (*automate, lynx::tr ("Volume")));
- const auto& song = engine.getSong();
- const auto made = (int) song.automations.size() - 1;
- check ("automate_makes_current_clip", made >= 0 && playlist.brush.kind == lynx::ClipKind::automation && playlist.brush.index == made,
- juce::String (playlist.brush.index));
- // (PL-2: Levels VOL 147 %, FL's clip plays unity)
- check ("automate_volume_unity", made >= 0 && song.automations.back().points[0].value == 0.5f
- && lynx::lasttweak::valueText (song, song.automations.back().target, song.automations.back().points[0].value) == "100% 0.0dB 1.00");
- const auto again = playlist.getClipMenuForSnapshot (clipIndex);
- const auto* automate2 = findSub (again, lynx::tr ("Automate"));
- check ("automate_second_is_2", automate2 != nullptr && click (*automate2, lynx::tr ("Volume"))
- && juce::String::fromUTF8 (engine.getSong().automations.back().name.c_str()).endsWith (" #2"),
- juce::String::fromUTF8 (engine.getSong().automations.back().name.c_str()));
- // PL-7: Fade in / out curve
- const auto* fadeIn = findSub (menu, lynx::tr ("Fade in curve"));
- const auto* fadeOut = findSub (menu, lynx::tr ("Fade out curve"));
- const juce::StringArray curve { lynx::tr ("Reset"), lynx::tr ("Normalize"), lynx::tr ("Normalize selection as a group"), lynx::tr ("Create crossfade"),
- lynx::tr ("Manual"), "[" + lynx::tr ("Declicker") + "]", lynx::tr ("Automatic"), lynx::tr ("Disabled"), lynx::tr ("Enabled"),
- "[" + lynx::tr ("Curve shape") + "]", lynx::tr ("Smooth curve"), lynx::tr ("Single curve") };
- check ("fade_curve_submenus", fadeIn != nullptr && fadeOut != nullptr && texts (*fadeIn) == curve && texts (*fadeOut) == curve,
- fadeIn != nullptr ? texts (*fadeIn).joinIntoString ("|") : juce::String ("missing"));
- if (fadeOut != nullptr)
- saveMenus (juce::StringArray { "Audio clip menu", "Fade out curve" }, std::vector<juce::PopupMenu> { menu, *fadeOut }, prefix + "-fade-curve-menu.png");
- // PL-8: Detect tempo is one item now
- bool detectItem = false;
- for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
- if (plain (it.getItem().text) == plain (lynx::tr ("Detect tempo")))
- detectItem = it.getItem().subMenu == nullptr && it.getItem().action != nullptr;
- check ("detect_tempo_item", detectItem);
- // PL-3: Preview through the channel; transport start ends it
- check ("preview_through_channel", engine.previewClipThroughChannel ((std::size_t) clipIndex) && engine.isClipPreviewing());
- engine.play();
- check ("preview_stops_on_transport", ! engine.isClipPreviewing());
- engine.stop();
- check ("preview_again_then_stop", engine.previewClipThroughChannel ((std::size_t) clipIndex) && engine.isClipPreviewing());
- engine.stop();
- check ("preview_stops_on_stop", ! engine.isClipPreviewing());
- }
- // PL-8: the dialog
- {
- lynx::ui::TempoDetectionRequest r;
- r.name = "Amount Too - Bass";
- // (a drum-like loop at 117.5 BPM, 100 beats as in FL's dialog: clicks on every beat)
- {
- auto beats = std::make_shared<lynx::SampleData>();
- beats->sampleRate = 44100.0;
- const auto period = 44100.0 * 60.0 / 117.5;
- beats->left.assign ((std::size_t) std::llround (period * 100.0), 0.0f);
- for (int b = 0; b < 100; ++b)
- for (int i = 0; i < 2000; ++i)
- if (const auto at = (std::size_t) std::llround (b * period) + (std::size_t) i; at < beats->left.size())
- beats->left[at] = (float) (0.9 * std::sin (i * 0.09) * std::exp (-i / 400.0));
- r.sample = beats;
- }
- r.projectBpm = 100.0;
- double applied = -1.0;
- r.apply = [&applied] (double beats) { applied = beats; };
- auto panel = lynx::ui::makeTempoDetectionPanel (r);
- panel->setSize (panel->getWidth(), panel->getHeight());
- shoot (*panel, "tempo-detection");
- report.add ("tempo dialog title: " + lynx::ui::tempoDetectionTitle (r.name));
- const auto project = lynx::ui::pressTempoDetectionButton (*panel, panel->getNumChildComponents() - 3);
- const auto seconds = (double) r.sample->frames() / r.sample->sampleRate; // (100 beats at 117.5 BPM)
- check ("tempo_project_button", std::abs (applied - seconds * 100.0 / 60.0) < 1.0e-6, project + " -> " + juce::String (applied));
- const auto none = lynx::ui::pressTempoDetectionButton (*panel, panel->getNumChildComponents() - 2);
- check ("tempo_no_tempo_button", applied == 0.0, none);
- }
- // ---- 4. issue #152's question (ISS152-1): FL's message with "Remember my choice"
- {
- auto box = lynx::makeFlMessageDialog ({ lynx::tr ("External input"),
- lynx::tr ("You've selected an external input. Do you want to switch to |External input only| to avoid recording internal audio on this track?"),
- { lynx::tr ("Yes"), lynx::tr ("No") }, true });
- shoot (*box, "external-input-question");
- bool listed = false;
- for (const auto& m : lynx::messages::all())
- listed = listed || juce::String (m.id) == "RecAutoSwitchExternalInput";
- check ("external_input_in_manage_messages", listed);
- }
- // ---- 5. round 190gk: FL's Start in the render window; the Sampler's "Open in new Fruity Slicer / Slicex channel";
- // a Gross Beat slot picked by MIDI becomes its parameter
- {
- lynx::AudioEngine engine (false);
- auto panel = lynx::makeClipRenderPanel (engine);
- panel->setSize (panel->getWidth() > 0 ? panel->getWidth() : 640, panel->getHeight() > 0 ? panel->getHeight() : 480);
- juce::String button;
- for (auto* c : panel->getChildren())
- if (auto* b = dynamic_cast<juce::TextButton*> (c); b != nullptr && b->isVisible() && b->getTooltip() == lynx::tr ("Start rendering"))
- button = b->getButtonText();
- check ("render_button_start", button == lynx::trc ("@render button: Start") && button == "Start", button);
- shoot (*panel, "fltails190gk-render-start");
- const auto clap = writeWav (folder.getChildFile ("Slice me.wav"), 44100.0, 44100, 140.0);
- engine.editSong ([] (lynx::Song& s) {
- s.channels.resize (2);
- s.channels[0] = {};
- s.channels[0].instrument = lynx::InstrumentKind::fruityslicer;
- s.channels[0].name = "Fruity Slicer";
- s.channels[1] = {};
- s.channels[1].instrument = lynx::InstrumentKind::slicex;
- s.channels[1].name = "Slicex";
- });
- const auto locate = [] (int index) {
- return [index] (lynx::Song& s) -> lynx::ChannelDef* { return index < (int) s.channels.size() ? &s.channels[(std::size_t) index] : nullptr; };
- };
- lynx::loadSampleWhenOpened (0, clap.getFullPathName());
- auto slicer = lynx::makeFruitySlicerEditor (engine, locate (0), 0);
- const auto& fs = engine.getSong().channels[0];
- check ("open_in_new_fruity_slicer", fs.samplePath == clap.getFullPathName().toStdString() && ! fs.pluginState.empty(), juce::String (fs.samplePath));
- lynx::loadSlicexSampleWhenOpened (1, clap.getFullPathName());
- auto slicex = lynx::makeSlicexEditor (engine, locate (1), 1);
- const auto& sx = engine.getSong().channels[1];
- check ("open_in_new_slicex", sx.samplePath == clap.getFullPathName().toStdString() && ! sx.pluginState.empty(), juce::String (sx.samplePath));
- auto again = lynx::makeSlicexEditor (engine, locate (1), 1); // (the request is used once)
- check ("open_in_new_used_once", engine.getSong().channels[1].samplePath == sx.samplePath);
- // Gross Beat on insert 1: two notes on its MIDI input, one block, the engine's timer step
- engine.editSong ([] (lynx::Song& s) {
- if (s.mixer.size() < 2)
- s.mixer.resize (2);
- s.mixer[1].effects = { lynx::makeEffectSlot (lynx::EffectKind::grossBeat) };
- });
- engine.dispatchPendingMessages();
- auto fx = engine.getEffect (1, 0);
- check ("gb_running", fx != nullptr);
- if (fx != nullptr)
- {
- std::vector<float> l (512, 0.1f), r (512, 0.1f);
- fx->prepare (44100.0);
- fx->setSongPosition (0.0);
- fx->midiNote (60 + 9, 100, 0);
- fx->midiNote (24 + 3, 100, 0);
- fx->process (l.data(), r.data(), 512, engine.getSong().mixer[1].effects[0].params, 120.0);
- engine.pumpGrossBeatPicks();
- const auto& p = engine.getSong().mixer[1].effects[0].params;
- check ("gb_midi_pick_sets_parameters", lynx::grossbeat::rawFromParam (0, p[0]) == 9 && lynx::grossbeat::rawFromParam (1, p[1]) == 3,
- juce::String (lynx::grossbeat::rawFromParam (0, p[0])) + " " + juce::String (lynx::grossbeat::rawFromParam (1, p[1])));
- }
- }
- juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
- return allOk;
- }
- // --grooveshot190fm (round 190fm): see the dispatch above
- bool runGrooveShot190fm (const juce::String& prefix)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- juce::StringArray report;
- bool allOk = true;
- const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
- report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
- allOk = allOk && ok;
- };
- const auto plain = [] (juce::String t) {
- t = t.upToFirstOccurrenceOf ("\t", false, false);
- return t.removeCharacters (juce::String ("&_") + juce::String::charToString (1));
- };
- const auto sub = [&plain] (const juce::PopupMenu& menu, const juce::String& start) -> const juce::PopupMenu* {
- for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
- if (it.getItem().subMenu != nullptr && plain (it.getItem().text).startsWith (start))
- return it.getItem().subMenu.get();
- return nullptr;
- };
- const auto item = [&plain] (const juce::PopupMenu& menu, const juce::String& text) -> const juce::PopupMenu::Item* {
- for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
- if (plain (it.getItem().text) == text)
- return &it.getItem();
- return nullptr;
- };
- lynx::AudioEngine engine (false);
- lynx::MainComponent ui (engine, false);
- ui.setSize (1600, 900);
- std::uint32_t classic = 0;
- {
- auto song = lynx::Song::makeDefault();
- song.mode = lynx::PlayMode::song;
- song.playlist.push_back ({ 0, 0, 0, 4 * lynx::ppq, 0 });
- song.playlist.push_back ({ 0, 1, 4 * lynx::ppq, 4 * lynx::ppq, 0 });
- for (const auto& e : lynx::groove::factoryBank())
- if (juce::String (e.folder) == "Classic swing" && e.groove.base == lynx::GrooveBase::sixteenth
- && (e.groove.name == "Swing 16ths 54 %" || e.groove.name == "Swing 16ths 58 %" || e.groove.name == "Swing 16ths 62 %"
- || e.groove.name == "Swing 16ths 71 %"))
- {
- const auto id = lynx::groove::add (song.grooves, e.groove);
- if (e.groove.name == "Swing 16ths 58 %")
- classic = id;
- }
- song.playlist[0].groove = classic;
- engine.setSong (std::move (song));
- }
- engine.dispatchPendingMessages();
- auto& playlist = ui.getPlaylistForSnapshot();
- const auto menu = playlist.getClipMenuForSnapshot (0);
- const auto* chooser = sub (menu, lynx::tr ("Groove"));
- check ("groove_chooser_in_clip_menu", chooser != nullptr);
- const auto* add = chooser != nullptr ? sub (*chooser, lynx::tr ("Add a groove")) : nullptr;
- const auto* folder = add != nullptr ? sub (*add, lynx::tr ("Classic swing")) : nullptr;
- check ("classic_swing_folder", folder != nullptr && folder->getNumItems() == 27, folder != nullptr ? juce::String (folder->getNumItems()) : juce::String ("missing"));
- const auto* commit = item (menu, lynx::tr ("Commit groove"));
- check ("commit_enabled_with_a_groove", commit != nullptr && commit->isEnabled);
- check ("extract_present", item (menu, lynx::tr ("Extract groove")) != nullptr);
- {
- juce::StringArray names { "Pattern clip menu" };
- std::vector<juce::PopupMenu> menus { menu };
- if (chooser != nullptr)
- {
- names.add ("Groove");
- menus.push_back (*chooser);
- }
- if (add != nullptr)
- {
- names.add ("Add a groove");
- menus.push_back (*add);
- }
- if (folder != nullptr)
- {
- names.add ("Classic swing");
- menus.push_back (*folder);
- }
- saveMenus (names, menus, prefix + "-playlist-clip-menu.png");
- }
- // the second clip (no groove): Commit is off; choosing a groove from the menu sets it
- {
- const auto other = playlist.getClipMenuForSnapshot (1);
- const auto* c2 = item (other, lynx::tr ("Commit groove"));
- check ("commit_disabled_without_a_groove", c2 != nullptr && ! c2->isEnabled);
- const auto* ch2 = sub (other, lynx::tr ("Groove"));
- const auto* pick = ch2 != nullptr ? item (*ch2, "Swing 16ths 71 %") : nullptr;
- if (pick != nullptr && pick->action != nullptr)
- pick->action();
- const auto& song = engine.getSong();
- check ("chooser_sets_the_clip_groove", song.playlist.size() == 2 && lynx::groove::ofClip (song, song.playlist[1]) != nullptr
- && lynx::groove::ofClip (song, song.playlist[1])->name == "Swing 16ths 71 %");
- }
- // the pool with the classic grooves
- {
- auto pool = lynx::makeGroovePool (engine);
- pool->setSize (900, lynx::groovePoolHeight (engine));
- savePng (pool->createComponentSnapshot (pool->getLocalBounds()), prefix + "-pool.png");
- }
- // .lynx: a Playlist clip's groove comes back; a project without one writes nothing new
- {
- juce::String error;
- const auto& song = engine.getSong();
- const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
- check ("lynx_round_trip", back && back->playlist.size() == 2 && back->playlist[0].groove == song.playlist[0].groove
- && back->playlist[1].groove == song.playlist[1].groove && back->grooves == song.grooves,
- error);
- auto old = lynx::Song::makeDefault();
- old.playlist.push_back ({ 0, 0, 0, 4 * lynx::ppq, 0 });
- const auto json = lynx::ProjectFile::toJson (old, false);
- const auto reloaded = lynx::ProjectFile::fromJson (json, error);
- check ("old_project_unchanged", reloaded && lynx::ProjectFile::toJson (*reloaded, false) == json && reloaded->playlist[0].groove == 0);
- }
- // Commit from the menu: the clip's pattern (shared with the second clip) is copied, the groove is off
- {
- const auto patterns = engine.getSong().patterns.size();
- const auto again = playlist.getClipMenuForSnapshot (0);
- if (const auto* c = item (again, lynx::tr ("Commit groove")); c != nullptr && c->action != nullptr)
- c->action();
- const auto& song = engine.getSong();
- check ("commit_runs", song.playlist[0].groove == 0 && song.patterns.size() == patterns + 1 && song.playlist[0].pattern == (int) patterns);
- }
- juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\n" + (allOk ? "ALL OK" : "SOME FAILED") + "\n");
- return allOk;
- }
- bool runFlClipShot (const juce::String& prefix)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- juce::StringArray report;
- bool allOk = true;
- const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
- report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
- allOk = allOk && ok;
- };
- const auto plain = [] (juce::String t) {
- t = t.upToFirstOccurrenceOf ("\t", false, false);
- if (const auto at = t.indexOf (juce::String (" (") + juce::String::charToString (1)); at >= 0)
- t = t.substring (0, at);
- return t.removeCharacters (juce::String ("&_") + juce::String::charToString (1));
- };
- const auto find = [&plain] (const juce::PopupMenu& menu, const juce::String& text) -> const juce::PopupMenu::Item* {
- for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
- if (plain (it.getItem().text) == plain (text))
- return &it.getItem();
- return nullptr;
- };
- const auto click = [&find] (const juce::PopupMenu& menu, const juce::String& text) {
- const auto* item = find (menu, text);
- if (item == nullptr || ! item->isEnabled || item->action == nullptr)
- return false;
- item->action();
- return true;
- };
- lynx::AudioEngine engine (false);
- lynx::MainComponent ui (engine, false);
- ui.setSize (1600, 900);
- int vox = -1;
- {
- auto song = lynx::Song::makeDefault();
- song.channels.push_back ({});
- song.channels.back().name = "Vox";
- song.channels.back().instrument = lynx::InstrumentKind::audioClip;
- song.channels.back().samplePath = writeShotSample (juce::File (prefix + "-vox.wav"), 330.0).getFullPathName().toStdString();
- vox = (int) song.channels.size() - 1;
- lynx::Clip c;
- c.kind = lynx::ClipKind::audio;
- c.channel = vox;
- c.track = 3;
- c.start = 4 * lynx::ppq;
- c.length = 2 * lynx::ppq;
- c.fadeIn = lynx::ppq / 4;
- song.playlist.push_back (c);
- engine.setSong (std::move (song));
- }
- engine.dispatchPendingMessages();
- auto& playlist = ui.getPlaylistForSnapshot();
- // ---- 1. the audio clip menu: FL's order, sections and columns, then LYNX's own items
- {
- const auto menu = playlist.getClipMenuForSnapshot (0);
- juce::StringArray got, want;
- int breakAfter = -1;
- for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
- {
- const auto& item = it.getItem();
- got.add (item.customComponent != nullptr ? "[" + lynx::tr ("Audio clip") + "]"
- : item.isSeparator ? juce::String ("-")
- : item.isSectionHeader ? "[" + plain (item.text) + "]"
- : plain (item.text));
- if (item.shouldBreakAfter)
- breakAfter = got.size() - 1;
- }
- for (const auto& e : lynx::flclipmenu::shown (true, false))
- if (e.kind != lynx::flclipmenu::Entry::Kind::columnBreak)
- want.add (e.kind == lynx::flclipmenu::Entry::Kind::separator ? juce::String ("-")
- : e.kind == lynx::flclipmenu::Entry::Kind::header ? "[" + lynx::tr (e.text.c_str()) + "]"
- : lynx::tr (e.text.c_str()));
- want.add ("-");
- want.add ("[" + lynx::tr ("LYNX extras") + "]"); // (round 190gi)
- for (const auto& x : lynx::flclipmenu::lynxExtras())
- want.add (lynx::tr (x.c_str()));
- check ("clip_menu_fl_order", got == want, got.joinIntoString ("|"));
- check ("clip_menu_two_columns", breakAfter >= 0 && got[breakAfter] == lynx::tr ("Chop") && got[breakAfter + 1] == "[" + lynx::tr ("Sample") + "]",
- juce::String (breakAfter));
- const auto* crossfade = find (menu, lynx::tr ("Crossfade with"));
- check ("crossfade_with_greyed", crossfade != nullptr && ! crossfade->isEnabled);
- const auto* region = find (menu, lynx::tr ("Select region"));
- const auto* full = region != nullptr && region->subMenu != nullptr ? find (*region->subMenu, lynx::tr ("Full")) : nullptr;
- check ("select_region_full_ticked", full != nullptr && full->isTicked);
- const auto* chop = find (menu, lynx::tr ("Chop"));
- check ("chop_time_based", chop != nullptr && chop->subMenu != nullptr && find (*chop->subMenu, lynx::tr ("Chop in 32nd beats")) != nullptr
- && find (*chop->subMenu, lynx::tr ("Chop to grid")) != nullptr);
- savePng (columnMenuImage (menu), prefix + "-clip-menu.png");
- std::fprintf (stderr, "flclipshot: menu saved\n");
- // Muted is a check; Reset fades clears the fades; Select all similar clips selects
- check ("muted_toggles", click (menu, lynx::tr ("Muted")) && engine.getSong().playlist[0].muted);
- const auto again = playlist.getClipMenuForSnapshot (0);
- const auto* muted = find (again, lynx::tr ("Muted"));
- check ("muted_ticked", muted != nullptr && muted->isTicked);
- check ("reset_fades", click (again, lynx::tr ("Reset fades")) && engine.getSong().playlist[0].fadeIn == 0);
- engine.undo();
- engine.undo();
- engine.dispatchPendingMessages();
- std::fprintf (stderr, "flclipshot: automate\n");
- // Automate › Volume / Panning: the clip channel's Levels adjustment (FL's channel parameters 0x11 / 0x10)
- const auto fresh = playlist.getClipMenuForSnapshot (0);
- const auto* automate = find (fresh, lynx::tr ("Automate"));
- const auto before = engine.getSong().automations.size();
- check ("automate_volume_runs", automate != nullptr && automate->subMenu != nullptr && click (*automate->subMenu, lynx::tr ("Volume")));
- const auto& song = engine.getSong();
- const auto ok = song.automations.size() == before + 1 && song.automations.back().target.kind == lynx::AutomationTargetKind::channelAdjust
- && song.automations.back().target.param == lynx::leveladjust::volume && song.automations.back().target.index == vox
- && std::abs (song.automations.back().points[0].value - 0.5f) < 1.0e-6f;
- check ("automate_volume_is_level_adjust", ok, ok ? juce::String::fromUTF8 (song.automations.back().name.c_str()) : juce::String());
- engine.undo();
- engine.dispatchPendingMessages();
- }
- std::fprintf (stderr, "flclipshot: overlap\n");
- // ---- 2. a second channel's clip overlapping: Crossfade with lists it and makes FL's crossfade clip (round 190gw)
- {
- engine.editSong ([vox] (lynx::Song& s) {
- auto copy = s.playlist[0]; // (another audio clip channel's clip, at the same time)
- s.channels.push_back (s.channels[(std::size_t) vox]);
- s.channels.back().name = "Vox 2";
- copy.channel = (int) s.channels.size() - 1;
- copy.track = 4;
- s.playlist.push_back (copy);
- });
- engine.dispatchPendingMessages();
- const auto overlapped = playlist.getClipMenuForSnapshot (0);
- const auto* with = find (overlapped, lynx::tr ("Crossfade with"));
- check ("crossfade_with_lists_the_overlap", with != nullptr && with->isEnabled && with->subMenu != nullptr && find (*with->subMenu, "Vox 2") != nullptr);
- const auto made = with != nullptr && with->subMenu != nullptr && click (*with->subMenu, "Vox 2");
- engine.dispatchPendingMessages();
- const auto& xsong = engine.getSong();
- const auto xok = made && ! xsong.automations.empty() && xsong.automations.back().links.size() == 2
- && juce::String::fromUTF8 (xsong.automations.back().name.c_str()).endsWith (" to Vox 2 crossfade");
- check ("crossfade_with_makes_the_clip", xok, xok ? juce::String::fromUTF8 (xsong.automations.back().name.c_str()) : juce::String());
- if (made)
- engine.undo();
- engine.undo();
- engine.dispatchPendingMessages();
- }
- std::fprintf (stderr, "flclipshot: misc\n");
- // ---- 3. the channel's Misc tab: Levels adjustment = the offsets (pan 0, volume 100 %, Mod X / Y 0 %)
- {
- engine.editSong ([vox] (lynx::Song& s) {
- s.channels[(std::size_t) vox].misc.levels.volume = 0.5f;
- s.channels[(std::size_t) vox].misc.levels.pan = -0.25f;
- });
- engine.dispatchPendingMessages();
- auto frame = lynx::makeChannelFrame (engine, vox, -1);
- frame->setSize (juce::jmax (frame->getWidth(), 800), juce::jmax (frame->getHeight(), 420));
- savePng (frame->createComponentSnapshot (frame->getLocalBounds()), prefix + "-misc-levels.png");
- auto synthFrame = lynx::makeChannelFrame (engine, 0, -1);
- synthFrame->setSize (juce::jmax (synthFrame->getWidth(), 800), juce::jmax (synthFrame->getHeight(), 420));
- savePng (synthFrame->createComponentSnapshot (synthFrame->getLocalBounds()), prefix + "-misc-levels-ch1.png");
- std::fprintf (stderr, "flclipshot: round trip\n");
- // the .lynx round trip of the adjustment and of an automation of it; an old project writes nothing new
- juce::String error;
- auto song = engine.getSong();
- lynx::Automation a;
- a.target = { lynx::AutomationTargetKind::channelAdjust, vox, 0, lynx::leveladjust::volume };
- a.points = { { 0, 0.25f, 0.0f } };
- song.automations.push_back (a);
- const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
- check ("lynx_round_trip", back && back->channels[(std::size_t) vox].misc.levels == song.channels[(std::size_t) vox].misc.levels
- && back->automations.back().target == a.target,
- error);
- auto old = lynx::Song::makeDefault();
- const auto json = lynx::ProjectFile::toJson (old, false);
- const auto reloaded = lynx::ProjectFile::fromJson (json, error);
- check ("old_project_unchanged", ! json.contains ("\"levels\"") && reloaded && lynx::ProjectFile::toJson (*reloaded, false) == json
- && std::all_of (reloaded->channels.begin(), reloaded->channels.end(),
- [] (const lynx::ChannelDef& c) { return c.misc.levels.neutral(); }));
- }
- juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
- return allOk;
- }
- // --bandlabshot <prefix> (round 190ch): the Lyrics / Notes panel (Pattern and Simple layouts, and on its own), the
- // Reference match window measured on a real render and a real file, "Start from", and Clean voice, off-screen; and
- // <prefix>-report.txt with what each route did (ok / FAIL lines)
- void runBandlabShot (const juce::String& prefix)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- lynx::AudioEngine offline (false);
- lynx::MainComponent ui (offline, false);
- ui.setSize (1600, 900);
- // (each step is named on stderr as it starts: a run that stops says where)
- const auto note = [] (const juce::String& what) { std::fprintf (stderr, "bandlabshot: %s\n", what.toRawUTF8()); };
- const auto shoot = [&prefix, ¬e] (juce::Component& c, const char* name) {
- note (name);
- savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png");
- };
- juce::String report;
- const auto check = [&report, ¬e] (const juce::String& what, bool ok) {
- note ((ok ? "ok " : "FAIL ") + what);
- report << (ok ? "ok " : "FAIL ") << what << "\n";
- };
- const auto bar = (double) lynx::ppq * 4.0;
- // ---- 1. Lyrics / Notes: the project's Comments
- {
- auto song = lynx::makeShowcaseSong (0);
- song.info.title = "Night Drive";
- song.info.comments = "[Intro]\n\n[5] [Verse 1]\n[5] Headlights on the empty road\n[7] Radio is playing low\n[9] Every sign says slow\n"
- "I keep driving through the night\n\n[Chorus]\nNight drive, night drive\nNothing but the white line\n\n"
- "Notes: double the chorus vocal, try the second verse an octave down.";
- lynx::Marker chorus;
- chorus.tick = (std::int64_t) (12.0 * bar);
- chorus.name = "Chorus";
- song.addMarker (chorus);
- offline.setSong (std::move (song));
- }
- note ("song set");
- offline.dispatchPendingMessages();
- ui.selectTabForSnapshot (2);
- note ("show lyrics");
- ui.showLyrics (false);
- note ("lyrics shown");
- if (auto* panel = ui.getLyricsPanelForSnapshot())
- {
- panel->showForSnapshot ({}, 6.5 * bar); // the playhead inside bar 7: that line is the one playing
- shoot (ui, "lyrics-pattern");
- shoot (*panel, "lyrics-panel");
- const auto markersBefore = offline.getSong().markers().size();
- panel->setCaretLineForSnapshot (6); // "I keep driving through the night"
- panel->markAtPlayheadForSnapshot (10.0 * bar + 2.0 * lynx::ppq);
- offline.dispatchPendingMessages();
- ui.commitSongNotes();
- const auto& s = offline.getSong();
- check ("Marker at playhead stamps the line [11.3] and adds one marker",
- juce::String::fromUTF8 (s.info.comments.c_str()).contains ("[11.3] I keep driving") && s.markers().size() == markersBefore + 1);
- // (no audio device here: the seek is the request the audio thread takes at its next block)
- const auto& seek = offline.getTransport().seekRequest;
- check ("clicking the stamped line moves the playhead to bar 7", panel->jumpToLineForSnapshot (4) && std::abs (seek.load() - 6.0 * bar) < 1.0);
- check ("clicking [Chorus] (no position) goes to the marker of that name, bar 13",
- panel->jumpToLineForSnapshot (8) && std::abs (seek.load() - 12.0 * bar) < 1.0);
- check ("a line without a position does not jump", ! panel->jumpToLineForSnapshot (9));
- panel->showForSnapshot ("night", 10.5 * bar);
- shoot (*panel, "lyrics-search");
- // the text travels in the project file, and old readers see it as the Comments they always had
- juce::String error;
- const auto json = lynx::ProjectFile::toJson (offline.getSong());
- const auto back = lynx::ProjectFile::fromJson (json, error);
- check ("lyrics round-trip through .lynx (the Comments field)", back.has_value() && back->info.comments == offline.getSong().info.comments);
- const auto text = lynx::lyrics::exportText (offline.getSong(), lynx::lyrics::Stamps::times);
- juce::File (prefix + "-lyrics-export.txt").replaceWithText (juce::String::fromUTF8 (text.c_str()));
- check ("export as text with times", text.find ("[0:") != std::string::npos);
- panel->showForSnapshot ({}, 6.5 * bar);
- }
- else
- check ("the docked Lyrics panel exists", false);
- {
- const auto names = ui.getMenuNamesForSnapshot();
- const auto view = names.indexOf (lynx::tr ("View"));
- saveMenus (juce::StringArray { lynx::tr ("View") }, std::vector<juce::PopupMenu> { ui.getMenuForSnapshot (juce::jmax (0, view)) }, prefix + "-menu-view.png");
- }
- ui.showDesktopForSnapshot (false);
- check ("the panel stays docked beside the Playlist in the default desktop", ui.isLyricsShowing());
- shoot (ui, "lyrics-desktop");
- // ---- the Simple layout: the Lyrics button in its title tools, the chooser's "Start from" link
- ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
- offline.dispatchPendingMessages();
- ui.selectTabForSnapshot (2); // (the Playlist alone, as --simpleshot shows the layout)
- auto* simple = ui.getSimpleWorkflowForSnapshot();
- check ("the Simple workflow exists", simple != nullptr);
- if (simple != nullptr)
- {
- simple->hideChooser();
- if (! ui.isLyricsShowing())
- ui.showLyrics (false);
- shoot (ui, "lyrics-simple");
- ui.hideLyrics();
- check ("closing the panel keeps the text", juce::String::fromUTF8 (offline.getSong().info.comments.c_str()).contains ("Night drive, night drive"));
- // ---- 4. Clean voice: on a voice track, from the track's menu
- lynx::simpletracks::Result voice;
- offline.editSongStructural ([&voice] (lynx::Song& s) {
- lynx::simpletracks::Request q;
- q.kind = lynx::simpletracks::Kind::voice;
- q.name = "Lead vocal";
- voice = lynx::simpletracks::addTrack (s, q);
- });
- offline.dispatchPendingMessages();
- check ("a voice track was added", voice.insert > 0);
- if (voice.insert > 0)
- {
- auto menu = ui.getPlaylistForSnapshot().getTrackMenuForSnapshot (voice.track);
- juce::StringArray names { "Track" };
- std::vector<juce::PopupMenu> menus { menu };
- for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
- if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::tr ("Clean voice"))
- {
- names.add (lynx::tr ("Clean voice"));
- menus.push_back (*it.getItem().subMenu);
- }
- check ("the Simple track menu has Clean voice", menus.size() == 2);
- saveMenus (names, menus, prefix + "-cleanvoice-menu.png");
- const auto before = offline.getSong().mixer[(std::size_t) voice.insert].effects.size();
- check ("Clean voice applies", lynx::ui::applyCleanVoice (offline, voice.insert, false));
- offline.dispatchPendingMessages();
- const auto& fx = offline.getSong().mixer[(std::size_t) voice.insert].effects;
- check ("four slots in front of the track's effects", fx.size() == before + 4 && lynx::cleanvoice::slotsOf (offline.getSong(), voice.insert).size() == 4
- && fx[0].kind == lynx::EffectKind::facetEq);
- check ("with noise reduction: five, none doubled", lynx::ui::applyCleanVoice (offline, voice.insert, true)
- && offline.getSong().mixer[(std::size_t) voice.insert].effects.size() == before + 5);
- offline.dispatchPendingMessages();
- juce::String error;
- const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (offline.getSong()), error);
- check ("the chain round-trips through .lynx and is still found", back.has_value() && lynx::cleanvoice::slotsOf (*back, voice.insert).size() == 5
- && back->mixer[(std::size_t) voice.insert].effects == offline.getSong().mixer[(std::size_t) voice.insert].effects);
- saveMenus (juce::StringArray { lynx::tr ("Clean voice") }, std::vector<juce::PopupMenu> { lynx::ui::cleanVoiceMenu (offline, voice.insert) },
- prefix + "-cleanvoice-menu-on.png");
- ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
- offline.dispatchPendingMessages();
- ui.showPanelsForSnapshot ({ lynx::workspace::Panel::mixer });
- ui.selectMixerTrackForSnapshot (voice.insert);
- shoot (ui, "cleanvoice-mixer");
- offline.undo(); // the second chain
- offline.dispatchPendingMessages();
- check ("undo brings the first chain back", lynx::cleanvoice::slotsOf (offline.getSong(), voice.insert).size() == 4);
- ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
- offline.dispatchPendingMessages();
- ui.selectTabForSnapshot (2); // (the Playlist alone, as --simpleshot shows the layout)
- simple = ui.getSimpleWorkflowForSnapshot();
- }
- }
- // ---- 2. Reference match: the song's Master render against a file (pink noise with more top, at about -14 LUFS)
- {
- const auto file = juce::File (prefix + "-reference.wav");
- file.deleteFile();
- const auto rate = 44100.0;
- const auto frames = (int) (20.0 * rate);
- juce::AudioBuffer<float> audio (2, frames);
- juce::Random random (190);
- for (int ch = 0; ch < 2; ++ch)
- {
- double b0 = 0, b1 = 0, b2 = 0, hp = 0;
- for (int i = 0; i < frames; ++i)
- {
- const auto w = (double) random.nextFloat() * 2.0 - 1.0;
- b0 = 0.99765 * b0 + w * 0.0990460;
- b1 = 0.96300 * b1 + w * 0.2965164;
- b2 = 0.57000 * b2 + w * 1.0526913;
- const auto pink = (b0 + b1 + b2 + w * 0.1848) * 0.071; // (about -14 LUFS: a streaming master)
- hp += 0.25 * (pink - hp); // a little more top than pink noise has
- audio.setSample (ch, i, (float) (pink + 0.35 * (pink - hp)));
- }
- }
- if (auto out = file.createOutputStream())
- if (auto writer = std::unique_ptr<juce::AudioFormatWriter> (juce::WavAudioFormat().createWriterFor (out.get(), rate, 2, 24, {}, 0)))
- {
- out.release();
- writer->writeFromAudioSampleBuffer (audio, 0, frames);
- }
- note ("measure reference");
- const auto reference = lynx::ReferenceMatchPanel::measureFile (offline, file);
- note ("measure song");
- const auto song = lynx::ReferenceMatchPanel::measureSong (offline.getSong(), false);
- check ("the reference file was measured", reference.valid);
- check ("the song's Master render was measured", song.valid);
- lynx::ReferenceMatchPanel panel (offline, {});
- panel.setSize (lynx::ReferenceMatchPanel::defaultWidth, lynx::ReferenceMatchPanel::defaultHeight);
- panel.showForSnapshot ("Reference.wav", song, reference, nullptr);
- shoot (panel, "refmatch-measured");
- const auto masterBefore = offline.getSong().mixer[0].effects.size();
- check ("Match adds its two slots at the end of the Master", panel.matchForSnapshot() && offline.getSong().mixer[0].effects.size() == masterBefore + 2);
- offline.dispatchPendingMessages();
- const auto first = lynx::ReferenceMatchPanel::measureSong (offline.getSong(), true);
- panel.showForSnapshot ("Reference.wav", song, reference, &first);
- panel.refresh();
- shoot (panel, "refmatch-matched");
- report << " first Match: " << juce::String (first.lufs, 2) << " LUFS, " << juce::String (first.truePeakDb, 2) << " dBTP, EQ output "
- << juce::String (lynx::facet::outputDb (offline.getSong().mixer[0].effects[masterBefore].params[(std::size_t) lynx::facet::outputParam]), 2) << " dB\n";
- // a result more than 0.5 LU from the reference (a limiter that has to hold peaks back): Match again takes
- // what is missing, as the window's note says
- auto after = first;
- const auto secondPass = std::abs (first.lufs - reference.lufs) > 0.5;
- if (secondPass)
- {
- check ("Match again replaces the two slots (level corrected)", panel.matchForSnapshot() && offline.getSong().mixer[0].effects.size() == masterBefore + 2);
- offline.dispatchPendingMessages();
- after = lynx::ReferenceMatchPanel::measureSong (offline.getSong(), true);
- panel.showForSnapshot ("Reference.wav", song, reference, &after);
- panel.refresh();
- shoot (panel, "refmatch-matched-again");
- }
- report << " " << (secondPass ? "a second Match was needed for the level" : "one Match was enough for the level") << "\n";
- const auto& s = panel.suggestionForSnapshot();
- report << " song " << juce::String (song.lufs, 2) << " LUFS, " << juce::String (song.truePeakDb, 2) << " dBTP, width " << juce::String (song.widthPercent(), 1)
- << " % | reference " << juce::String (reference.lufs, 2) << " LUFS, " << juce::String (reference.truePeakDb, 2) << " dBTP, width "
- << juce::String (reference.widthPercent(), 1) << " % | after " << juce::String (after.lufs, 2) << " LUFS, " << juce::String (after.truePeakDb, 2)
- << " dBTP\n next suggestion: gain " << juce::String (s.gainDb, 2) << " dB, EQ fit error " << juce::String (s.fitErrorDb, 2) << " dB\n";
- double before = 0.0, now = 0.0;
- int counted = 0;
- {
- // tone only (each curve around its own mean), over the bands both hold
- double ms = 0, mr = 0, ma = 0;
- const auto used = juce::jmin (song.usedBands, reference.usedBands);
- for (int k = 0; k < used; ++k)
- ms += song.spectrumDb[(std::size_t) k], mr += reference.spectrumDb[(std::size_t) k], ma += after.spectrumDb[(std::size_t) k];
- for (int k = 2; k < used; ++k, ++counted)
- {
- before += std::abs ((song.spectrumDb[(std::size_t) k] - ms / used) - (reference.spectrumDb[(std::size_t) k] - mr / used));
- now += std::abs ((after.spectrumDb[(std::size_t) k] - ma / used) - (reference.spectrumDb[(std::size_t) k] - mr / used));
- }
- }
- report << " mean tone difference to the reference: " << juce::String (before / juce::jmax (1, counted), 2) << " dB before, "
- << juce::String (now / juce::jmax (1, counted), 2) << " dB after one Match (each band moves 6 dB at most)\n";
- check ("after Match the tone is closer to the reference", after.valid && now < before);
- check ("after Match the loudness is within 1 LU of the reference", std::abs (after.lufs - reference.lufs) < 1.0);
- check ("the limiter holds the peaks: under 0 dBTP, within 0.6 dB of its -1 dB ceiling", after.truePeakDb < 0.0 && after.truePeakDb <= -1.0 + 0.6);
- juce::String error;
- const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (offline.getSong()), error);
- check ("the match round-trips through .lynx as two ordinary Master slots", back.has_value() && lynx::refmatch::present (*back)
- && back->mixer[0].effects == offline.getSong().mixer[0].effects);
- ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
- offline.dispatchPendingMessages();
- ui.showPanelsForSnapshot ({ lynx::workspace::Panel::mixer });
- ui.selectMixerTrackForSnapshot (0);
- shoot (ui, "refmatch-mixer");
- ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
- offline.dispatchPendingMessages();
- ui.selectTabForSnapshot (2); // (the Playlist alone, as --simpleshot shows the layout)
- simple = ui.getSimpleWorkflowForSnapshot();
- if (simple != nullptr)
- {
- simple->hideChooser();
- simple->showFinish();
- shoot (ui, "finish-dock"); // "Match a reference track..." under the saving buttons
- simple->hideFinish();
- }
- file.deleteFile();
- }
- // ---- 3. Start from: the chooser's link, the list, and opening an entry
- if (simple != nullptr)
- {
- simple->showChooser();
- shoot (ui, "chooser");
- simple->hideChooser();
- auto* panel = dynamic_cast<lynx::StartFromPanel*> (simple->startFromForSnapshot());
- check ("the Start from list opens", panel != nullptr && simple->isStartFromShowing());
- if (panel != nullptr)
- {
- shoot (ui, "startfrom");
- auto list = lynx::startfrom::entries();
- check ("it lists the demo song and the templates shipped", list.size() >= 3 && list[0].kind == lynx::startfrom::Entry::Kind::demo
- && (int) list.size() == panel->entryCountForSnapshot());
- for (auto& e : list)
- report << " " << e.name << " | " << juce::String (e.bpm, 0) << " BPM, " << e.channels << " channels, " << e.bars << " bars"
- << (e.playable ? ", preview" : "") << "\n";
- if (const auto demo = lynx::startfrom::songOf (list[0]))
- {
- const auto wav = juce::File (prefix + "-preview.wav");
- const auto ok = lynx::startfrom::renderPreview (*demo, wav);
- check ("the demo's preview renders (" + juce::String (wav.getSize() / 1024) + " kB)", ok && wav.getSize() > 100000);
- wav.deleteFile();
- }
- panel->selectForSnapshot (juce::jmin (2, panel->entryCountForSnapshot() - 1));
- shoot (ui, "startfrom-selected");
- offline.markSaved(); // (a project with changes asks first: Save / Don't save / Cancel)
- const auto opened = panel->openForSnapshot (0);
- offline.dispatchPendingMessages();
- check ("opening the demo starts a new project from it and closes the list",
- opened && ! simple->isStartFromShowing() && offline.getSong().info.comments.empty() && ! offline.getSong().channels.empty());
- shoot (ui, "startfrom-opened");
- }
- }
- juce::File (prefix + "-report.txt").replaceWithText (report);
- }
- void runVersionsShot (const juce::String& prefix)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- const auto shoot = [&prefix] (juce::Component& c, const char* name) {
- savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png");
- };
- // ---- the Versions panel, on files in a temporary folder
- const auto root = juce::File::getSpecialLocation (juce::File::tempDirectory)
- .getChildFile ("lynx-versionsshot-" + juce::String::toHexString (juce::Random::getSystemRandom().nextInt64()));
- const juce::ScopeGuard cleanUp { [&root] { root.deleteRecursively(); } };
- const auto project = root.getChildFile ("Night Drive"), backup = root.getChildFile ("Backup");
- project.createDirectory();
- backup.createDirectory();
- const auto now = juce::Time::getCurrentTime();
- const auto put = [&now] (const juce::File& folder, const juce::String& name, const char* kind, int kilobytes, double hoursAgo) {
- const auto time = now - juce::RelativeTime::hours (hoursAgo);
- const auto file = folder.getChildFile (kind == nullptr ? name + ".lynx" : name + " (" + kind + " on " + time.formatted ("%Y-%m-%d at %Hh%M") + ").lynx");
- juce::MemoryBlock data ((size_t) kilobytes * 1024, true);
- file.replaceWithData (data.getData(), data.getSize());
- file.setLastModificationTime (time);
- };
- put (project, "Night Drive", nullptr, 412, 26.0 * 24.0);
- put (project, "Night Drive_2", nullptr, 688, 9.0 * 24.0);
- put (project, "Night Drive_3", nullptr, 731, 2.0 * 24.0);
- put (project, "Night Drive_4", nullptr, 905, 1.6);
- put (backup, "Night Drive_4", "autosaved", 907, 0.07);
- put (backup, "Night Drive_4", "autosaved", 906, 0.4);
- put (backup, "Night Drive_4", "overwritten", 890, 1.6);
- put (backup, "Night Drive_4", "autosaved", 884, 3.2);
- put (backup, "Night Drive_3", "overwritten", 720, 2.0 * 24.0);
- put (backup, "Night Drive_2", "autosaved", 690, 8.0 * 24.0);
- const lynx::VersionsContext context { project.getChildFile ("Night Drive_4.lynx"), "Night Drive_4", backup, ".lynx" };
- {
- const auto entries = lynx::versionEntries (context);
- const auto label = [&] (const juce::String& startsWith, const char* text) {
- for (const auto& e : entries)
- if (juce::String::fromUTF8 (e.name.c_str()).startsWith (startsWith))
- {
- lynx::setVersionLabel (context, e, text);
- return;
- }
- };
- label ("Night Drive_2", "first full arrangement");
- label ("Night Drive_3", "sent to the singer");
- label ("Night Drive_4 (autosaved", "new bass line");
- }
- {
- lynx::VersionsActions actions;
- actions.context = [context] { return context; };
- auto panel = lynx::makeVersionsPanel (actions);
- shoot (*panel, "versions");
- lynx::VersionsActions fresh;
- fresh.context = [backup] { return lynx::VersionsContext { juce::File(), "Untitled", backup, ".lynx" }; };
- auto empty = lynx::makeVersionsPanel (fresh);
- shoot (*empty, "versions-unsaved");
- }
- // ---- the window
- 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()));
- const auto saveFileMenu = [&] (const char* name) {
- const auto index = juce::jmax (0, ui.getMenuNamesForSnapshot().indexOf (lynx::tr ("File")));
- saveMenus (juce::StringArray { lynx::tr ("File") }, std::vector<juce::PopupMenu> { ui.getMenuForSnapshot (index) }, prefix + "-" + name + ".png");
- };
- saveFileMenu ("menu-file");
- // ---- a project opened without its third-party plugins (the plugins are not installed: nothing foreign runs)
- {
- const auto ref = [] (const char* id, const char* name) {
- lynx::PluginRef r;
- r.id = id;
- r.name = name;
- r.state = "c2V0dGluZ3M=";
- return r;
- };
- auto song = lynx::Song::makeDefault();
- while (song.channels.size() < 4)
- song.channels.push_back (song.channels.front());
- while (song.mixer.size() < 5)
- song.mixer.push_back (song.mixer.back());
- const char* names[] = { "Lead", "Pad" };
- for (int c = 0; c < 2; ++c)
- {
- auto& channel = song.channels[(std::size_t) (c + 2)];
- channel.instrument = lynx::InstrumentKind::plugin;
- channel.plugin = ref ("VST3-ShotSynth-11111111-aaaaaaaa", "Shot Synth");
- channel.name = names[c];
- channel.mixerTrack = c + 1;
- }
- lynx::EffectSlot fx;
- fx.kind = lynx::EffectKind::plugin;
- fx.plugin = ref ("VST3-ShotVerb-22222222-bbbbbbbb", "Shot Verb");
- song.mixer[1].effects.push_back (fx);
- fx.plugin = ref ("VST3-ShotComp-33333333-cccccccc", "Shot Comp");
- song.mixer[2].effects.push_back (fx);
- song.mixer[0].effects.push_back (fx);
- offline.setSongWithPluginsOff (std::move (song));
- ui.showDesktopForSnapshot (false);
- shoot (ui, "pluginsoff-window");
- ui.showPanelsForSnapshot ({ lynx::workspace::Panel::channelRack, lynx::workspace::Panel::mixer });
- shoot (ui, "pluginsoff-mixer"); // (the rack's and the mixer's "off" tags together)
- saveFileMenu ("menu-file-pluginsoff");
- auto panel = lynx::makePluginsOffPanel (offline);
- shoot (*panel, "pluginsoff-panel");
- offline.switchPluginOn ("VST3-ShotVerb-22222222-bbbbbbbb"); // (not installed: "Did not load")
- auto after = lynx::makePluginsOffPanel (offline);
- shoot (*after, "pluginsoff-panel-one");
- }
- // ---- the Export window: as it opens, and with a preset chosen, sections on and a last export to repeat
- {
- auto song = lynx::Song::makeDefault();
- const auto bar = song.barTicks();
- song.mode = lynx::PlayMode::song;
- song.playlist.clear();
- lynx::Clip clip;
- clip.length = 32 * bar;
- song.playlist.push_back (clip);
- const char* sections[] = { "Intro", "Verse", "Chorus", "Outro" };
- for (int i = 0; i < 4; ++i)
- {
- lynx::Marker m;
- m.tick = i * 8 * bar;
- m.name = sections[i];
- song.addMarker (m);
- }
- offline.setSong (std::move (song)); // (also ends the plugins-off mode)
- auto plain = lynx::makeExportPanel (offline, 0);
- shoot (*plain, "export-default");
- auto additions = lynx::makeExportPanelWithAdditions (offline);
- shoot (*additions, "export");
- }
- }
- void runGamepadShot (const juce::String& prefix)
- {
- juce::String report;
- int failures = 0;
- {
- lynx::AudioEngine engine (false);
- auto hints = lynx::makeGamepadHints();
- savePng (lynx::shot::snapshot (*hints), prefix + "-hints.png");
- auto prefs = engine.getMidiPrefs();
- prefs.gamepad = true;
- engine.setMidiPrefs (prefs, false);
- auto page = lynx::makeMidiPage (engine, {}, false);
- page->setSize (760, 1400);
- savePng (lynx::shot::snapshot (*page), prefix + "-settings.png");
- // the poller with fake states: what the handler gets
- using namespace lynx::gamepad;
- std::vector<std::string> got;
- lynx::GamepadInput input ([&got] (const Changes& c, const State&, double dt) {
- for (int i = 0; i < c.pressedCount; ++i)
- got.push_back (std::string ("press ") + buttonName (c.pressed[(std::size_t) i]));
- for (int i = 0; i < c.releasedCount; ++i)
- got.push_back (std::string ("release ") + buttonName (c.released[(std::size_t) i]));
- for (int i = 0; i < c.controllerCount; ++i)
- got.push_back ("cc " + std::to_string (c.controller[(std::size_t) i]) + "=" + std::to_string (c.value[(std::size_t) i]));
- if (c.connectedChanged)
- got.push_back ("connected changed");
- got.push_back ("dt " + std::to_string ((int) std::lround (dt * 1000)));
- });
- State pad;
- pad.connected = true;
- input.inject (pad, 1.0 / 60.0);
- pad.buttons = mask (Button::a);
- pad.rightTrigger = 255;
- input.inject (pad, 1.0 / 60.0);
- pad.buttons = 0;
- input.inject (pad, 1.0 / 60.0);
- const std::vector<std::string> expected { "connected changed", "dt 17", "press A", "cc 102=127", "cc 21=127", "dt 17",
- "release A", "cc 102=0", "dt 17" };
- for (const auto& line : got)
- report << line << "\n";
- if (got != expected)
- {
- ++failures;
- report << "FAILED: the poller's changes differ from the expected ones\n";
- }
- report << "xinput " << (input.available() ? "loaded" : "not available") << "\n";
- }
- report << (failures == 0 ? "gamepad OK" : "gamepad FAILED") << "\n";
- juce::File (prefix + "-gamepad.txt").replaceWithText (report);
- setApplicationReturnValue (failures == 0 ? 0 : 1);
- quit();
- }
- void runBundleExport (const juce::String& inputPath, const juce::String& folderPath, bool zip, bool mixdown, const juce::String& shotPrefix)
- {
- juce::String error;
- bool ok = false;
- lynx::otherapps::Result result;
- {
- lynx::AudioEngine loader (false);
- const juce::File input (inputPath);
- if (input.hasFileExtension ("flp;als"))
- ok = loader.importFlpFile (input, error);
- else if (auto song = lynx::ProjectFile::load (input, error))
- {
- loader.setSong (std::move (*song));
- ok = true;
- }
- if (ok)
- {
- loader.capturePluginStates();
- lynx::otherapps::Context context;
- context.host = &loader.getPluginHost();
- context.flOptions = lynx::flstudio::optionsFor (context.host, lynx::flpexport::LynxOnly::renderAudio, loader.getSong());
- context.render = [] (const lynx::Song& s, const lynx::exportopts::Options& o, const juce::File& file,
- const std::function<bool (double)>& progress, juce::String& err) {
- lynx::ExportJob job (s, o, file);
- return job.run (progress, err);
- };
- context.onMessageThread = [] (std::function<void()> f) { f(); };
- lynx::exportbundle::Options options;
- options.zip = zip;
- options.mixdown = mixdown;
- const auto name = input.getFileNameWithoutExtension();
- const auto shot = [&shotPrefix] (juce::Component& c, const juce::String& suffix) {
- if (shotPrefix.isNotEmpty())
- savePng (lynx::shot::snapshot (c), shotPrefix + suffix);
- };
- if (auto panel = lynx::makeOtherAppsExportPanel (loader, name))
- shot (*panel, "-panel.png");
- ok = lynx::otherapps::write (loader.getSong(), name, options, juce::File (folderPath), context, result);
- if (auto report = lynx::makeOtherAppsReportPanel (result.folder, result.written, result.failed))
- shot (*report, "-report.png");
- }
- }
- juce::String report;
- report << (ok ? "ok " + result.folder.getFullPathName() : "error=" + error) << "\n";
- for (const auto& w : result.written)
- report << "written " << w << "\n";
- for (const auto& f : result.failed)
- report << "failed " << f << "\n";
- juce::File (folderPath).getChildFile ("export-bundle.txt").replaceWithText (report);
- setApplicationReturnValue (ok && result.failed.isEmpty() ? 0 : 1);
- quit();
- }
- 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);
- // a Live set opens through the same import as an .flp (as File › Open does, and --export-als accepts an .flp)
- if (input.hasFileExtension ("flp;als"))
- 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|als|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;als")) // a Live set opens through the same import (round 182b)
- 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();
- }
- struct ParityShow
- {
- std::unique_ptr<lynx::AudioEngine> engine;
- std::unique_ptr<juce::Component> editor;
- std::unique_ptr<juce::DocumentWindow> window;
- ~ParityShow() { window.reset(); editor.reset(); engine.reset(); }
- };
- std::shared_ptr<ParityShow> parityShow;
- bool parityShotFailed = false; // --parityshot: the effect name matched no built-in effect
- 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)
- {
- // round tp172b7: say so and fail (a silent exit 0 hid a split effect name in a launch script)
- std::fprintf (stderr, "unknown effect: %s\n", effectName.toRawUTF8());
- std::fflush (stderr);
- parityShotFailed = true;
- 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();
- }
- auto offlineOwner = std::make_unique<lynx::AudioEngine> (false); // (kept alive by LYNX_PARITYSHOT_SHOW's window)
- auto& offline = *offlineOwner;
- 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);
- }
- // round tp172b5: LYNX_PARITYSHOT_CLICKS drives the editor before the picture (the originals' pictures have their
- // panels open), tokens in order: "x,y" a click, then the pointer leaves; "h:x,y" the pointer rests there (a hover);
- // "d:x,y,x2,y2" a drag from there to there, the button still down in the picture
- for (const auto& token : juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_PARITYSHOT_CLICKS", {}), " ", ""))
- {
- const auto hover = token.startsWith ("h:"), drag = token.startsWith ("d:");
- const auto xy = juce::StringArray::fromTokens (hover || drag ? token.substring (2) : token, ",", "");
- if (xy.size() < (drag ? 4 : 2))
- continue;
- const juce::Point<int> at (xy[0].getIntValue(), xy[1].getIntValue());
- editor->setVisible (true); // (getComponentAt finds nothing in a hidden component; it never goes on screen)
- auto* target = editor->getComponentAt (at);
- if (target == nullptr)
- continue;
- const auto local = target->getLocalPoint (editor.get(), at).toFloat();
- const auto now = juce::Time::getCurrentTime();
- auto source = juce::Desktop::getInstance().getMainMouseSource();
- const juce::ModifierKeys left (juce::ModifierKeys::leftButtonModifier);
- const auto event = [&] (juce::Point<float> p, juce::ModifierKeys mods, bool dragged) {
- return juce::MouseEvent (source, p, mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, target, target, now, local, now, 1, dragged);
- };
- target->mouseMove (event (local, {}, false));
- if (hover)
- continue;
- target->mouseDown (event (local, left, false));
- if (drag)
- {
- const auto end = target->getLocalPoint (editor.get(), juce::Point<int> (xy[2].getIntValue(), xy[3].getIntValue())).toFloat();
- target->mouseDrag (event (end, left, true));
- continue;
- }
- target->mouseUp (event (local, {}, false));
- target->mouseExit (event ({ -1000.0f, -1000.0f }, {}, false));
- }
- // round tp172b6: LYNX_PARITYSHOT_SHOW=1 puts the same editor in a real window and keeps it open (for a guarded GUI check
- // of its pop-up menus, which the offscreen picture cannot hold); closing the window quits
- if (juce::SystemStats::getEnvironmentVariable ("LYNX_PARITYSHOT_SHOW", {}) == "1")
- {
- struct ShowWindow final : juce::DocumentWindow
- {
- ShowWindow() : juce::DocumentWindow ("LYNX parity check", juce::Colours::black, juce::DocumentWindow::closeButton) {}
- void closeButtonPressed() override { juce::JUCEApplication::getInstance()->systemRequestedQuit(); }
- };
- parityShow = std::make_shared<ParityShow>();
- parityShow->engine = std::move (offlineOwner);
- parityShow->editor = std::move (editor);
- auto window = std::make_unique<ShowWindow>();
- window->setUsingNativeTitleBar (true);
- window->setContentNonOwned (parityShow->editor.get(), true);
- window->setTopLeftPosition (80, 80);
- window->setVisible (true);
- parityShow->window = std::move (window);
- return;
- }
- // round 190ar: LYNX_PARITYSHOT_SCALE=2 draws the same editor at twice the pixel density (as on a 200 % display);
- // round 190bi: the shared shot scale (--shot-scale, LYNX_SHOT_SCALE, LYNX_PARITYSHOT_SCALE as before)
- const auto shotScale = lynx::shot::scale();
- juce::Image image (juce::Image::ARGB, juce::roundToInt ((float) editor->getWidth() * shotScale), juce::roundToInt ((float) editor->getHeight() * shotScale), true);
- {
- juce::Graphics g (image);
- g.fillAll (lynx::theme::panel);
- g.addTransform (juce::AffineTransform::scale (shotScale));
- editor->paintEntireComponent (g, false);
- }
- const auto file = lynx::shot::file (juce::File (path));
- file.deleteFile();
- juce::PNGImageFormat png;
- if (auto stream = file.createOutputStream())
- png.writeImageToStream (image, *stream);
- }
- // an Audio Effect Rack shaped like Live's reference (REA_rodada183c §8): two chains with chain-select zones and fades,
- // four named macros (one on a chain's volume, one on two parameters), two variations, every view open
- static lynx::EffectSlot shotRack()
- {
- auto slot = lynx::rack::makeRackSlot (lynx::RackDoc::Kind::audioEffect);
- auto& doc = slot.patcher;
- doc.rack[0].chains[0].name = "Vocoder";
- lynx::PatchNode vocoder, eq, verb;
- vocoder.effect = lynx::makeEffectSlot (lynx::EffectKind::vocodex);
- eq.effect = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
- verb.effect = lynx::makeEffectSlot (lynx::EffectKind::reeverb2);
- const auto nVoc = lynx::rack::addDevice (doc, 0, vocoder);
- const auto nEq = lynx::rack::addDevice (doc, 0, eq);
- lynx::rack::addChain (doc, "dry bypass");
- lynx::rack::addDevice (doc, 1, verb);
- doc.rack[0].chains[0].select = { 0, 79, 0, 63 };
- doc.rack[0].chains[1].select = { 32, 127, 48, 127 };
- lynx::rack::setChainVolume (doc, 0, 0.33f);
- lynx::rack::setChainVolume (doc, 1, 0.5f);
- const char* names[] { "Sibilance", "Intensity", "Formant Shift", "Bright Level" };
- for (int m = 0; m < 4; ++m)
- doc.rack[0].macros[(std::size_t) m].name = names[m];
- lynx::RackMapping vol;
- vol.target = lynx::RackMapping::Target::chainVolume, vol.chain = 0, vol.min = 0.0f, vol.max = lynx::rack::unityVolume;
- lynx::rack::map (doc, 0, vol);
- lynx::RackMapping a, b, c, d;
- a.node = nVoc, a.param = 0;
- b.node = nVoc, b.param = 1, b.min = 0.2f, b.max = 0.8f;
- c.node = nEq, c.param = 0, c.min = 0.3f, c.max = 0.9f;
- d.node = nEq, d.param = 1;
- lynx::rack::map (doc, 1, a);
- lynx::rack::map (doc, 2, b);
- lynx::rack::map (doc, 3, c);
- lynx::rack::map (doc, 3, d);
- lynx::rack::setMacro (doc, 0, 60.0f);
- lynx::rack::setMacro (doc, 1, 40.0f);
- lynx::rack::setMacro (doc, 2, 70.0f);
- lynx::rack::setMacro (doc, 3, 86.0f);
- lynx::rack::storeVariation (doc);
- lynx::rack::renameVariation (doc, 0, "Verse");
- lynx::rack::setMacro (doc, 3, 120.0f);
- lynx::rack::storeVariation (doc);
- lynx::rack::renameVariation (doc, 1, "Drop");
- lynx::rack::launchVariation (doc, 0);
- auto& r = doc.rack[0];
- r.showMacros = r.showChains = r.showDevices = r.showVariations = true;
- r.zoneEditor = 2;
- r.selectedChain = 0;
- lynx::rack::setSelector (doc, 56.0f);
- lynx::rack::compile (doc);
- return slot;
- }
- bool runRackShots (const juce::File& out, const juce::String& liveSet = {})
- {
- out.createDirectory();
- lynx::AudioEngine offline (false);
- auto save = [&] (juce::Component& c, const juce::String& name) {
- auto image = lynx::shot::paint (c, lynx::theme::panel);
- const auto f = lynx::shot::file (out.getChildFile (name));
- f.deleteFile();
- juce::PNGImageFormat png;
- if (auto stream = f.createOutputStream())
- return png.writeImageToStream (image, *stream);
- return false;
- };
- auto song = lynx::Song::makeDefault();
- song.mixer.resize (3);
- song.mixer[1].name = "Vocal Main";
- auto slot = shotRack();
- song.mixer[1].effects = { slot };
- // an Instrument Rack: three chains split over the keyboard
- lynx::ChannelDef inst;
- inst.name = "Keys Rack";
- inst.instrument = lynx::InstrumentKind::patcher;
- inst.patcher = lynx::rack::makeRack (lynx::RackDoc::Kind::instrument);
- for (int k = 0; k < 3; ++k)
- {
- if (k > 0)
- lynx::rack::addChain (inst.patcher);
- lynx::PatchNode synth;
- synth.generator = true;
- synth.channel.instrument = lynx::InstrumentKind::synth;
- synth.channel.name = "Synth";
- lynx::rack::addDevice (inst.patcher, k, synth);
- }
- inst.patcher.rack[0].chains[0].key = { 0, 52, 0, 47 };
- inst.patcher.rack[0].chains[1].key = { 48, 76, 53, 71 };
- inst.patcher.rack[0].chains[2].key = { 72, 127, 77, 127 };
- inst.patcher.rack[0].chains[0].name = "Low";
- inst.patcher.rack[0].chains[1].name = "Mid";
- inst.patcher.rack[0].chains[2].name = "High";
- inst.patcher.rack[0].showChains = inst.patcher.rack[0].showDevices = true;
- inst.patcher.rack[0].zoneEditor = 0;
- lynx::rack::compile (inst.patcher);
- song.channels.push_back (inst);
- const auto channel = (int) song.channels.size() - 1;
- offline.setSong (std::move (song));
- offline.dispatchPendingMessages();
- bool ok = true;
- // [set.als]: a Live set's racks as LYNX imports them, the one with the most chains drawn with its title bar (the
- // like-for-like pair with Live's own picture of that set)
- if (liveSet.isNotEmpty())
- {
- juce::MemoryBlock bytes;
- juce::File (liveSet).loadFileAsData (bytes);
- const std::vector<std::uint8_t> data ((const std::uint8_t*) bytes.getData(), (const std::uint8_t*) bytes.getData() + bytes.getSize());
- lynx::AlsImportOptions o;
- o.common.projectFolder = juce::File (liveSet).getParentDirectory().getFullPathName().toStdString();
- std::string error;
- if (auto imported = lynx::importAls (data, o, &error))
- {
- int bestTrack = -1, bestSlot = -1;
- std::size_t most = 0;
- for (int t = 0; t < (int) imported->mixer.size(); ++t)
- for (int s = 0; s < (int) imported->mixer[(std::size_t) t].effects.size(); ++s)
- if (const auto& fx = imported->mixer[(std::size_t) t].effects[(std::size_t) s]; lynx::rack::isRack (fx) && fx.patcher.rack[0].chains.size() > most)
- most = fx.patcher.rack[0].chains.size(), bestTrack = t, bestSlot = s;
- if (bestTrack >= 0)
- {
- offline.setSong (std::move (*imported));
- offline.dispatchPendingMessages();
- auto view = lynx::RackWindows::makeSlotView (offline, bestTrack, bestSlot, true);
- view->setSize (view->preferredWidth (228), 228);
- ok = save (*view, "rack-live-import.png") && ok;
- view->setMapMode (true);
- view->setSize (view->preferredWidth (228), 228);
- ok = save (*view, "rack-live-import-map.png") && ok;
- return ok;
- }
- }
- return false;
- }
- {
- auto view = lynx::RackWindows::makeSlotView (offline, 1, 0, false);
- view->setSize (view->preferredWidth (206), 206);
- ok = save (*view, "rack-deviceview.png") && ok;
- }
- {
- auto view = lynx::RackWindows::makeSlotView (offline, 1, 0, true);
- view->setMapMode (true);
- view->setSize (view->preferredWidth (228), 228);
- ok = save (*view, "rack-mapmode.png") && ok;
- }
- {
- auto view = lynx::RackWindows::makeChannelView (offline, channel, true);
- view->setSize (view->preferredWidth (228), 228);
- ok = save (*view, "rack-instrument.png") && ok;
- }
- return ok;
- }
- 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) {
- auto image = lynx::shot::paint (editor, lynx::theme::panel);
- const auto f = lynx::shot::file (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" || source == "flm" ? lynx::natives::makeChannel (e.kind, lynx::flStudioAccess())
- : lynx::banks::defaultChannel (e.kind, e.name);
- // (round 190u) source "flm": the channel as the .flm import makes it (Transistor Bass: FL Studio Mobile's build)
- if (source == "flm" && channel && e.kind == lynx::InstrumentKind::transistorbass)
- {
- channel->pluginState = lynx::transistorBassFlmState ({ 1.0f, 0.0f, 1.0f, 1.0f, 0.1f, 1.0f, 0.1f, 0.0f, 0.0f, 0.3f, 0.5f, 0.0f, 0.0f, 0.0f }); // FLM's defaults
- channel->modelParams = { 1.0f };
- channel->samplePath.clear();
- }
- 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 (lynx::shot::snapshot (*editor), 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;
- // round 173d3: the parity pictures of one editor — LYNX_PLUGUI_ONLY=<effect name>, LYNX_PLUGUI_PRESET=<.fst>,
- // LYNX_PLUGUI_PAGES=<page,page,…> (the page numbers as the editor encodes them)
- const auto only = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGUI_ONLY", {});
- const auto onlyPreset = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGUI_PRESET", {});
- const auto onlyPages = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGUI_PAGES", {}), ",", "");
- for (const auto kind : kinds)
- {
- if (only.isNotEmpty() && only != lynx::effectInfo (kind).name)
- continue;
- 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 (only.isNotEmpty() && onlyPreset.isNotEmpty())
- file = juce::File (onlyPreset);
- 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, lynx::natives::flDataReader (lynx::flStudioAccess())); 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);
- auto image = lynx::shot::paint (*editor);
- const auto file = lynx::shot::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());
- std::vector<int> pageList;
- for (int page = 0; page < pages; ++page)
- pageList.push_back (page);
- if (only.isNotEmpty() && ! onlyPages.isEmpty())
- {
- pageList.clear();
- for (const auto& p : onlyPages)
- pageList.push_back (p.getIntValue());
- }
- for (const auto page : pageList)
- {
- auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, page);
- auto image = lynx::shot::paint (*editor, lynx::theme::panel);
- const auto file = lynx::shot::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);
- auto image = lynx::shot::paint (*editor, lynx::theme::panel);
- const auto file = lynx::shot::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);
- auto image = lynx::shot::paint (*editor, lynx::theme::panel);
- const auto file = lynx::shot::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);
- auto image = lynx::shot::paint (*editor, lynx::theme::panel);
- const auto file = lynx::shot::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);
- auto image = lynx::shot::paint (*editor, lynx::theme::panel);
- const auto file = lynx::shot::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);
- auto image = lynx::shot::paint (*editor, lynx::theme::panel);
- const auto file = lynx::shot::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);
- auto image = lynx::shot::paint (*editor, lynx::theme::panel);
- const auto f = lynx::shot::file (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);
- auto image = lynx::shot::paint (*panel, lynx::theme::panel);
- const auto out2 = lynx::shot::file (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 };
- constexpr int typeInStep = (int) std::size (times) + 1;
- if (step > 0 && step < typeInStep && editor != nullptr)
- savePng (lynx::shot::snapshot (*editor), prefix + "-" + juce::String (step - 1) + ".png");
- if (editor != nullptr && step == (int) std::size (times))
- {
- // round 174d: FL's in-place type-in of the current time (a right click on it)
- lynx::videoview::openTypeIn (*editor, 2);
- ++step;
- return;
- }
- if (editor != nullptr && step == typeInStep)
- savePng (lynx::shot::snapshot (*editor), prefix + "-typein.png");
- if (editor == nullptr || step >= typeInStep)
- {
- 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();
- {
- // round 174d (A3): the same Video Player in a song whose tempo drops from 120 to 60 BPM at bar 5, for FL
- // (LYNX.exe --export-flp <prefix>-tempo.lynx <prefix>-tempo.flp), to compare FL's video clock with LYNX's
- auto fl = song;
- fl.bpm = 120.0;
- fl.mode = lynx::PlayMode::song;
- auto settings = vs;
- settings.delay = 0;
- settings.timeDisplay = lynx::video::Settings {}.timeDisplay;
- fl.channels[0].pluginState = lynx::video::write (settings);
- fl.patterns[0].name = "Pattern 1";
- lynx::Automation tempo;
- tempo.name = "Tempo";
- tempo.target = { lynx::AutomationTargetKind::tempo, 0, 0, 0 };
- const auto bar = (std::int64_t) lynx::ppq * 4;
- tempo.points = { { 0, lynx::valueFromTempo (120.0), 0.0f }, { bar * 4 - 1, lynx::valueFromTempo (120.0), 0.0f },
- { bar * 4, lynx::valueFromTempo (60.0), 0.0f }, { bar * 8, lynx::valueFromTempo (60.0), 0.0f } };
- fl.automations.push_back (tempo);
- lynx::Clip at;
- at.kind = lynx::ClipKind::automation;
- at.automation = 0;
- at.track = 1;
- at.start = 0;
- at.length = bar * 8;
- fl.playlist.push_back (at);
- lynx::Clip pc;
- pc.pattern = 0;
- pc.track = 0;
- pc.start = 0;
- pc.length = bar * 8;
- fl.playlist.push_back (pc);
- juce::String error;
- lynx::ProjectFile::save (fl, juce::File (prefix + "-tempo.lynx"), error);
- }
- 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 runVideoTrackShot (const juce::String& prefix, const juce::String& videoPath, const juce::String& secondPath)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- struct TrackShot final : juce::Timer
- {
- lynx::AudioEngine offline { false };
- std::unique_ptr<lynx::PlaylistComponent> playlist;
- std::unique_ptr<lynx::media::FrameDecoder> decoder;
- juce::String prefix, report, path;
- double fps = 25.0;
- int step = 0, waits = 0, adrStep = 0;
- std::unique_ptr<juce::Component> adrPanel;
- std::function<void()> done;
- // song times (s): before, inside the first clip (on and between frame edges), across the second clip
- std::vector<double> times { 0.0, 1.0, 2.0 + 1.0 / 25.0, 2.5, 4.0, 7.3 };
- void timerCallback() override
- {
- if (step > 0 && adrStep == 0)
- {
- // the frame the decoder shows for the wanted file time (the clip starts at song 1.0 s, offset 0)
- const auto want = times[(std::size_t) step - 1] - 1.0;
- double ft = -1.0;
- const auto img = decoder->frame (ft);
- const auto expected = std::floor (want * fps + 1e-6) / fps;
- if (want >= 0.0 && ft < expected - 1e-3 && ++waits < 20)
- return; // (still decoding)
- waits = 0;
- report << "song " << juce::String (times[(std::size_t) step - 1], 3) << " s: wanted file time " << juce::String (want, 4)
- << ", frame shown at " << juce::String (ft, 4) << " (expected " << juce::String (expected, 4) << ")"
- << (want < 0.0 ? " [before the clip]" : std::abs (ft - expected) < 1e-3 ? " OK" : " MISMATCH") << "\n";
- savePng (lynx::shot::snapshot (*playlist), prefix + "-playlist-" + juce::String (step - 1) + ".png");
- if (img.isValid())
- savePng (img, prefix + "-frame-" + juce::String (step - 1) + ".png");
- for (int w = 0; w < juce::Desktop::getInstance().getNumComponents(); ++w)
- if (auto* c = juce::Desktop::getInstance().getComponent (w); c != nullptr && c->getName().startsWith ("Picture"))
- savePng (lynx::shot::snapshot (*c), prefix + "-window-" + juce::String (step - 1) + ".png");
- }
- if (step >= (int) times.size() && adrStep == 0)
- {
- // the ADR window: two cues, takes on the first; the play position inside the streamer before the in
- // point (4.0 s), so the video window shows the streamer and the line
- adrStep = 1;
- offline.editSong ([] (lynx::Song& s) {
- lynx::AdrCue a, b;
- a.id = "SC1-01";
- a.in = 4.0;
- a.out = 6.4;
- a.character = "Dr. Silva";
- a.line = "We have to leave before the storm reaches the coast.";
- a.notes = "softer, out of breath";
- a.status = lynx::AdrCue::Status::recorded;
- for (int n = 1; n <= 3; ++n)
- {
- lynx::AdrTake t;
- t.number = n;
- t.name = lynx::adr::takeName (a, n);
- t.rating = n == 2 ? 4 : n;
- t.circled = n == 2;
- a.takes.push_back (t);
- }
- a.selected = 2;
- lynx::adr::setCompRange (a, 4.0, 5.1, 2);
- lynx::adr::setCompRange (a, 5.1, 6.4, 3);
- b.id = "SC1-02";
- b.in = 8.0;
- b.out = 9.5;
- b.character = "Marta";
- b.line = "Then we go now.";
- s.adr.cues = { a, b };
- s.adr.current = 0;
- });
- adrPanel = lynx::adrwindow::makePanel (offline);
- adrPanel->setSize (1200, 640);
- adrPanel->setVisible (true);
- offline.getTransport().positionTicks.store (3.0 * offline.getSong().bpm / 60.0 * lynx::ppq);
- decoder->request (2.0, false);
- return;
- }
- if (adrStep == 1)
- {
- adrStep = 2;
- savePng (lynx::shot::snapshot (*adrPanel), prefix + "-adr.png");
- for (int w = 0; w < juce::Desktop::getInstance().getNumComponents(); ++w)
- if (auto* c = juce::Desktop::getInstance().getComponent (w); c != nullptr && c->getName().startsWith ("Picture"))
- savePng (lynx::shot::snapshot (*c), prefix + "-adr-window.png");
- offline.getTransport().positionTicks.store (4.5 * offline.getSong().bpm / 60.0 * lynx::ppq);
- decoder->request (3.5, false);
- return;
- }
- if (adrStep == 2)
- {
- for (int w = 0; w < juce::Desktop::getInstance().getNumComponents(); ++w)
- if (auto* c = juce::Desktop::getInstance().getComponent (w); c != nullptr && c->getName().startsWith ("Picture"))
- savePng (lynx::shot::snapshot (*c), prefix + "-adr-window-line.png");
- adrPanel.reset();
- // export with video: a 3 s mix under the picture, re-encoded (the clip starts at 1 s) and copied (from 1 s)
- {
- const juce::File wav (prefix + "-mix.wav");
- wav.deleteFile();
- juce::WavAudioFormat format;
- if (std::unique_ptr<juce::OutputStream> os (wav.createOutputStream().release()); os != nullptr)
- if (std::unique_ptr<juce::AudioFormatWriter> w (format.createWriterFor (os.get(), 48000.0, 2, 16, {}, 0)); w != nullptr)
- {
- os.release();
- juce::AudioBuffer<float> b (2, 48000 * 3);
- for (int k = 0; k < b.getNumSamples(); ++k)
- b.setSample (0, k, 0.25f * (float) std::sin (k * 2.0 * juce::MathConstants<double>::pi * 330.0 / 48000.0)), b.setSample (1, k, b.getSample (0, k));
- w->writeFromAudioSampleBuffer (b, 0, b.getNumSamples());
- }
- for (const auto origin : { 0.0, 1.0 })
- {
- const juce::File out (prefix + "-mux-" + juce::String ((int) origin) + ".mp4");
- const auto t0 = juce::Time::getMillisecondCounterHiRes();
- const auto error = lynx::videotracks::muxWithVideo (offline.getSong(), origin, wav, out);
- report << "export with video from " << origin << " s: " << (error.isEmpty() ? "OK " + juce::String (out.getSize()) + " bytes" : "FAILED " + error)
- << " (" << juce::String ((juce::Time::getMillisecondCounterHiRes() - t0) / 1000.0, 2) << " s)\n";
- }
- }
- stopTimer();
- report << "frames decoded " << decoder->frameCount() << ", dropped " << decoder->droppedCount() << "\n";
- juce::File (prefix + "-report.txt").replaceWithText (report);
- if (done)
- done();
- return;
- }
- const auto t = times[(std::size_t) step++];
- offline.getTransport().positionTicks.store (t * offline.getSong().bpm / 60.0 * lynx::ppq);
- decoder->request (std::max (0.0, t - 1.0), false);
- }
- };
- static std::unique_ptr<TrackShot> shot;
- shot = std::make_unique<TrackShot>();
- shot->prefix = prefix;
- auto& offline = shot->offline;
- lynx::Song song;
- song.mixer = lynx::Song::defaultMixer (2);
- song.patterns.emplace_back();
- song.mode = lynx::PlayMode::song;
- song.bpm = 120.0;
- offline.setSong (std::move (song));
- offline.dispatchPendingMessages();
- const juce::File video (videoPath);
- const auto pr = lynx::media::probe (video.getFullPathName());
- auto& report = shot->report;
- report << "decoder: " << (pr.backend.isEmpty() ? juce::String ("none") : pr.backend) << " (system: " << lynx::media::nativeBackendName()
- << ", ffmpeg: " << lynx::findFfmpeg().getFullPathName() << ")\n";
- report << "video: " << pr.info.width << "x" << pr.info.height << " " << juce::String (pr.info.fps, 3) << " fps " << juce::String (pr.info.duration, 3)
- << " s, sound " << (pr.info.hasAudio ? "yes" : "no") << "\n";
- shot->fps = pr.info.fps > 1.0 ? pr.info.fps : 25.0;
- shot->times[2] = 2.0 + 1.0 / shot->fps; // (exactly on a frame edge)
- lynx::videotracks::importVideo (offline, video, 1.0, -1);
- if (secondPath.isNotEmpty())
- lynx::videotracks::importVideo (offline, juce::File (secondPath), 3.0, 1);
- offline.editSong ([] (lynx::Song& s) {
- s.video.startTimecode = 3600.0;
- s.video.burnIn = true;
- if (s.videoTracks.size() < 2)
- s.videoTracks.push_back ({});
- s.videoTracks[0].name = "Picture";
- s.videoTracks[1].name = "Reference";
- });
- report << "project rate: " << lynx::vtime::rateName (offline.getSong().video.rate) << ", clip 1: "
- << juce::String (offline.getSong().videoTracks[0].clips.empty() ? -1.0 : offline.getSong().videoTracks[0].clips[0].length, 3) << " s\n";
- // the project round trip
- {
- const juce::File file (prefix + "-project.lynx");
- juce::String error;
- lynx::ProjectFile::save (offline.getSong(), file, error);
- const auto back = lynx::ProjectFile::load (file, error);
- report << "project file round trip: " << (back && back->videoTracks == offline.getSong().videoTracks && back->video == offline.getSong().video ? "OK" : "MISMATCH " + error) << "\n";
- }
- shot->playlist = std::make_unique<lynx::PlaylistComponent> (offline);
- shot->playlist->setSize (1400, 640);
- shot->playlist->setVisible (true);
- shot->decoder = std::make_unique<lynx::media::FrameDecoder>();
- shot->decoder->setSource (video.getFullPathName(), pr.info);
- shot->decoder->setSize (pr.info.width, pr.info.height);
- shot->decoder->startThread (juce::Thread::Priority::low);
- lynx::videotracks::showWindow (offline, 0);
- shot->done = [this] { juce::MessageManager::callAsync ([this] { shot.reset(); quit(); }); };
- shot->startTimer (700);
- }
- 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;
- auto sheet = lynx::shot::canvas (130 + cols * cell, lynx::dance::moveCount * cell + 10);
- {
- // (the picture is complete when its Graphics is gone: round 190ba, the file was blank on Windows)
- juce::Graphics g (sheet);
- lynx::shot::logical (g);
- 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);
- }
- // Issue #121 (round 190ba): a sprite sheet in FL's Fruity Dance format (8 frames across, a row per move, a names
- // file beside it), made here from LYNX's own poses, loaded back as a user's sheet would be
- juce::String sheetReport;
- {
- constexpr int fw = 120, fh = 150;
- const std::vector<std::pair<const char*, int>> rows { { "Idle", lynx::dance::waiting }, { "Step", lynx::dance::stepping },
- { "Jump", lynx::dance::jumping }, { "Wave", lynx::dance::waving },
- { "Windmill", lynx::dance::windmill }, { "Held", lynx::dance::held } };
- juce::Image sheet (juce::Image::ARGB, fw * lynx::dance::sheetColumns, fh * (int) rows.size(), true);
- {
- juce::Graphics g (sheet);
- for (int r = 0; r < (int) rows.size(); ++r)
- for (int k = 0; k < lynx::dance::sheetColumns; ++k)
- {
- juce::Graphics::ScopedSaveState save (g);
- g.reduceClipRegion (k * fw, r * fh, fw, fh);
- lynx::dancer::draw (g, { (k + 0.5f) * fw, (float) (r + 1) * fh - 8.0f }, 96.0f,
- lynx::dance::pose (rows[(std::size_t) r].second, k / (double) lynx::dance::sheetColumns, 1), false, juce::Colour (0xff35c46a));
- }
- }
- const juce::File picture (prefix + "-sheet.png");
- savePng (sheet, picture.getFullPathName());
- juce::String names;
- for (const auto& [name, move] : rows)
- names << (names.isEmpty() ? "" : "\r\n") << name;
- picture.withFileExtension ("txt").replaceWithText (names, false, false, nullptr);
- // a picture that is not a whole number of frames: FL's "Bitmap size is incorrect."
- const juce::File wrong (prefix + "-sheet-wrong.png");
- savePng (sheet.getClippedImage ({ 0, 0, sheet.getWidth() - 3, sheet.getHeight() }), wrong.getFullPathName());
- wrong.withFileExtension ("txt").replaceWithText (names, false, false, nullptr);
- auto error = lynx::dancer::SheetError::none;
- const auto loaded = lynx::dancer::sheetFor (picture.getFullPathName().toStdString(), &error);
- auto wrongError = lynx::dancer::SheetError::none;
- const auto refused = lynx::dancer::sheetFor (wrong.getFullPathName().toStdString(), &wrongError);
- auto missingError = lynx::dancer::SheetError::none;
- const auto missing = lynx::dancer::sheetFor (juce::File (prefix + "-sheet-none.png").getFullPathName().toStdString(), &missingError);
- sheetReport << "sheet_loaded=" << (loaded != nullptr ? 1 : 0) << "\n"
- << "sheet_wrong_size_refused=" << (refused == nullptr && wrongError == lynx::dancer::SheetError::size ? 1 : 0) << "\n"
- << "sheet_missing_refused=" << (missing == nullptr && missingError == lynx::dancer::SheetError::missing ? 1 : 0) << "\n";
- bool ok = loaded != nullptr && refused == nullptr && missing == nullptr;
- if (loaded != nullptr)
- {
- sheetReport << "sheet_rows=" << loaded->layout.rows << "\nsheet_frame=" << loaded->layout.frameWidth << "x" << loaded->layout.frameHeight
- << "\nsheet_moves=" << loaded->moves() << "\nsheet_names=";
- for (const auto& n : loaded->names)
- sheetReport << juce::String::fromUTF8 (n.c_str()) << ";";
- sheetReport << "\n";
- ok = ok && loaded->layout.rows == (int) rows.size() && loaded->layout.frameWidth == fw && loaded->layout.frameHeight == fh;
- // the animation as the stage draws it: a row of moments of the move "Wave" (blending on), then mirrored,
- // then the row shown while the dancer is held
- auto strip = lynx::shot::canvas (fw * 12, fh * 3 + 20);
- int solid = 0;
- {
- juce::Graphics g (strip);
- lynx::shot::logical (g);
- g.fillAll (lynx::theme::colour::bg0);
- for (int line = 0; line < 3; ++line)
- {
- lynx::dance::SheetAnimator animator (3);
- for (int k = 0; k < 12; ++k)
- {
- const auto frame = animator.advance (k / 12.0 + 0.001, loaded->layout.rows, 4, line == 1, true, 0.5f, line == 2);
- const juce::Point<float> feet ((k + 0.5f) * fw, (float) (line + 1) * fh + 5.0f);
- lynx::dancer::drawSheet (g, *loaded, feet, 1.0f, frame);
- solid += lynx::dancer::sheetSolidAt (*loaded, feet, 1.0f, frame, feet.translated (0.0f, -70.0f)) ? 1 : 0;
- ok = ok && ! lynx::dancer::sheetSolidAt (*loaded, feet, 1.0f, frame, feet.translated (-(float) fw * 0.5f + 1.0f, -(float) fh + 1.0f));
- }
- }
- }
- // mirrored = the same frame flipped left-right, on whatever renderer this build draws with
- {
- lynx::dance::SheetFrame plain;
- plain.row = 3;
- plain.column = 2;
- auto turned = plain;
- turned.mirrored = true;
- juce::Image a (juce::Image::ARGB, fw, fh, true), b (juce::Image::ARGB, fw, fh, true);
- {
- juce::Graphics ga (a);
- lynx::dancer::drawSheet (ga, *loaded, { fw * 0.5f, (float) fh }, 1.0f, plain);
- }
- {
- juce::Graphics gb (b);
- lynx::dancer::drawSheet (gb, *loaded, { fw * 0.5f, (float) fh }, 1.0f, turned);
- }
- int same = 0, flippedSame = 0, solidPixels = 0;
- for (int y = 0; y < fh; ++y)
- for (int x = 0; x < fw; ++x)
- {
- const auto pa = a.getPixelAt (x, y);
- if (pa.getAlpha() < 200)
- continue;
- ++solidPixels;
- auto alike = [pa] (juce::Colour c) {
- return std::abs ((int) c.getRed() - (int) pa.getRed()) + std::abs ((int) c.getGreen() - (int) pa.getGreen())
- + std::abs ((int) c.getBlue() - (int) pa.getBlue()) + std::abs ((int) c.getAlpha() - (int) pa.getAlpha()) < 12;
- };
- same += alike (b.getPixelAt (x, y)) ? 1 : 0;
- flippedSame += alike (b.getPixelAt (fw - 1 - x, y)) ? 1 : 0;
- }
- const auto flips = solidPixels > 500 && flippedSame >= solidPixels * 98 / 100 && same < solidPixels * 95 / 100;
- sheetReport << "sheet_mirror_flips=" << (flips ? 1 : 0) << " (" << flippedSame << " of " << solidPixels << " solid pixels match flipped, " << same
- << " unflipped)\n";
- ok = ok && flips;
- }
- sheetReport << "sheet_body_solid=" << solid << "/36\n";
- ok = ok && solid >= 18;
- savePng (strip, prefix + "-sheet-frames.png");
- }
- sheetReport << "sheet_result=" << (ok ? "OK" : "ERROR") << "\n";
- lynx::ChannelDef c;
- c.name = "Fruity Dance #3";
- c.instrument = lynx::InstrumentKind::fruitydance;
- lynx::dance::Settings s;
- s.move = 2; // (the sheet's second row: "Step")
- s.x = 1000;
- s.y = 560;
- s.sheet = picture.getFullPathName().toStdString();
- 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 (lynx::shot::snapshot (*editor), prefix + "-editor.png");
- if (auto frame = lynx::makeChannelFrame (offline, 1, 0))
- savePng (lynx::shot::snapshot (*frame), prefix + "-frame.png");
- if (auto editor = lynx::makeChannelSettingsPanel (offline, 2))
- savePng (lynx::shot::snapshot (*editor), prefix + "-sheet-editor.png");
- {
- // the stage with the three dancers (the third from the sheet)
- lynx::DanceStage stage (offline);
- stage.setSize (1280, 640);
- stage.update();
- sheetReport << "stage_dancers=" << stage.dancerCount() << "\n";
- auto picture = lynx::shot::canvas (1280, 640);
- {
- juce::Graphics g (picture);
- lynx::shot::logical (g);
- g.fillAll (lynx::theme::colour::bg0);
- stage.paintEntireComponent (g, true);
- }
- savePng (picture, prefix + "-sheet-stage.png");
- }
- juce::File (prefix + "-sheetreport.txt").replaceWithText (sheetReport);
- }
- 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 (lynx::shot::snapshot (*c), 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 (lynx::shot::snapshot (*ec), 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 (lynx::shot::snapshot (*w->getContentComponent()), prefix + "-formula-controller.png");
- lynx::FormulaControllerWindows::closeAll();
- }
- bool runEdisonSlotTest (const juce::String& folderPath, const juce::String& flp)
- {
- namespace ae = lynx::audioedit;
- namespace ef = lynx::edisonfx;
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- const juce::File folder (folderPath);
- folder.createDirectory();
- juce::String report;
- bool all = true;
- auto check = [&] (const juce::String& name, bool ok, const juce::String& note = {}) {
- report << name << "=" << (ok ? "ok" : "FAIL") << (note.isNotEmpty() ? " (" + note + ")" : juce::String()) << "\n";
- all = all && ok;
- };
- auto shot = [&folder] (juce::Component& c, const juce::String& name) {
- savePng (lynx::shot::paint (c, lynx::theme::panel), folder.getChildFile (name).getFullPathName());
- };
- auto findSlot = [] (const lynx::Song& song, int& track, int& slot) {
- for (track = 0; track < (int) song.mixer.size(); ++track)
- for (slot = 0; slot < (int) song.mixer[(std::size_t) track].effects.size(); ++slot)
- if (song.mixer[(std::size_t) track].effects[(std::size_t) slot].kind == lynx::EffectKind::edison)
- return true;
- return false;
- };
- {
- lynx::AudioEngine engine (false);
- engine.setRecordingTarget (folder.getChildFile ("Audio").getChildFile ("Recorded"), "Test");
- // a project without the plugin is written as before: nothing of it in the file, and it reads back the same
- const auto before = lynx::ProjectFile::toJson (engine.getSong(), false);
- juce::String error;
- const auto same = lynx::ProjectFile::fromJson (before, error);
- check ("old_project_text_has_no_trace", ! before.containsIgnoreCase ("edison"));
- check ("old_project_round_trip_stable", same.has_value() && lynx::ProjectFile::toJson (*same, false) == before);
- const auto at = lynx::addEdisonSlot (engine, 1);
- engine.dispatchPendingMessages();
- check ("slot_added_to_first_empty_slot", at == 0 && engine.getSong().mixer[1].effects.size() == 1
- && engine.getSong().mixer[1].effects[0].kind == lynx::EffectKind::edison);
- if (at < 0)
- {
- folder.getChildFile ("report.txt").replaceWithText (report);
- return false;
- }
- const auto second = lynx::addEdisonSlot (engine, 1); // several instances on a track
- engine.dispatchPendingMessages();
- check ("second_instance_on_the_same_track", second == 1);
- engine.editSong ([at] (lynx::Song& s) {
- s.mixer[1].effects[(std::size_t) at].params[ef::recordMode] = ef::modeValue (ef::Mode::now);
- });
- engine.dispatchPendingMessages();
- const auto slotOf = [&engine, at] { return engine.getSong().mixer[1].effects[(std::size_t) at]; };
- const auto fx = engine.getEffect (1, at);
- const auto p = std::dynamic_pointer_cast<ef::Processor> (fx);
- const auto session = ef::findSession (slotOf().instance.id);
- check ("engine_built_the_effect_with_its_session", p != nullptr && session != nullptr);
- const auto other = ef::findSession (engine.getSong().mixer[1].effects[1].instance.id);
- check ("instances_have_their_own_audio", other != nullptr && other != session);
- if (p == nullptr || session == nullptr)
- {
- folder.getChildFile ("report.txt").replaceWithText (report);
- return false;
- }
- // idle: the audio passes through bit for bit
- const auto rate = p->sampleRate();
- std::vector<float> l (512), r (512);
- auto fill = [&] (int block) {
- for (int k = 0; k < 512; ++k)
- {
- const auto t = (double) (block * 512 + k) / rate;
- l[(std::size_t) k] = 0.6f * (float) std::sin (2.0 * 3.141592653589793 * 220.0 * t);
- r[(std::size_t) k] = 0.4f * (float) std::sin (2.0 * 3.141592653589793 * 330.0 * t);
- }
- };
- fill (0);
- auto inL = l, inR = r;
- p->process (l.data(), r.data(), 512, slotOf().params, 120.0);
- check ("idle_pass_through_bit_exact", l == inL && r == inR);
- // a take through the slot (Now), then the flush that makes it a file of the project
- std::vector<float> wantL, wantR;
- check ("record_starts", session->start (p, true));
- for (int block = 0; block < 60; ++block)
- {
- fill (block);
- wantL.insert (wantL.end(), l.begin(), l.end());
- wantR.insert (wantR.end(), r.begin(), r.end());
- p->process (l.data(), r.data(), 512, slotOf().params, 120.0);
- }
- session->stop();
- check ("take_is_the_input", session->document().audio.numChannels() == 2 && session->document().audio.channels[0] == wantL
- && session->document().audio.channels[1] == wantR);
- ae::Document withMarkers = session->document();
- ae::addMarker (withMarkers, 4000, "Verse");
- ae::addMarker (withMarkers, 12000);
- ae::setLoop (withMarkers, { 2000, 20000 });
- session->setDocument (withMarkers);
- engine.flushEdisonAudio();
- engine.dispatchPendingMessages();
- const juce::File file (juce::String::fromUTF8 (slotOf().samplePath.c_str()));
- check ("audio_written_to_the_project_folder", file.existsAsFile() && file.isAChildOf (folder.getChildFile ("Audio").getChildFile ("Recorded")),
- file.getFullPathName());
- check ("file_listed_with_the_session_recordings", std::find (engine.getSessionRecordings().begin(), engine.getSessionRecordings().end(), file)
- != engine.getSessionRecordings().end());
- check ("effect_kept_running_through_the_flush", engine.getEffect (1, at) == fx);
- check ("nothing_unsaved_after_the_flush", ! session->dirty());
- engine.flushEdisonAudio(); // (a second flush writes nothing new)
- check ("second_flush_keeps_the_file", juce::File (juce::String::fromUTF8 (slotOf().samplePath.c_str())) == file);
- // the project file: saved, loaded, the same slot with the same audio
- engine.editSong ([at] (lynx::Song& s) {
- auto& params = s.mixer[1].effects[(std::size_t) at].params;
- params[ef::recordMode] = ef::modeValue (ef::Mode::onPlay);
- params[ef::append] = 0.0f;
- params[ef::muteInput] = 1.0f;
- params[ef::slave] = 1.0f;
- params[ef::maxTime] = 5.0f / 6.0f;
- });
- engine.capturePluginStates();
- const auto project = folder.getChildFile ("edison-slot.lynx");
- check ("project_saved", lynx::ProjectFile::save (engine.getSong(), project, error), error);
- auto loaded = lynx::ProjectFile::load (project, error);
- check ("project_loaded", loaded.has_value(), error);
- if (loaded)
- {
- const auto& a = slotOf();
- const auto& b = loaded->mixer[1].effects[(std::size_t) at];
- check ("slot_kind_kept", b.kind == lynx::EffectKind::edison && loaded->mixer[1].effects.size() == 2);
- check ("slot_settings_kept", ef::modeOf (b.params) == ef::Mode::onPlay && b.params[ef::append] < 0.5f && b.params[ef::muteInput] >= 0.5f
- && b.params[ef::slave] >= 0.5f && ef::maxTimeIndexOf (b.params) == 5
- && std::abs (b.params[ef::noiseThreshold] - a.params[ef::noiseThreshold]) < 1.0e-6f);
- check ("slot_audio_path_kept", b.samplePath == a.samplePath);
- check ("project_text_round_trip_stable", lynx::ProjectFile::toJson (*loaded, false) == lynx::ProjectFile::toJson (engine.getSong(), false));
- lynx::AudioEngine second (false);
- second.setSong (std::move (*loaded));
- second.dispatchPendingMessages();
- const auto reopened = ef::findSession (second.getSong().mixer[1].effects[(std::size_t) at].instance.id);
- check ("reopened_project_has_the_audio", reopened != nullptr && reopened != session
- && reopened->document().audio.channels == withMarkers.audio.channels
- && reopened->document().audio.sampleRate == withMarkers.audio.sampleRate);
- check ("reopened_project_has_markers_and_loop", reopened != nullptr && reopened->document().markers.size() == 2
- && reopened->document().markers[0].name == "Verse"
- && reopened->document().loopStart == 2000 && reopened->document().loopEnd == 20000);
- check ("reopened_empty_instance_is_empty", ef::findSession (second.getSong().mixer[1].effects[1].instance.id) != nullptr
- && ef::findSession (second.getSong().mixer[1].effects[1].instance.id)->document().audio.empty());
- if (auto editor = lynx::makeEdisonSlotEditor (second, 1, at))
- {
- editor->setSize (1120, 600);
- second.dispatchPendingMessages();
- shot (*editor, "slot-editor-reopened.png");
- }
- }
- // the plugin's window: the audio editor on the slot (empty instance, then the one with the take)
- if (auto editor = lynx::makeEdisonSlotEditor (engine, 1, 1))
- {
- editor->setSize (1120, 600);
- engine.dispatchPendingMessages();
- shot (*editor, "slot-editor-empty.png");
- }
- auto editor = lynx::makeEdisonSlotEditor (engine, 1, at);
- check ("slot_window_is_the_audio_editor", editor != nullptr);
- if (editor != nullptr)
- {
- editor->setSize (1120, 600);
- engine.dispatchPendingMessages();
- shot (*editor, "slot-editor.png");
- juce::File (folder.getChildFile ("slot-menu.txt")).replaceWithText (lynx::audioEditorMenuForSnapshot (*editor).joinIntoString ("\n") + "\n");
- }
- check ("no_editor_for_other_slots", lynx::makeEdisonSlotEditor (engine, 0, 0) == nullptr);
- editor.reset();
- // deleting the slot leaves the song without it (the file stays for the unused-recordings prompt)
- engine.editSong ([at] (lynx::Song& s) { s.mixer[1].effects.erase (s.mixer[1].effects.begin() + at); });
- engine.dispatchPendingMessages();
- check ("deleted_slot_is_gone", engine.getSong().mixer[1].effects.size() == 1 && file.existsAsFile());
- }
- if (flp.isNotEmpty())
- {
- lynx::AudioEngine engine (false);
- juce::String error;
- const auto imported = engine.importFlpFile (juce::File (flp), error);
- engine.dispatchPendingMessages();
- check ("flp_imported", imported, error);
- int count = 0, withAudio = 0;
- const auto& song = engine.getSong();
- for (int t = 0; t < (int) song.mixer.size(); ++t)
- for (int s = 0; s < (int) song.mixer[(std::size_t) t].effects.size(); ++s)
- {
- const auto& fx = song.mixer[(std::size_t) t].effects[(std::size_t) s];
- if (fx.kind != lynx::EffectKind::edison)
- continue;
- ++count;
- const auto session = ef::findSession (fx.instance.id);
- const auto frames = session != nullptr ? session->document().audio.frames() : -1;
- withAudio += frames > 0 ? 1 : 0;
- report << "flp_slot track " << t << " slot " << s << ": mode " << ef::modeName (ef::modeOf (fx.params))
- << ", append " << (fx.params[ef::append] >= 0.5f ? "on" : "off") << ", mute input " << (fx.params[ef::muteInput] >= 0.5f ? "on" : "off")
- << ", slave " << (fx.params[ef::slave] >= 0.5f ? "on" : "off") << ", loop " << (fx.params[ef::loopPlay] >= 0.5f ? "on" : "off")
- << ", max time index " << ef::maxTimeIndexOf (fx.params) << ", threshold " << juce::String (fx.params[ef::noiseThreshold], 4)
- << ", state " << (int) fx.state.size() << " bytes, audio " << (juce::int64) frames << " frames"
- << (session != nullptr && frames > 0 ? " at " + juce::String (session->document().audio.sampleRate, 0) + " Hz, "
- + juce::String (session->document().audio.numChannels()) + " ch, "
- + juce::String ((int) session->document().markers.size()) + " markers"
- : juce::String())
- << "\n";
- if (count == 1 || (frames > 0 && withAudio == 1))
- if (auto editor = lynx::makeEdisonSlotEditor (engine, t, s))
- {
- editor->setSize (1120, 600);
- engine.dispatchPendingMessages();
- shot (*editor, frames > 0 ? "slot-editor-flp-audio.png" : "slot-editor-flp.png");
- }
- }
- check ("flp_edison_slots_kept_as_the_plugin", count > 0, juce::String (count) + " slots, " + juce::String (withAudio) + " with audio");
- // saved as .lynx and read again: still the plugin, FL's state (the audio) with it
- int t = 0, s = 0;
- if (findSlot (song, t, s))
- {
- const auto project = folder.getChildFile ("edison-flp.lynx");
- const auto saved = lynx::ProjectFile::save (song, project, error);
- std::optional<lynx::Song> loaded;
- if (saved)
- loaded = lynx::ProjectFile::load (project, error);
- check ("flp_slot_survives_the_project_file", loaded.has_value() && t < (int) loaded->mixer.size()
- && s < (int) loaded->mixer[(std::size_t) t].effects.size()
- && loaded->mixer[(std::size_t) t].effects[(std::size_t) s].kind == lynx::EffectKind::edison
- && loaded->mixer[(std::size_t) t].effects[(std::size_t) s].state == song.mixer[(std::size_t) t].effects[(std::size_t) s].state
- && loaded->mixer[(std::size_t) t].effects[(std::size_t) s].params == song.mixer[(std::size_t) t].effects[(std::size_t) s].params,
- error);
- }
- }
- // round 190ct (live FL check 190cq): the open-and-record preset, the fresh defaults and the question before
- // "Remove all Edison instances", in the app
- {
- lynx::AudioEngine engine (false);
- lynx::MainComponent ui (engine, false);
- ui.setSize (1600, 900);
- engine.dispatchPendingMessages();
- const auto toolsMenu = [&ui] {
- const auto names = ui.getMenuNamesForSnapshot();
- for (int m = 0; m < names.size(); ++m)
- if (names[m] == lynx::tr ("Tools"))
- return ui.getMenuForSnapshot (m);
- return juce::PopupMenu();
- };
- const auto removeItem = [&toolsMenu] (bool& found, bool& enabled) {
- found = enabled = false;
- const auto menu = toolsMenu(); // (the iterator keeps a reference)
- for (juce::PopupMenu::MenuItemIterator it (menu, true); it.next();)
- if (it.getItem().text == lynx::tr ("Remove all Edison instances"))
- {
- found = true;
- enabled = it.getItem().isEnabled;
- if (enabled && it.getItem().action)
- it.getItem().action(); // asks: nothing may go before the answer
- return;
- }
- };
- const auto count = [&engine] {
- int n = 0;
- for (const auto& track : engine.getSong().mixer)
- for (const auto& fx : track.effects)
- n += fx.kind == lynx::EffectKind::edison ? 1 : 0;
- return n;
- };
- bool found = false, enabled = false;
- removeItem (found, enabled);
- check ("remove_all_edison_enabled_with_none", found && enabled && count() == 0);
- const auto plain = lynx::addEdisonSlot (engine, 1);
- const auto armed = lynx::addEdisonSlot (engine, 2, true);
- engine.dispatchPendingMessages();
- if (plain >= 0 && armed >= 0)
- {
- const auto& a = engine.getSong().mixer[1].effects[(std::size_t) plain].params;
- const auto& b = engine.getSong().mixer[2].effects[(std::size_t) armed].params;
- check ("open_audio_editor_fresh_defaults", ef::modeOf (a) == ef::Mode::onInput && ef::maxTimeIndexOf (a) == 5 && a[ef::append] >= 0.5f
- && a[ef::slave] < 0.5f);
- check ("open_audio_editor_and_record_preset", ef::modeOf (b) == ef::Mode::onPlay && ef::maxTimeIndexOf (b) == 3 && b[ef::append] < 0.5f
- && b[ef::slave] >= 0.5f);
- }
- else
- check ("open_audio_editor_slots_added", false);
- removeItem (found, enabled);
- engine.dispatchPendingMessages();
- check ("remove_all_edison_asks_first", found && enabled && count() == 2);
- const auto question = lynx::removeAllEdisonInstancesQuestion();
- check ("remove_all_edison_question_is_fls", question.getTitle() == lynx::tr ("Remove Edison instances")
- && question.getMessage() == lynx::tr ("Are you sure you want to remove all Edison instances from the project ?")
- && question.getNumButtons() == 2 && question.getButtonText (0) == lynx::tr ("Yes")
- && question.getButtonText (1) == lynx::tr ("No"));
- // LYNX keeps an undo for the removal (rollup 190cv), so the question may not promise "(No undo)" in any
- // language, and the Yes action must come back with one undo
- {
- bool noUndoLine = false;
- for (const auto& line : juce::StringArray::fromLines (question.getMessage()))
- noUndoLine = noUndoLine || line.trim().startsWithChar ('(');
- check ("remove_all_edison_question_has_no_no_undo_line", ! noUndoLine && ! question.getMessage().contains ("No undo"));
- const int before = count();
- lynx::removeAllEdisonInstances (engine);
- engine.dispatchPendingMessages();
- const int removed = count();
- engine.undo();
- engine.dispatchPendingMessages();
- check ("remove_all_edison_yes_removes_and_undo_restores", before == 2 && removed == 0 && count() == 2);
- }
- {
- juce::AlertWindow box (question.getTitle(), question.getMessage(), question.getIconType());
- box.addButton (question.getButtonText (0), 1);
- box.addButton (question.getButtonText (1), 0);
- box.setSize (box.getWidth(), box.getHeight());
- savePng (lynx::shot::paint (box, lynx::theme::panel), folder.getChildFile ("remove-all-edison-question.png").getFullPathName());
- }
- {
- lynx::EffectSlot slot = lynx::makeEffectSlot (lynx::EffectKind::edison);
- lynx::edisonfx::setOpenAndRecord (slot.params);
- engine.editSong ([&slot] (lynx::Song& s) { s.mixer[3].effects.push_back (slot); });
- engine.dispatchPendingMessages();
- if (const auto editor = lynx::makeEdisonSlotEditor (engine, 3, 0))
- {
- editor->setSize (1120, 600);
- engine.dispatchPendingMessages();
- shot (*editor, "slot-editor-open-and-record.png");
- }
- if (const auto editor = lynx::makeEdisonSlotEditor (engine, 1, plain))
- {
- editor->setSize (1120, 600);
- engine.dispatchPendingMessages();
- shot (*editor, "slot-editor-fresh-defaults.png");
- }
- }
- }
- report << (all ? "ALL OK\n" : "FAILURES\n");
- folder.getChildFile ("report.txt").replaceWithText (report);
- return all;
- }
- 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) {
- auto image = lynx::shot::paint (c, lynx::theme::panel);
- 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");
- // round 190ee: the first marker's menu (Trigger note) and FL's four snap modes on a probe frame
- if (! d.markers.empty())
- juce::File (prefix + "-marker-menu.txt").replaceWithText (lynx::audioEditorMarkerMenuForSnapshot (*editor, 0).joinIntoString ("\n") + "\n");
- {
- juce::StringArray snaps;
- const auto probe = (std::int64_t) (d.audio.frames() * 3 / 8) + 777;
- for (int mode = 0; mode < 4; ++mode)
- snaps.add (lynx::setAudioEditorSnapForSnapshot (*editor, mode, probe));
- juce::File (prefix + "-snap.txt").replaceWithText (snaps.joinIntoString ("\n") + "\n");
- shot (*editor, "-editor-snap-on.png");
- }
- 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 (lynx::shot::snapshot (panel), 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 (lynx::shot::snapshot (*broken), 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 (lynx::shot::snapshot (*panel),
- 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 (lynx::shot::snapshot (*panel), 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 (lynx::shot::snapshot (*content), 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 (lynx::shot::snapshot (*palette), prefix + "-quickadd-renamed.png");
- }
- ui.selectTabForSnapshot (3);
- ui.getMixerForSnapshot().selectTrack (1);
- offline.dispatchPendingMessages();
- savePng (lynx::shot::snapshot (ui), prefix + "-mixer-renamed.png");
- offline.getPluginHost().setPluginName (key, "");
- }
- }
- void runAudioXShot (const juce::String& prefix)
- {
- 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()));
- offline.dispatchPendingMessages();
- // 1. sends: insert 1 feeds insert 3 pre-fader and insert 4 post-fader (FL's way)
- offline.editSong ([] (lynx::Song& s) {
- if (s.mixer.size() < 5)
- return;
- s.mixer[1].name = "Vocal";
- s.mixer[3].name = "Reverb";
- s.mixer[4].name = "Delay";
- s.setRoute (1, 3, true);
- s.setRoute (1, 4, true);
- s.setRouteLevel (1, 3, 0.6f);
- s.setRouteLevel (1, 4, 0.4f);
- s.setSendPre (1, 3, true);
- });
- offline.dispatchPendingMessages();
- ui.selectTabForSnapshot (3);
- ui.getMixerForSnapshot().selectTrack (1);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-send-pre.png");
- auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
- saveMenus (juce::StringArray { "Send to Reverb (pre-fader)", "Send to Delay (post-fader)" },
- std::vector<juce::PopupMenu> { strips.buildSendMenu (3), strips.buildSendMenu (4) }, prefix + "-send-menu.png");
- // 2. low latency while recording: the monitored track's look-ahead limiter is bypassed, the EQ stays
- offline.editSong ([] (lynx::Song& s) {
- s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::parametricEq));
- s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::limiter));
- s.mixer[1].inputChannel = 0;
- s.mixer[1].monitor = lynx::InputMonitor::on;
- });
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-lowlat-off.png");
- auto options = offline.getRecordOptions();
- options.lowLatencyRecording = true;
- offline.setRecordOptions (options);
- offline.dispatchPendingMessages();
- ui.getMixerForSnapshot().selectTrack (1);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-lowlat-on.png");
- saveMenus (juce::StringArray { "Record" }, std::vector<juce::PopupMenu> { ui.getFullRecordMenuForSnapshot() }, prefix + "-lowlat-menu.png");
- juce::String report;
- report << "latency_with_option=" << offline.getLatencySamples() << " bypassed_slots=" << offline.lowLatencyBypassedCount() << "\n";
- options.lowLatencyRecording = false;
- offline.setRecordOptions (options);
- offline.dispatchPendingMessages();
- report << "latency_without_option=" << offline.getLatencySamples() << "\n";
- // 3. the Browser's "Preview in time": a 120 BPM loop previewed in a 140 BPM project
- const auto dir = juce::File (prefix).getParentDirectory().getChildFile ("audiox-preview");
- dir.createDirectory();
- const auto wav = dir.getChildFile ("Drum loop 120 bpm.wav");
- {
- const int frames = 44100 * 4;
- juce::AudioBuffer<float> audio (1, frames);
- for (int i = 0; i < frames; ++i)
- {
- const auto t = (double) (i % 22050) / 44100.0;
- audio.setSample (0, i, (float) (0.8 * std::exp (-t * 30.0) * std::sin (6.283185307179586 * (50.0 + 80.0 * std::exp (-t * 40.0)) * t)));
- }
- wav.deleteFile();
- juce::WavAudioFormat format;
- std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
- if (auto* w = format.createWriterFor (out.get(), 44100.0, 1, 16, {}, 0))
- {
- out.release();
- std::unique_ptr<juce::AudioFormatWriter> writer (w);
- writer->writeFromAudioSampleBuffer (audio, 0, frames);
- }
- }
- offline.getTransport().bpm.store (140.0);
- offline.setPreviewInTime (true);
- ui.showDesktopForSnapshot (false);
- offline.previewFile (wav);
- offline.finishPreviewJobs();
- ui.getBrowserForSnapshot().showPreviewForSnapshot (wav);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-preview-in-time.png");
- saveMenus (juce::StringArray { "Browser options" }, std::vector<juce::PopupMenu> { ui.getBrowserForSnapshot().buildViewMenu() }, prefix + "-preview-menu.png");
- const auto& timing = offline.getPreviewTiming();
- report << "preview file_bpm=" << timing.fileBpm << " project_bpm=" << timing.projectBpm << " ratio=" << timing.ratio
- << " prepare_ms=" << juce::String (offline.getLastPreviewPrepareMs(), 1) << "\n";
- offline.previewFile ({});
- offline.setPreviewInTime (false);
- juce::File (prefix + "-report.txt").replaceWithText (report);
- }
- }
- void runComp177Shot (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()));
- ui.openFile (juce::File (projectPath));
- offline.dispatchPendingMessages();
- ui.selectTabForSnapshot (2);
- offline.dispatchPendingMessages();
- auto& playlist = ui.getPlaylistForSnapshot();
- std::int64_t last = 0;
- for (const auto& c : offline.getSong().playlist)
- last = std::max (last, c.end());
- const auto bars = juce::jmax (1, (int) (last / (4 * lynx::ppq)) + 1);
- playlist.setViewForSnapshot (juce::jmax (60.0, (ui.getWidth() - 300.0) / bars), 0, 0);
- // (the first paint asks for the clips' waveforms, a worker thread loads them)
- saveSnapshot (ui, prefix + "-opened.png");
- juce::Thread::sleep (3000);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-opened.png");
- // a muted clip selected
- for (int c = 0; c < (int) offline.getSong().playlist.size(); ++c)
- if (offline.getSong().playlist[(std::size_t) c].muted)
- {
- playlist.selectClipsForSnapshot ({ c });
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-selected.png");
- playlist.selectClipsForSnapshot ({});
- break;
- }
- juce::String report;
- const auto listTracks = [&offline, &report] (const juce::String& title) {
- const auto& s = offline.getSong();
- report << title << "\n";
- for (int t = 0; t < (int) s.playlistTracks.size(); ++t)
- {
- int clips = 0, muted = 0;
- for (const auto& c : s.playlist)
- if (c.track == t)
- ++clips, muted += c.muted ? 1 : 0;
- const auto& pt = s.playlistTracks[(std::size_t) t];
- if (clips > 0 || pt.grouped || ! pt.name.empty())
- report << "track " << (t + 1) << " '" << juce::String::fromUTF8 (pt.name.c_str()) << "' grouped=" << (pt.grouped ? 1 : 0) << " collapsed=" << (pt.collapsed ? 1 : 0)
- << " comp=" << (pt.compTrack ? 1 : 0) << " clips=" << clips << " muted=" << muted << "\n";
- }
- };
- listTracks ("opened");
- // the first group's header (a member's menu holds "Comp these takes" too)
- int firstGroup = -1;
- for (int t = 0; t < (int) offline.getSong().playlistTracks.size() && firstGroup < 0; ++t)
- if (lynx::comp::canComp (offline.getSong(), t))
- firstGroup = t;
- report << "first group with takes: track " << (firstGroup + 1) << "\n";
- if (firstGroup >= 0)
- {
- saveMenus (juce::StringArray { "Playlist track" }, std::vector<juce::PopupMenu> { playlist.getTrackMenuForSnapshot (firstGroup) }, prefix + "-trackmenu.png");
- int comp = -1;
- offline.editSong ([firstGroup, &comp] (lynx::Song& s) { comp = lynx::comp::compTakes (s, firstGroup); });
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-comped.png");
- listTracks ("after Comp these takes");
- const auto g = lynx::comp::groupOf (offline.getSong(), comp);
- std::int64_t from = -1, to = 0;
- for (const auto& c : offline.getSong().playlist)
- if (c.track == g.first)
- from = from < 0 ? c.start : std::min (from, c.start), to = std::max (to, c.end());
- if (g.valid() && to > from)
- {
- offline.editSong ([&g, from, to] (lynx::Song& s) { lynx::comp::swipe (s, g.first, from + (to - from) / 4, from + (to - from) / 2); });
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-swiped.png");
- listTracks ("after a swipe of the middle of the first lane");
- // a lane auditioned; the crossfade close up; the comp flattened
- offline.editSong ([&g] (lynx::Song& s) { lynx::comp::setAudition (s, g.first); }, false);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-audition.png");
- offline.editSong ([] (lynx::Song& s) { lynx::comp::setAudition (s, -1); }, false);
- const auto switchAt = from + (to - from) / 4;
- playlist.setViewForSnapshot (4.0 * 4.0 * lynx::ppq, 0, 0);
- playlist.setScrollTickForSnapshot ((double) (switchAt - 100));
- juce::Thread::sleep (1500);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-crossfade.png");
- playlist.setViewForSnapshot (juce::jmax (60.0, (ui.getWidth() - 300.0) / bars), 0, 0);
- offline.editSong ([comp] (lynx::Song& s) { lynx::comp::flatten (s, comp); });
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-flattened.png");
- listTracks ("after Flatten comp");
- }
- }
- saveMenus (juce::StringArray { "Record" }, std::vector<juce::PopupMenu> { ui.getRecordMenuForSnapshot() }, prefix + "-recordmenu.png");
- juce::File (prefix + "-tracks.txt").replaceWithText (report);
- }
- }
- // Round 190bx: the Settings pages alone (the full --snapshot takes minutes). prefix-settings-<page>.png at the
- // window's size, -small.png at 390 x 390 (rows must scroll, never be cut off or squeezed) and -whole.png tall
- // enough to show every row of the page.
- void runSettingsShot (const juce::String& prefix)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- {
- lynx::AudioEngine offline (false);
- 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);
- auto shoot = [&] (lynx::SettingsPage page, const juce::String& name, int width, int height) {
- auto panel = lynx::makeSettingsPanel (offline, page);
- if (width > 0)
- panel->setSize (width, height);
- juce::Component frame;
- frame.setSize (panel->getWidth(), panel->getHeight());
- frame.addAndMakeVisible (*panel);
- panel->setTopLeftPosition (0, 0);
- juce::Image image (juce::Image::ARGB, frame.getWidth(), frame.getHeight(), true);
- {
- juce::Graphics g (image);
- g.fillAll (lynx::theme::panel);
- frame.paintEntireComponent (g, false);
- }
- savePng (image, prefix + "-settings-" + name + ".png");
- };
- const std::pair<lynx::SettingsPage, const char*> pages[] = { { lynx::SettingsPage::audio, "audio" }, { lynx::SettingsPage::midi, "midi" },
- { lynx::SettingsPage::general, "general" }, { lynx::SettingsPage::theme, "theme" },
- { lynx::SettingsPage::files, "files" }, { lynx::SettingsPage::extras, "extras" },
- { lynx::SettingsPage::project, "project" }, { lynx::SettingsPage::info, "info" } };
- for (const auto& [page, name] : pages)
- {
- shoot (page, name, 0, 0);
- shoot (page, juce::String (name) + "-small", 390, 390);
- }
- shoot (lynx::SettingsPage::audio, "audio-whole", 680, 1500);
- shoot (lynx::SettingsPage::general, "general-whole", 680, 2400); // (round 190gh: + the Updates section's previous-version row)
- }
- juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
- }
- // round 190bw: FL's 13 curve modes of an automation clip's points (see --curveshot)
- bool runTrackModeShot (const juce::String& prefix)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- lynx::AudioEngine offline (false);
- bool all = true;
- juce::String report;
- {
- lynx::MainComponent ui (offline, false);
- ui.setSize (1600, 900);
- offline.dispatchPendingMessages();
- auto& playlist = ui.getPlaylistForSnapshot();
- // the track's menu, Track mode and Audio track side by side; the Audio track entries as FL writes them
- // ("-" in front = greyed, "v" = ticked)
- const auto shoot = [&] (int track, const juce::String& name, const juce::StringArray& fl) {
- const auto menu = playlist.getTrackMenuForSnapshot (track);
- juce::StringArray names { "Track " + juce::String (track + 1) };
- std::vector<juce::PopupMenu> menus { menu };
- for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
- if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::theme::mnemonic (lynx::tr ("Track mode"), 'T'))
- {
- names.add (lynx::tr ("Track mode"));
- menus.push_back (*it.getItem().subMenu);
- }
- if (menus.size() == 2)
- for (juce::PopupMenu::MenuItemIterator it (menus[1]); it.next();)
- if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::theme::mnemonic (lynx::tr ("Audio track"), 'A'))
- {
- names.add (lynx::tr ("Audio track"));
- menus.push_back (*it.getItem().subMenu);
- }
- juce::StringArray lynxList;
- if (menus.size() == 3)
- for (juce::PopupMenu::MenuItemIterator it (menus[2]); it.next();)
- lynxList.add (it.getItem().isSeparator ? juce::String ("|")
- : (it.getItem().isTicked ? "v " : "") + juce::String (it.getItem().isEnabled ? "" : "- ") + it.getItem().text);
- saveMenus (names, menus, prefix + "-" + name + ".png");
- const auto same = menus.size() == 3 && lynxList == fl;
- all = all && same;
- report << name << ": " << (same ? "SAME AS FL" : "DIFFERENT") << "\n LYNX: " << lynxList.joinIntoString (" / ")
- << "\n FL: " << fl.joinIntoString (" / ") << "\n";
- };
- const auto flList = [] (int inserts, std::map<int, juce::String> named, std::set<int> greyed) {
- juce::StringArray l { "New mixer track(s)", "|" };
- for (int i = 1; i <= inserts; ++i)
- l.add ((greyed.count (i) ? "- " : "") + juce::String (i) + ". " + (named.count (i) ? named[i] : "Insert " + juce::String (i)));
- return l;
- };
- // q1-01: a fresh project, Track 1 unassigned
- shoot (0, "fresh", flList (16, {}, {}));
- // q1-02: Track 1 linked to insert 6, insert 7 renamed "Vox chain"; Track 2's menu
- offline.editSong ([] (lynx::Song& s) {
- lynx::trackmodes::assignAudioTracks (s, { 0 }, 6);
- s.mixer[7].name = "Vox chain";
- });
- offline.dispatchPendingMessages();
- shoot (1, "linked-renamed", flList (16, { { 7, "Vox chain" } }, { 6 }));
- // q1-07: the rest of FL's session (live 190cu Q2): Track 3 → 7; Track 4 → New mixer track (17), insert 9
- // renamed "Vox chain", Track 4 → 9; Track 5 "Lead" → 11, insert 12 "Vox chain", Track 5 → 12; Track 6 "Lead"
- // (unassigned), insert 13 "Vox chain", Track 6 → 13. Track 7's menu
- offline.editSong ([] (lynx::Song& s) {
- namespace tm = lynx::trackmodes;
- if (s.playlistTracks.size() < 8)
- s.playlistTracks.resize (8);
- tm::assignAudioTracks (s, { 2 }, 7);
- tm::assignAudioTracks (s, { 3 }, tm::newMixerTrack);
- s.mixer[9].name = "Vox chain";
- tm::assignAudioTracks (s, { 3 }, 9);
- s.playlistTracks[4].name = "Lead";
- tm::assignAudioTracks (s, { 4 }, 11);
- s.mixer[12].name = "Vox chain";
- tm::assignAudioTracks (s, { 4 }, 12);
- s.playlistTracks[5].name = "Lead";
- s.mixer[13].name = "Vox chain";
- tm::assignAudioTracks (s, { 5 }, 13);
- });
- offline.dispatchPendingMessages();
- shoot (6, "full-state", flList (17, { { 7, "Vox chain" }, { 9, "Insert 17" }, { 12, "Lead" }, { 13, "Vox chain" } }, { 6, 7, 9, 12, 13 }));
- }
- report << (all ? "ALL SAME AS FL\n" : "FAILURES\n");
- juce::File (prefix + "-report.txt").replaceWithText (report);
- return all;
- }
- void runCurveShot (const juce::String& prefix)
- {
- 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()));
- offline.dispatchPendingMessages();
- // FL's menu order, one bar per mode, the levels going up and down; a tension where the mode needs one to show
- static const int order[] = { lynx::flcurve::smooth, lynx::flcurve::hold, lynx::flcurve::singleCurve, lynx::flcurve::singleCurve2,
- lynx::flcurve::singleCurve3, lynx::flcurve::doubleCurve, lynx::flcurve::doubleCurve2, lynx::flcurve::doubleCurve3,
- lynx::flcurve::halfSine, lynx::flcurve::stairs, lynx::flcurve::smoothStairs, lynx::flcurve::pulse, lynx::flcurve::wave };
- const auto bar = (std::int64_t) lynx::ppq * 4;
- offline.editSong ([bar] (lynx::Song& song) {
- song.mode = lynx::PlayMode::song;
- lynx::Automation a;
- a.name = "Curve modes";
- a.target = { lynx::AutomationTargetKind::mixerVolume, 1 };
- a.points.push_back ({ 0, 0.15f, 0.0f });
- int k = 0;
- for (const auto mode : order)
- {
- const auto stepped = mode == lynx::flcurve::stairs || mode == lynx::flcurve::smoothStairs || mode == lynx::flcurve::pulse || mode == lynx::flcurve::wave;
- a.points.back().mode = (std::uint8_t) mode;
- a.points.back().tension = mode == lynx::flcurve::smooth || mode == lynx::flcurve::hold ? 0.0f : stepped ? -0.72f : (k % 2 == 0 ? 0.55f : -0.55f);
- ++k;
- a.points.push_back ({ bar * k, k % 2 == 1 ? 0.85f : 0.15f, 0.0f });
- }
- song.automations.insert (song.automations.begin(), a);
- for (auto& c : song.playlist)
- if (c.kind == lynx::ClipKind::automation)
- ++c.automation;
- lynx::Clip clip;
- clip.kind = lynx::ClipKind::automation;
- clip.automation = 0;
- clip.track = 3;
- clip.length = bar * 13;
- song.playlist.push_back (clip);
- if (song.playlistTracks.size() < 4)
- song.playlistTracks.resize (4);
- song.playlistTracks[3].height = 150;
- }, false);
- offline.dispatchPendingMessages();
- ui.selectTabForSnapshot (2);
- offline.dispatchPendingMessages();
- auto& playlist = ui.getPlaylistForSnapshot();
- saveSnapshot (ui, prefix + "-playlist.png");
- const auto clipIndex = (int) offline.getSong().playlist.size() - 1;
- // the point menu of the point that ends the "Stairs" segment (point 10), and of the first point
- saveMenus (juce::StringArray { "Automation point (ends a Stairs segment)", "First point" },
- std::vector<juce::PopupMenu> { playlist.getAutomationPointMenuForSnapshot (clipIndex, 10), playlist.getAutomationPointMenuForSnapshot (clipIndex, 0) },
- prefix + "-point-menu.png");
- auto editor = lynx::makeAutomationEditor (offline, 0);
- editor->setSize (1500, 420);
- savePng (editor->createComponentSnapshot (editor->getLocalBounds()), prefix + "-editor.png");
- editor.reset();
- // the project itself, for --export-flp and a look at the same clip in FL
- {
- juce::String saveError;
- lynx::ProjectFile::save (offline.getSong(), juce::File (prefix + "-modes.lynx"), saveError);
- }
- // part 2: the Piano roll tools that gained FL's options (they preview on the pattern and put the notes back)
- ui.selectTabForSnapshot (1);
- offline.dispatchPendingMessages();
- auto& roll = ui.getPianoRollForSnapshot();
- const std::pair<lynx::NoteTool, const char*> tools[] = { { lynx::NoteTool::flip, "-tool-flip.png" },
- { lynx::NoteTool::limit, "-tool-limit.png" },
- { lynx::NoteTool::scaleLevels, "-tool-scalelevels.png" },
- { lynx::NoteTool::randomise, "-tool-randomise.png" },
- { lynx::NoteTool::lfo, "-tool-lfo.png" } };
- // round 190ct: checks of the FL-live fixes, one line each in <prefix>-checks.txt (OK / FAIL)
- juce::StringArray checks;
- const auto check = [&checks] (bool ok, const juce::String& what) { checks.add ((ok ? "OK " : "FAIL ") + what); };
- {
- juce::String header;
- const auto pointMenu = playlist.getAutomationPointMenuForSnapshot (clipIndex, 10); // (the iterator keeps a reference)
- for (juce::PopupMenu::MenuItemIterator it (pointMenu); it.next();)
- {
- header = it.getItem().text;
- break;
- }
- check (header == "Point 11/14", "point menu header \"" + header + "\" (FL: \"Point n/N\")");
- }
- for (const auto& [tool, name] : tools)
- {
- auto panel = lynx::makeNoteToolPanel (offline, tool, roll.noteIndicesForSnapshot(), roll.gridForSnapshot());
- offline.dispatchPendingMessages();
- savePng (panel->createComponentSnapshot (panel->getLocalBounds()), prefix + name);
- if (tool == lynx::NoteTool::flip)
- {
- std::vector<juce::ToggleButton*> toggles;
- for (auto* child : panel->getChildren())
- if (auto* t = dynamic_cast<juce::ToggleButton*> (child))
- toggles.push_back (t);
- check (toggles.size() == 3 && toggles[0]->getToggleState() && toggles[1]->getToggleState() && ! toggles[2]->getToggleState(),
- "flip opens with Flip horizontally on, Preserve start times on, Flip vertically off");
- if (toggles.size() == 3)
- {
- toggles[2]->setToggleState (true, juce::sendNotificationSync);
- check (! toggles[0]->getToggleState() && toggles[2]->getToggleState(), "flip: vertically turns horizontally off (radios)");
- toggles[0]->setToggleState (true, juce::sendNotificationSync);
- check (toggles[0]->getToggleState() && ! toggles[2]->getToggleState(), "flip: horizontally turns vertically off (radios)");
- }
- }
- if (tool == lynx::NoteTool::limit)
- {
- auto* list = lynx::noteToolLongestChoiceForSnapshot (*panel);
- juce::ComboBox* key = nullptr;
- for (auto* child : panel->getChildren())
- if (auto* box = dynamic_cast<juce::ComboBox*> (child); box != nullptr && box->getNumItems() == 12)
- key = box;
- check (list != nullptr && list->getNumItems() == 89, "limit list has (none) + 66 chords + 22 scales: "
- + juce::String (list != nullptr ? list->getNumItems() : 0));
- check (list != nullptr && key != nullptr && list->getY() == key->getY() && list->getX() > key->getRight(),
- "limit: Key and the chord / scale list share one row");
- if (list != nullptr)
- saveMenus (juce::StringArray { "Limit: Key / scale list" }, std::vector<juce::PopupMenu> { *list->getRootMenu() },
- prefix + "-tool-limit-list.png");
- }
- if (tool == lynx::NoteTool::lfo)
- saveMenus (juce::StringArray { "LFO tool: right-click on a Period slider" },
- std::vector<juce::PopupMenu> { lynx::noteToolPresetMenuForSnapshot (*panel) }, prefix + "-tool-lfo-steps.png");
- }
- juce::File (prefix + "-checks.txt").replaceWithText (checks.joinIntoString ("\n") + "\n");
- }
- juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
- }
- bool runEvPaneShot (const juce::String& prefix, const juce::String& projectPath)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- lynx::AudioEngine offline (false);
- juce::StringArray report;
- bool ok = true;
- {
- 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
- offline.dispatchPendingMessages();
- auto& roll = ui.getPianoRollForSnapshot();
- roll.scrollToNotes();
- const auto area = ui.getLocalArea (&roll, roll.getLocalBounds());
- const auto file = lynx::platform::settingsFile ("piano-roll-event-pane.txt");
- auto source = juce::Desktop::getInstance().getMainMouseSource();
- const auto now = juce::Time::getCurrentTime();
- auto event = [&] (juce::Point<int> p, juce::Point<int> down, juce::ModifierKeys mods, int clicks, bool dragged) {
- return juce::MouseEvent (source, p.toFloat(), mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, &roll, &roll, now, down.toFloat(), now, clicks, dragged);
- };
- auto barCentre = [&roll] { return roll.eventPaneBarArea().getCentre(); };
- const juce::ModifierKeys left (juce::ModifierKeys::leftButtonModifier), right (juce::ModifierKeys::rightButtonModifier),
- middle (juce::ModifierKeys::middleButtonModifier);
- auto click = [&] (juce::ModifierKeys button, int clicks) {
- const auto at = barCentre();
- roll.mouseDown (event (at, at, button, clicks, false));
- roll.mouseUp (event (at, at, {}, clicks, false));
- offline.dispatchPendingMessages();
- };
- auto dragTo = [&] (int y) {
- const auto at = barCentre();
- roll.mouseDown (event (at, at, left, 1, false));
- for (int step = 1; step <= 8; ++step) // (a few moves, as a hand does)
- roll.mouseDrag (event ({ at.x, at.y + (y - at.y) * step / 8 }, at, left, 1, true));
- roll.mouseUp (event ({ at.x, y }, at, {}, 1, true));
- offline.dispatchPendingMessages();
- };
- auto state = [&] (const juce::String& name) {
- const auto grid = roll.getHeight() - lynx::PianoRollComponent::headerHeight - roll.velocityHeight - lynx::evpane::barThickness;
- const auto& st = lynx::PianoRollComponent::eventPaneState();
- report.add (name + ": roll " + juce::String (roll.getHeight()) + " px, grid " + juce::String (juce::jmax (0, grid)) + " px, bar top "
- + juce::String (roll.eventPaneBarTopForTests()) + ", event editor " + juce::String (roll.velocityHeight) + " px, aspect "
- + juce::String (st.aspect, 4) + ", spare " + juce::String (st.spare, 4) + ", file \"" + file.loadFileAsString().trim().replace ("\n", " ") + "\"");
- saveArea (ui, area, prefix + "-" + name + ".png");
- };
- auto expect = [&] (bool condition, const juce::String& what) {
- report.add ((condition ? "PASS " : "FAIL ") + what);
- ok = ok && condition;
- };
- state ("1-default");
- const auto defaultLane = roll.velocityHeight;
- expect (std::abs (lynx::PianoRollComponent::eventPaneState().aspect - 0.8f) < 1e-6f, "default place is FL's 0.8");
- ui.setHintForSnapshot (roll.hintAt (barCentre()));
- saveSnapshot (ui, prefix + "-2-hover-hint.png");
- ui.setHintForSnapshot ({});
- const auto travelTop = lynx::PianoRollComponent::headerHeight, travelBottom = roll.getHeight() - lynx::evpane::barThickness;
- dragTo (travelTop + (travelBottom - travelTop) * 45 / 100);
- state ("3-dragged-larger");
- const auto largeLane = roll.velocityHeight;
- expect (largeLane > defaultLane * 2, "drag up makes the event editor taller");
- expect (lynx::evpane::fromText (file.loadFileAsString().toStdString()) == lynx::PianoRollComponent::eventPaneState(),
- "the place is written to the settings file on release");
- click (right, 1);
- state ("4-right-click-alternate");
- expect (roll.velocityHeight == 0, "right-click: the alternate size (FL's spare 1.0) folds the event editor away");
- click (right, 1);
- state ("5-right-click-back");
- expect (roll.velocityHeight == largeLane, "right-click again: back to the dragged size");
- roll.runAction ("pianoRoll.eventPaneAlternate");
- offline.dispatchPendingMessages();
- expect (roll.velocityHeight == 0, "Shift+Enter (pianoRoll.eventPaneAlternate) swaps too");
- roll.runAction ("pianoRoll.eventPaneAlternate");
- offline.dispatchPendingMessages();
- dragTo (travelTop + 10);
- state ("6-grid-folded");
- expect (roll.eventPaneBarTopForTests() == travelTop, "a drag within 23 px of the top folds the note grid away");
- click (middle, 1);
- state ("7-middle-click-default");
- expect (roll.velocityHeight == defaultLane, "middle-click: back to the default place");
- // a taller window keeps the proportion (the place is a fraction of the travel)
- dragTo (travelTop + (travelBottom - travelTop) * 60 / 100);
- const auto before = lynx::PianoRollComponent::eventPaneState().aspect;
- roll.setSize (roll.getWidth(), roll.getHeight() + 200);
- offline.dispatchPendingMessages();
- const auto newTravel = roll.getHeight() - lynx::evpane::barThickness - travelTop;
- expect (std::abs (roll.eventPaneBarTopForTests() - (travelTop + juce::roundToInt (before * (float) newTravel))) <= 1,
- "a taller window keeps the proportion");
- roll.setSize (roll.getWidth(), roll.getHeight() - 200);
- offline.dispatchPendingMessages();
- click (middle, 1); // leave FL's default behind
- }
- report.add (ok ? "RESULT OK" : "RESULT FAIL");
- juce::File (prefix + "-report.txt").replaceWithText (report.joinIntoString ("\n") + "\n");
- return ok;
- }
- 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");
- }
- }
- // Round 190ay, Freeze, end to end with the real engine, files and export (LYNX.exe --freezetest prefix [project]).
- // The project (.lynx / .flp / .als; without one, a small demo song) is rendered live, every channel that can be
- // frozen is frozen, and the same render is made again: the two mixes must null. Written to prefix-report.txt: the
- // null residual, the process memory and the render time before / frozen / unfrozen, what a save holds, whether
- // Unfreeze gives the channels back as they were, the out-of-date and missing-audio states. Shots: the Channel Rack
- // (live, frozen, out of date), the channel menus, the Piano roll of a frozen channel. The frozen audio goes to
- // prefix-data (never next to the project). True = every check passed.
- bool runFreezeTest (const juce::String& prefix, const juce::String& projectPath, const juce::String& mode = {})
- {
- 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()));
- const auto write = [&prefix, &ui] (const char* name) {
- const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
- file.deleteFile();
- juce::FileOutputStream out (file);
- juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
- };
- juce::String report;
- int failures = 0;
- const auto check = [&] (bool ok, const juce::String& what) {
- report << (ok ? "ok " : "FAIL ") << what << "\n";
- failures += ok ? 0 : 1;
- };
- const auto flush = [&] { juce::File (prefix + "-report.txt").replaceWithText (report + "failures=" + juce::String (failures) + "\n"); };
- if (projectPath.isNotEmpty())
- {
- ui.openFile (juce::File (projectPath));
- offline.dispatchPendingMessages();
- }
- else
- offline.editSong ([] (lynx::Song& s) {
- s.channels.clear();
- s.patterns.clear();
- s.playlist.clear();
- s.bpm = 120.0;
- const char* names[] = { "Lead", "Bass", "Pad", "Kick" };
- for (int c = 0; c < 4; ++c)
- {
- lynx::ChannelDef d;
- d.name = names[c];
- d.instrument = c == 3 ? lynx::InstrumentKind::kick : lynx::InstrumentKind::synth;
- d.synth.release = 0.3f + 0.3f * (float) c;
- d.synth.cutoff = 1500.0f + 900.0f * (float) c;
- d.mixerTrack = c + 1;
- s.channels.push_back (d);
- }
- for (int p = 0; p < 2; ++p)
- {
- auto& pattern = s.patterns.emplace_back();
- pattern.name = p == 0 ? "Verse" : "Break";
- pattern.lengthTicks = 4 * lynx::ppq * 4;
- for (int c = 0; c < 4; ++c)
- for (int step = 0; step < (p == 0 ? 8 : 2); ++step)
- {
- lynx::Note n;
- n.channel = c;
- n.start = (std::int64_t) step * lynx::ppq * (p == 0 ? 2 : 1) + (c == 2 ? lynx::ppq / 2 : 0);
- n.length = c == 3 ? lynx::ppq / 4 : lynx::ppq;
- n.key = c == 3 ? 36 : 48 + c * 7 + (step * 5) % 12;
- pattern.notes.push_back (n);
- }
- pattern.sortNotes();
- }
- const int order[] = { 0, 0, 1, 0 };
- for (int i = 0; i < 4; ++i)
- {
- lynx::Clip clip;
- clip.pattern = order[i];
- clip.start = (std::int64_t) i * 16 * lynx::ppq;
- clip.length = 16 * lynx::ppq;
- s.playlist.push_back (clip);
- }
- s.mode = lynx::PlayMode::song;
- });
- offline.dispatchPendingMessages();
- // the case Freeze exists for, a heavy hosted plugin: LYNX_FREEZETEST_PLUGIN = a plugin file whose first
- // instrument plays the demo song's Lead (tools/testplugin/lynx_test_heavy_vst3.cpp: memory, CPU, latency, a
- // state, and with LYNX_TEST_HEAVY_LOG the instances alive)
- int hostedChannel = -1;
- const auto hostedLog = juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_HEAVY_LOG", {});
- const auto hostedAlive = [&hostedLog] {
- int alive = 0;
- juce::StringArray lines;
- juce::File (hostedLog).readLines (lines);
- for (const auto& l : lines)
- alive += l.startsWith ("create") ? 1 : l.startsWith ("destroy") ? -1 : 0;
- return alive;
- };
- if (const auto pluginPath = juce::SystemStats::getEnvironmentVariable ("LYNX_FREEZETEST_PLUGIN", {}); pluginPath.isNotEmpty() && projectPath.isEmpty())
- {
- auto& host = offline.getPluginHost();
- const auto added = host.addPluginFile (juce::File (pluginPath));
- report << "hosted plugin file: " << pluginPath << " (" << added << " plugins)\n";
- for (const auto& type : host.getKnownPlugins().getTypes())
- if (type.isInstrument && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
- {
- offline.editSong ([&type] (lynx::Song& s) {
- auto& c = s.channels[0];
- c.instrument = lynx::InstrumentKind::plugin;
- c.plugin.id = type.createIdentifierString().toStdString();
- c.plugin.name = type.name.toStdString();
- });
- hostedChannel = 0;
- break;
- }
- offline.dispatchPendingMessages();
- auto* instance = dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (0).get());
- check (hostedChannel == 0 && instance != nullptr, "the hosted plugin is loaded on channel 1");
- report << "hosted plugin: " << juce::String::fromUTF8 (offline.getSong().channels[0].plugin.name.c_str())
- << ", engine latency " << offline.getLatencySamples() << " frames, instances alive " << hostedAlive() << "\n";
- }
- const auto hostedLine = [&] (const char* stage) {
- if (hostedChannel < 0)
- return;
- offline.freeRetiredRacks();
- report << "hosted, " << stage << ": instance on the channel "
- << (dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (hostedChannel).get()) != nullptr ? "yes" : "no")
- << ", plugin instances alive in the process " << (hostedLog.isNotEmpty() ? juce::String (hostedAlive()) : juce::String ("(no log)")) << "\n";
- };
- const juce::File data (prefix + "-data");
- data.deleteRecursively();
- offline.setRecordingTarget (data.getChildFile ("Audio").getChildFile ("Recorded"), "freezetest");
- report << "project=" << (projectPath.isNotEmpty() ? projectPath : juce::String ("(demo song)")) << "\n"
- << "frozen_audio_folder=" << offline.getFreezeFolder().getFullPathName() << "\n";
- const auto megabytes = [] (std::int64_t bytes) { return juce::String ((double) bytes / 1048576.0, 1); };
- struct Mix
- {
- juce::AudioBuffer<float> audio;
- double renderSeconds = 0.0, audioSeconds = 0.0;
- std::int64_t workingSet = 0, privateBytes = 0;
- };
- // the song as it stands, rendered by an export (its own engine: frozen channels play their audio there too)
- const auto renderMix = [&] (const char* name, const lynx::Song* other = nullptr, std::vector<int>* renderedLive = nullptr, int range = 0) {
- Mix m;
- offline.dispatchPendingMessages();
- offline.freeRetiredRacks(); // (what the message loop does in the app: this mode runs without one)
- m.workingSet = lynx::toolbar::PerformanceMeter::processMemoryBytes();
- m.privateBytes = lynx::toolbar::PerformanceMeter::processPrivateBytes();
- const juce::File file (prefix + "-" + name + ".wav");
- lynx::ExportSettings settings;
- settings.format = lynx::ExportSettings::Format::wav32Float;
- settings.sampleRate = offline.getTransport().sampleRate.load();
- settings.tailSeconds = 2.0;
- juce::String error;
- {
- auto options = settings.toOptions();
- options.hqAllPlugins = false; // the quality heard while playing: what a frozen channel's audio is made at
- options.disableMaxPolyphony = false; // (and each channel's Max polyphony, as while playing)
- if (range == 1)
- options.range = lynx::exportopts::Range::selection;
- if (range == 2)
- {
- options.range = lynx::exportopts::Range::pattern;
- options.loops = 2;
- }
- lynx::ExportJob job (other != nullptr ? *other : offline.getSong(), options, file);
- if (renderedLive != nullptr)
- *renderedLive = job.channelsRenderedLive();
- const auto started = juce::Time::getMillisecondCounterHiRes();
- const auto ok = job.run ([] (double) { return true; }, error);
- m.renderSeconds = (juce::Time::getMillisecondCounterHiRes() - started) / 1000.0;
- check (ok, juce::String ("render ") + name + (ok ? juce::String() : ": " + error));
- }
- juce::WavAudioFormat wav;
- if (std::unique_ptr<juce::AudioFormatReader> reader { wav.createReaderFor (file.createInputStream().release(), true) })
- {
- m.audio.setSize (2, (int) reader->lengthInSamples);
- reader->read (&m.audio, 0, (int) reader->lengthInSamples, 0, true, true);
- m.audioSeconds = (double) reader->lengthInSamples / reader->sampleRate;
- }
- file.deleteFile();
- return m;
- };
- // the worst sample difference, in dB below the first mix's peak
- const auto residual = [] (const Mix& a, const Mix& b, float& peak) {
- float worst = 0.0f;
- peak = 0.0f;
- const auto n = juce::jmin (a.audio.getNumSamples(), b.audio.getNumSamples());
- for (int ch = 0; ch < 2; ++ch)
- for (int i = 0; i < n; ++i)
- {
- worst = juce::jmax (worst, std::abs (a.audio.getSample (ch, i) - b.audio.getSample (ch, i)));
- peak = juce::jmax (peak, std::abs (a.audio.getSample (ch, i)));
- }
- return worst <= 0.0f ? -200.0 : 20.0 * std::log10 ((double) worst / (double) juce::jmax (peak, 1.0e-12f));
- };
- const auto line = [&] (const char* name, const Mix& m) {
- report << name << ": working set " << megabytes (m.workingSet) << " MB, private " << megabytes (m.privateBytes) << " MB, render "
- << juce::String (m.renderSeconds, 2) << " s for " << juce::String (m.audioSeconds, 2) << " s of audio ("
- << juce::String (m.audioSeconds > 0.0 ? 100.0 * m.renderSeconds / m.audioSeconds : 0.0, 1) << " % of real time)\n";
- };
- if (mode == "measure")
- {
- // a process that only loaded this project and renders it: its memory with the project loaded, and after
- int frozenCount = 0, hosted = 0;
- for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
- {
- frozenCount += offline.getSong().channels[(std::size_t) c].freeze.on();
- hosted += dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (c).get()) != nullptr;
- }
- report << "channels " << (int) offline.getSong().channels.size() << ", frozen " << frozenCount << ", hosted plugin instances " << hosted << "\n";
- const auto m = renderMix ("measure");
- line ("loaded ", m);
- report << "after the render: working set " << megabytes (lynx::toolbar::PerformanceMeter::processMemoryBytes()) << " MB, private "
- << megabytes (lynx::toolbar::PerformanceMeter::processPrivateBytes()) << " MB\n";
- flush();
- return failures == 0;
- }
- // --- live ---
- offline.capturePluginStates();
- offline.editSong ([] (lynx::Song&) {}, false); // (whatever any edit settles — ids of new objects... — settled first)
- const auto before = offline.getSong();
- // (the project's working-time counter runs on while the test does: not part of what is compared)
- const auto savedJson = [] (lynx::Song song) {
- song.info.workSeconds = 0.0;
- return lynx::ProjectFile::toJson (song, false);
- };
- const auto jsonBefore = savedJson (before);
- std::vector<int> targets;
- for (int c = 0; c < (int) before.channels.size(); ++c)
- {
- const auto* why = lynx::freeze::whyNot (before, c);
- const auto plays = std::any_of (before.patterns.begin(), before.patterns.end(), [c] (const lynx::Pattern& p) {
- return std::any_of (p.notes.begin(), p.notes.end(), [c] (const lynx::Note& n) { return n.channel == c; });
- });
- report << "channel " << (c + 1) << " '" << juce::String::fromUTF8 (before.channels[(std::size_t) c].name.c_str()) << "': "
- << (why != nullptr ? juce::String ("not frozen (") + why + ")" : plays ? juce::String ("freeze") : juce::String ("no notes, left alone")) << "\n";
- if (why == nullptr && plays)
- {
- targets.push_back (c);
- // what could make a stem differ from the live channel, for the record
- const auto& def = before.channels[(std::size_t) c];
- int volPan = 0, params = 0, live = 0, lanes = 0, routes = 0;
- for (const auto& a : before.automations)
- if (a.target.index == c)
- {
- volPan += a.target.kind == lynx::AutomationTargetKind::channelVolume || a.target.kind == lynx::AutomationTargetKind::channelPan;
- params += a.target.kind == lynx::AutomationTargetKind::channelParam;
- live += a.isLive() && (a.target.kind == lynx::AutomationTargetKind::channelVolume || a.target.kind == lynx::AutomationTargetKind::channelPan
- || a.target.kind == lynx::AutomationTargetKind::channelParam);
- }
- for (const auto& p : before.patterns)
- for (const auto& lane : p.events)
- lanes += lane.target.index == c && (lane.target.kind == lynx::AutomationTargetKind::channelVolume
- || lane.target.kind == lynx::AutomationTargetKind::channelPan
- || lane.target.kind == lynx::AutomationTargetKind::channelParam);
- for (const auto& m : before.modulators)
- for (const auto& r : m.routes)
- routes += r.target.index == c && (r.target.kind == lynx::AutomationTargetKind::channelVolume
- || r.target.kind == lynx::AutomationTargetKind::channelPan
- || r.target.kind == lynx::AutomationTargetKind::channelParam);
- report << " instrument kind " << (int) def.instrument << ", insert " << def.mixerTrack << ", automation: volume/pan " << volPan
- << ", parameters " << params << ", live links " << live << ", event lanes " << lanes << ", modulator routes " << routes << "\n";
- }
- }
- check (! targets.empty(), "the project has channels to freeze (" + juce::String ((int) targets.size()) + ")");
- if (targets.empty())
- {
- flush();
- return false;
- }
- const auto first = targets.front();
- offline.setSelectedChannel (first);
- ui.selectTabForSnapshot (0);
- write ("rack-live");
- saveMenus (juce::StringArray { "Channel (live)" }, std::vector<juce::PopupMenu> { ui.getRackForSnapshot().getChannelMenuForSnapshot (first) }, prefix + "-menu-live.png");
- const auto live = renderMix ("live");
- line ("live ", live);
- hostedLine ("live");
- const auto hostedState = hostedChannel >= 0 ? before.channels[(std::size_t) hostedChannel].plugin.state : std::string();
- if (hostedChannel >= 0)
- check (! hostedState.empty(), "the hosted plugin's state is in the project (" + juce::String ((int) hostedState.size()) + " characters)");
- flush();
- // --- frozen ---
- const auto freezeStarted = juce::Time::getMillisecondCounterHiRes();
- for (const auto c : targets)
- {
- const auto error = lynx::freezeChannelNow (offline, c);
- check (error.isEmpty(), "freeze channel " + juce::String (c + 1) + (error.isEmpty() ? juce::String() : ": " + error));
- }
- const auto freezeSeconds = (juce::Time::getMillisecondCounterHiRes() - freezeStarted) / 1000.0;
- offline.dispatchPendingMessages();
- std::int64_t stemBytes = 0;
- int stemFiles = 0;
- bool pluginsGone = true, allFrozen = true;
- for (const auto c : targets)
- {
- const auto& ch = offline.getSong().channels[(std::size_t) c];
- allFrozen = allFrozen && ch.freeze.on() && ! offline.frozenAudioMissing (c) && ! offline.freezeOutOfDate (c);
- for (const auto& stem : ch.freeze.stems)
- {
- stemBytes += juce::File (juce::String::fromUTF8 (stem.path.c_str())).getSize();
- ++stemFiles;
- }
- pluginsGone = pluginsGone && dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (c).get()) == nullptr;
- auto thawed = ch;
- thawed.freeze = {};
- check (thawed == before.channels[(std::size_t) c], "channel " + juce::String (c + 1) + " keeps its instrument and settings as they were while frozen");
- }
- check (allFrozen, "every target is frozen, its audio on disk and up to date");
- check (pluginsGone, "no hosted plugin instance is left on a frozen channel");
- report << "freeze: " << juce::String (freezeSeconds, 2) << " s for " << (int) targets.size() << " channels, " << stemFiles << " files, "
- << megabytes (stemBytes) << " MB on disk\n";
- if (mode == "keep")
- {
- juce::String error;
- check (lynx::ProjectFile::save (offline.getSong(), juce::File (prefix + "-frozen.lynx"), error), "the frozen project is saved" + (error.isEmpty() ? juce::String() : ": " + error));
- flush();
- return failures == 0;
- }
- const auto frozen = renderMix ("frozen");
- line ("frozen ", frozen);
- hostedLine ("frozen");
- if (hostedChannel >= 0 && hostedLog.isNotEmpty())
- check (hostedAlive() == 0, "while frozen no instance of the hosted plugin is alive in the process");
- float peak = 0.0f;
- const auto nullFrozen = residual (live, frozen, peak);
- report << "null frozen vs live: " << juce::String (nullFrozen, 1) << " dB (peak " << juce::String (peak, 4) << ", "
- << live.audio.getNumSamples() << " / " << frozen.audio.getNumSamples() << " samples)\n";
- check (peak > 0.001f && nullFrozen < -90.0 && live.audio.getNumSamples() == frozen.audio.getNumSamples(), "the frozen mix nulls against the live mix (below -90 dB)");
- ui.selectTabForSnapshot (0);
- ui.setHintForSnapshot (ui.getRackForSnapshot().getChannelHintForSnapshot (first));
- write ("rack-frozen");
- saveMenus (juce::StringArray { "Channel (frozen)" }, std::vector<juce::PopupMenu> { ui.getRackForSnapshot().getChannelMenuForSnapshot (first) }, prefix + "-menu-frozen.png");
- report << "hint frozen: " << ui.getRackForSnapshot().getChannelHintForSnapshot (first).text << "\n";
- offline.setSelectedChannel (first);
- ui.selectTabForSnapshot (1);
- offline.setSelectedChannel (first);
- offline.dispatchPendingMessages();
- ui.setHintForSnapshot ({ lynx::tr ("{0} is frozen: Unfreeze to edit ([RMB] on the channel, Unfreeze)",
- { juce::String::fromUTF8 (offline.getSong().channels[(std::size_t) first].name.c_str()) }), {} });
- write ("pianoroll-frozen");
- // --- exports that do not play the song's timeline once: a selection, one pattern twice ---
- // (the frozen audio is the whole song from its start: those renders play the instruments, never a wrong part of it)
- if (projectPath.isEmpty())
- {
- auto part = offline.getSong();
- part.loopStart = 16 * lynx::ppq;
- part.loopEnd = 40 * lynx::ppq;
- const auto partLive = lynx::freeze::thawed (part);
- for (int range = 1; range <= 2; ++range)
- {
- std::vector<int> renderedLive;
- const auto a = renderMix (range == 1 ? "selection-live" : "pattern-live", &partLive, nullptr, range);
- const auto b = renderMix (range == 1 ? "selection-frozen" : "pattern-frozen", &part, &renderedLive, range);
- float partPeak = 0.0f;
- const auto null = residual (a, b, partPeak);
- report << (range == 1 ? "export of a selection (bars 5-10)" : "export of the current pattern, twice") << ", frozen vs live: " << juce::String (null, 1)
- << " dB (peak " << juce::String (partPeak, 4) << ", " << juce::String (b.audioSeconds, 2) << " s), channels rendered live: " << (int) renderedLive.size() << "\n";
- check (partPeak > 0.001f && null < -90.0 && a.audio.getNumSamples() == b.audio.getNumSamples(),
- range == 1 ? "an export of a selection of a frozen project is the selection" : "an export of one pattern of a frozen project is that pattern");
- }
- }
- // --- what a save holds ---
- {
- const auto json = lynx::ProjectFile::toJson (offline.getSong(), false);
- juce::String error;
- const auto loaded = lynx::ProjectFile::fromJson (json, error);
- check (json.contains ("\"freeze\""), "the saved project holds the frozen state");
- check (loaded.has_value() && loaded->channels.size() == offline.getSong().channels.size()
- && loaded->channels[(std::size_t) first].freeze == offline.getSong().channels[(std::size_t) first].freeze,
- "a frozen project loads frozen, with the same audio files");
- check (savedJson (lynx::freeze::thawed (offline.getSong())) == jsonBefore,
- "without the frozen state the saved project is byte for byte what it was before the freeze");
- check (! jsonBefore.contains ("\"freeze\""), "a project with nothing frozen has no freeze field");
- }
- // --- out of date: the tempo, a note of the frozen channel; not another channel's notes ---
- {
- offline.editSong ([] (lynx::Song& s) { s.bpm += 4.0; });
- check (offline.freezeOutOfDate (first), "a tempo change marks the freeze out of date");
- ui.selectTabForSnapshot (0);
- ui.setHintForSnapshot (ui.getRackForSnapshot().getChannelHintForSnapshot (first));
- write ("rack-out-of-date");
- report << "hint out of date: " << ui.getRackForSnapshot().getChannelHintForSnapshot (first).text << "\n";
- offline.editSong ([] (lynx::Song& s) { s.bpm -= 4.0; });
- check (! offline.freezeOutOfDate (first), "the tempo back: up to date again");
- int pattern = -1;
- for (int p = 0; p < (int) before.patterns.size() && pattern < 0; ++p)
- for (const auto& n : before.patterns[(std::size_t) p].notes)
- if (n.channel == first)
- {
- pattern = p;
- break;
- }
- if (pattern >= 0)
- {
- offline.editSong ([pattern, first] (lynx::Song& s) {
- lynx::Note n;
- n.channel = first;
- n.start = 0;
- n.key = 71;
- s.patterns[(std::size_t) pattern].notes.push_back (n);
- s.patterns[(std::size_t) pattern].sortNotes();
- });
- check (offline.freezeOutOfDate (first), "a note edit on the frozen channel marks it out of date");
- bool othersFresh = true;
- for (const auto c : targets)
- othersFresh = othersFresh && (c == first || ! offline.freezeOutOfDate (c));
- check (othersFresh, "the other frozen channels stay up to date");
- // an export of the project in that state: the out-of-date channel renders live (never the old audio),
- // the others keep their frozen audio — the same mix as the edited project with nothing frozen
- {
- std::vector<int> renderedLive;
- const auto stale = renderMix ("stale", nullptr, &renderedLive);
- const auto edited = lynx::freeze::thawed (offline.getSong());
- const auto reference = renderMix ("stale-reference", &edited);
- float stalePeak = 0.0f;
- const auto nullStale = residual (reference, stale, stalePeak);
- const auto nullOld = residual (frozen, stale, stalePeak);
- report << "export with channel " << (first + 1) << " out of date: " << juce::String (nullStale, 1) << " dB vs the edited project live, "
- << juce::String (nullOld, 1) << " dB vs the old frozen mix; channels rendered live: " << (int) renderedLive.size() << "\n";
- check (renderedLive == std::vector<int> { first }, "an export renders the out-of-date frozen channel live, and only that one");
- check (nullStale < -90.0 && nullOld > -60.0, "an export of an out-of-date freeze holds the edited notes, not the old audio");
- }
- offline.editSong ([&before] (lynx::Song& s) { s.patterns = before.patterns; });
- check (! offline.freezeOutOfDate (first), "the notes back: up to date again");
- }
- }
- // --- the audio gone: the instrument plays, never silence ---
- {
- const auto stems = offline.getSong().channels[(std::size_t) first].freeze.stems;
- std::vector<std::pair<juce::File, juce::File>> moved;
- for (const auto& stem : stems)
- {
- const juce::File file (juce::String::fromUTF8 (stem.path.c_str()));
- const auto away = file.getSiblingFile (file.getFileName() + ".away");
- if (file.moveFileTo (away))
- moved.emplace_back (file, away);
- }
- offline.editSong ([] (lynx::Song&) {}, false);
- check (offline.frozenAudioMissing (first), "frozen audio that is not on disk is noticed");
- report << "hint audio missing: " << ui.getRackForSnapshot().getChannelHintForSnapshot (first).text << "\n";
- const auto fallback = renderMix ("missing");
- const auto nullMissing = residual (live, fallback, peak);
- report << "null with the first channel's audio missing vs live: " << juce::String (nullMissing, 1) << " dB\n";
- check (nullMissing < -90.0, "with its audio missing the channel plays its instrument");
- for (const auto& [file, away] : moved)
- away.moveFileTo (file);
- offline.editSong ([] (lynx::Song&) {}, false);
- check (! offline.frozenAudioMissing (first), "the audio back: frozen again");
- // the frozen mix did not null and the first channel is not (alone) why: which one is, each thawed in turn
- if (nullFrozen >= -90.0 && nullMissing >= -90.0)
- for (const auto c : targets)
- {
- if (c == first)
- continue;
- std::vector<std::pair<juce::File, juce::File>> aside;
- for (const auto& stem : offline.getSong().channels[(std::size_t) c].freeze.stems)
- {
- const juce::File file (juce::String::fromUTF8 (stem.path.c_str()));
- const auto away = file.getSiblingFile (file.getFileName() + ".away");
- if (file.moveFileTo (away))
- aside.emplace_back (file, away);
- }
- offline.editSong ([] (lynx::Song&) {}, false);
- const auto one = renderMix ("thawed");
- report << "null with channel " << (c + 1) << " thawed vs live: " << juce::String (residual (live, one, peak), 1) << " dB\n";
- for (const auto& [file, away] : aside)
- away.moveFileTo (file);
- offline.editSong ([] (lynx::Song&) {}, false);
- }
- }
- // --- unfrozen ---
- std::vector<juce::File> stemPaths;
- for (const auto c : targets)
- for (const auto& stem : offline.getSong().channels[(std::size_t) c].freeze.stems)
- stemPaths.emplace_back (juce::String::fromUTF8 (stem.path.c_str()));
- for (const auto c : targets)
- lynx::unfreezeChannel (offline, c);
- offline.dispatchPendingMessages();
- check (offline.getSong().channels == before.channels, "Unfreeze gives every channel back exactly as it was (instrument, plugin state, settings)");
- {
- const auto jsonAfter = savedJson (offline.getSong());
- check (jsonAfter == jsonBefore, "the unfrozen project saves byte for byte as before the freeze");
- if (jsonAfter != jsonBefore)
- {
- juce::File (prefix + "-before.json").replaceWithText (jsonBefore);
- juce::File (prefix + "-after.json").replaceWithText (jsonAfter);
- }
- }
- int left = 0;
- for (const auto& f : stemPaths)
- left += f.existsAsFile() ? 1 : 0;
- check (left == 0, "Unfreeze deletes the frozen audio (" + juce::String (left) + " of " + juce::String ((int) stemPaths.size()) + " files left)");
- if (hostedChannel >= 0)
- {
- // the new instance (it starts with another tuning than the first one had) took the saved state
- offline.capturePluginStates();
- check (dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (hostedChannel).get()) != nullptr, "Unfreeze loads the hosted plugin again");
- check (offline.getSong().channels[(std::size_t) hostedChannel].plugin.state == hostedState,
- "the hosted plugin's state, read back from the new instance, is the state it had before the freeze");
- }
- const auto unfrozen = renderMix ("unfrozen");
- line ("unfrozen ", unfrozen);
- hostedLine ("unfrozen");
- const auto nullUnfrozen = residual (live, unfrozen, peak);
- report << "null unfrozen vs live: " << juce::String (nullUnfrozen, 1) << " dB\n";
- check (nullUnfrozen < -90.0, "the unfrozen mix nulls against the live mix");
- ui.selectTabForSnapshot (0);
- flush();
- data.deleteRecursively();
- return failures == 0;
- }
- // Round 190ff, the Clip-launch workflow's track commands end to end with the real engine, files and export
- // (LYNX --trackfreezetest prefix). A demo song of three tracks (Lead through a delay and a reverb whose mix is
- // automated, Bass through a delay, Drums on a bare insert; each insert's fader, pan and EQ set) is rendered live; then
- // Freeze Track on every track (the instrument with its volume and pan through its insert's effects), the same render
- // again (must null), the effects and instruments unloaded, the render time (the CPU while frozen), what a save holds;
- // Flatten (Bounce Track in Place on a frozen track) with its undo; Bounce Track in Place of a live track; Bounce to New
- // Track of a track's clips against that track's device output; Consolidate of pattern clips; Unfreeze. Written to
- // prefix-report.txt; shots of the grid, the column menus, the Detail View's frozen devices and the Playlist's clip
- // menu. True = every check passed.
- bool runTrackFreezeTest (const juce::String& prefix)
- {
- 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()));
- const auto write = [&prefix, &ui] (const char* name) {
- const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
- file.deleteFile();
- juce::FileOutputStream out (file);
- juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
- };
- juce::String report;
- int failures = 0;
- const auto check = [&] (bool ok, const juce::String& what) {
- report << (ok ? "ok " : "FAIL ") << what << "\n";
- failures += ok ? 0 : 1;
- };
- const auto flush = [&] { juce::File (prefix + "-report.txt").replaceWithText (report + "failures=" + juce::String (failures) + "\n"); };
- const juce::File data (prefix + "-data");
- data.deleteRecursively();
- offline.setRecordingTarget (data.getChildFile ("Audio").getChildFile ("Recorded"), "trackfreezetest");
- ui.setVisible (true);
- lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
- ui.setClipLaunchWorkflow (true);
- offline.editSong ([] (lynx::Song& s) {
- s.channels.clear();
- s.patterns.clear();
- s.playlist.clear();
- s.automations.clear();
- s.bpm = 120.0;
- s.mode = lynx::PlayMode::song;
- const char* names[] = { "Lead", "Bass", "Drums" };
- for (int c = 0; c < 3; ++c)
- {
- lynx::ChannelDef d;
- d.name = names[c];
- d.instrument = c == 2 ? lynx::InstrumentKind::kick : lynx::InstrumentKind::synth;
- d.synth.release = c == 0 ? 0.6f : 0.2f;
- d.synth.cutoff = c == 0 ? 2400.0f : 900.0f;
- d.volume = c == 0 ? 0.65f : 0.78f;
- d.pan = c == 0 ? 0.25f : 0.0f;
- d.mixerTrack = c + 1;
- s.channels.push_back (d);
- }
- if (s.mixer.size() < 5)
- s.mixer.resize (5);
- s.mixer[1].effects = { lynx::makeEffectSlot (lynx::EffectKind::delay), lynx::makeEffectSlot (lynx::EffectKind::reverb) };
- s.mixer[2].effects = { lynx::makeEffectSlot (lynx::EffectKind::delay) };
- s.mixer[3].effects.clear();
- for (int t = 1; t <= 3; ++t)
- {
- s.mixer[(std::size_t) t].name = names[t - 1];
- s.mixer[(std::size_t) t].volume = 0.7f;
- s.mixer[(std::size_t) t].pan = t == 1 ? -0.3f : 0.1f;
- s.mixer[(std::size_t) t].eq.gainDb[1] = 3.0f;
- }
- for (int p = 0; p < 3; ++p)
- {
- auto& pattern = s.patterns.emplace_back();
- pattern.name = names[p];
- pattern.lengthTicks = 4 * lynx::ppq * 2;
- for (int step = 0; step < 8; ++step)
- {
- lynx::Note n;
- n.channel = p;
- n.start = (std::int64_t) step * lynx::ppq;
- n.length = p == 2 ? lynx::ppq / 4 : lynx::ppq / 2;
- n.key = p == 2 ? 36 : (p == 0 ? 60 : 36) + (step * 5) % 12;
- pattern.notes.push_back (n);
- }
- }
- s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 4));
- for (int t = 0; t < 3; ++t)
- {
- s.playlistTracks[(std::size_t) t].name = names[t];
- for (int k = 0; k < 3; ++k)
- {
- if (t == 0 && k == 1)
- continue; // (a gap in the Lead: its tail rings into it)
- lynx::Clip clip;
- clip.pattern = t;
- clip.track = t;
- clip.start = (std::int64_t) k * 8 * lynx::ppq;
- clip.length = 8 * lynx::ppq;
- s.playlist.push_back (clip);
- }
- }
- // the Lead's reverb mix rises over the song (automation the freeze takes into its audio)
- lynx::Automation a;
- a.name = "Lead reverb mix";
- a.target = { lynx::AutomationTargetKind::effectMix, 1, 1, 0 };
- a.points = { { 0, 0.2f }, { 24 * lynx::ppq, 0.9f } };
- s.automations.push_back (a);
- lynx::Clip lane;
- lane.kind = lynx::ClipKind::automation;
- lane.automation = 0;
- lane.track = 3;
- lane.length = 24 * lynx::ppq;
- s.playlist.push_back (lane);
- std::stable_sort (s.playlist.begin(), s.playlist.end(), [] (const lynx::Clip& x, const lynx::Clip& y) { return x.start < y.start; });
- });
- offline.dispatchPendingMessages();
- const auto megabytes = [] (std::int64_t bytes) { return juce::String ((double) bytes / 1048576.0, 1); };
- struct Mix
- {
- juce::AudioBuffer<float> audio;
- double renderSeconds = 0.0, audioSeconds = 0.0;
- };
- const auto renderMix = [&] (const char* name, const lynx::Song* other = nullptr) {
- Mix m;
- offline.dispatchPendingMessages();
- offline.freeRetiredRacks();
- const juce::File file (prefix + "-" + name + ".wav");
- lynx::ExportSettings settings;
- settings.format = lynx::ExportSettings::Format::wav32Float;
- settings.sampleRate = offline.getTransport().sampleRate.load();
- settings.tailSeconds = 2.0;
- juce::String error;
- auto options = settings.toOptions();
- options.hqAllPlugins = false;
- options.disableMaxPolyphony = false;
- {
- lynx::ExportJob job (other != nullptr ? *other : offline.getSong(), options, file);
- const auto started = juce::Time::getMillisecondCounterHiRes();
- const auto ok = job.run ([] (double) { return true; }, error);
- m.renderSeconds = (juce::Time::getMillisecondCounterHiRes() - started) / 1000.0;
- check (ok, juce::String ("render ") + name + (ok ? juce::String() : ": " + error));
- }
- juce::WavAudioFormat wav;
- if (std::unique_ptr<juce::AudioFormatReader> reader { wav.createReaderFor (file.createInputStream().release(), true) })
- {
- m.audio.setSize (2, (int) reader->lengthInSamples);
- reader->read (&m.audio, 0, (int) reader->lengthInSamples, 0, true, true);
- m.audioSeconds = (double) reader->lengthInSamples / reader->sampleRate;
- }
- if (juce::SystemStats::getEnvironmentVariable ("LYNX_TRACKFREEZE_KEEP", {}).isEmpty()) // (kept: to look at a residual)
- file.deleteFile();
- return m;
- };
- const auto residual = [] (const Mix& a, const Mix& b, float& peak) {
- float worst = 0.0f;
- peak = 0.0f;
- const auto n = juce::jmin (a.audio.getNumSamples(), b.audio.getNumSamples());
- for (int ch = 0; ch < 2; ++ch)
- for (int i = 0; i < n; ++i)
- {
- worst = juce::jmax (worst, std::abs (a.audio.getSample (ch, i) - b.audio.getSample (ch, i)));
- peak = juce::jmax (peak, std::abs (a.audio.getSample (ch, i)));
- }
- return worst <= 0.0f ? -200.0 : 20.0 * std::log10 ((double) worst / (double) juce::jmax (peak, 1.0e-12f));
- };
- const auto nullLine = [&] (const char* what, const Mix& a, const Mix& b, double limit) {
- float peak = 0.0f;
- const auto r = residual (a, b, peak);
- report << what << ": " << juce::String (r, 1) << " dB (peak " << juce::String (peak, 4) << ", " << a.audio.getNumSamples() << " / "
- << b.audio.getNumSamples() << " samples)\n";
- check (peak > 0.001f && r < limit && a.audio.getNumSamples() == b.audio.getNumSamples(), juce::String (what) + " below " + juce::String (limit, 0) + " dB");
- return r;
- };
- const auto savedJson = [] (lynx::Song song) {
- song.info.workSeconds = 0.0;
- return lynx::ProjectFile::toJson (song, false);
- };
- // --- live ---
- offline.capturePluginStates();
- offline.editSong ([] (lynx::Song&) {}, false);
- const auto before = offline.getSong();
- const auto jsonBefore = savedJson (before);
- auto* grid = ui.getClipGridForSnapshot();
- check (grid != nullptr, "the Clip-launch workflow's grid is there");
- if (grid == nullptr)
- {
- flush();
- return false;
- }
- ui.setClipGridView (lynx::PlaylistArea::GridView::beside);
- write ("live");
- saveMenus (juce::StringArray { "Track title (live)" }, std::vector<juce::PopupMenu> { lynx::clipGridHeaderMenu (*grid, 0) }, prefix + "-menu-track-live.png");
- int leadClip = -1;
- for (int i = 0; i < (int) before.playlist.size() && leadClip < 0; ++i)
- if (before.playlist[(std::size_t) i].track == 0 && before.playlist[(std::size_t) i].kind == lynx::ClipKind::pattern)
- leadClip = i;
- ui.getPlaylistForSnapshot().selectForSnapshot ({ leadClip });
- saveMenus (juce::StringArray { "Playlist clip (Clip-launch workflow)" }, std::vector<juce::PopupMenu> { ui.getPlaylistForSnapshot().getClipMenuForSnapshot (leadClip) },
- prefix + "-menu-clip.png");
- const auto live = renderMix ("live");
- report << "live: render " << juce::String (live.renderSeconds, 2) << " s for " << juce::String (live.audioSeconds, 2) << " s of audio\n";
- // --- Freeze Track on every track ---
- std::vector<int> channels;
- for (int t = 0; t < 3; ++t)
- {
- const auto c = lynx::detailchain::forTrack (before, t).channel;
- check (c == t, "track " + juce::String (t + 1) + " shows channel " + juce::String (t + 1));
- const auto* why = lynx::freeze::whyNotTrack (before, c);
- check (why == nullptr, "track " + juce::String (t + 1) + " can be frozen" + (why != nullptr ? juce::String (": ") + why : juce::String()));
- const auto error = lynx::freezeTrackNow (offline, c);
- check (error.isEmpty(), "Freeze Track " + juce::String (t + 1) + (error.isEmpty() ? juce::String() : ": " + error));
- channels.push_back (c);
- }
- offline.dispatchPendingMessages();
- offline.freeRetiredRacks();
- int loadedEffects = 0;
- for (int t = 1; t <= 3; ++t)
- for (int slot = 0; slot < (int) offline.getSong().mixer[(std::size_t) t].effects.size(); ++slot)
- loadedEffects += offline.getEffect (t, slot) != nullptr ? 1 : 0;
- check (loadedEffects == 0, "no effect of a frozen track is loaded (" + juce::String (loadedEffects) + " left)");
- bool fresh = true;
- for (const auto c : channels)
- {
- const auto& f = offline.getSong().channels[(std::size_t) c].freeze;
- fresh = fresh && f.on() && f.insert == c + 1 && lynx::freeze::trackFreezeHolds (offline.getSong(), c) && ! offline.freezeOutOfDate (c)
- && ! offline.frozenAudioMissing (c);
- }
- check (fresh, "every track is frozen with its insert, its audio on disk and up to date");
- check (offline.getSong().mixer == before.mixer, "the project keeps every effect as it was (Unfreeze brings them back)");
- const auto frozenSong = offline.getSong();
- const auto frozen = renderMix ("frozen");
- report << "frozen: render " << juce::String (frozen.renderSeconds, 2) << " s (" << juce::String (100.0 * frozen.renderSeconds / juce::jmax (0.001, live.renderSeconds), 0)
- << " % of the live render's time)\n";
- nullLine ("frozen vs live", live, frozen, -90.0);
- write ("frozen");
- saveMenus (juce::StringArray { "Track title (frozen)" }, std::vector<juce::PopupMenu> { lynx::clipGridHeaderMenu (*grid, 0) }, prefix + "-menu-track-frozen.png");
- if (auto* detail = ui.getDetailViewForSnapshot())
- {
- detail->showSelection (0, 0);
- detail->setPage (lynx::DetailView::Page::devices);
- write ("detail-frozen");
- }
- // the insert's fader is live: moved, the frozen and the live song change alike
- {
- auto liveLouder = before, frozenLouder = frozenSong;
- liveLouder.mixer[1].volume = frozenLouder.mixer[1].volume = 0.8f;
- nullLine ("frozen vs live, the Lead's fader moved afterwards", renderMix ("live-louder", &liveLouder), renderMix ("frozen-louder", &frozenLouder), -90.0);
- }
- // --- what a save holds ---
- {
- const auto json = lynx::ProjectFile::toJson (offline.getSong(), false);
- juce::String error;
- const auto loaded = lynx::ProjectFile::fromJson (json, error);
- check (json.contains ("\"trackFreeze\"") && ! json.contains ("\"freeze\""), "a track freeze is saved under its own key (older versions play it live)");
- check (loaded.has_value() && loaded->channels.size() == frozenSong.channels.size() && loaded->channels[0].freeze == frozenSong.channels[0].freeze,
- "a track-frozen project loads frozen, with its insert and audio files");
- check (savedJson (lynx::freeze::thawed (offline.getSong())) == jsonBefore, "without the frozen state the project saves as before the freeze");
- }
- // --- an edit of a frozen device's insert routing: the freeze stops holding, the track plays live ---
- {
- offline.editSong ([] (lynx::Song& s) { s.channels[1].mixerTrack = 1; }); // (the Bass into the Lead's insert)
- check (! lynx::freeze::trackFreezeHolds (offline.getSong(), 0) && offline.freezeOutOfDate (0), "another channel routed into a frozen insert: out of date, plays live");
- offline.undo();
- offline.dispatchPendingMessages();
- check (lynx::freeze::trackFreezeHolds (offline.getSong(), 0) && ! offline.freezeOutOfDate (0), "undo: frozen again");
- }
- // --- Flatten: Bounce Track in Place on the frozen Lead, and its undo ---
- {
- const auto error = lynx::flattenChannelNow (offline, 0);
- check (error.isEmpty(), "Bounce Track in Place of the frozen Lead (Flatten)" + (error.isEmpty() ? juce::String() : ": " + error));
- const auto& song = offline.getSong();
- check (song.channels[0].instrument == lynx::InstrumentKind::audioClip && song.mixer[1].effects.empty() && song.mixer[1].volume == before.mixer[1].volume
- && song.channels[0].name == "Lead (Bounce)",
- "the Lead is audio now (\"Lead (Bounce)\"), its insert's effects removed, its fader kept");
- int audioClips = 0;
- for (const auto& c : song.playlist)
- audioClips += c.kind == lynx::ClipKind::audio && c.channel == 0;
- report << "flattened Lead: " << audioClips << " audio clips\n";
- write ("flattened");
- // over the song (the flattened clips end where the arrangement ends, as a frozen track plays; an export's
- // ring-out after the song's end is not in them)
- const auto span = (int) std::llround (before.secondsForTicks (24 * lynx::ppq) * offline.getTransport().sampleRate.load());
- auto flatMix = renderMix ("flattened");
- auto reference = live;
- reference.audio.setSize (2, juce::jmin (span, reference.audio.getNumSamples()), true);
- flatMix.audio.setSize (2, reference.audio.getNumSamples(), true);
- nullLine ("flattened (Lead) + frozen (others) vs live, over the song", reference, flatMix, -90.0);
- offline.undo();
- offline.dispatchPendingMessages();
- check (savedJson (offline.getSong()) == savedJson (frozenSong), "undo of the Flatten: the frozen project exactly as before");
- }
- // --- Unfreeze every track ---
- for (const auto c : channels)
- lynx::unfreezeChannel (offline, c);
- offline.dispatchPendingMessages();
- check (savedJson (offline.getSong()) == jsonBefore, "Unfreeze: the project saves byte for byte as before the freeze");
- nullLine ("unfrozen vs live", live, renderMix ("unfrozen"), -90.0);
- // --- Bounce Track in Place of a live track (render and flatten in one step, one undo) ---
- {
- const auto error = lynx::freezeTrackNow (offline, 1, true);
- check (error.isEmpty(), "Bounce Track in Place of the live Bass" + (error.isEmpty() ? juce::String() : ": " + error));
- check (offline.getSong().channels[1].instrument == lynx::InstrumentKind::audioClip && ! offline.getSong().channels[1].freeze.on(),
- "the Bass is audio, not frozen");
- auto bouncedMix = renderMix ("bounced");
- auto reference = live;
- const auto span = (int) std::llround (before.secondsForTicks (24 * lynx::ppq) * offline.getTransport().sampleRate.load());
- reference.audio.setSize (2, juce::jmin (span, reference.audio.getNumSamples()), true);
- bouncedMix.audio.setSize (2, reference.audio.getNumSamples(), true);
- nullLine ("Bass bounced in place vs live, over the song", reference, bouncedMix, -90.0);
- offline.undo();
- offline.dispatchPendingMessages();
- check (savedJson (offline.getSong()) == jsonBefore, "undo of Bounce Track in Place: the project as before");
- }
- // --- Bounce to New Track: the Lead's clips onto a new track (the clips muted, the new track with the Lead's mixer) ---
- {
- std::vector<int> leadClips;
- for (int i = 0; i < (int) offline.getSong().playlist.size(); ++i)
- if (offline.getSong().playlist[(std::size_t) i].track == 0 && offline.getSong().playlist[(std::size_t) i].kind == lynx::ClipKind::pattern)
- leadClips.push_back (i);
- const auto channelsBefore = offline.getSong().channels.size();
- const auto error = lynx::bounceToNewTrack (offline, leadClips, true);
- check (error.isEmpty(), "Bounce to New Track of the Lead's clips" + (error.isEmpty() ? juce::String() : ": " + error));
- const auto& song = offline.getSong();
- check (song.channels.size() == channelsBefore + 1 && song.channels.back().instrument == lynx::InstrumentKind::audioClip
- && song.channels.back().mixerTrack > 3 && song.mixer[(std::size_t) song.channels.back().mixerTrack].volume == before.mixer[1].volume,
- "a new audio channel holds the bounce, on an insert with the Lead's mixer");
- // the song's span (the bounce stops at the last clip's end, the live render rings on after it)
- auto bounced = renderMix ("bounced-new-track");
- auto reference = live;
- const auto span = (int) std::llround (before.secondsForTicks (24 * lynx::ppq) * offline.getTransport().sampleRate.load());
- reference.audio.setSize (2, juce::jmin (span, reference.audio.getNumSamples()), true);
- bounced.audio.setSize (2, reference.audio.getNumSamples(), true);
- nullLine ("Bounce to New Track (Lead's clips muted) vs live, over the song", reference, bounced, -90.0);
- write ("bounced-new-track");
- offline.undo();
- offline.dispatchPendingMessages();
- check (savedJson (offline.getSong()) == jsonBefore, "undo of Bounce to New Track: the project as before");
- }
- // --- Consolidate: the Bass's three pattern clips become one ---
- {
- std::vector<int> bassClips;
- for (int i = 0; i < (int) offline.getSong().playlist.size(); ++i)
- if (offline.getSong().playlist[(std::size_t) i].track == 1 && offline.getSong().playlist[(std::size_t) i].kind == lynx::ClipKind::pattern)
- bassClips.push_back (i);
- const auto error = lynx::consolidateClips (offline, bassClips, true);
- check (error.isEmpty(), "Consolidate of the Bass's clips" + (error.isEmpty() ? juce::String() : ": " + error));
- int left = 0;
- for (const auto& c : offline.getSong().playlist)
- left += c.track == 1 && c.kind == lynx::ClipKind::pattern;
- check (left == 1, "one clip on the Bass track (" + juce::String (left) + ")");
- nullLine ("consolidated vs live", live, renderMix ("consolidated"), -90.0);
- offline.undo();
- offline.dispatchPendingMessages();
- check (savedJson (offline.getSong()) == jsonBefore, "undo of Consolidate: the project as before");
- }
- report << "frozen audio folder: " << offline.getFreezeFolder().getFullPathName() << "\n";
- flush();
- data.deleteRecursively();
- (void) megabytes;
- return failures == 0;
- }
- // --paintbench (round 190ge): the paint cost of every main view, off screen. Each view is shown maximised in a
- // LYNX_SNAPSHOT_SIZE window (default 1920x1080) and drawn whole into a picture `frames` times (after a repaint of
- // all of it, so no cached picture is reused: the cost of a frame after an edit), then `frames` times without the
- // repaint (what a view's own caches leave of a frame). The report gives the median and the 90th percentile of
- // the message thread's CPU per frame.
- void runPaintBench (const juce::File& project, const juce::File& report)
- {
- // LYNX_PROFILE_MAIN=<file> (round 190gr): the message thread sampled while it paints (Windows; one view at a time
- // with LYNX_PAINTBENCH_VIEWS)
- const auto profile = juce::SystemStats::getEnvironmentVariable ("LYNX_PROFILE_MAIN", {});
- if (profile.isNotEmpty())
- lynx::crashguard::startMainProfiler (profile.toStdString(), 1000, 2);
- 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", "1920x1080"), "x", "");
- ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
- juce::String text;
- text << "project: " << project.getFullPathName() << "\nLYNX " << getApplicationVersion() << ", " << juce::SystemStats::getCpuModel()
- << ", window " << ui.getWidth() << "x" << ui.getHeight() << "\n";
- if (project.existsAsFile())
- {
- ui.openFile (project);
- offline.dispatchPendingMessages();
- }
- const auto& song = offline.getSong();
- text << "channels " << (int) song.channels.size() << ", patterns " << (int) song.patterns.size() << ", playlist clips " << (int) song.playlist.size()
- << ", inserts " << (int) song.mixer.size() << "\n";
- // the playhead a third into the song (song mode) so the views draw it as when playing
- offline.getTransport().songMode = true;
- offline.getTransport().positionTicks.store ((double) song.songLength() / 3.0);
- const auto frames = juce::jlimit (3, 500, juce::SystemStats::getEnvironmentVariable ("LYNX_PAINTBENCH_FRAMES", "40").getIntValue());
- juce::Image image (juce::Image::ARGB, ui.getWidth(), ui.getHeight(), true);
- {
- // (round 190gr) which renderer draws the frames: the software one (Linux), Direct2D (Windows), Core Graphics
- juce::Graphics g (image);
- auto& context = g.getInternalContext();
- text << "renderer: " << (dynamic_cast<juce::LowLevelGraphicsSoftwareRenderer*> (&context) != nullptr ? "software" : typeid (context).name())
- << ", paint caches " << (lynx::ui::paintCache() ? "on" : "off (LYNX_PAINT_CACHE=0)") << ", paint savings "
- << (lynx::ui::paintSavings() ? "on" : "off (LYNX_PAINT_SAVINGS=0)") << "\n";
- }
- // LYNX_PAINTBENCH_VIEWS="mixer,channel rack" (round 190gr): only those views
- const auto onlyViews = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_PAINTBENCH_VIEWS", {}), ",", "");
- const auto wanted = [&onlyViews] (const juce::String& name) { return onlyViews.isEmpty() || onlyViews.contains (name); };
- // the picture's pixels as one number: the same before and after a change = the same drawing
- auto pixelHash = [&image] {
- const juce::Image::BitmapData data (image, juce::Image::BitmapData::readOnly);
- std::uint64_t h = 1469598103934665603ull;
- for (int y = 0; y < data.height; ++y)
- for (int x = 0; x < data.width; ++x)
- h = (h ^ data.getPixelColour (x, y).getARGB()) * 1099511628211ull;
- return juce::String::toHexString ((juce::int64) h);
- };
- // mode 0: whole frames after a repaint of everything; 1: whole frames, the views' own caches kept; 2: a 14-pixel
- // column of the whole height at 40 places (what a moving playhead repaints each frame)
- auto measure = [&] (const juce::String& name, int mode) {
- offline.dispatchPendingMessages();
- std::vector<double> ms, wall;
- juce::String hash;
- for (int f = -3; f < frames; ++f) // (3 frames to warm the caches up)
- {
- if (mode == 0)
- ui.repaint();
- const auto column = juce::Rectangle<int> ((juce::jmax (0, f) * 97) % juce::jmax (1, ui.getWidth() - 14), 0, 14, ui.getHeight());
- const auto t0 = lynx::threadCpuSeconds();
- const auto w0 = juce::Time::getMillisecondCounterHiRes();
- {
- juce::Graphics g (image);
- if (mode == 2)
- g.reduceClipRegion (column);
- ui.paintEntireComponent (g, true);
- }
- if (f >= 0)
- {
- ms.push_back (1000.0 * (lynx::threadCpuSeconds() - t0));
- wall.push_back (juce::Time::getMillisecondCounterHiRes() - w0); // (round 190gr: Direct2D's work ends with the frame)
- }
- if (f == 0 && mode == 0)
- {
- hash = pixelHash();
- // LYNX_PAINTBENCH_PNG=<prefix> (round 190gr): the whole frame as <prefix>-<view>.png, to compare pixels
- if (const auto png = juce::SystemStats::getEnvironmentVariable ("LYNX_PAINTBENCH_PNG", {}); png.isNotEmpty())
- {
- const juce::File file (png + "-" + name.replaceCharacter (' ', '-') + ".png");
- file.deleteFile();
- juce::FileOutputStream out (file);
- juce::PNGImageFormat().writeImageToStream (image, out);
- }
- }
- }
- std::sort (ms.begin(), ms.end());
- std::sort (wall.begin(), wall.end());
- text << name << (mode == 0 ? ", whole frame" : mode == 1 ? ", cached frame" : ", playhead column") << ": median "
- << juce::String (ms[ms.size() / 2], 3) << " ms, p90 " << juce::String (ms[(ms.size() * 9) / 10], 3) << " ms, wall median "
- << juce::String (wall[wall.size() / 2], 3) << " ms"
- << (hash.isNotEmpty() ? ", pixels " + hash : juce::String()) << "\n";
- report.replaceWithText (text);
- };
- auto measureAll = [&] (const juce::String& name) {
- if (! wanted (name))
- return;
- measure (name, 0);
- measure (name, 1);
- measure (name, 2);
- // the columns' pixels too (painted over the whole frame: culling must not change a pixel)
- ui.repaint();
- {
- juce::Graphics g (image);
- ui.paintEntireComponent (g, true);
- for (int x = 3; x < ui.getWidth() - 14; x += 211)
- {
- juce::Graphics::ScopedSaveState state (g);
- g.reduceClipRegion (x, 0, 14, ui.getHeight());
- ui.paintEntireComponent (g, true);
- }
- }
- text << name << ", columns over the whole frame: pixels " << pixelHash() << "\n";
- };
- const char* views[] { "channel rack", "piano roll", "playlist", "mixer" };
- for (int v = 0; v < 4; ++v)
- {
- ui.selectTabForSnapshot (v);
- measureAll (views[v]);
- }
- ui.showDesktopForSnapshot (false);
- measureAll ("desktop");
- ui.selectTabForSnapshot (2);
- ui.setClipLaunchWorkflow (true);
- ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
- measureAll ("clip grid");
- ui.setClipLaunchWorkflow (false);
- text << "result=OK\n";
- report.replaceWithText (text);
- if (profile.isNotEmpty())
- lynx::crashguard::stopMainProfiler();
- }
- void runGridShot (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()));
- const auto write = [&prefix, &ui] (const char* name) {
- const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
- file.deleteFile();
- juce::FileOutputStream out (file);
- juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
- };
- ui.selectTabForSnapshot (2); // the Playlist panel, maximized
- if (projectPath.isNotEmpty())
- {
- ui.openFile (juce::File (projectPath));
- offline.dispatchPendingMessages();
- ui.setClipLaunchWorkflow (true);
- offline.dispatchPendingMessages();
- write ("file-both");
- ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
- write ("file-grid");
- const auto& song = offline.getSong();
- juce::String info;
- info << "grid " << (song.clipGrid ? "yes" : "no") << ", clips " << (song.clipGrid ? (int) song.clipGrid->clips.size() : 0)
- << ", scenes " << (song.clipGrid ? (int) song.clipGrid->scenes.size() : 0) << ", playlist clips " << (int) song.playlist.size() << "\n";
- juce::File (prefix + "-file.txt").replaceWithText (info);
- ui.setClipLaunchWorkflow (false);
- return;
- }
- write ("pattern"); // Pattern workflow: nothing of the grid exists yet
- const auto madeBefore = lynx::launcher::Runtime::instances.load();
- offline.editSong ([] (lynx::Song& s) {
- while (s.patterns.size() < 6)
- s.patterns.emplace_back();
- for (int p = 0; p < 6; ++p)
- {
- auto& pattern = s.patterns[(std::size_t) p];
- const char* names[] { "Drums A", "Drums B", "Bass", "Chords", "Lead", "Pad" };
- pattern.name = names[p];
- pattern.lengthTicks = 4 * lynx::ppq;
- }
- s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 6));
- const char* tracks[] { "Drums", "Bass", "Chords", "Lead", "Vocals", "FX" };
- for (int t = 0; t < 6; ++t)
- s.playlistTracks[(std::size_t) t].name = tracks[t];
- const int placed[][3] { { 0, 0, 0 }, { 0, 1, 1 }, { 0, 2, 0 }, { 0, 3, 1 }, { 1, 0, 2 }, { 1, 2, 2 }, { 2, 1, 3 }, { 2, 2, 3 }, { 3, 2, 4 }, { 3, 3, 4 }, { 4, 3, 5 } };
- for (const auto& c : placed)
- {
- lynx::Clip clip;
- clip.pattern = c[2];
- clip.length = 4 * lynx::ppq;
- lynx::launcher::setClip (s, c[0], c[1], clip);
- }
- auto& grid = lynx::launcher::ensureGrid (s);
- const char* scenes[] { "Intro", "Verse", "Drop", "Break" };
- grid.scenes.resize (6);
- for (int r = 0; r < 4; ++r)
- grid.scenes[(std::size_t) r].name = scenes[r];
- }, false);
- offline.dispatchPendingMessages();
- write ("pattern-edited"); // the same song as -pattern-after: the workflow must leave no trace
- ui.setClipLaunchWorkflow (true);
- offline.dispatchPendingMessages();
- if (auto* runtime = offline.launcherStateForSnapshot())
- {
- runtime->tracks[0].playing.store (2);
- runtime->tracks[0].progress.store (0.4f);
- runtime->tracks[0].taken.store (true);
- runtime->tracks[1].playing.store (2);
- runtime->tracks[1].progress.store (0.4f);
- runtime->tracks[1].taken.store (true);
- runtime->tracks[2].pending.store (2);
- runtime->tracks[3].taken.store (true);
- }
- write ("both");
- ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
- write ("grid");
- // round 190bv: recording into slots and the Groove Pool. Two tracks armed (round record buttons in their empty
- // slots, their arm buttons lit), one of them recording and one waiting for its start; then a clip through a
- // groove with the pool shown, and the slot menus
- if (auto* gridView = ui.getClipGridForSnapshot())
- {
- offline.setGridTrackArmed (4, true);
- offline.setGridTrackArmed (5, true, false);
- offline.dispatchPendingMessages();
- write ("rec-armed");
- if (auto* runtime = offline.launcherStateForSnapshot())
- {
- runtime->tracks[4].recording.store (1);
- runtime->tracks[4].recordFrom.store (0.0); // (round 190cy: one beat recorded, the counter reads 0.1.0)
- runtime->clockNow.store ((double) lynx::ppq);
- runtime->tracks[5].recordPending.store (1);
- }
- write ("rec-recording");
- if (auto* runtime = offline.launcherStateForSnapshot())
- {
- runtime->tracks[4].recording.store (-1);
- runtime->tracks[5].recordPending.store (-1);
- }
- offline.editSong ([] (lynx::Song& s) {
- const auto& bank = lynx::groove::factoryBank();
- std::uint32_t first = 0;
- for (const auto index : { std::size_t (9), std::size_t (20), std::size_t (27) })
- if (index < bank.size())
- {
- const auto id = lynx::groove::add (s.grooves, bank[index].groove);
- first = first == 0 ? id : first;
- }
- lynx::groove::setClipGroove (s, 0, 0, first);
- }, false);
- offline.dispatchPendingMessages();
- lynx::setClipGridGroovePoolShown (*gridView, true);
- write ("groove-pool");
- saveMenus ({ "Clip slot", "Groove", "Empty slot" },
- { lynx::clipGridSlotMenu (*gridView, 0, 0), [&] {
- juce::PopupMenu found;
- const auto menu = lynx::clipGridSlotMenu (*gridView, 0, 0);
- for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
- if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::tr ("Groove"))
- found = *it.getItem().subMenu;
- return found;
- }(), lynx::clipGridSlotMenu (*gridView, 4, 1) },
- prefix + "-rec-menus.png");
- lynx::setClipGridGroovePoolShown (*gridView, false);
- // round 190cy: a second record button pressed while recording: the first take ("Vocals 1") plays on, the
- // clicked slot records "Vocals 2" with its counter at 2.0.2 (as Live 12.4.16, live check 190cw shot 03b)
- {
- const auto name = offline.slotRecordingName (4);
- offline.editSong ([&name] (lynx::Song& s) { lynx::session::placeRecordedPattern (s, 4, 0, {}, 8 * lynx::ppq, name); }, false);
- offline.dispatchPendingMessages();
- if (auto* runtime = offline.launcherStateForSnapshot())
- {
- runtime->tracks[4].playing.store (0);
- runtime->tracks[4].progress.store (0.3f);
- runtime->tracks[4].recording.store (1);
- runtime->tracks[4].recordFrom.store (0.0);
- runtime->clockNow.store (8.0 * lynx::ppq + 2.0 * lynx::ppq / 4.0);
- }
- write ("rec-second");
- if (auto* runtime = offline.launcherStateForSnapshot())
- {
- runtime->tracks[4].playing.store (-1);
- runtime->tracks[4].recording.store (-1);
- }
- offline.editSong ([] (lynx::Song& s) {
- if (lynx::session::cut (s, 4, 0) && ! s.patterns.empty())
- s.patterns.pop_back();
- }, false);
- offline.dispatchPendingMessages();
- }
- offline.setGridTrackArmed (4, false);
- offline.setGridTrackArmed (5, false);
- offline.dispatchPendingMessages();
- }
- ui.setClipGridView (lynx::PlaylistArea::GridView::song);
- write ("song");
- ui.setClipLaunchWorkflow (false);
- write ("pattern-after");
- juce::File (prefix + "-counts.txt").replaceWithText ("runtimes before " + juce::String (madeBefore) + ", after " + juce::String (lynx::launcher::Runtime::instances.load()) + "\n");
- }
- // Round 190bu: the Simple workflow's track dock (ui/SimpleDock.h), off-screen
- void runSimpleFxShot (const juce::String& prefix)
- {
- 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()));
- const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
- const auto file = juce::File (prefix + "-" + name + ".png");
- file.deleteFile();
- juce::FileOutputStream out (file);
- juce::PNGImageFormat().writeImageToStream (image, out);
- };
- juce::String report;
- const auto line = [&report] (const juce::String& text) { report << text << "\n"; };
- const auto check = [&report] (const juce::String& what, bool ok) { report << (ok ? "OK " : "ERROR ") << what << "\n"; };
- const auto madeBefore = lynx::SimpleWorkflow::instances.load();
- ui.selectTabForSnapshot (2);
- ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
- offline.dispatchPendingMessages();
- auto* simple = ui.getSimpleWorkflowForSnapshot();
- if (simple == nullptr)
- {
- juce::File (prefix + "-report.txt").replaceWithText ("ERROR no Simple workflow\n");
- return;
- }
- simple->hideChooser();
- // three tracks: a voice, keys with a few chords, a drum kit
- int keysInsert = -1;
- offline.editSong ([&keysInsert] (lynx::Song& s) {
- namespace st = lynx::simpletracks;
- st::Request q;
- q.kind = st::Kind::voice;
- q.name = "Lead vocal";
- st::addTrack (s, q);
- q = {};
- q.kind = st::Kind::instrument;
- q.name = "Keys";
- lynx::ChannelDef keys;
- keys.instrument = lynx::InstrumentKind::synth;
- q.channel = keys;
- lynx::Pattern chords;
- for (int i = 0; i < 4; ++i)
- for (int k : { 60, 64, 67 })
- chords.notes.push_back (lynx::Note { (std::int64_t) i * 4 * lynx::ppq, 4 * lynx::ppq - lynx::ppq / 4, 0, k });
- q.pattern = chords;
- keysInsert = st::addTrack (s, q).insert;
- q = {};
- q.kind = st::Kind::drums;
- for (auto kind : { lynx::InstrumentKind::kick, lynx::InstrumentKind::snare, lynx::InstrumentKind::hat })
- {
- lynx::ChannelDef c;
- c.instrument = kind;
- c.name = kind == lynx::InstrumentKind::kick ? "Kick" : kind == lynx::InstrumentKind::snare ? "Snare" : "Hat";
- q.kit.push_back (c);
- }
- lynx::Pattern beat;
- for (int step = 0; step < 16; step += 2)
- beat.notes.push_back (lynx::Note { (std::int64_t) step * lynx::ticksPerStep, lynx::ticksPerStep, 2, 60 });
- q.pattern = beat;
- st::addTrack (s, q);
- });
- offline.dispatchPendingMessages();
- simple->hideChooser();
- auto& playlist = ui.getPlaylistForSnapshot();
- // the tracks' places in the Playlist
- int voiceTrack = -1, keysTrack = -1, drumsTrack = -1;
- {
- const auto& song = offline.getSong();
- for (int t = 0; t < (int) song.playlistTracks.size(); ++t)
- if (const auto kind = lynx::simpletracks::kindOf (song, t))
- {
- if (*kind == lynx::simpletracks::Kind::audio && voiceTrack < 0)
- voiceTrack = t;
- else if (*kind == lynx::simpletracks::Kind::instrument && keysTrack < 0)
- keysTrack = t;
- else if (*kind == lynx::simpletracks::Kind::drums && drumsTrack < 0)
- drumsTrack = t;
- }
- }
- check ("three Simple tracks (voice, keys, drums)", voiceTrack >= 0 && keysTrack >= 0 && drumsTrack >= 0);
- playlist.selectTrack (keysTrack);
- offline.dispatchPendingMessages();
- auto* dock = simple->dockForSnapshot();
- if (dock == nullptr)
- {
- juce::File (prefix + "-report.txt").replaceWithText (report + "ERROR no dock\n");
- return;
- }
- // the whole window and the dock alone, at 1x and 2x
- const auto shots = [&] (const juce::String& name) {
- offline.dispatchPendingMessages();
- for (float scale : { 1.0f, 2.0f })
- {
- const auto suffix = scale > 1.0f ? juce::String ("@2x") : juce::String();
- writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), name + suffix);
- writeImage (dock->createComponentSnapshot (dock->getLocalBounds(), true, scale), "dock-" + name + suffix);
- }
- };
- const auto menuShot = [&] (const juce::PopupMenu& menu, const juce::String& title, const juce::String& subTitle, const juce::String& name) {
- juce::StringArray names { title };
- std::vector<juce::PopupMenu> menus { menu };
- for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
- if (it.getItem().subMenu != nullptr && it.getItem().text == subTitle)
- {
- names.add (subTitle);
- menus.push_back (*it.getItem().subMenu);
- }
- saveMenus (names, menus, prefix + "-" + name + ".png");
- };
- // --- the Instrument tab ---------------------------------------------------------------------------------------
- check ("the dock shows the selected track", dock->shownTrack() == keysTrack && dock->isVisible() && dock->getParentComponent() != nullptr);
- check ("an instrument track opens on its sound", dock->hasInstrumentTabForCheck() && dock->getTab() == lynx::SimpleDock::Tab::instrument);
- const auto channel = dock->channelForCheck();
- line ("sound at first: " + dock->soundNameForCheck() + ", rows in its category: " + juce::String (dock->soundRowsForCheck()));
- shots ("instrument");
- // a click on a row of another category: the track plays that sound, its own settings stay
- const auto before = offline.getSong().channels[(std::size_t) channel];
- dock->showCategoryForSnapshot ((int) lynx::soundlib::Category::pad);
- offline.dispatchPendingMessages();
- const auto padRows = dock->soundRowsForCheck();
- dock->clickSoundForCheck (juce::jmin (2, padRows - 1));
- offline.dispatchPendingMessages();
- {
- const auto& now = offline.getSong().channels[(std::size_t) channel];
- const auto found = lynx::soundlib::find (lynx::soundlib::builtIn(), now);
- check ("a click on a sound puts it on the track's channel (" + dock->soundNameForCheck() + ")",
- padRows > 0 && found >= 0 && lynx::soundlib::builtIn()[(std::size_t) found].category == lynx::soundlib::Category::pad
- && ! lynx::soundlib::sameSound (before, now));
- check ("the channel keeps its name, level and insert", now.name == before.name && now.volume == before.volume && now.mixerTrack == before.mixerTrack);
- double seconds = 0.0;
- const auto heard = offline.auditionSound (now, { 60, 64, 67 }, &seconds);
- check ("the sound's audition renders (" + juce::String (seconds, 2) + " s)", heard && seconds > 1.0);
- }
- shots ("instrument-pad");
- const auto picked = dock->soundNameForCheck();
- dock->stepSoundForCheck (1);
- offline.dispatchPendingMessages();
- const auto stepped = dock->soundNameForCheck();
- dock->stepSoundForCheck (-1);
- offline.dispatchPendingMessages();
- check ("the arrows step through the category (" + picked + " -> " + stepped + " -> back)", stepped != picked && dock->soundNameForCheck() == picked);
- check ("one undo step per sound", offline.canUndo());
- // the user's SoundFont files (an index made here: no file is read)
- {
- std::vector<lynx::sf::IndexedFont> fonts (2);
- fonts[0].path = "/home/me/SoundFonts/Concert Band.sf2";
- fonts[0].name = "Concert Band";
- int program = 0;
- for (const char* name : { "Grand Piano", "Bright Piano", "Electric Piano", "Harpsichord", "Clavinet", "Celesta", "Music Box", "Vibraphone" })
- fonts[0].presets.push_back ({ name, 0, program++ });
- for (const auto& [name, p] : std::initializer_list<std::pair<const char*, int>> { { "Finger Bass", 33 }, { "Picked Bass", 34 }, { "Nylon Guitar", 24 }, { "Strings", 48 }, { "Choir Aahs", 52 }, { "Trumpet", 56 } })
- fonts[0].presets.push_back ({ name, 0, p });
- fonts[0].presets.push_back ({ "Standard Kit", 128, 0 });
- fonts[1].path = "/home/me/SoundFonts/Old Upright.sf2";
- fonts[1].name = "Old Upright";
- fonts[1].presets.push_back ({ "Old Upright", 0, 0 });
- fonts[1].presets.push_back ({ "Old Upright Soft", 0, 1 });
- dock->setFontsForSnapshot (fonts);
- dock->showCategoryForSnapshot ((int) lynx::soundlib::Category::keys);
- offline.dispatchPendingMessages();
- check ("My SoundFonts lists the presets of the user's files by category (Keys: " + juce::String (dock->soundRowsForCheck()) + " of 17)", dock->soundRowsForCheck() == 7);
- dock->clickSoundForCheck (0);
- offline.dispatchPendingMessages();
- const auto& now = offline.getSong().channels[(std::size_t) channel];
- check ("a SoundFont preset becomes the track's sound (" + dock->soundNameForCheck() + ")",
- now.instrument == lynx::InstrumentKind::soundfont && juce::String (now.samplePath).endsWith (".sf2"));
- shots ("instrument-soundfonts");
- }
- // --- the Effects tab ------------------------------------------------------------------------------------------
- playlist.selectTrack (voiceTrack);
- offline.dispatchPendingMessages();
- const auto insert = dock->insertForCheck();
- check ("an audio track has no Instrument tab and opens on its effects",
- dock->shownTrack() == voiceTrack && ! dock->hasInstrumentTabForCheck() && dock->getTab() == lynx::SimpleDock::Tab::effects && insert > 0);
- check ("no effects yet: no cards", dock->cardCountForCheck() == 0);
- shots ("effects-empty");
- menuShot (dock->addMenuForSnapshot(), lynx::tr ("Add an effect"), {}, "menu-add");
- // + adds one-knob effects at the end of the chain
- dock->addOneKnobForCheck (lynx::goals::brighter);
- dock->addOneKnobForCheck (lynx::goals::room);
- dock->addOneKnobForCheck (lynx::goals::level);
- offline.dispatchPendingMessages();
- const auto slotsText = [&offline] (int t) {
- juce::String text;
- const auto rows = lynx::mixerops::effectRows (offline.getSong().mixer[(std::size_t) t].effects); // (the Mixer's slot of each)
- std::size_t at = 0;
- for (const auto& fx : offline.getSong().mixer[(std::size_t) t].effects)
- text << "[slot " << rows[at++] + 1 << " " << lynx::effectInfo (fx.kind).name
- << (lynx::goals::active (fx) ? " = " + juce::String (lynx::goals::name (fx.goal)) + " " + juce::String (juce::roundToInt (fx.goalAmount * 100.0f)) + "%" : juce::String())
- << (fx.enabled ? "" : " off") << "] ";
- return text.trimEnd();
- };
- line ("after + x3: " + slotsText (insert));
- check ("three cards, three one-knob effects", dock->cardCountForCheck() == 3 && dock->oneKnobCardsForCheck() == 3);
- // the knob writes the effect's own parameters
- const auto roomBefore = offline.getSong().mixer[(std::size_t) insert].effects[1];
- dock->turnKnobForCheck (1, 0.8f);
- offline.dispatchPendingMessages();
- {
- const auto& room = offline.getSong().mixer[(std::size_t) insert].effects[1];
- check ("the knob at 80 % writes the mapped parameters", std::abs (room.goalAmount - 0.8f) < 1.0e-6f && lynx::goals::active (room) && ! (room.params == roomBefore.params));
- }
- // ‹ › reorder, × removes
- dock->moveCardForCheck (2, -1);
- offline.dispatchPendingMessages();
- line ("Level moved left: " + slotsText (insert));
- {
- const auto& fx = offline.getSong().mixer[(std::size_t) insert].effects;
- check ("the card moved one place earlier", fx.size() == 3 && fx[1].goal == lynx::goals::level && fx[2].goal == lynx::goals::room);
- }
- dock->removeCardForCheck (0);
- offline.dispatchPendingMessages();
- line ("Brighter removed: " + slotsText (insert));
- check ("the card is gone", dock->cardCountForCheck() == 2 && offline.getSong().mixer[(std::size_t) insert].effects.size() == 2);
- // a hand edit in the full editor: the slot is an ordinary effect again (its card shows Mix)
- offline.editSong ([insert] (lynx::Song& s) {
- auto& slot = s.mixer[(std::size_t) insert].effects[0];
- const auto moved = (std::size_t) lynx::goals::mapping (slot.goal, slot.goalAmount).back().param;
- slot.params[moved] = slot.params[moved] > 0.5f ? 0.2f : 0.9f;
- });
- offline.dispatchPendingMessages();
- check ("a parameter moved by hand makes the card an ordinary effect", dock->cardCountForCheck() == 2 && dock->oneKnobCardsForCheck() == 1);
- dock->turnKnobForCheck (0, 0.5f); // (its knob is the slot's Mix now)
- offline.dispatchPendingMessages();
- check ("an ordinary card's knob is the slot's Mix", std::abs (offline.getSong().mixer[(std::size_t) insert].effects[0].mix - 0.5f) < 1.0e-6f);
- // a preset replaces the chain; Blend is the chain's dry/wet
- if (const auto* preset = lynx::chains::find ("Clear Voice"))
- offline.editSongStructural ([insert, preset] (lynx::Song& s) { lynx::chains::apply (s, insert, *preset); });
- offline.dispatchPendingMessages();
- line ("preset Clear Voice: " + slotsText (insert));
- check ("the preset's chain is on the insert", offline.getSong().mixer[(std::size_t) insert].chainPreset == "Clear Voice" && lynx::chains::unchanged (offline.getSong(), insert)
- && dock->cardCountForCheck() == (int) offline.getSong().mixer[(std::size_t) insert].effects.size());
- shots ("effects-preset");
- menuShot (dock->presetMenuForSnapshot(), lynx::tr ("Preset"), lynx::tr ("Voice"), "menu-preset");
- dock->setBlendForCheck (0.7f);
- dock->addOneKnobForCheck (lynx::goals::echo);
- offline.dispatchPendingMessages();
- check ("Blend 70 % is the insert's chain blend; the preset shows as edited",
- std::abs (offline.getSong().mixer[(std::size_t) insert].chainBlend - 0.7f) < 1.0e-6f && ! lynx::chains::unchanged (offline.getSong(), insert));
- shots ("effects-edited");
- // a user preset: saved to a file, loaded on another track (its slots and Blend; that track's level stays)
- const auto mine = offline.getSong().mixer[(std::size_t) insert];
- const auto saved = lynx::SimpleDock::saveUserPreset (offline, insert, "My voice");
- const auto file = lynx::SimpleDock::userPresetFolder().getChildFile ("My voice.lynxtrack");
- check ("the preset is saved as " + file.getFileName(), saved && file.existsAsFile() && offline.getSong().mixer[(std::size_t) insert].chainPreset == "My voice");
- offline.editSong ([keysInsert] (lynx::Song& s) { s.mixer[(std::size_t) keysInsert].volume = 0.42f; });
- const auto loaded = keysInsert > 0 && lynx::SimpleDock::loadUserPreset (offline, keysInsert, file);
- offline.dispatchPendingMessages();
- {
- const auto& other = offline.getSong().mixer[(std::size_t) keysInsert];
- auto same = loaded && other.effects.size() == mine.effects.size() && std::abs (other.chainBlend - mine.chainBlend) < 1.0e-6f && other.chainPreset == "My voice";
- for (std::size_t i = 0; same && i < mine.effects.size(); ++i)
- same = other.effects[i].kind == mine.effects[i].kind && other.effects[i].goal == mine.effects[i].goal
- && lynx::mixerops::effectRows (other.effects)[i] == lynx::mixerops::effectRows (mine.effects)[i] && std::abs (other.effects[i].goalAmount - mine.effects[i].goalAmount) < 1.0e-6f && lynx::goals::active (other.effects[i]) == lynx::goals::active (mine.effects[i]);
- check ("loaded on the Keys track: the same slots and Blend", same);
- check ("the Keys track keeps its level", std::abs (other.volume - 0.42f) < 1.0e-6f);
- line ("Keys after load: " + slotsText (keysInsert));
- }
- menuShot (dock->presetMenuForSnapshot(), lynx::tr ("Preset"), lynx::tr ("My presets"), "menu-preset-mine");
- file.deleteFile();
- // the drums: effects only (a kit has no single sound to pick)
- playlist.selectTrack (drumsTrack);
- offline.dispatchPendingMessages();
- check ("the Drums track shows its insert's effects, no Instrument tab", dock->shownTrack() == drumsTrack && ! dock->hasInstrumentTabForCheck() && dock->insertForCheck() > 0);
- if (const auto* preset = lynx::chains::find ("Smash Room"))
- offline.editSongStructural ([t = dock->insertForCheck(), preset] (lynx::Song& s) { lynx::chains::apply (s, t, *preset); });
- shots ("effects-drums");
- // the project file keeps all of it
- {
- juce::String error;
- const auto json = lynx::ProjectFile::toJson (offline.getSong());
- const auto back = lynx::ProjectFile::fromJson (json, error);
- auto same = back && back->mixer.size() == offline.getSong().mixer.size();
- for (std::size_t t = 0; same && t < back->mixer.size(); ++t)
- {
- const auto& a = offline.getSong().mixer[t];
- const auto& b = back->mixer[t];
- same = a.effects.size() == b.effects.size() && std::abs (a.chainBlend - b.chainBlend) < 1.0e-6f && a.chainPreset == b.chainPreset;
- for (std::size_t i = 0; same && i < a.effects.size(); ++i)
- same = a.effects[i].kind == b.effects[i].kind && a.effects[i].goal == b.effects[i].goal && a.effects[i].row == b.effects[i].row
- && std::abs (a.effects[i].goalAmount - b.effects[i].goalAmount) < 1.0e-6f;
- }
- check ("saved and loaded as a project: the same chains, knobs, Blend and preset names", same);
- }
- // --- the same plugins in the same slots in FL's layout --------------------------------------------------------
- const auto simpleSong = offline.getSong();
- const auto inSimple = slotsText (insert);
- ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
- offline.dispatchPendingMessages();
- check ("Pattern workflow: the dock is gone", dock->getParentComponent() == nullptr);
- ui.selectTabForSnapshot (3);
- ui.getMixerForSnapshot().selectTrack (insert);
- offline.dispatchPendingMessages();
- for (float scale : { 1.0f, 2.0f })
- writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), juce::String ("pattern-mixer") + (scale > 1.0f ? "@2x" : ""));
- line ("Simple layout: " + inSimple);
- line ("Pattern layout: " + slotsText (insert));
- check ("the same effects in the same Mixer slots in the Pattern workflow", offline.getSong().mixer == simpleSong.mixer && offline.getSong().channels == simpleSong.channels);
- // an effect added in the Mixer's way shows as a card when the Simple workflow comes back
- offline.editSongStructural ([insert] (lynx::Song& s) { lynx::mixerops::insertEffectAtRow (s, insert, lynx::makeEffectSlot (lynx::EffectKind::chorus), 7); });
- ui.selectTabForSnapshot (2);
- ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
- offline.dispatchPendingMessages();
- simple->hideChooser();
- playlist.selectTrack (voiceTrack);
- offline.dispatchPendingMessages();
- check ("back in Simple: the dock shows the insert as it is now, the Mixer's new effect too",
- dock->getParentComponent() != nullptr && dock->cardCountForCheck() == (int) offline.getSong().mixer[(std::size_t) insert].effects.size()
- && lynx::mixerops::effectRows (offline.getSong().mixer[(std::size_t) insert].effects).back() == 7);
- line ("Simple again: " + slotsText (insert));
- shots ("effects-back");
- // hidden with its key, shown again by "+FX"
- simple->toggleDock();
- offline.dispatchPendingMessages();
- check ("Ctrl+Alt+L hides the dock", ! simple->isDockShowing() && ! lynx::SimpleDock::shownSetting);
- writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, 1.0f), "dock-hidden");
- simple->showEffectsOfInsert (keysInsert);
- offline.dispatchPendingMessages();
- check ("+FX on a track header shows the dock on that track's effects",
- simple->isDockShowing() && dock->shownTrack() == keysTrack && dock->getTab() == lynx::SimpleDock::Tab::effects && dock->insertForCheck() == keysInsert);
- simple->cycleDockTab();
- check ("Shift+Tab goes to the Instrument tab", dock->getTab() == lynx::SimpleDock::Tab::instrument);
- line ("Simple workflow objects: " + juce::String (madeBefore) + " before, " + juce::String (lynx::SimpleWorkflow::instances.load()) + " after");
- line (report.contains ("ERROR ") ? "RESULT ERROR" : "RESULT OK");
- juce::File (prefix + "-report.txt").replaceWithText (report);
- }
- // --simpleclosetest (round 190fc, 0.1.27 RC blocker B1): every close in the Simple layout crashed (the Simple workflow
- // was destroyed after the Workspace and its destructor called into it). Off-screen, no window: the main window in the
- // Simple layout with everything of it open — Welcome, the first-song tour's card, Start from, a demo song, each dock
- // tab (the Editor tab docks the Piano roll), Finish, Lyrics, the chooser — then destroyed as the app's shutdown does.
- // A second main window goes Simple -> Pattern -> Simple and closes too. Checks: no Simple workflow outlives its main
- // window's destructor body, none is left at all. (Under ASan on Linux the old order is a heap-use-after-free.)
- bool runDonateShot (const juce::String& prefix)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- juce::String report;
- bool ok = true;
- const auto line = [&report, &prefix] (const juce::String& text) {
- report << text << "\n";
- juce::File (prefix + "-report.txt").replaceWithText (report); // (written as it goes)
- };
- const auto check = [&line, &ok] (const juce::String& what, bool good) {
- line ((good ? "ok " : "FAIL ") + what);
- ok = ok && good;
- };
- const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
- const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
- file.deleteFile();
- juce::FileOutputStream out (file);
- juce::PNGImageFormat().writeImageToStream (image, out);
- };
- // a window as the --snapshot route saves one (off the desktop, on the theme's panel colour), at 1x and 2x
- const auto saveAlert = [&] (juce::AlertWindow& w, const juce::String& name) {
- if (w.isOnDesktop())
- w.removeFromDesktop();
- w.setOpaque (true);
- juce::Component frame;
- frame.setSize (w.getWidth(), w.getHeight());
- frame.setOpaque (true);
- frame.addAndMakeVisible (w);
- w.setTopLeftPosition (0, 0);
- writeImage (lynx::shot::paint (frame, lynx::theme::panel), name);
- writeImage (frame.createComponentSnapshot (frame.getLocalBounds(), true, 2.0f), name + "@2x");
- frame.removeChildComponent (&w);
- };
- const auto buttonTexts = [] (juce::AlertWindow& w) {
- juce::StringArray texts;
- for (int b = 0; b < w.getNumButtons(); ++b)
- if (auto* button = w.getButton (b))
- texts.add (button->getButtonText());
- return texts;
- };
- check ("the donation page is one constant, on Ko-fi", juce::String (lynx::links::donate).startsWith ("https://ko-fi"));
- line ("donate URL: " + juce::String (lynx::links::donate));
- const auto stateFile = lynx::PluginHost::settingsFolder().getChildFile ("support-note.txt");
- const auto hadState = stateFile.existsAsFile();
- const auto oldState = stateFile.loadFileAsString();
- line ("state file: " + stateFile.getFullPathName() + (hadState ? " (exists; put back at the end)" : ""));
- {
- 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()));
- ui.setVisible (true);
- const auto settle = [&] {
- for (int k = 0; k < 3; ++k)
- offline.dispatchPendingMessages();
- };
- // --- Help › Support LYNX SHARE..., right above About, in the three layouts ----------------------------------
- for (auto [style, name] : { std::pair { lynx::layoutstyle::Style::pattern, "pattern" }, { lynx::layoutstyle::Style::clipLaunch, "cliplaunch" },
- { lynx::layoutstyle::Style::simple, "simple" } })
- {
- ui.setLayoutStyle (style);
- settle();
- const auto help = ui.getMenuForSnapshot (ui.getMenuNamesForSnapshot().indexOf (lynx::tr ("Help")));
- juce::StringArray items;
- for (juce::PopupMenu::MenuItemIterator it (help); it.next();)
- if (! it.getItem().isSeparator)
- items.add (it.getItem().text);
- const auto support = items.indexOf (lynx::tr ("Support LYNX SHARE..."));
- const auto about = items.indexOf (lynx::tr ("About LYNX SHARE"));
- check (juce::String ("Help has Support LYNX SHARE... right above About LYNX SHARE (") + name + " layout)",
- support >= 0 && about == support + 1);
- saveMenus ({ lynx::tr ("Help") }, { help }, prefix + "-menu-help-" + name + ".png");
- }
- ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
- settle();
- // --- the Support window -------------------------------------------------------------------------------------
- {
- auto w = lynx::support::makeSupportWindow();
- const auto texts = buttonTexts (*w);
- check ("Support window: Donate on Ko-fi, Close", texts == juce::StringArray { lynx::tr ("Donate on Ko-fi"), lynx::tr ("Close") });
- check ("Support window: Donate on Ko-fi points at the constant",
- w->getButton (0) != nullptr && w->getButton (0)->getTooltip() == juce::String (lynx::links::donate));
- check ("Support window title", w->getName() == lynx::tr ("Support LYNX SHARE"));
- saveAlert (*w, "support");
- }
- // --- the About window ---------------------------------------------------------------------------------------
- {
- auto w = lynx::MainComponent::makeAboutWindow();
- const auto texts = buttonTexts (*w);
- check ("About window: Support LYNX SHARE (result 2) and OK", texts == juce::StringArray { lynx::tr ("Support LYNX SHARE"), lynx::tr ("OK") });
- saveAlert (*w, "about");
- }
- // --- Settings › General › Show the support note -------------------------------------------------------------
- {
- auto page = lynx::makeGeneralPage (offline, {}, false);
- bool found = false;
- std::function<void (juce::Component&)> walk = [&] (juce::Component& c) {
- if (auto* t = dynamic_cast<juce::ToggleButton*> (&c); t != nullptr && t->getButtonText() == lynx::tr ("Show the support note"))
- found = t->getToggleState();
- for (auto* child : c.getChildren())
- walk (*child);
- };
- walk (*page);
- check ("Settings > General: \"Show the support note\", ticked by default", found);
- }
- // --- the start-up note's rules, end to end on the saved state ----------------------------------------------
- lynx::supportnote::Moment moment; // (the main window here is off-screen: the moment is set by hand)
- lynx::support::StartupNote note (ui, [&moment] { return moment; }, [] { return 0; });
- const auto state = [] { return lynx::support::loadState(); };
- const auto setState = [] (int launches, int next, bool show) { lynx::support::saveState ({ launches, next, show }); };
- stateFile.deleteFile();
- for (int k = 0; k < 15; ++k)
- note.begin (true);
- note.pollForSnapshot();
- check ("test mode / CI runs: 15 starts, nothing counted, no file, no card", ! stateFile.existsAsFile() && ! note.isCardShowing());
- check ("a first start's defaults: next at start 10, shown", state() == lynx::supportnote::State { 0, 10, true });
- for (int k = 1; k <= 9; ++k)
- {
- note.begin (false);
- note.pollForSnapshot();
- }
- check ("starts 1 to 9: counted, no card", state().launches == 9 && ! note.isCardShowing());
- moment.playing = true;
- note.begin (false); // the 10th start
- note.pollForSnapshot();
- check ("10th start while playing: the card waits", state().launches == 10 && ! note.isCardShowing());
- moment = {};
- moment.dialogOpen = true;
- note.pollForSnapshot();
- check ("... and while a dialog is open", ! note.isCardShowing());
- moment = {};
- note.pollForSnapshot();
- check ("10th start, a quiet moment: the card shows", note.isCardShowing());
- check ("shown: left without an answer it comes back 30 starts later", state().nextAt == 40);
- if (auto* card = note.cardForSnapshot())
- {
- const auto b = card->getBounds();
- check ("the card sits in the bottom-right corner", b.getRight() <= ui.getWidth() - 8 && b.getRight() >= ui.getWidth() - 40
- && b.getBottom() <= ui.getHeight() - 4 && b.getBottom() >= ui.getHeight() - 40);
- writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, 1.0f), "note-in-window");
- writeImage (card->createComponentSnapshot (card->getLocalBounds(), true, 2.0f), "note@2x");
- // the corner of the window around the card, at 2x
- writeImage (ui.createComponentSnapshot (b.expanded (220, 120).getIntersection (ui.getLocalBounds()), true, 2.0f), "note-corner@2x");
- }
- moment.playing = true;
- note.pollForSnapshot();
- check ("playback starts: the card steps aside", ! note.isCardShowing());
- moment = {};
- // Not now: again after 30 more starts
- setState (10, 10, true);
- note.begin (false); // start 11
- note.pollForSnapshot();
- if (auto* card = note.cardForSnapshot(); card != nullptr && card->buttonForSnapshot (lynx::supportnote::Choice::notNow) != nullptr)
- card->buttonForSnapshot (lynx::supportnote::Choice::notNow)->onClick();
- note.closeCard(); // (the click closes it on the next message turn)
- check ("Not now: next at start 41", state() == lynx::supportnote::State { 11, 41, true });
- for (int k = 12; k <= 40; ++k)
- {
- note.begin (false);
- note.pollForSnapshot();
- if (note.isCardShowing())
- break;
- }
- check ("Not now: starts 12 to 40 without the card", ! note.isCardShowing() && state().launches == 40);
- note.begin (false);
- note.pollForSnapshot();
- check ("Not now: the card again at start 41", note.isCardShowing());
- // Don't show again: never, and Settings shows the box unticked
- if (auto* card = note.cardForSnapshot())
- card->buttonForSnapshot (lynx::supportnote::Choice::never)->onClick();
- note.closeCard();
- check ("Don't show again: off", ! state().show && ! lynx::support::noteEnabled());
- for (int k = 0; k < 200; ++k)
- {
- note.begin (false);
- note.pollForSnapshot();
- }
- check ("Don't show again: 200 more starts, never", ! note.isCardShowing());
- // Support: opens the Support window (on the next message turn) and the note doesn't come back
- setState (20, 10, true);
- note.begin (false);
- note.pollForSnapshot();
- if (auto* card = note.cardForSnapshot())
- card->buttonForSnapshot (lynx::supportnote::Choice::support)->onClick();
- note.closeCard();
- check ("Support: the note has done its job", ! state().show);
- // Settings off: never; on again: counts from now
- setState (5, 10, true);
- lynx::support::setNoteEnabled (false);
- for (int k = 0; k < 100; ++k)
- {
- note.begin (false);
- note.pollForSnapshot();
- }
- check ("Settings off: 100 starts, never", ! note.isCardShowing() && state().launches == 105);
- lynx::support::setNoteEnabled (true);
- check ("Settings on again: next 30 starts later", state() == lynx::supportnote::State { 105, 135, true });
- note.closeCard();
- }
- stateFile.deleteFile();
- if (hadState)
- stateFile.replaceWithText (oldState);
- line (ok ? "result=OK" : "result=FAILED");
- return ok;
- }
- bool runSimpleCloseTest (const juce::String& reportPath)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- juce::String report;
- bool ok = true;
- const auto line = [&report, &reportPath] (const juce::String& text) {
- report << text << "\n";
- juce::File (reportPath).replaceWithText (report); // (written as it goes: a crash still leaves the last step)
- };
- const auto check = [&line, &ok] (const juce::String& what, bool good) {
- line ((good ? "ok " : "FAIL ") + what);
- ok = ok && good;
- };
- const auto aliveBefore = lynx::SimpleWorkflow::alive.load();
- {
- lynx::AudioEngine offline (false);
- {
- lynx::MainComponent ui (offline, false);
- ui.setSize (1600, 900);
- ui.setVisible (true); // (no window: the docked editor and the tour only need their parents visible)
- const auto settle = [&] {
- for (int k = 0; k < 3; ++k)
- offline.dispatchPendingMessages();
- };
- ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
- settle();
- auto* simple = ui.getSimpleWorkflowForSnapshot();
- check ("the Simple workflow is up", simple != nullptr);
- if (simple != nullptr)
- {
- const auto empty = lynx::builtInTemplateIndex ("Empty");
- offline.setSong (empty >= 0 ? lynx::makeNewProject (empty) : lynx::makeNewProject());
- settle();
- simple->showWelcome();
- settle();
- auto* tour = simple->tourForSnapshot();
- check ("Welcome screen shown", tour != nullptr && tour->isWelcomeShowing());
- simple->startOrContinueTour();
- settle();
- simple->doTourStep (lynx::tour::beat);
- settle();
- check ("the tour runs with its card up", simple->tourRunning() && tour != nullptr && tour->cardForSnapshot() != nullptr);
- // a demo song from Start from (the panel stays up over the Playlist)
- if (auto* start = simple->startFromForSnapshot(); start != nullptr && lynx::demos::count > 1)
- {
- offline.setSong (lynx::demos::make (1));
- settle();
- check ("a demo song opened, Start from up", simple->isStartFromShowing() && ! offline.getSong().playlist.empty());
- }
- // the dock on a track, every tab (the Editor tab docks the Piano roll)
- if (auto* dock = simple->dockForSnapshot())
- {
- simple->trackSelected ([] (const lynx::Song& song) { // the first Instrument track (the dock's Keyboard and Editor tabs are for it)
- for (int t = 0; t < (int) song.playlistTracks.size(); ++t)
- if (lynx::simpletracks::kindOf (song, t) == lynx::simpletracks::Kind::instrument)
- return t;
- return 0;
- } (offline.getSong()));
- for (auto tab : { lynx::SimpleDock::Tab::instrument, lynx::SimpleDock::Tab::keyboard, lynx::SimpleDock::Tab::editor,
- lynx::SimpleDock::Tab::effects, lynx::SimpleDock::Tab::editor })
- {
- dock->setTab (tab);
- settle();
- }
- check ("the dock shows", simple->isDockShowing());
- line ("dock tab at the close: " + juce::String ((int) dock->getTab()) + " (2 = Editor, the docked Piano roll)");
- }
- ui.toggleLyrics(); // (Lyrics, then Finish: they share the dock on the right)
- settle();
- simple->showFinish();
- settle();
- check ("Finish open", simple->isFinishShowing());
- simple->showChooser();
- settle();
- line ("Simple workflow objects alive before the close: " + juce::String (lynx::SimpleWorkflow::alive.load() - aliveBefore));
- }
- } // (the main window goes as at shutdown)
- check ("no Simple workflow outlived its main window's destructor body (it reaches the Workspace)",
- lynx::MainComponent::simpleWorkflowAliveAfterTeardown == aliveBefore);
- check ("none left after the close", lynx::SimpleWorkflow::alive.load() == aliveBefore);
- // Simple, then Pattern, then Simple again, and closed
- {
- lynx::MainComponent ui (offline, false);
- ui.setSize (1600, 900);
- ui.setVisible (true);
- ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
- offline.dispatchPendingMessages();
- ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
- offline.dispatchPendingMessages();
- ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
- offline.dispatchPendingMessages();
- if (auto* simple = ui.getSimpleWorkflowForSnapshot())
- simple->showWelcome();
- offline.dispatchPendingMessages();
- }
- check ("Simple -> Pattern -> Simple, closed: none outlived the destructor body", lynx::MainComponent::simpleWorkflowAliveAfterTeardown == aliveBefore
- && lynx::SimpleWorkflow::alive.load() == aliveBefore);
- }
- line (ok ? "result=OK" : "result=FAILED");
- return ok;
- }
- void runTour190dvShot (const juce::String& prefix)
- {
- 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()));
- ui.setVisible (true); // (no window: the docked editor and the ring's targets only need their parents visible)
- const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
- const auto file = juce::File (prefix + "-" + name + ".png");
- file.deleteFile();
- juce::FileOutputStream out (file);
- juce::PNGImageFormat().writeImageToStream (image, out);
- };
- juce::String report;
- // (written as it goes: a run that stops halfway still leaves its checks)
- const auto line = [&report, &prefix] (const juce::String& text) {
- report << text << "\n";
- juce::File (prefix + "-report.txt").replaceWithText (report);
- };
- const auto check = [&line] (const juce::String& what, bool ok) { line ((ok ? "OK " : "ERROR ") + what); };
- ui.selectTabForSnapshot (2);
- ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
- offline.dispatchPendingMessages();
- auto* simple = ui.getSimpleWorkflowForSnapshot();
- auto* tour = simple != nullptr ? simple->tourForSnapshot() : nullptr;
- if (tour == nullptr)
- {
- juce::File (prefix + "-report.txt").replaceWithText ("ERROR no Simple workflow / tour\n");
- return;
- }
- check ("no Welcome screen by itself in a --snapshot route (not a real first start)", ! tour->isWelcomeShowing());
- const auto settle = [&] {
- for (int k = 0; k < 3; ++k)
- offline.dispatchPendingMessages();
- };
- const auto window = [&] (const juce::String& name, bool twoX = false) {
- settle();
- tour->ringForSnapshot(); // (the ring follows the layout: resolved now, as its timer would)
- writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, 1.0f), name);
- if (twoX)
- if (auto* card = tour->cardForSnapshot(); card != nullptr && card->getParentComponent() != nullptr)
- writeImage (card->createComponentSnapshot (card->getLocalBounds(), true, 2.0f), name + "-card@2x");
- };
- const auto stepIs = [&] (int step, const juce::String& target) {
- settle();
- const auto ring = tour->ringForSnapshot();
- const auto id = tour->targetIdForSnapshot();
- line ("step " + juce::String (tour->step() + 1) + " (" + lynx::tour::stepId (tour->step()) + "): ring on " + (id.isEmpty() ? juce::String ("-") : id) + " "
- + ring.toString());
- check (juce::String ("the card shows step ") + lynx::tour::stepId (step), tour->isRunning() && tour->step() == step);
- if (target.isNotEmpty())
- check ("the ring is on " + target, id == target && ! ring.isEmpty());
- };
- // --- the Welcome screen (on a new, empty project: the built-in "Empty" template, as File › New can give) -------------
- const auto emptyProject = [] {
- const auto index = lynx::builtInTemplateIndex ("Empty");
- return index >= 0 ? lynx::makeNewProject (index) : lynx::makeNewProject();
- };
- offline.setSong (emptyProject());
- settle();
- check ("the new project is empty for the Simple workflow (it opens on the chooser)", lynx::simpletracks::isEmptySong (offline.getSong()));
- simple->showWelcome();
- settle();
- check ("Help › Welcome screen shows it", tour->isWelcomeShowing());
- window ("welcome");
- if (auto* w = tour->welcomeForSnapshot())
- writeImage (w->createComponentSnapshot (w->getLocalBounds(), true, 2.0f), "welcome@2x");
- tour->clickForSnapshot ("welcome.tour");
- settle();
- check ("Make my first song: the Welcome screen closes, the tour starts, the chooser comes up for the beat",
- ! tour->isWelcomeShowing() && tour->isRunning() && simple->isChooserShowing());
- // --- step 1: the beat ---------------------------------------------------------------------------------------------
- stepIs (lynx::tour::beat, "simple.tile.drums");
- window ("step1-beat", true);
- simple->showStarterPageForSnapshot();
- stepIs (lynx::tour::beat, "simple.starters");
- window ("step1-beat-starters");
- tour->clickForSnapshot ("do");
- settle();
- check ("Do it for me added a starter beat", lynx::tour::hasBeat (offline.getSong()));
- // --- step 2: the key ----------------------------------------------------------------------------------------------
- stepIs (lynx::tour::key, "toolbar.key");
- window ("step2-key", true);
- tour->clickForSnapshot ("do");
- settle();
- check ("Do it for me set A minor", lynx::projectkey::get (offline.getSong()).has_value());
- // --- step 3: an instrument (Add track opens the chooser: the ring moves to its tile) ------------------------------
- stepIs (lynx::tour::instrument, "simple.addTrack");
- window ("step3-instrument", true);
- simple->showChooser();
- stepIs (lynx::tour::instrument, "simple.tile.instrument");
- window ("step3-instrument-chooser");
- tour->clickForSnapshot ("do");
- settle();
- check ("Do it for me added an Instrument track (the chooser closed)", lynx::tour::firstInstrumentTrack (offline.getSong()) >= 0 && ! simple->isChooserShowing());
- // --- step 4: chords -----------------------------------------------------------------------------------------------
- stepIs (lynx::tour::chords, "keyboard.chordPad");
- window ("step4-chords", true);
- tour->clickForSnapshot ("do");
- settle();
- check ("Do it for me wrote four chords (12 notes) on the instrument's pattern", [&] {
- const auto& song = offline.getSong();
- const auto p = lynx::simpletracks::patternOf (song, lynx::tour::firstInstrumentTrack (song));
- return p >= 0 && song.patterns[(std::size_t) p].notes.size() == 12;
- }());
- // --- step 5: a voice or a loop (no "Do it for me": a loop is dropped as a user would) ------------------------------
- stepIs (lynx::tour::loop, "simple.addTrack");
- window ("step5-loop", true);
- {
- const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-190dv-loops");
- dir.deleteRecursively();
- dir.createDirectory();
- const auto wav = dir.getChildFile ("Warm Keys 120 Am.wav");
- const int frames = 192000;
- juce::AudioBuffer<float> audio (1, frames);
- for (int i = 0; i < frames; ++i)
- {
- const auto t = (double) i / 48000.0;
- double v = 0.0;
- for (const auto key : { 57, 60, 64 })
- v += std::sin (2.0 * juce::MathConstants<double>::pi * 440.0 * std::pow (2.0, (key - 69) / 12.0) * t);
- audio.setSample (0, i, (float) (0.1 * v * (1.0 - std::exp (-std::fmod (t, 0.5) * 60.0))));
- }
- {
- juce::WavAudioFormat format;
- 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 (audio, 0, frames);
- }
- }
- simple->dropFiles ({ wav.getFullPathName() }, 0);
- settle();
- check ("a dropped loop (A minor in its name) follows the key", [&] {
- for (const auto& c : offline.getSong().playlist)
- if (c.kind == lynx::ClipKind::audio)
- return c.followKey;
- return false;
- }());
- }
- // --- step 6: a one-knob effect --------------------------------------------------------------------------------------
- stepIs (lynx::tour::effect, "simple.dock.addEffect");
- window ("step6-effect", true);
- tour->clickForSnapshot ("do");
- settle();
- check ("Do it for me put Room on the instrument track", lynx::tour::hasOneKnob (offline.getSong()));
- // --- step 7: Finish -----------------------------------------------------------------------------------------------
- stepIs (lynx::tour::finish, "simple.finish");
- window ("step7-finish", true);
- tour->clickForSnapshot ("do");
- settle();
- check ("Do it for me opened Finish and chose Balanced", simple->isFinishShowing() && lynx::looks::present (offline.getSong()));
- // --- the end card, Back / Next, close -------------------------------------------------------------------------------
- settle();
- check ("the end card", tour->isRunning() && tour->step() == lynx::tour::stepCount);
- window ("end", true);
- tour->clickForSnapshot ("back");
- settle();
- check ("Back: the Finish step again, shown done (the tour waits for Next)", tour->step() == lynx::tour::finish
- && tour->machineForCheck().shownDone (offline.getSong()));
- window ("back-done", true);
- tour->clickForSnapshot ("next");
- settle();
- check ("Next: the end card again", tour->step() == lynx::tour::stepCount);
- check ("all seven steps done by the song", tour->machineForCheck().state().completed == 0x7fu);
- tour->clickForSnapshot ("close");
- settle();
- check ("closing the end card ends the tour (not continued from Help)", ! tour->isRunning() && ! tour->canContinue()
- && tour->machineForCheck().state().done);
- line ("-- paused tour");
- // --- a paused tour, the Help menu and the chooser's button ---------------------------------------------------------
- offline.setSong (emptyProject());
- settle();
- tour->machineForCheck() = lynx::tour::Machine {};
- simple->startOrContinueTour();
- settle();
- line ("-- do beat");
- simple->doTourStep (lynx::tour::beat);
- settle();
- check ("a new tour on an empty project: the beat done moves it to the key", tour->step() == lynx::tour::key);
- tour->clickForSnapshot ("close");
- settle();
- check ("closing the card pauses the tour (Help continues it)", ! tour->isRunning() && tour->canContinue());
- line ("-- help menu");
- {
- const auto help = ui.getMenuForSnapshot (ui.getMenuNamesForSnapshot().indexOf (lynx::tr ("Help")));
- bool continueItem = false, welcomeItem = false;
- for (juce::PopupMenu::MenuItemIterator it (help); it.next();)
- {
- continueItem = continueItem || it.getItem().text.startsWith (lynx::tr ("Continue the first-song tour (step {0} of {1})", { "2", "7" }));
- welcomeItem = welcomeItem || it.getItem().text == lynx::tr ("Welcome screen...");
- }
- check ("Help: Continue the first-song tour (step 2 of 7) and Welcome screen...", continueItem && welcomeItem);
- saveMenus ({ lynx::tr ("Help") }, { help }, prefix + "-menu-help.png");
- }
- simple->startOrContinueTour();
- settle();
- check ("Help › Continue: back on the key step", tour->isRunning() && tour->step() == lynx::tour::key);
- tour->clickForSnapshot ("skip");
- settle();
- check ("Skip tour ends it", ! tour->isRunning() && ! tour->canContinue());
- offline.setSong (emptyProject());
- settle();
- simple->showChooser();
- window ("chooser");
- line ("-- start from");
- // --- Start from: the three demo songs; a demo opened in Simple -------------------------------------------------------
- if (auto* start = simple->startFromForSnapshot())
- {
- settle();
- writeImage (start->createComponentSnapshot (start->getLocalBounds(), true, 1.0f), "startfrom");
- const auto list = lynx::startfrom::entries();
- int demos = 0;
- for (const auto& e : list)
- demos += e.kind == lynx::startfrom::Entry::Kind::demo && e.playable ? 1 : 0;
- check ("Start from lists three playable demo songs first", demos == 3 && list.size() >= 3 && list[1].demo == 1 && list[2].demo == 2);
- for (int d = 1; d < 3 && d < (int) list.size(); ++d)
- line ("demo " + list[(std::size_t) d].name + ": " + juce::String (list[(std::size_t) d].bpm) + " BPM, " + juce::String (list[(std::size_t) d].bars) + " bars");
- simple->hideStartFrom();
- }
- line ("-- demos");
- for (int d = 1; d < lynx::demos::count; ++d)
- {
- offline.setSong (lynx::demos::make (d));
- settle();
- simple->hideChooser();
- window (juce::String ("demo-") + (d == 1 ? "hiphop" : "pop"));
- // the committed file is the generated song
- const auto file = juce::File::getCurrentWorkingDirectory().getChildFile ("resources/demos").getChildFile (lynx::demos::fileName (d));
- juce::String error;
- const auto loaded = lynx::ProjectFile::load (file, error);
- check ("resources/demos/" + juce::String (lynx::demos::fileName (d)) + " loads and is the generated song",
- loaded.has_value() && lynx::ProjectFile::toJson (*loaded, false) == lynx::ProjectFile::toJson (lynx::demos::make (d), false));
- }
- line (report.contains ("ERROR ") ? "RESULT ERROR" : "RESULT OK");
- juce::File (prefix + "-report.txt").replaceWithText (report);
- }
- // --patterns190ea (round 190ea): FL keeps at least one pattern; the engine now does too (AudioEngine::publishSong,
- // Song::keepOnePattern). Before, a Song without a pattern crashed the docked Piano roll's listener.
- bool runPatterns190ea (const juce::String& reportPath)
- {
- namespace st = lynx::simpletracks;
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- lynx::AudioEngine offline (false);
- lynx::MainComponent ui (offline, false);
- ui.setSize (1600, 900);
- ui.setVisible (true); // (no window: the docked editor only needs its parents visible)
- juce::String report;
- bool ok = true;
- const auto check = [&report, &ok] (const juce::String& what, bool good) {
- report << (good ? "OK " : "ERROR ") << what << "\n";
- ok = ok && good;
- };
- const auto save = [&report, &reportPath] { juce::File (reportPath).replaceWithText (report); };
- const auto settle = [&] { offline.dispatchPendingMessages(); ui.getPianoRollForSnapshot().repaint(); };
- const auto onePattern = [&offline] {
- const auto& s = offline.getSong();
- return s.patterns.size() >= 1 && s.currentPattern >= 0 && s.currentPattern < (int) s.patterns.size();
- };
- // the hand-built songs the engine can be given: none of them has a pattern
- const auto bare = [] {
- lynx::Song s;
- s.mixer = lynx::Song::defaultMixer();
- return s;
- };
- // every way to reach "no pattern" in the current layout
- const auto paths = [&] (const juce::String& where) {
- offline.setSong (bare());
- settle();
- check (where + ": a song without a pattern opens with one empty \"Pattern 1\"",
- onePattern() && offline.getSong().patterns.size() == 1 && offline.getSong().patterns[0].name == "Pattern 1"
- && offline.getSong().patterns[0].notes.empty());
- offline.editSong ([] (lynx::Song& s) { s.patterns.clear(); });
- settle();
- check (where + ": an edit that clears every pattern leaves one", onePattern());
- offline.editSong ([] (lynx::Song& s) {
- s.patterns.resize (2);
- s.patterns[1].notes.push_back ({});
- s.currentPattern = 1;
- });
- settle();
- offline.editSong ([] (lynx::Song& s) { s.removePattern (s.currentPattern); });
- offline.editSong ([] (lynx::Song& s) { s.removePattern (s.currentPattern); });
- settle();
- check (where + ": deleting the last pattern leaves an empty \"Pattern 1\" (FL's invariant)",
- onePattern() && offline.getSong().patterns.size() == 1 && offline.getSong().patterns[0].notes.empty());
- for (int k = 0; k < 6; ++k)
- {
- offline.undo();
- settle();
- }
- check (where + ": undo back over those steps keeps a pattern", onePattern());
- for (int k = 0; k < 6; ++k)
- {
- offline.redo();
- settle();
- }
- check (where + ": redo keeps a pattern", onePattern());
- offline.applyRemote (bare());
- settle();
- check (where + ": a live session's remote song without a pattern gets one", onePattern());
- offline.editSong ([] (lynx::Song& s) { s.currentPattern = 99; });
- settle();
- check (where + ": a current pattern out of range is put back in range", onePattern() && offline.getSong().currentPattern == 0);
- };
- // the Simple layout with the Piano roll docked in the Editor tab (round 190dv's crash)
- ui.selectTabForSnapshot (2);
- ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
- settle();
- auto* simple = ui.getSimpleWorkflowForSnapshot();
- check ("the Simple workflow is up", simple != nullptr);
- if (simple == nullptr)
- {
- save();
- return false;
- }
- simple->hideChooser();
- st::Request q;
- q.kind = st::Kind::instrument;
- q.name = "Keys";
- lynx::ChannelDef synth;
- synth.instrument = lynx::InstrumentKind::synth;
- q.channel = synth;
- q.emptyBars = 4;
- st::Result r;
- offline.editSong ([&] (lynx::Song& s) { r = st::addTrack (s, q); });
- settle();
- ui.getPlaylistForSnapshot().selectTrack (r.track);
- simple->trackSelected (r.track);
- settle();
- auto* dock = simple->dockForSnapshot();
- check ("the instrument track's dock has the Editor tab", dock != nullptr && dock->hasPlayTabsForCheck());
- if (dock != nullptr)
- dock->setTab (lynx::SimpleDock::Tab::editor);
- settle();
- check ("the Piano roll is docked in the Editor tab", dock != nullptr && dock->isEditorDocked() && dock->isParentOf (&ui.getPianoRollForSnapshot()));
- paths ("Simple, Editor tab");
- // the Pattern layout with the Piano roll panel, then the Clip-launch layout
- ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
- settle();
- ui.showPanelsForSnapshot ({ lynx::workspace::Panel::pianoRoll });
- settle();
- paths ("Pattern layout, Piano roll");
- ui.setLayoutStyle (lynx::layoutstyle::Style::clipLaunch);
- settle();
- paths ("Clip-launch layout");
- report << (ok ? "RESULT OK\n" : "RESULT FAILED\n");
- save();
- return ok;
- }
- // round 190fo: the Simple layout's Sampler track (16 pads) and a folder of stems and MIDI files, off-screen at 1x and
- // 2x, with a text report of the checks (.lynx round trip, kits, typing keys, the folder import)
- void runReabl190foShot (const juce::String& prefix)
- {
- namespace st = lynx::simpletracks;
- namespace sp = lynx::simplepads;
- 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()));
- ui.setVisible (true);
- const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
- const auto file = juce::File (prefix + "-" + name + ".png");
- file.deleteFile();
- juce::FileOutputStream out (file);
- juce::PNGImageFormat().writeImageToStream (image, out);
- };
- juce::String report;
- const auto line = [&report] (const juce::String& text) { report << text << "\n"; };
- const auto check = [&report] (const juce::String& what, bool ok) { report << (ok ? "OK " : "ERROR ") << what << "\n"; };
- ui.selectTabForSnapshot (2);
- ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
- offline.dispatchPendingMessages();
- auto* simple = ui.getSimpleWorkflowForSnapshot();
- if (simple == nullptr)
- {
- juce::File (prefix + "-report.txt").replaceWithText ("ERROR no Simple workflow\n");
- return;
- }
- const auto whole = [&] (const juce::String& name) {
- offline.dispatchPendingMessages();
- for (float scale : { 1.0f, 2.0f })
- writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), name + (scale > 1.0f ? "@2x" : ""));
- };
- // the chooser: the Sampler tile (16 pads, "On keys..." for one sample over the keys) and Import's "Folder..."
- simple->showChooser();
- whole ("chooser");
- simple->hideChooser();
- // --- test sounds -------------------------------------------------------------------------------------------------
- const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-190fo");
- dir.deleteRecursively();
- dir.createDirectory();
- const auto writeWav = [] (const juce::File& wav, int frames, const std::function<float (int)>& f) {
- juce::AudioBuffer<float> audio (1, frames);
- for (int i = 0; i < frames; ++i)
- audio.setSample (0, i, f (i));
- wav.getParentDirectory().createDirectory();
- juce::WavAudioFormat format;
- 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 (audio, 0, frames);
- }
- return wav;
- };
- juce::Random rnd (190);
- const auto pi = juce::MathConstants<double>::pi;
- const auto kick = writeWav (dir.getChildFile ("pads/Kick.wav"), 24000, [pi] (int i) {
- const auto t = i / 48000.0;
- return (float) (0.9 * std::sin (2.0 * pi * (50.0 * t + 60.0 * (1.0 - std::exp (-t * 30.0)) / 30.0)) * std::exp (-t * 7.0));
- });
- const auto snare = writeWav (dir.getChildFile ("pads/Snare.wav"), 14400, [&rnd] (int i) { return (float) ((rnd.nextFloat() * 2.0f - 1.0f) * 0.6f * std::exp (-i / 4000.0f)); });
- const auto hat = writeWav (dir.getChildFile ("pads/Hat.wav"), 4800, [&rnd] (int i) { return (float) ((rnd.nextFloat() * 2.0f - 1.0f) * 0.4f * std::exp (-i / 900.0f)); });
- const auto chord = writeWav (dir.getChildFile ("pads/Chord stab.wav"), 48000, [pi] (int i) {
- const auto t = i / 48000.0;
- double v = 0.0;
- for (int k : { 57, 60, 64 })
- v += std::sin (2.0 * pi * 440.0 * std::pow (2.0, (k - 69) / 12.0) * t);
- return (float) (0.2 * v * std::exp (-t * 2.5));
- });
- const auto vox = writeWav (dir.getChildFile ("pads/Vox hey.wav"), 30000, [pi] (int i) {
- const auto t = i / 48000.0;
- return (float) (0.5 * std::sin (2.0 * pi * 220.0 * t + 2.0 * std::sin (2.0 * pi * 660.0 * t)) * std::sin (pi * t / 0.625));
- });
- // --- the Sampler track ---------------------------------------------------------------------------------------------
- check ("the Sampler tile's track was added", simple->addPads());
- offline.dispatchPendingMessages();
- const auto& song0 = offline.getSong();
- int track = -1;
- for (int t = 0; t < (int) song0.playlistTracks.size() && track < 0; ++t)
- if (st::kindOf (song0, t) == st::Kind::pads)
- track = t;
- check ("a Sampler track with 16 pads", track >= 0 && [&] {
- const auto c = sp::padChannels (song0, track);
- return std::all_of (c.begin(), c.end(), [] (int i) { return i >= 0; });
- }());
- auto* dock = simple->dockForSnapshot();
- if (dock == nullptr || track < 0)
- {
- juce::File (prefix + "-report.txt").replaceWithText (report + "ERROR no dock / track\n");
- return;
- }
- simple->trackSelected (track);
- offline.dispatchPendingMessages();
- check ("the dock opens on the Pads tab", dock->hasPadsTabForCheck() && dock->getTab() == lynx::SimpleDock::Tab::pads);
- const auto shots = [&] (const juce::String& name) {
- offline.dispatchPendingMessages();
- for (float scale : { 1.0f, 2.0f })
- {
- const auto suffix = scale > 1.0f ? juce::String ("@2x") : juce::String();
- writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), name + suffix);
- writeImage (dock->createComponentSnapshot (dock->getLocalBounds(), true, scale), "dock-" + name + suffix);
- }
- };
- shots ("pads-empty");
- const juce::File files[] { kick, snare, hat, hat, chord, vox };
- for (int p = 0; p < 6; ++p)
- dock->padsLoadForCheck (p, files[p]);
- offline.dispatchPendingMessages();
- check ("six pads hold a sound", [&] {
- int n = 0;
- for (int p = 0; p < sp::padCount; ++p)
- n += sp::hasSample (offline.getSong(), track, p) ? 1 : 0;
- return n == 6;
- }());
- // pad 3 = the open hat: one-shot, group 1 with pad 2 (closed hat), a colour; pad 4 = the chord, looped and darker
- dock->padsSelectForCheck (2);
- dock->padsModeForCheck (1);
- dock->padsSelectForCheck (3);
- dock->padsModeForCheck (1);
- offline.editSong ([track] (lynx::Song& s) {
- for (int p : { 2, 3 })
- if (const auto c = sp::padChannel (s, track, p); c >= 0)
- {
- s.channels[(std::size_t) c].simplePad.group = 1;
- s.channels[(std::size_t) c].simplePad.colour = 2;
- sp::apply (s.channels[(std::size_t) c], 4800);
- }
- });
- dock->padsSelectForCheck (4);
- dock->padsModeForCheck (2);
- dock->padsKnobForCheck (2, 0.3f); // tone: a low-pass
- dock->padsKnobForCheck (1, 0.35f); // release
- dock->padsRegionForCheck (0.05f, 0.7f);
- dock->padsNormalizeForCheck();
- dock->padsUpdateForCheck();
- {
- const auto& s = offline.getSong();
- const auto& c = s.channels[(std::size_t) sp::padChannel (s, track, 4)];
- line ("pad 5: mode " + juce::String ((int) c.simplePad.mode) + " tone " + juce::String (c.simplePad.tone, 2) + " cutoff " + juce::String (c.sampler.cutoff, 0)
- + " release " + juce::String (c.sampler.release, 3) + " region " + juce::String (c.sampler.regionStart, 2) + "-" + juce::String (c.sampler.regionEnd, 2)
- + " gain " + juce::String (c.sampler.gainDb, 2) + " dB zones " + juce::String ((int) c.zones.size()));
- check ("pad 5 loops its region, darker, normalized", c.simplePad.mode == 2 && c.zones.size() == 1 && c.zones[0].loopMode == 2 && c.simplePad.tone < -0.3f
- && c.sampler.filterType == 0 && c.sampler.cutoff < 5000.0f && c.sampler.gainDb > 0.5f);
- const auto& h = s.channels[(std::size_t) sp::padChannel (s, track, 3)];
- check ("the hats share a choke group of this insert", h.cutGroup > 1000 && h.cutGroup == s.channels[(std::size_t) sp::padChannel (s, track, 2)].cutGroup);
- }
- shots ("pads");
- dock->padsHitForCheck (0);
- dock->lightPad (2);
- shots ("pads-hit");
- // the typing keys: V plays pad 1, M pad 4, 7 pad 16; Z is not a pad key
- check ("typing keys reach the pads", simple->padChannelForKey ('V') == sp::padChannel (offline.getSong(), track, 0)
- && simple->padChannelForKey ('m') == sp::padChannel (offline.getSong(), track, 3)
- && simple->padChannelForKey ('7') == sp::padChannel (offline.getSong(), track, 15)
- && simple->padChannelForKey ('Z') == -1);
- // drag pad 6 (vox) onto the empty pad 9: it moves; Alt-drag pad 1 onto pad 10: a copy
- dock->padsDragForCheck (5, 8, false);
- dock->padsDragForCheck (0, 9, true);
- check ("a pad moved and a pad copied", ! sp::hasSample (offline.getSong(), track, 5) && sp::hasSample (offline.getSong(), track, 8)
- && sp::hasSample (offline.getSong(), track, 9) && sp::hasSample (offline.getSong(), track, 0));
- dock->padsSelectForCheck (4);
- shots ("pads-moved");
- saveMenus ({ "Pad menu", "Colour", "Copy a value to every pad" }, [&] {
- const auto top = dock->padMenuForSnapshot (4);
- std::vector<juce::PopupMenu> menus { top };
- for (juce::PopupMenu::MenuItemIterator it (top); it.next();)
- if (it.getItem().subMenu != nullptr)
- menus.push_back (*it.getItem().subMenu);
- return menus;
- }(), prefix + "-menu-pad.png");
- // kits: saved, the pads cleared, opened again
- const auto kitFile = lynx::platform::documentsFolder().getChildFile ("LYNX/Sampler kits/Test kit 190fo.lynxkit");
- kitFile.deleteFile();
- check ("the pads saved as a kit", dock->saveKitForCheck ("Test kit 190fo") && kitFile.existsAsFile());
- saveMenus ({ "Kit", "My kits" }, [&] {
- const auto top = dock->kitMenuForSnapshot();
- std::vector<juce::PopupMenu> menus { top };
- for (juce::PopupMenu::MenuItemIterator it (top); it.next();)
- if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::tr ("My kits"))
- menus.push_back (*it.getItem().subMenu);
- return menus;
- }(), prefix + "-menu-kit.png");
- const auto before = offline.getSong().channels;
- offline.editSong ([track] (lynx::Song& s) {
- for (int p = 0; p < sp::padCount; ++p)
- sp::clearPad (s, track, p);
- });
- check ("the kit opens the same pads again", dock->openKitForCheck (kitFile) && [&] {
- const auto& now = offline.getSong().channels;
- for (int p = 0; p < sp::padCount; ++p)
- {
- const auto c = sp::padChannel (offline.getSong(), track, p);
- if (c < 0 || now[(std::size_t) c].samplePath != before[(std::size_t) c].samplePath || now[(std::size_t) c].simplePad != before[(std::size_t) c].simplePad
- || now[(std::size_t) c].sampler.release != before[(std::size_t) c].sampler.release || now[(std::size_t) c].zones != before[(std::size_t) c].zones)
- return false;
- }
- return true;
- }());
- {
- const auto renamed = kitFile.getSiblingFile ("Renamed kit 190fo.lynxkit");
- renamed.deleteFile();
- check ("a kit renamed (and a one-letter name refused)", ! lynx::SimpleDock::renameKitForCheck (kitFile, "x")
- && lynx::SimpleDock::renameKitForCheck (kitFile, "Renamed kit 190fo") && renamed.existsAsFile()
- && ! kitFile.exists());
- renamed.deleteFile();
- }
- kitFile.deleteFile();
- // a beat on the pads (the track's pattern) and the .lynx round trip
- offline.editSong ([track] (lynx::Song& s) {
- const auto pattern = [&] {
- for (const auto& c : s.playlist)
- if (c.track == track && c.kind == lynx::ClipKind::pattern)
- return c.pattern;
- return -1;
- }();
- if (pattern < 0)
- return;
- for (int step = 0; step < 16; ++step)
- {
- const int pad = step % 4 == 0 ? 0 : step % 8 == 4 ? 1 : 2;
- lynx::Note n;
- n.channel = sp::padChannel (s, track, pad);
- n.key = sp::padKey;
- n.start = (std::int64_t) step * lynx::ticksPerStep;
- n.length = lynx::ticksPerStep;
- s.patterns[(std::size_t) pattern].notes.push_back (n);
- }
- });
- {
- const auto json = lynx::ProjectFile::toJson (offline.getSong());
- juce::String error;
- const auto back = lynx::ProjectFile::fromJson (json, error);
- bool same = back.has_value() && back->channels.size() == offline.getSong().channels.size() && st::kindOf (*back, track) == st::Kind::pads;
- for (std::size_t c = 0; same && c < back->channels.size(); ++c)
- {
- const auto& a = back->channels[c];
- const auto& b = offline.getSong().channels[c];
- same = a.simplePad == b.simplePad && a.zones == b.zones && a.cutGroup == b.cutGroup && a.cutBy == b.cutBy && a.samplePath == b.samplePath
- && a.sampler.regionStart == b.sampler.regionStart && a.sampler.release == b.sampler.release && a.sampler.cutoff == b.sampler.cutoff;
- }
- check ("pads, their modes, groups and loops survive .lynx", same);
- lynx::Song plain = lynx::Song::makeDefault();
- check ("a project without pads writes no pad field", ! lynx::ProjectFile::toJson (plain).contains ("simplePad"));
- }
- ui.getPlaylistForSnapshot().selectTrack (track);
- // --- a folder of stems and MIDI files (the other app's "download stems" naming) --------------------------------------
- const auto stems = dir.getChildFile ("My song stems");
- writeWav (stems.getChildFile ("01_Drums.wav"), 96000, [&rnd] (int i) { return (i % 24000) < 2000 ? (rnd.nextFloat() - 0.5f) * 0.8f : 0.0f; });
- writeWav (stems.getChildFile ("02_Bass.wav"), 96000, [pi] (int i) { return (float) (0.3 * std::sin (2.0 * pi * 55.0 * i / 48000.0)); });
- writeWav (stems.getChildFile ("10_Lead Vox.wav"), 96000, [pi] (int i) { return (float) (0.2 * std::sin (2.0 * pi * 330.0 * i / 48000.0)); });
- {
- juce::MidiMessageSequence seq;
- for (int k = 0; k < 8; ++k)
- {
- seq.addEvent (juce::MidiMessage::noteOn (1, 36 + (k % 4) * 3, (juce::uint8) 100), k * 480.0);
- seq.addEvent (juce::MidiMessage::noteOff (1, 36 + (k % 4) * 3), k * 480.0 + 400.0);
- }
- seq.updateMatchedPairs();
- juce::MidiFile midi;
- midi.setTicksPerQuarterNote (960);
- midi.addTrack (seq);
- for (const auto& name : { "02_Bass.mid", "03_Keys.mid" })
- {
- juce::FileOutputStream out (stems.getChildFile (name));
- midi.writeTo (out);
- }
- }
- const auto tracksBefore = [&] {
- int n = 0;
- for (int t = 0; t < (int) offline.getSong().playlistTracks.size(); ++t)
- n += st::kindOf (offline.getSong(), t).has_value() ? 1 : 0;
- return n;
- }();
- simple->addFilesForCheck ({ stems });
- offline.dispatchPendingMessages();
- {
- const auto& s = offline.getSong();
- juce::StringArray names;
- int muted = 0, count = 0;
- for (int t = 0; t < (int) s.playlistTracks.size(); ++t)
- if (st::kindOf (s, t).has_value())
- {
- ++count;
- if (count > tracksBefore)
- {
- names.add (juce::String::fromUTF8 (s.playlistTracks[(std::size_t) t].name.c_str()) + (s.playlistTracks[(std::size_t) t].muted ? " (muted)" : ""));
- muted += s.playlistTracks[(std::size_t) t].muted ? 1 : 0;
- }
- }
- line ("folder tracks: " + names.joinIntoString (", "));
- check ("the folder gave 5 tracks in number order, named without numbers, the Bass notes muted (its stem plays)",
- names == juce::StringArray { "Drums", "Bass", "Lead Vox", "Bass 2 (muted)", "Keys" } && muted == 1);
- bool atZero = true;
- for (const auto& c : s.playlist)
- if (c.track >= 0 && st::kindOf (s, c.track) == st::Kind::audio)
- atZero = atZero && c.start == 0;
- check ("every stem starts at the song's start", atZero);
- }
- simple->hideChooser();
- whole ("folder-import");
- dir.deleteRecursively();
- line (report.contains ("ERROR ") ? "RESULT ERROR" : "RESULT OK");
- juce::File (prefix + "-report.txt").replaceWithText (report);
- }
- void runSimple190dsShot (const juce::String& prefix)
- {
- namespace st = lynx::simpletracks;
- 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()));
- ui.setVisible (true); // (no window: the docked editor only needs its parents visible)
- const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
- const auto file = juce::File (prefix + "-" + name + ".png");
- file.deleteFile();
- juce::FileOutputStream out (file);
- juce::PNGImageFormat().writeImageToStream (image, out);
- };
- juce::String report;
- const auto line = [&report] (const juce::String& text) { report << text << "\n"; };
- const auto check = [&report] (const juce::String& what, bool ok) { report << (ok ? "OK " : "ERROR ") << what << "\n"; };
- ui.selectTabForSnapshot (2);
- ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
- offline.dispatchPendingMessages();
- auto* simple = ui.getSimpleWorkflowForSnapshot();
- if (simple == nullptr)
- {
- juce::File (prefix + "-report.txt").replaceWithText ("ERROR no Simple workflow\n");
- return;
- }
- simple->hideChooser();
- auto& playlist = ui.getPlaylistForSnapshot();
- // --- three loops: two with their key in the name, one only in its sound ---------------------------------------
- const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-190ds-loops");
- dir.deleteRecursively();
- dir.createDirectory();
- // a chord loop (two bars at 120 BPM, 48 kHz): each chord's notes with six harmonics, a soft attack per beat
- const auto writeLoop = [&dir] (const juce::String& name, std::vector<std::vector<int>> chords) {
- const int frames = 192000;
- juce::AudioBuffer<float> audio (1, frames);
- audio.clear();
- for (int i = 0; i < frames; ++i)
- {
- const auto& chord = chords[(std::size_t) (i / (frames / (int) chords.size()))];
- const auto t = (double) i / 48000.0;
- const auto beat = std::fmod (t, 0.5);
- double v = 0.0;
- for (const auto key : chord)
- {
- const auto f = 440.0 * std::pow (2.0, (key - 69) / 12.0);
- for (int h = 1; h <= 6; ++h)
- v += std::sin (2.0 * juce::MathConstants<double>::pi * f * h * t) / (h * h);
- }
- audio.setSample (0, i, (float) (0.08 * v * (1.0 - std::exp (-beat * 60.0)) * (0.6 + 0.4 * std::exp (-beat * 3.0))));
- }
- const auto wav = dir.getChildFile (name);
- juce::WavAudioFormat format;
- 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 (audio, 0, frames);
- }
- return wav.getFullPathName();
- };
- const auto gMinor = writeLoop ("Night Pad 120 Gm.wav", { { 55, 58, 62 }, { 51, 55, 58 }, { 53, 57, 60 }, { 55, 58, 62 } });
- const auto dMinor = writeLoop ("Pluck_120_D_minor.wav", { { 50, 53, 57 }, { 46, 50, 53 }, { 48, 52, 55 }, { 50, 53, 57 } });
- const auto eMinor = writeLoop ("Warm Keys Loop 120 bpm.wav", { { 52, 55, 59, 64 }, { 48, 52, 55, 60 }, { 50, 54, 57, 62 }, { 52, 55, 59, 64 } });
- lynx::SimpleWorkflow::answerForSnapshot = 1; // "Set the project key to G minor?" — yes
- simple->dropFiles ({ gMinor, dMinor, eMinor }, 0);
- lynx::SimpleWorkflow::answerForSnapshot = -1;
- offline.dispatchPendingMessages();
- simple->hideChooser();
- line ("question: " + simple->lastKeyQuestionForCheck());
- check ("the first keyed loop offered its key (G minor)", simple->lastKeyQuestionForCheck().contains ("G minor"));
- {
- const auto& song = offline.getSong();
- const auto key = lynx::projectkey::get (song);
- check ("the project key is G minor", key && key->root == 7 && lynx::projectkey::isMinor (*key));
- std::vector<int> clips;
- for (int i = 0; i < (int) song.playlist.size(); ++i)
- if (song.playlist[(std::size_t) i].kind == lynx::ClipKind::audio)
- clips.push_back (i);
- check ("three loop clips", clips.size() == 3);
- const int expect[] { 0, 5, 3 }; // G minor, D minor (F -> Bb: +5), E minor detected (G -> Bb: +3)
- const int roots[] { 7, 2, 4 };
- const int sources[] { 1, 1, 2 };
- for (std::size_t k = 0; k < clips.size() && k < 3; ++k)
- {
- const auto& c = song.playlist[(std::size_t) clips[k]];
- const auto& sampler = song.channels[(std::size_t) c.channel].sampler;
- line ("loop " + juce::String ((int) k + 1) + ": key " + juce::String (sampler.loopKeyRoot) + (sampler.loopKeyMinor ? "m" : "") + " source "
- + juce::String ((int) sampler.loopKeySource) + " follow " + juce::String (c.followKey ? 1 : 0) + " shift " + juce::String ((int) c.keyShift)
- + " pitch " + juce::String (c.pitch));
- check ("loop " + juce::String ((int) k + 1) + " key, source and move", sampler.loopKeyRoot == roots[k] && sampler.loopKeyMinor
- && sampler.loopKeySource == sources[k] && c.followKey
- && c.keyShift == expect[k] && std::abs (c.pitch - (float) expect[k]) < 1.0e-4f);
- }
- }
- // the key changes: every following loop moves with it (one undo step)
- offline.editSong ([] (lynx::Song& s) { lynx::projectkey::set (s, lynx::projectkey::Key { 9, lynx::projectkey::commonFirst()[1] }); });
- offline.dispatchPendingMessages();
- {
- const auto& song = offline.getSong();
- std::vector<int> shifts;
- for (const auto& c : song.playlist)
- if (c.kind == lynx::ClipKind::audio)
- shifts.push_back (c.keyShift);
- line ("after A minor: " + juce::String (shifts.size() > 2 ? shifts[0] : 99) + " " + juce::String (shifts.size() > 2 ? shifts[1] : 99) + " "
- + juce::String (shifts.size() > 2 ? shifts[2] : 99));
- check ("A minor: the loops move by +2, -5, +5", shifts == std::vector<int> { 2, -5, 5 });
- }
- // the loop tracks in the dock: the switch and what it does
- int loopTrack = -1;
- for (const auto& c : offline.getSong().playlist)
- if (c.kind == lynx::ClipKind::audio && loopTrack < 0)
- loopTrack = c.track;
- playlist.selectTrack (loopTrack);
- offline.dispatchPendingMessages();
- auto* dock = simple->dockForSnapshot();
- if (dock == nullptr)
- {
- juce::File (prefix + "-report.txt").replaceWithText (report + "ERROR no dock\n");
- return;
- }
- simple->trackSelected (loopTrack);
- offline.dispatchPendingMessages();
- const auto shots = [&] (const juce::String& name) {
- offline.dispatchPendingMessages();
- for (float scale : { 1.0f, 2.0f })
- {
- const auto suffix = scale > 1.0f ? juce::String ("@2x") : juce::String();
- writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), name + suffix);
- writeImage (dock->createComponentSnapshot (dock->getLocalBounds(), true, scale), "dock-" + name + suffix);
- }
- };
- const auto menuShot = [&] (const juce::PopupMenu& menu, const juce::String& title, const juce::String& subTitle, const juce::String& name) {
- juce::StringArray names { title };
- std::vector<juce::PopupMenu> menus { menu };
- for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
- if (it.getItem().subMenu != nullptr && it.getItem().text.startsWith (subTitle))
- {
- names.add (subTitle);
- menus.push_back (*it.getItem().subMenu);
- }
- saveMenus (names, menus, prefix + "-" + name + ".png");
- };
- check ("the dock shows the follow switch for the loop track", dock->followShownForCheck());
- shots ("follow-on");
- {
- int clip = -1;
- for (int i = 0; i < (int) offline.getSong().playlist.size() && clip < 0; ++i)
- if (offline.getSong().playlist[(std::size_t) i].kind == lynx::ClipKind::audio)
- clip = i;
- const auto menu = playlist.getClipMenuForSnapshot (clip);
- bool follow = false, keyItem = false;
- for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
- {
- follow = follow || (it.getItem().text.startsWith (lynx::tr ("Follow the project key")) && it.getItem().isTicked);
- keyItem = keyItem || it.getItem().text.startsWith (lynx::tr ("Loop key"));
- }
- check ("the clip menu has Follow the project key (ticked) and Loop key", follow && keyItem);
- menuShot (menu, lynx::tr ("Audio clip"), lynx::tr ("Loop key"), "menu-clip-key");
- }
- dock->clickFollowForCheck(); // off: back to its own key
- offline.dispatchPendingMessages();
- {
- float pitch = 99.0f;
- bool following = true;
- for (const auto& c : offline.getSong().playlist)
- if (c.kind == lynx::ClipKind::audio && c.track == loopTrack)
- pitch = c.pitch, following = c.followKey;
- check ("switched off: the loop plays in its own key (pitch 0)", ! following && std::abs (pitch) < 1.0e-6f);
- }
- shots ("follow-off");
- dock->clickFollowForCheck();
- offline.dispatchPendingMessages();
- // --- an instrument track from the tile: a pattern to write into, the Editor tab ------------------------------
- {
- st::Request q;
- q.kind = st::Kind::instrument;
- q.name = "Keys";
- lynx::ChannelDef synth;
- synth.instrument = lynx::InstrumentKind::synth;
- q.channel = synth;
- q.emptyBars = 4;
- st::Result r;
- offline.editSong ([&] (lynx::Song& s) { r = st::addTrack (s, q); });
- offline.dispatchPendingMessages();
- check ("the new Instrument track has an empty 4-bar pattern on it", r.ok() && r.pattern >= 0
- && st::patternOf (offline.getSong(), r.track) == r.pattern
- && offline.getSong().patterns[(std::size_t) r.pattern].notes.empty());
- // a few notes, as the first clicks would write them (A minor: A C E, then G B D)
- offline.editSong ([r] (lynx::Song& s) {
- auto& p = s.patterns[(std::size_t) r.pattern];
- const int keys[] { 57, 60, 64, 67, 71, 74, 69, 72 };
- for (int i = 0; i < 8; ++i)
- {
- lynx::Note n;
- n.channel = r.channels.front();
- n.key = keys[i];
- n.start = (std::int64_t) (i / 3) * lynx::ppq * 2 + (i % 3 == 0 ? 0 : 0);
- n.length = lynx::ppq * 2;
- n.velocity = 0.8f;
- p.notes.push_back (n);
- }
- p.sortNotes();
- });
- offline.dispatchPendingMessages();
- playlist.selectTrack (r.track);
- simple->trackSelected (r.track);
- offline.dispatchPendingMessages();
- check ("the instrument track has the Keyboard and Editor tabs", dock->hasPlayTabsForCheck());
- dock->setTab (lynx::SimpleDock::Tab::editor);
- offline.dispatchPendingMessages();
- check ("the Piano roll is docked in the Editor tab", dock->isEditorDocked());
- check ("on the track's pattern", offline.getSong().currentPattern == r.pattern);
- ui.getPianoRollForSnapshot().scrollToNotes(); // (done asynchronously when it docks)
- shots ("editor");
- dock->clickFoldForCheck (true); // "Only notes in key"
- check ("Only notes in key folds the rows to A minor", ui.getPianoRollForSnapshot().isFoldedToScale());
- ui.getPianoRollForSnapshot().scrollToNotes();
- shots ("editor-in-key");
- dock->clickFoldForCheck (false);
- // --- the keyboard's modes ------------------------------------------------------------------------------
- auto& keyboard = lynx::scalekeys::current();
- const auto saved = keyboard;
- keyboard = {};
- keyboard.lockToKey = true;
- dock->setTab (lynx::SimpleDock::Tab::keyboard);
- if (auto* panel = dock->keyboardPanelForSnapshot())
- {
- lynx::refreshKeyboardPanel (*panel);
- shots ("keys-locked");
- keyboard.lockToKey = false;
- keyboard.mode = lynx::scalekeys::Mode::scaleKeys;
- lynx::refreshKeyboardPanel (*panel);
- shots ("scale-keys");
- keyboard.mode = lynx::scalekeys::Mode::chordPad;
- keyboard.complexity = lynx::scalekeys::Complexity::seventh;
- keyboard.strumMs = 40;
- lynx::refreshKeyboardPanel (*panel);
- shots ("chord-pad");
- }
- check ("the Keyboard tab shows the keyboard panel", dock->keyboardPanelForSnapshot() != nullptr);
- // the same panel as the Touch keyboard window, each mode with a key / pad held
- for (const auto& [mode, name, pressed] : { std::tuple { lynx::scalekeys::Mode::scaleKeys, juce::String ("window-scale-keys"), 4 },
- std::tuple { lynx::scalekeys::Mode::chordPad, juce::String ("window-chord-pad"), 3 } })
- {
- auto panel = lynx::makeKeyboardPanelForSnapshot (offline, mode, pressed, [ch = r.channels.front()] { return ch; });
- panel->setSize (1100, 260);
- for (float scale : { 1.0f, 2.0f })
- writeImage (panel->createComponentSnapshot (panel->getLocalBounds(), true, scale), name + (scale > 1.0f ? "@2x" : ""));
- if (mode == lynx::scalekeys::Mode::chordPad)
- menuShot (lynx::chordPadMenuForSnapshot (*panel, 3), lynx::tr ("Edit chord"), lynx::tr ("Chord type"), "menu-chord-edit");
- }
- // the Chord pad on an FL Studio Mobile chord set (the default set's shape: C Dm Em F G Am B° C)
- {
- const auto set = lynx::scalekeys::parseFlmChordSet (R"({"chords":[{"baseNote":0,"extensions":[],"octave":3,"quality":0},{"baseNote":2,"extensions":[],"octave":3,"quality":1},{"baseNote":4,"extensions":[],"octave":3,"quality":1},{"baseNote":5,"extensions":[],"octave":3,"quality":0},{"baseNote":7,"extensions":[],"octave":3,"quality":0},{"baseNote":9,"extensions":[],"octave":3,"quality":1},{"baseNote":11,"extensions":[],"octave":3,"quality":3},{"baseNote":0,"extensions":[],"octave":4,"quality":0}],"rootNote":0})");
- check ("an FLM chord set reads as 8 chords (B diminished)", set.size() == 8 && set[6].quality == 3);
- offline.editSong ([set] (lynx::Song& s) { s.keyboardChords = set; });
- keyboard.projectChords = true;
- keyboard.complexity = lynx::scalekeys::Complexity::triad;
- auto panel = lynx::makeKeyboardPanelForSnapshot (offline, lynx::scalekeys::Mode::chordPad, 5, [ch = r.channels.front()] { return ch; });
- panel->setSize (1100, 260);
- for (float scale : { 1.0f, 2.0f })
- writeImage (panel->createComponentSnapshot (panel->getLocalBounds(), true, scale), juce::String ("window-chord-set") + (scale > 1.0f ? "@2x" : ""));
- }
- // the typing keys in each mode (A minor; Z = the root)
- {
- const auto& song = offline.getSong();
- lynx::scalekeys::Settings s;
- s.mode = lynx::scalekeys::Mode::scaleKeys;
- juce::String z;
- for (const int typed : { 60, 62, 64, 65, 67, 69, 71, 72, 61 })
- {
- const auto n = lynx::scalekeys::typedNotes (song, s, typed, 60);
- z << (n.empty() ? juce::String ("-") : juce::String (n.front())) << " ";
- }
- line ("Scale keys, typing C D E F G A B C C#: " + z);
- check ("Scale keys: the white typing keys play A minor from A", z.trim() == "69 71 72 74 76 77 79 81 -");
- s.mode = lynx::scalekeys::Mode::chordPad;
- s.projectChords = false;
- const auto pad = lynx::scalekeys::typedNotes (song, s, 60, 60);
- check ("Chord pad: Z plays A minor (A C E)", pad == std::vector<int> { 69, 72, 76 });
- }
- keyboard = saved;
- }
- // --- the project round trip --------------------------------------------------------------------------------
- {
- const auto json = lynx::ProjectFile::toJson (offline.getSong());
- juce::String error;
- const auto back = lynx::ProjectFile::fromJson (json, error);
- bool same = back.has_value() && back->keyboardChords == offline.getSong().keyboardChords && back->playlist.size() == offline.getSong().playlist.size();
- for (std::size_t i = 0; same && i < back->playlist.size(); ++i)
- same = back->playlist[i].followKey == offline.getSong().playlist[i].followKey && back->playlist[i].keyShift == offline.getSong().playlist[i].keyShift
- && back->playlist[i].pitch == offline.getSong().playlist[i].pitch;
- for (std::size_t c = 0; same && c < back->channels.size(); ++c)
- same = back->channels[c].sampler.loopKeyRoot == offline.getSong().channels[c].sampler.loopKeyRoot
- && back->channels[c].sampler.loopKeySource == offline.getSong().channels[c].sampler.loopKeySource;
- check ("follow, key moves, loop keys and the chord set survive .lynx", same);
- }
- dir.deleteRecursively();
- line (report.contains ("ERROR ") ? "RESULT ERROR" : "RESULT OK");
- juce::File (prefix + "-report.txt").replaceWithText (report);
- }
- void runSimple190dgShot (const juce::String& prefix)
- {
- 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()));
- const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
- const auto file = juce::File (prefix + "-" + name + ".png");
- file.deleteFile();
- juce::FileOutputStream out (file);
- juce::PNGImageFormat().writeImageToStream (image, out);
- };
- juce::String report;
- const auto line = [&report] (const juce::String& text) { report << text << "\n"; };
- const auto check = [&report] (const juce::String& what, bool ok) { report << (ok ? "OK " : "ERROR ") << what << "\n"; };
- ui.selectTabForSnapshot (2);
- ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
- offline.dispatchPendingMessages();
- auto* simple = ui.getSimpleWorkflowForSnapshot();
- if (simple == nullptr)
- {
- juce::File (prefix + "-report.txt").replaceWithText ("ERROR no Simple workflow\n");
- return;
- }
- simple->hideChooser();
- offline.editSong ([] (lynx::Song& s) {
- namespace st = lynx::simpletracks;
- st::Request q;
- q.kind = st::Kind::voice;
- q.name = "Lead vocal";
- st::addTrack (s, q);
- q = {};
- q.kind = st::Kind::instrument;
- q.name = "Keys";
- lynx::ChannelDef keys;
- keys.instrument = lynx::InstrumentKind::synth;
- q.channel = keys;
- st::addTrack (s, q);
- });
- offline.dispatchPendingMessages();
- simple->hideChooser();
- auto& playlist = ui.getPlaylistForSnapshot();
- int voiceTrack = -1, keysTrack = -1;
- {
- const auto& song = offline.getSong();
- for (int t = 0; t < (int) song.playlistTracks.size(); ++t)
- if (const auto kind = lynx::simpletracks::kindOf (song, t))
- {
- if (*kind == lynx::simpletracks::Kind::audio && voiceTrack < 0)
- voiceTrack = t;
- else if (*kind == lynx::simpletracks::Kind::instrument && keysTrack < 0)
- keysTrack = t;
- }
- }
- check ("two Simple tracks (voice, keys)", voiceTrack >= 0 && keysTrack >= 0);
- playlist.selectTrack (voiceTrack);
- offline.dispatchPendingMessages();
- auto* dock = simple->dockForSnapshot();
- if (dock == nullptr)
- {
- juce::File (prefix + "-report.txt").replaceWithText (report + "ERROR no dock\n");
- return;
- }
- const auto shots = [&] (const juce::String& name) {
- offline.dispatchPendingMessages();
- for (float scale : { 1.0f, 2.0f })
- {
- const auto suffix = scale > 1.0f ? juce::String ("@2x") : juce::String();
- writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), name + suffix);
- writeImage (dock->createComponentSnapshot (dock->getLocalBounds(), true, scale), "dock-" + name + suffix);
- }
- };
- const auto menuShot = [&] (const juce::PopupMenu& menu, const juce::String& title, const juce::String& subTitle, const juce::String& name) {
- juce::StringArray names { title };
- std::vector<juce::PopupMenu> menus { menu };
- for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
- if (it.getItem().subMenu != nullptr && it.getItem().text == subTitle)
- {
- names.add (subTitle);
- menus.push_back (*it.getItem().subMenu);
- }
- saveMenus (names, menus, prefix + "-" + name + ".png");
- };
- const auto insert = dock->insertForCheck();
- // --- every one-knob effect as a card, each at a knob position of its own -------------------------------------
- const float at[] { 0.0f, 0.55f, 0.40f, 0.70f, 0.30f, 0.60f, 0.45f, 0.35f, 0.80f };
- for (int id = 1; id <= lynx::goals::count; ++id)
- dock->addOneKnobForCheck (id);
- offline.dispatchPendingMessages();
- for (int id = 1; id <= lynx::goals::count; ++id)
- dock->turnKnobForCheck (id - 1, at[id]);
- offline.dispatchPendingMessages();
- check ("eight one-knob cards on the insert", dock->cardCountForCheck() == 8 && dock->oneKnobCardsForCheck() == 8);
- {
- const auto& fx = offline.getSong().mixer[(std::size_t) insert].effects;
- bool turned = fx.size() == 8;
- for (std::size_t i = 0; turned && i < fx.size(); ++i)
- turned = lynx::goals::active (fx[i]) && std::abs (fx[i].goalAmount - at[i + 1]) < 1.0e-6f;
- check ("each knob wrote its effect's parameters", turned);
- }
- shots ("effects-all");
- offline.dispatchPendingMessages();
- for (int card = 0; card < dock->cardCountForCheck(); ++card)
- {
- const auto area = dock->cardBoundsForSnapshot (card);
- const auto name = juce::String (lynx::goals::name (card + 1)).toLowerCase();
- check ("card " + juce::String (card + 1) + " (" + name + ") is on screen", ! area.isEmpty() && dock->getLocalBounds().contains (area));
- for (float scale : { 1.0f, 2.0f })
- writeImage (dock->createComponentSnapshot (area.expanded (4), true, scale), "card-" + name + (scale > 1.0f ? "@2x" : ""));
- }
- // --- a chain preset with Blend --------------------------------------------------------------------------------
- if (const auto* preset = lynx::chains::find ("Canyon"))
- offline.editSongStructural ([insert, preset] (lynx::Song& s) { lynx::chains::apply (s, insert, *preset); });
- offline.dispatchPendingMessages();
- dock->setBlendForCheck (0.6f);
- offline.dispatchPendingMessages();
- check ("preset Canyon with Blend 60 % (shown as edited)", offline.getSong().mixer[(std::size_t) insert].chainPreset == "Canyon"
- && std::abs (offline.getSong().mixer[(std::size_t) insert].chainBlend - 0.6f) < 1.0e-6f
- && ! lynx::chains::unchanged (offline.getSong(), insert));
- shots ("effects-preset-blend");
- // favourites: the track's preset starred; the menu lists it first
- const auto favFile = lynx::SimpleDock::favouritesFile();
- const auto hadFavourites = favFile.existsAsFile();
- const auto oldFavourites = favFile.loadFileAsString();
- lynx::SimpleDock::setFavouritePreset ("Canyon", true);
- lynx::SimpleDock::setFavouritePreset ("Clear Voice", true);
- lynx::SimpleDock::setFavouritePreset ("Canyon", true); // (twice: once in the list)
- check ("two favourites kept, in order", lynx::SimpleDock::favouritePresets() == juce::StringArray { "Canyon", "Clear Voice" });
- {
- bool first = false, toggle = false;
- const auto menu = dock->presetMenuForSnapshot();
- juce::PopupMenu::MenuItemIterator it (menu);
- if (it.next())
- first = it.getItem().subMenu != nullptr && it.getItem().text.contains (lynx::tr ("Favourites"));
- for (juce::PopupMenu::MenuItemIterator all (menu); all.next();)
- toggle = toggle || all.getItem().text == lynx::tr ("Remove \"{0}\" from favourites", { "Canyon" });
- check ("the Preset menu starts with the favourites and offers to unstar the track's preset", first && toggle);
- menuShot (menu, lynx::tr ("Preset"), juce::String::fromUTF8 ("\xe2\x98\x85 ") + lynx::tr ("Favourites"), "menu-preset-favourites");
- }
- lynx::SimpleDock::setFavouritePreset ("Canyon", false);
- check ("unstarred", lynx::SimpleDock::favouritePresets() == juce::StringArray { "Clear Voice" });
- if (hadFavourites)
- favFile.replaceWithText (oldFavourites);
- else
- favFile.deleteFile();
- // --- the sound picker: a search, and the installed plugins -----------------------------------------------------
- playlist.selectTrack (keysTrack);
- offline.dispatchPendingMessages();
- check ("the Keys track opens on its sound", dock->getTab() == lynx::SimpleDock::Tab::instrument);
- dock->showCategoryForSnapshot ((int) lynx::soundlib::Category::bass);
- dock->setSearchForSnapshot ("sub");
- offline.dispatchPendingMessages();
- line ("search \"sub\" in Bass: " + juce::String (dock->soundRowsForCheck()) + " rows");
- check ("a search narrows the category", dock->soundRowsForCheck() > 0 && dock->soundRowsForCheck() < (int) lynx::soundlib::filter (lynx::soundlib::builtIn(), lynx::soundlib::Category::bass).size());
- shots ("picker-search");
- dock->setSearchForSnapshot ({});
- // a made-up list of installed plugins (nothing is scanned or loaded)
- dock->setPluginsForSnapshot ({ { "VST3-demo-1", "Analog Mono", "Example Audio", "VST3", "Instrument|Synth" },
- { "VST3-demo-2", "Grand Upright", "Example Audio", "VST3", "Instrument|Piano" },
- { "VST3-demo-3", "Beat Kit 808", "Sample Lab", "VST3", "Instrument|Drum" },
- { "CLAP-demo-4", "Orchestra Strings", "Sample Lab", "CLAP", "Instrument|Sampler" },
- { "VST3-demo-5", "Wave Table One", "Example Audio", "VST3", "Instrument|Synth" },
- { "VST-demo-6", "Sub Bass Machine", "Low End", "VST", "Synth" },
- { "VST3-demo-7", "Sample Player", "Sample Lab", "VST3", "Instrument|Sampler" } });
- dock->showCategoryForSnapshot ((int) lynx::soundlib::Category::synths);
- offline.dispatchPendingMessages();
- check ("My plugins: the generic synths and samplers in their own category (" + juce::String (dock->soundRowsForCheck()) + " of 7)", dock->soundRowsForCheck() == 3);
- shots ("picker-plugins");
- line (report.contains ("ERROR ") ? "RESULT ERROR" : "RESULT OK");
- juce::File (prefix + "-report.txt").replaceWithText (report);
- }
- void runSimpleShot (const juce::String& prefix)
- {
- 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()));
- const auto writeImage = [&prefix] (const juce::Image& image, const char* name) {
- const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
- file.deleteFile();
- juce::FileOutputStream out (file);
- juce::PNGImageFormat().writeImageToStream (image, out);
- };
- const auto write = [&ui, &writeImage] (const char* name) { writeImage (lynx::shot::snapshot (ui), name); };
- // View › Layout style, with its submenu, as it is with `style` chosen
- const auto viewMenu = [&ui] {
- const auto names = ui.getMenuNamesForSnapshot();
- const auto view = names.indexOf (lynx::tr ("View"));
- return ui.getMenuForSnapshot (juce::jmax (0, view));
- };
- const auto saveStyleMenus = [&] (const juce::String& suffix) {
- const auto view = viewMenu();
- juce::StringArray names { lynx::tr ("View") };
- std::vector<juce::PopupMenu> menus { view };
- for (juce::PopupMenu::MenuItemIterator it (view); it.next();)
- if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::tr ("Layout style"))
- {
- names.add (lynx::tr ("Layout style"));
- menus.push_back (*it.getItem().subMenu);
- }
- saveMenus (names, menus, prefix + "-menu-" + suffix + ".png");
- };
- // Settings › General with `style` selected, and its style list
- const auto saveSettings = [&] (lynx::layoutstyle::Style style, const char* name) {
- lynx::SettingsHooks hooks;
- hooks.getGeneral = [style] {
- lynx::GeneralOptions o;
- o.language = lynx::i18n::current();
- o.layoutStyle = (int) style;
- return o;
- };
- auto page = lynx::makeSettingsPanel (offline, lynx::SettingsPage::general, false, hooks);
- const auto image = lynx::shot::paint (*page, lynx::theme::panel, -1, juce::jmin (page->getHeight(), 420));
- writeImage (image, name);
- std::function<juce::ComboBox* (juce::Component&)> find = [&find] (juce::Component& c) -> juce::ComboBox* {
- if (c.getComponentID() == "layoutStyle")
- return dynamic_cast<juce::ComboBox*> (&c);
- for (auto* child : c.getChildren())
- if (auto* box = find (*child))
- return box;
- return nullptr;
- };
- if (auto* box = find (*page); box != nullptr && box->getRootMenu() != nullptr)
- saveMenus (juce::StringArray { lynx::tr ("Layout style") }, std::vector<juce::PopupMenu> { *box->getRootMenu() },
- prefix + "-" + name + "-list.png");
- };
- const auto madeBefore = lynx::SimpleWorkflow::instances.load();
- ui.selectTabForSnapshot (2); // the Playlist panel, maximized (as --gridshot)
- write ("pattern");
- saveStyleMenus ("pattern");
- saveSettings (lynx::layoutstyle::Style::pattern, "settings-pattern");
- const auto madePattern = lynx::SimpleWorkflow::instances.load();
- ui.setLayoutStyle (lynx::layoutstyle::Style::clipLaunch);
- saveStyleMenus ("cliplaunch");
- ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
- offline.dispatchPendingMessages();
- if (auto* simple = ui.getSimpleWorkflowForSnapshot())
- simple->showChooser(); // (an empty project opens on it by itself; the offline project may hold the default song)
- write ("simple"); // the New track chooser (slice S3)
- if (auto* simple = ui.getSimpleWorkflowForSnapshot())
- {
- simple->showStarterPageForSnapshot();
- write ("simple-starter");
- simple->hideChooser();
- write ("simple-closed");
- // round 190p: a loop keeps time. Two files with the same 4.8 s of audio dropped on the empty Simple timeline:
- // "Guitar loop 100.wav" (2 bars at 100 BPM) lasts 2 bars at the project's tempo, "Guitar take.wav" plays at
- // its own speed. Both are undone again, so the shots after this one are as they were.
- {
- const auto folder = juce::File (prefix + "-loops");
- folder.createDirectory();
- juce::StringArray files;
- for (const auto* name : { "Guitar loop 100.wav", "Guitar take.wav" })
- {
- const auto file = folder.getChildFile (name);
- file.deleteFile();
- const auto rate = 44100.0;
- const auto frames = (int) (4.8 * rate);
- juce::AudioBuffer<float> audio (1, frames);
- for (int i = 0; i < frames; ++i)
- {
- const auto t = (double) i / rate, inBeat = std::fmod (t, 0.6); // a plucked note on every beat at 100 BPM
- audio.setSample (0, i, (float) (0.7 * std::exp (-inBeat * 7.0) * std::sin (juce::MathConstants<double>::twoPi * 196.0 * t)));
- }
- if (auto out = file.createOutputStream())
- if (auto writer = std::unique_ptr<juce::AudioFormatWriter> (juce::WavAudioFormat().createWriterFor (out.get(), rate, 1, 16, {}, 0)))
- {
- out.release();
- writer->writeFromAudioSampleBuffer (audio, 0, frames);
- }
- files.add (file.getFullPathName());
- }
- simple->dropFiles (files, 0);
- offline.dispatchPendingMessages();
- // the clips' waveforms are analysed in the background and drawn once ready (a live window repaints by
- // itself; one off-screen paint came too early and showed empty clips)
- for (const auto& path : files)
- lynx::ui::WaveformCache::getInstance()->find (path, [&offline, path] { return offline.getSampleLibrary().load (path); });
- lynx::ui::WaveformCache::getInstance()->waitUntilIdle (30000);
- offline.dispatchPendingMessages();
- write ("simple-loop");
- const auto& song = offline.getSong();
- juce::String report;
- for (const auto& clip : song.playlist)
- if (clip.kind == lynx::ClipKind::audio)
- report << song.channels[(std::size_t) clip.channel].name << ": " << juce::String ((double) clip.length / lynx::ppq, 3) << " beats, stretch "
- << juce::String (song.channels[(std::size_t) clip.channel].sampler.stretchBeats, 2) << "\n";
- juce::File (prefix + "-loop.txt").replaceWithText ("tempo " + juce::String (song.bpm, 1) + "\n" + report);
- for (int i = 0; i < files.size() && offline.canUndo(); ++i) // (one undo step per dropped file)
- offline.undo();
- offline.dispatchPendingMessages();
- simple->hideChooser();
- }
- // round 190t, slice A: one click on a starter beat adds it, placed for four bars (undone again)
- {
- const auto clipsBefore = offline.getSong().playlist.size();
- const auto tempoBefore = offline.getSong().bpm;
- simple->clickStarterForSnapshot (1);
- offline.dispatchPendingMessages();
- write ("simple-starter-added");
- const auto& song = offline.getSong();
- juce::String report ("tempo " + juce::String (tempoBefore, 1) + " -> " + juce::String (song.bpm, 1) + "\n");
- for (auto i = clipsBefore; i < song.playlist.size(); ++i)
- report << "clip at beat " << juce::String ((double) song.playlist[i].start / lynx::ppq, 2) << ", " << juce::String ((double) song.playlist[i].length / lynx::ppq, 2)
- << " beats, pattern " << song.playlist[i].pattern << ", track " << song.playlist[i].track << "\n";
- juce::File (prefix + "-starter.txt").replaceWithText (report);
- if (song.playlist.size() > clipsBefore && offline.canUndo())
- offline.undo();
- offline.dispatchPendingMessages();
- simple->hideChooser();
- }
- // slice S4: the Simple headers with a few tracks (voice, instrument, drums, an audio file), some levels moved
- offline.editSong ([] (lynx::Song& s) {
- namespace st = lynx::simpletracks;
- st::Request q;
- q.kind = st::Kind::voice;
- q.name = "Lead vocal";
- st::addTrack (s, q);
- q = {};
- q.kind = st::Kind::instrument;
- q.name = "Keys";
- lynx::ChannelDef keys;
- keys.instrument = lynx::InstrumentKind::synth;
- q.channel = keys;
- lynx::Pattern chords;
- for (int i = 0; i < 4; ++i)
- for (int k : { 60, 64, 67 })
- chords.notes.push_back (lynx::Note { (std::int64_t) i * 4 * lynx::ppq, 4 * lynx::ppq - lynx::ppq / 4, 0, k });
- q.pattern = chords;
- const auto r = st::addTrack (s, q);
- q = {};
- q.kind = st::Kind::drums;
- for (auto kind : { lynx::InstrumentKind::kick, lynx::InstrumentKind::snare, lynx::InstrumentKind::hat })
- {
- lynx::ChannelDef c;
- c.instrument = kind;
- c.name = kind == lynx::InstrumentKind::kick ? "Kick" : kind == lynx::InstrumentKind::snare ? "Snare" : "Hat";
- q.kit.push_back (c);
- }
- lynx::Pattern beat;
- const auto hit = [&beat] (int step, int row) { beat.notes.push_back (lynx::Note { (std::int64_t) step * lynx::ticksPerStep, lynx::ticksPerStep, row, 60 }); };
- for (int step = 0; step < 16; step += 2)
- hit (step, 2); // hats on the 8ths, kick on 1 and 3, snare on 2 and 4
- for (int step : { 0, 8 })
- hit (step, 0);
- for (int step : { 4, 12 })
- hit (step, 1);
- q.pattern = beat;
- q.bpm = 96.0;
- st::addTrack (s, q);
- if (r.insert > 0)
- {
- s.mixer[(std::size_t) r.insert].volume = 0.55f;
- s.mixer[(std::size_t) r.insert].pan = -0.4f;
- s.mixer[(std::size_t) r.insert].solo = true;
- }
- });
- offline.dispatchPendingMessages();
- ui.getPlaylistForSnapshot().selectTrack (1);
- write ("simple-tracks");
- // round 190t, slice E: the backup status beside the title tools, in each of its states
- {
- const auto now = juce::Time::currentTimeMillis();
- juce::String states;
- int n = 0;
- for (const auto& text : { lynx::MainComponent::simpleSaveStatusText (true, false, 0, now), lynx::MainComponent::simpleSaveStatusText (true, false, now - 5000, now),
- lynx::MainComponent::simpleSaveStatusText (true, true, now - 125000, now), lynx::MainComponent::simpleSaveStatusText (false, true, 0, now),
- lynx::MainComponent::simpleSaveStatusText (false, false, 0, now) })
- {
- simple->setStatusForSnapshot (text);
- offline.dispatchPendingMessages();
- states << n << ": " << text << "\n";
- writeImage (lynx::shot::snapshot (ui, ui.getLocalBounds().withTop (juce::jmin (ui.getHeight() - 1, 70)).withHeight (juce::jmin (ui.getHeight(), 44))),
- ("status-" + juce::String (n++)).toRawUTF8());
- }
- juce::File (prefix + "-status.txt").replaceWithText (states);
- simple->setStatusForSnapshot (lynx::MainComponent::simpleSaveStatusText (true, true, now - 125000, now));
- offline.dispatchPendingMessages();
- write ("simple-status");
- }
- // slice S8: the Finish dock, empty, then with a look on the Master (Balanced, Normal, a little Tone)
- simple->showFinish();
- offline.dispatchPendingMessages();
- write ("simple-finish-empty");
- offline.editSongStructural ([] (lynx::Song& s) { lynx::looks::apply (s, lynx::MasterLookSettings { lynx::looks::balanced, 0.5f, { 1.5f, 0.0f, 1.0f }, -3.0f }); });
- offline.dispatchPendingMessages();
- simple->showFinish();
- write ("simple-finish");
- simple->hideFinish();
- }
- saveStyleMenus ("simple");
- saveSettings (lynx::layoutstyle::Style::simple, "settings-simple");
- // round 184a S11: the Key panel (no key, then an A minor riff and its guesses) and its menu
- const auto toolbarShot = [&] (const char* name) {
- writeImage (lynx::shot::snapshot (ui, ui.getLocalBounds().withHeight (juce::jmin (ui.getHeight(), 80))), name);
- };
- toolbarShot ("key-none");
- saveMenus (juce::StringArray { lynx::tr ("Key") }, std::vector<juce::PopupMenu> { ui.getKeyMenuForSnapshot() }, prefix + "-key-menu-empty.png");
- offline.editSong ([] (lynx::Song& s) {
- if (s.channels.empty())
- s.channels.resize (1);
- if (s.patterns.empty())
- s.patterns.emplace_back();
- int t = 0;
- for (int k : { 57, 60, 64, 67, 69, 67, 64, 60, 57, 59, 60, 62, 64, 62, 60, 59, 57, 57, 64, 45 })
- {
- lynx::Note n;
- n.channel = 0;
- n.key = k;
- n.start = t * lynx::ppq / 2;
- n.length = k == 57 || k == 45 ? lynx::ppq : lynx::ppq / 2;
- s.patterns[0].notes.push_back (n);
- ++t;
- }
- });
- offline.dispatchPendingMessages();
- saveMenus (juce::StringArray { lynx::tr ("Key") }, std::vector<juce::PopupMenu> { ui.getKeyMenuForSnapshot() }, prefix + "-key-menu-guess.png");
- const auto guesses = lynx::keyguess::guess (offline.getSong(), 3);
- if (! guesses.empty())
- offline.editSong ([k = guesses[0].key] (lynx::Song& s) { lynx::projectkey::set (s, k); });
- offline.dispatchPendingMessages();
- toolbarShot ("key-set");
- write ("simple-key");
- juce::String keyCounts;
- for (const auto& g : guesses)
- keyCounts << "guess " << lynx::projectkey::name (g.key) << " " << g.notesInScale << "/" << g.notes << " score " << g.score << "\n";
- offline.editSong ([] (lynx::Song& s) { lynx::projectkey::set (s, std::nullopt); });
- ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
- offline.dispatchPendingMessages();
- toolbarShot ("key-pattern-toolbar");
- write ("pattern-after");
- // round 184a S17: the setup wizard with its Workflow choice — a first start (Pattern selected), then reopened in Simple
- for (int style : { 0, 2 })
- {
- auto wizard = lynx::makeSetupWizardContent (offline, {}, {}, style, {});
- auto image = lynx::shot::paint (*wizard);
- writeImage (image, style == 0 ? "wizard-pattern" : "wizard-simple");
- }
- juce::File (prefix + "-counts.txt").replaceWithText ("simple workflows before " + juce::String (madeBefore) + ", in pattern workflow "
- + juce::String (madePattern) + ", after " + juce::String (lynx::SimpleWorkflow::instances.load())
- + "\nstyle after " + lynx::layoutstyle::id (ui.getLayoutStyle()) + "\n" + keyCounts);
- }
- void runLiveShot190ce (const juce::String& prefix)
- {
- 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()));
- const auto write = [&prefix, &ui, &offline] (const char* name) {
- offline.dispatchPendingMessages();
- const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
- file.deleteFile();
- juce::FileOutputStream out (file);
- juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
- };
- juce::String checks;
- const auto check = [&checks] (const char* what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
- // a small library of its own (empty files: only names are shown)
- const auto lib = juce::File (prefix + "-library");
- lib.deleteRecursively();
- for (const auto* path : { "Drums/Kicks/Kick Hard.wav", "Drums/Kicks/Kick Soft.wav", "Drums/Snare Tight.wav", "Drums/Hat Closed.wav",
- "Loops/Break 120.wav", "Loops/Shaker 98.wav", "Textures/Vinyl Noise.wav", "Textures/Rain.wav" })
- lib.getChildFile (path).create();
- auto& browser = ui.getBrowserForSnapshot();
- auto& store = lynx::BrowserComponent::collectionStore();
- store = {};
- const auto item = [&lib] (const char* path) { return lib.getChildFile (path).getFullPathName().toStdString(); };
- ui.setVisible (true);
- lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
- ui.setClipLaunchWorkflow (true);
- ui.showPanelsForSnapshot ({ lynx::workspace::Panel::browser, lynx::workspace::Panel::playlist });
- offline.editSong ([] (lynx::Song& s) {
- if (s.channels.size() < 2)
- s.channels.resize (2);
- s.channels[0].name = "Bass synth";
- s.channels[0].mixerTrack = 2;
- s.channels[1].mixerTrack = 3;
- if (s.mixer.size() < 4)
- s.mixer.resize (4);
- s.mixer[2].name = "Bass";
- s.mixer[2].effects.clear();
- for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor, lynx::EffectKind::delay })
- {
- lynx::EffectSlot fx;
- fx.kind = kind;
- const auto& info = lynx::effectInfo (kind);
- for (std::size_t k = 0; k < info.params.size() && k < fx.params.size(); ++k)
- fx.params[k] = info.params[k].defaultValue;
- s.mixer[2].effects.push_back (fx);
- }
- s.mixer[2].effects[1].enabled = false; // the compressor: off, at half mix
- s.mixer[2].effects[1].mix = 0.5f;
- while (s.patterns.size() < 2)
- s.patterns.emplace_back();
- s.patterns[0].name = "Bass line";
- lynx::Note note;
- note.channel = 0;
- note.key = 36;
- s.patterns[0].notes = { note };
- s.patterns[0].lengthTicks = 4 * lynx::ppq;
- s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 3));
- s.playlistTracks[1].name = "Bass";
- lynx::Clip clip;
- clip.pattern = 0;
- clip.length = 4 * lynx::ppq;
- lynx::launcher::setClip (s, 1, 0, clip);
- }, false);
- offline.dispatchPendingMessages();
- auto* detail = ui.getDetailViewForSnapshot();
- if (detail == nullptr)
- {
- juce::File (prefix + "-checks.txt").replaceWithText ("FAIL no detail view\n");
- return;
- }
- detail->showSelection (1, 0);
- detail->setPage (lynx::DetailView::Page::devices);
- detail->selectCardForCheck (2); // the compressor (card 0 is the instrument)
- write ("01-devices"); // the cards' title buttons: hot-swap, save, fold
- saveMenus (juce::StringArray { "Device (effect card)" }, std::vector<juce::PopupMenu> { detail->cardMenuForSnapshot (2) }, prefix + "-02-device-menu.png");
- // hot-swap on for the compressor: the Browser's bar, the Plugin database's effects, the card's button lit
- const auto compressor = lynx::hotswap::targetOfEffect (offline.getSong(), 2, 1);
- browser.beginHotSwap (compressor);
- write ("03-hotswap-effect");
- check ("hot-swap links the compressor", browser.isHotSwapping() && browser.hotSwapTarget() == compressor);
- // a swap through the Browser itself (the row of LYNX's Reverb, then Enter): the slot keeps its place, its off
- // state and its Mix; the link moves to the new device
- {
- browser.showPluginDatabase ("LYNX SHARE", 0); // (the folder of LYNX's own effects, opened as a click would)
- browser.selectRowForSnapshot (lynx::tr (lynx::effectInfo (lynx::EffectKind::reverb).name));
- write ("03a-hotswap-row"); // the candidate's row selected
- check ("swap: Enter on the Reverb row is taken by hot-swap", browser.hotSwapLoadSelected());
- offline.dispatchPendingMessages();
- const auto& slot = offline.getSong().mixer[2].effects[1];
- // (round 190cy: the device comes in with its own on / off state, on, as in Live 12.4.16; the Mix stays)
- check ("swap: reverb in the compressor's place, on (its own state), at 50 % mix", slot.kind == lynx::EffectKind::reverb && slot.enabled && slot.mix == 0.5f);
- check ("swap: three effects as before", offline.getSong().mixer[2].effects.size() == 3);
- check ("swap: the Browser is linked to the new device", browser.isHotSwapping() && browser.hotSwapTarget() == lynx::hotswap::targetOfEffect (offline.getSong(), 2, 1)
- && ! (browser.hotSwapTarget() == compressor));
- write ("03b-hotswap-swapped");
- offline.undo();
- offline.dispatchPendingMessages();
- const auto& back = offline.getSong().mixer[2].effects[1];
- check ("undo: the compressor is back with its instance", back.kind == lynx::EffectKind::compressor && back.instance.id == compressor.instance);
- check ("undo: the Browser is still linked to it", browser.isHotSwapping() && browser.hotSwapTarget() == compressor);
- }
- // round 190cy (Live 12.4.16 live check 190cw shot 02a): hot-swap starts on the device's current preset. The
- // compressor got its settings from a saved preset of LYNX's ("Glue bus", in this run's own settings folder)
- {
- browser.endHotSwap();
- const auto folder = lynx::pluginheader::userFolder (lynx::EffectKind::compressor);
- folder.createDirectory();
- const auto& fx = offline.getSong().mixer[2].effects[1];
- for (const auto* name : { "Glue bus", "Gentle", "Parallel smash" })
- folder.getChildFile (juce::String (name) + ".lynxpreset").replaceWithText (lynx::presets::toText (lynx::EffectKind::compressor, name, fx.params));
- offline.editSong ([] (lynx::Song& s) { s.mixer[2].effects[1].presetName = "Glue bus"; }, false);
- offline.dispatchPendingMessages();
- browser.beginHotSwap (compressor);
- write ("03c-hotswap-current-preset");
- check ("hot-swap starts on the current preset", browser.getSelectedFile() == folder.getChildFile ("Glue bus.lynxpreset"));
- // a preset of the same effect swapped in comes in on (the compressor was off)
- browser.selectRowForSnapshot ("Gentle.lynxpreset");
- check ("swap: the preset row is taken by hot-swap", browser.hotSwapLoadSelected());
- offline.dispatchPendingMessages();
- const auto& now = offline.getSong().mixer[2].effects[1];
- check ("swap: the preset's settings, the device on", now.kind == lynx::EffectKind::compressor && now.presetName == "Gentle" && now.enabled);
- write ("03d-hotswap-preset-swapped");
- offline.undo();
- offline.dispatchPendingMessages();
- check ("undo: the compressor off again", ! offline.getSong().mixer[2].effects[1].enabled);
- browser.endHotSwap();
- check ("hot-swap ended: the preset list goes", ! browser.isHotSwapping());
- browser.beginHotSwap (compressor);
- }
- // linked to the instrument instead
- const auto bass = lynx::hotswap::targetOfChannel (offline.getSong(), 0);
- browser.beginHotSwap (bass);
- detail->selectCardForCheck (0);
- write ("04-hotswap-instrument");
- check ("re-link to the instrument", browser.hotSwapTarget() == bass);
- browser.endHotSwap();
- check ("hot-swap ended", ! browser.isHotSwapping());
- write ("05-hotswap-ended"); // the Browser as it was before
- // the device is deleted while linked: the mode ends by itself
- browser.beginHotSwap (lynx::hotswap::targetOfEffect (offline.getSong(), 2, 2));
- offline.editSong ([] (lynx::Song& s) { s.mixer[2].effects.pop_back(); });
- offline.dispatchPendingMessages();
- check ("deleting the linked device ends hot-swap", ! browser.isHotSwapping());
- offline.undo();
- offline.dispatchPendingMessages();
- // Duplicate (Ctrl+D) of the EQ
- check ("duplicate", detail->duplicateCardForCheck (1));
- offline.dispatchPendingMessages();
- check ("duplicate: four effects, EQ twice", offline.getSong().mixer[2].effects.size() == 4 && offline.getSong().mixer[2].effects[1].kind == lynx::EffectKind::eq
- && offline.getSong().mixer[2].effects[0].instance.id != offline.getSong().mixer[2].effects[1].instance.id);
- write ("06-duplicated");
- // --- collections ---
- browser.showFilterForSnapshot (lib, lynx::browserview::ContentFilter::all);
- ui.waitForBrowserForSnapshot();
- browser.setInCollection (item ("Drums/Kicks/Kick Hard.wav"), 0, true);
- browser.setInCollection (item ("Drums/Snare Tight.wav"), 0, true);
- browser.setInCollection (item ("Loops"), 0, true);
- browser.setTab (lynx::BrowserComponent::starredTab);
- write ("07-starred-only"); // only Starred shown: the tab as it always was
- browser.setInCollection (item ("Drums/Kicks/Kick Hard.wav"), 4, true); // also Blue
- browser.setInCollection (item ("Loops/Break 120.wav"), 4, true);
- browser.setInCollection (item ("Textures/Vinyl Noise.wav"), 3, true);
- browser.setInCollection (item ("Textures/Rain.wav"), 3, true);
- browser.setInCollection (item ("Drums/Hat Closed.wav"), 1, true);
- store.rename (3, "Textures");
- browser.setCollectionShown (1, true);
- browser.setCollectionShown (3, true);
- browser.setCollectionShown (4, true);
- write ("08-collections"); // a heading per collection shown
- check ("collections: four shown", store.shown().size() == 4);
- check ("collections: an item in two", store.mask (item ("Drums/Kicks/Kick Hard.wav")) == 0b10001);
- // round 190cy: the Clip-launch workflow's row menu lists the collections flat, as Live's item menu (shot 05);
- // the Pattern workflow keeps the "Collections" sub-menu
- browser.setLiveItemMenus (false);
- saveMenus (juce::StringArray { "Collections (Pattern workflow: a row's sub-menu)" }, std::vector<juce::PopupMenu> { browser.collectionsMenuForSnapshot (item ("Drums/Kicks/Kick Hard.wav")) },
- prefix + "-09-collections-menu.png");
- browser.setLiveItemMenus (true);
- saveMenus (juce::StringArray { "Collections (Clip-launch workflow: a row's menu)" }, std::vector<juce::PopupMenu> { browser.collectionsMenuForSnapshot (item ("Drums/Kicks/Kick Hard.wav")) },
- prefix + "-09b-collections-flat.png");
- // the key of a hidden collection (6, Purple) labels the row and the collection appears
- check ("hidden collection: not shown before", ! store.isShown (5));
- browser.setInCollection (item ("Textures/Rain.wav"), 5, true);
- check ("hidden collection: its key shows it", store.isShown (5) && store.has (item ("Textures/Rain.wav"), 5));
- write ("08b-hidden-collection-shown");
- saveMenus (juce::StringArray { "Browser options" }, std::vector<juce::PopupMenu> { browser.buildViewMenu() }, prefix + "-10-browser-options.png");
- browser.setTab (lynx::BrowserComponent::allTab);
- write ("11-all-tab-chips"); // the colour chips on the rows of the ALL tab
- browser.setSearchForSnapshot ("textures");
- ui.waitForBrowserForSnapshot();
- write ("12-search-collection-name"); // found by the collection's name
- browser.setSearchForSnapshot ({});
- // the file round trip
- {
- const auto text = store.toText();
- check ("collections: text round trip", lynx::collections::Store::fromText (text) == store);
- }
- store = {};
- juce::File (prefix + "-checks.txt").replaceWithText (checks);
- lib.deleteRecursively();
- }
- void runLinkShot190gl (const juce::String& prefix)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- lynx::AudioEngine offline (false);
- lynx::MainComponent ui (offline, false);
- ui.setSize (1600, 900);
- ui.setVisible (true);
- juce::String checks;
- const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
- const auto writeImage = [&prefix] (const juce::Image& image, const char* name) {
- const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
- file.deleteFile();
- juce::FileOutputStream out (file);
- juce::PNGImageFormat().writeImageToStream (image, out);
- };
- const auto toolbarShot = [&] (const char* name) {
- ui.tickLinkForSnapshot();
- writeImage (lynx::shot::snapshot (ui, ui.getToolbarBoundsForSnapshot()), name);
- };
- auto& link = offline.getLink();
- auto& transport = offline.getTransport();
- link.deviceStarted (44100.0);
- // the audio callbacks the offline engine has none of: Link's per-block step, in real time
- const auto pump = [&] (double seconds, std::function<bool()> until = {}) {
- const auto end = juce::Time::getMillisecondCounterHiRes() + seconds * 1000.0;
- while (juce::Time::getMillisecondCounterHiRes() < end)
- {
- const auto start = link.beginBlock (transport, 256, 0.0);
- if (start >= 0)
- transport.playing.store (true);
- if (transport.playing.load())
- transport.positionTicks.store (transport.positionTicks.load() + 256 * transport.ticksPerSample());
- juce::Thread::sleep (6);
- if (until && until())
- return true;
- }
- return ! until || until();
- };
- auto peer = lynx::AbletonLink::makeTestPeer (97.0); // the other app in the session (it was there first)
- juce::Thread::sleep (1500); // (a session that started at the same moment as LYNX's could take either tempo)
- using lynx::toolbarlayout::Group;
- // FL's Pattern layout: no Link toggle on a new install
- check ("Pattern layout: the Link toggle is hidden by default", ! ui.getToolbarLayoutForSnapshot().isShown (Group::link));
- toolbarShot ("toolbar-fl-default");
- // shown by hand (Settings › Ableton Link › Show Link Toggle): "Link", off
- auto layout = ui.getToolbarLayoutForSnapshot();
- layout.setShown (Group::link, true);
- ui.setToolbarLayoutForSnapshot (layout);
- toolbarShot ("toolbar-fl-link-off");
- check ("off: the toggle says Link", ui.getLinkToggleForSnapshot().text() == lynx::trc ("@Ableton Link: Link"));
- // on: the session the other peer runs (its tempo, 97 BPM, wins over the project's)
- link.setEnabled (true, offline.getSong().bpm);
- // (a new peer is counted at once; its session's tempo is taken after Link measured it, a moment later)
- const auto joined = pump (8.0, [&] { return link.peers() > 0 && link.startProgress() >= 0.0 && std::abs (link.sessionTempo() - 97.0) < 1e-3; });
- check ("Link on: one peer found", joined && link.peers() == 1);
- check ("Link on: the session's tempo (97 BPM, the first peer's) is the one shown", std::abs (offline.shownTempo() - 97.0) < 1e-3);
- toolbarShot ("toolbar-fl-link-on");
- check ("on with one peer: the toggle says 1 Link", ui.getLinkToggleForSnapshot().text() == lynx::trc ("@Ableton Link: {0} Link").replace ("{0}", "1"));
- check ("stopped with a peer: the position display shows the session's progress", link.startProgress() >= 0.0);
- // the Clip-launch layout: the toggle is shown by default (the reference DAW's "Show Link Toggle": Show)
- ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
- ui.setClipLaunchWorkflow (true);
- check ("Clip-launch layout: the Link toggle is shown by default", ui.getToolbarLayoutForSnapshot().isShown (Group::link));
- pump (0.4);
- toolbarShot ("toolbar-cliplaunch-1link");
- writeImage (lynx::shot::snapshot (ui), "window-cliplaunch");
- // Play: it waits for the session's phase (the play button lit, the progress bar running), then starts
- transport.playing.store (true);
- pump (0.05);
- const auto waited = offline.isLinkWaiting();
- check ("Play with a peer waits for the session's phase", waited);
- toolbarShot ("toolbar-cliplaunch-waiting");
- const auto started = pump (4.0, [&] { return transport.playing.load() && ! offline.isLinkWaiting(); });
- check ("then playback starts on the session's phase", started);
- pump (0.5);
- toolbarShot ("toolbar-cliplaunch-playing");
- check ("playing: no progress bar", link.startProgress() < 0.0);
- // the toggle's drop-down and the Options menu
- saveMenus (juce::StringArray { lynx::trc ("@Ableton Link: Link") }, std::vector<juce::PopupMenu> { ui.getLinkToggleForSnapshot().makeMenu() },
- prefix + "-menu-link.png");
- {
- const auto names = ui.getMenuNamesForSnapshot();
- for (int m = 0; m < names.size(); ++m)
- if (names[m] == lynx::tr ("Options"))
- saveMenus (juce::StringArray { names[m] }, std::vector<juce::PopupMenu> { ui.getMenuForSnapshot (m) }, prefix + "-menu-options.png");
- }
- // Settings › Ableton Link
- {
- lynx::SettingsHooks hooks;
- hooks.linkToggleShown = [] { return true; };
- auto panel = lynx::makeSettingsPanel (offline, lynx::SettingsPage::link, false, hooks);
- panel->setSize (680, 620);
- writeImage (lynx::shot::snapshot (*panel), "settings-link");
- }
- // off: the project's own tempo comes back on the display
- transport.playing.store (false);
- pump (0.1);
- link.setEnabled (false, offline.getSong().bpm);
- pump (0.1);
- toolbarShot ("toolbar-cliplaunch-link-off");
- check ("off: the tempo display shows the project's tempo again", std::abs (offline.shownTempo() - offline.getSong().bpm) < 1e-9);
- const auto stats = link.stats();
- checks << "audio-thread cost of the Link step: mean " << juce::String (stats.meanUs, 2) << " us, max " << juce::String (stats.maxUs, 1)
- << " us over " << (juce::int64) stats.blocks << " blocks\n";
- juce::File (prefix + "-checks.txt").replaceWithText (checks);
- }
- void runMapShot190ef (const juce::String& prefix)
- {
- 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()));
- const auto write = [&prefix] (juce::Component& c, const char* name) {
- const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
- file.deleteFile();
- juce::FileOutputStream out (file);
- juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
- };
- juce::String checks;
- const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
- using namespace lynx::remotemap;
- ui.setVisible (true);
- // the Pattern layout first: Ctrl+M stays FL's metronome there and no map mode starts
- {
- const auto before = offline.getTransport().metronome.load();
- ui.keyPressed (juce::KeyPress ('M', juce::ModifierKeys::ctrlModifier, 0));
- check ("Pattern layout: Ctrl+M is the metronome, no map mode", ui.getMapMode() == Mode::off && offline.getTransport().metronome.load() != before);
- ui.keyPressed (juce::KeyPress ('M', juce::ModifierKeys::ctrlModifier, 0));
- ui.setMapMode (Mode::midi);
- check ("Pattern layout: setMapMode stays off", ui.getMapMode() == Mode::off);
- }
- ui.setClipLaunchWorkflow (true);
- offline.editSong ([] (lynx::Song& s) {
- if (s.mixer.size() < 6)
- s.mixer.resize (6);
- const char* inserts[] { "Master", "Drums", "Bass", "Keys", "Vox", "Reverb" };
- for (int i = 1; i < 6; ++i)
- s.mixer[(std::size_t) i].name = inserts[i];
- const int channels = (int) s.channels.size();
- s.channels.resize ((std::size_t) channels + 3);
- const char* names[] { "Drum kit", "Bass synth", "Keys" };
- for (int k = 0; k < 3; ++k)
- {
- auto& ch = s.channels[(std::size_t) (channels + k)];
- ch.name = names[k];
- ch.instrument = k == 0 ? lynx::InstrumentKind::sampler : lynx::InstrumentKind::synth;
- ch.mixerTrack = k + 1;
- }
- s.mixer[2].effects.clear();
- for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor })
- {
- lynx::EffectSlot fx;
- fx.kind = kind;
- const auto& info = lynx::effectInfo (kind);
- for (std::size_t k = 0; k < info.params.size() && k < fx.params.size(); ++k)
- fx.params[k] = info.params[k].defaultValue;
- s.mixer[2].effects.push_back (fx);
- }
- while (s.patterns.size() < 3)
- s.patterns.emplace_back();
- const char* patterns[] { "Beat", "Bassline", "Chords" };
- for (int p = 0; p < 3; ++p)
- {
- auto& pattern = s.patterns[(std::size_t) p];
- pattern.name = patterns[p];
- lynx::Note n;
- n.channel = channels + p;
- n.key = 48 + p * 5;
- pattern.notes = { n };
- pattern.lengthTicks = 4 * lynx::ppq;
- }
- s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 8));
- const char* tracks[] { "Drums", "Bass", "Keys", "Vox" };
- for (int t = 0; t < 4; ++t)
- s.playlistTracks[(std::size_t) t].name = tracks[t];
- for (int t = 0; t < 3; ++t)
- for (int r = 0; r < 3; ++r)
- {
- lynx::Clip clip;
- clip.pattern = t;
- clip.length = 4 * lynx::ppq;
- lynx::launcher::setClip (s, t, r, clip);
- }
- auto& grid = lynx::launcher::ensureGrid (s);
- const char* scenes[] { "Intro", "Verse", "Drop" };
- grid.scenes.resize (4);
- for (int r = 0; r < 3; ++r)
- grid.scenes[(std::size_t) r].name = scenes[r];
- // some mappings, as the lesson's pictures show them (pads on slots and scenes, knobs on volume and pan)
- assignMidi (s, Target::slot (0, 0), { 0, lynx::linkNoteBase + 36, -1 });
- assignMidi (s, Target::slot (1, 0), { 0, lynx::linkNoteBase + 37, -1 });
- assignMidi (s, Target::sceneLaunch (1), { 0, lynx::linkNoteBase + 44, -1 });
- assignMidi (s, Target::parameter ({ lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }), { 0, 17, -1 });
- assignMidi (s, Target::parameter ({ lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }), { 0, 16, -1 });
- assignMidi (s, Target::of (lynx::RemoteAction::play), { 0, 118, -1 });
- setRange (s, rows (s, Mode::midi)[0], 0.0f, 0.85f);
- assignKey (s, Target::slot (0, 1), 'A');
- assignKey (s, Target::slot (1, 1), 'S');
- assignKey (s, Target::sceneLaunch (2), '3');
- assignKey (s, Target::parameter ({ lynx::AutomationTargetKind::mixerVolume, 2, 0, 0 }), 'V');
- }, false);
- offline.dispatchPendingMessages();
- ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist, lynx::workspace::Panel::browser }); // (no floating Channel Rack over the grid)
- ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
- offline.dispatchPendingMessages();
- ui.resized();
- if (auto* detail = ui.getDetailViewForSnapshot())
- {
- detail->showSelection (1, 0);
- detail->setPage (lynx::DetailView::Page::devices);
- }
- ui.resized();
- offline.dispatchPendingMessages();
- write (ui, "00-clip-launch-before");
- // Ctrl+M in the Clip-launch layout: MIDI Map Mode (the metronome stays as it was)
- const auto metronome = offline.getTransport().metronome.load();
- ui.keyPressed (juce::KeyPress ('M', juce::ModifierKeys::ctrlModifier, 0));
- check ("Clip-launch layout: Ctrl+M starts MIDI Map Mode", ui.getMapMode() == Mode::midi && offline.getTransport().metronome.load() == metronome);
- auto* overlay = ui.mapOverlayForSnapshot();
- auto* list = ui.mappingBrowserForSnapshot();
- if (overlay == nullptr || list == nullptr)
- {
- juce::File (prefix + "-checks.txt").replaceWithText (checks + "FAIL no overlay\n");
- return;
- }
- overlay->refresh();
- const auto& spots = overlay->spots();
- const auto count = [&] (lynx::RemoteAction a) { return (int) std::count_if (spots.begin(), spots.end(), [a] (const lynx::mapmode::Spot& p) { return p.target.action == a; }); };
- const auto params = [&] (lynx::AutomationTargetKind k) {
- return (int) std::count_if (spots.begin(), spots.end(), [k] (const lynx::mapmode::Spot& p) { return p.target.action == lynx::RemoteAction::parameter && p.target.param.kind == k; });
- };
- check ("overlay: clip slots (" + juce::String (count (lynx::RemoteAction::clipSlot)) + ")", count (lynx::RemoteAction::clipSlot) >= 12);
- check ("overlay: scene launch buttons (" + juce::String (count (lynx::RemoteAction::sceneLaunch)) + ")", count (lynx::RemoteAction::sceneLaunch) >= 4);
- check ("overlay: track stop buttons", count (lynx::RemoteAction::trackStop) >= 4);
- check ("overlay: Stop all clips, Session Record", count (lynx::RemoteAction::stopAllClips) == 1 && count (lynx::RemoteAction::sessionRecord) == 1);
- check ("overlay: transport play / stop / record / metronome", count (lynx::RemoteAction::play) == 1 && count (lynx::RemoteAction::stop) == 1
- && count (lynx::RemoteAction::record) == 1 && count (lynx::RemoteAction::metronome) == 1);
- check ("overlay: tempo", params (lynx::AutomationTargetKind::tempo) == 1);
- check ("overlay: mixer volume / pan (" + juce::String (params (lynx::AutomationTargetKind::mixerVolume)) + " / " + juce::String (params (lynx::AutomationTargetKind::mixerPan)) + ")",
- params (lynx::AutomationTargetKind::mixerVolume) >= 3 && params (lynx::AutomationTargetKind::mixerPan) >= 3);
- check ("overlay: device knobs (" + juce::String (params (lynx::AutomationTargetKind::effectParam)) + ")", params (lynx::AutomationTargetKind::effectParam) >= 2);
- // a click on Keys' first slot selects it; a MIDI control assigns it (as the engine's catch would)
- for (const auto& spot : spots)
- if (spot.target == Target::slot (2, 0))
- {
- auto source = juce::Desktop::getInstance().getMainMouseSource();
- const auto now = juce::Time::getCurrentTime();
- const auto at = spot.area.getCentre().toFloat();
- overlay->mouseDown (juce::MouseEvent (source, at, juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f,
- overlay, overlay, now, at, now, 1, false));
- break;
- }
- if (spots.empty())
- {
- juce::File (prefix + "-checks.txt").replaceWithText (checks + "FAIL no spots\n");
- return;
- }
- check ("a click selects the slot", overlay->selection() == std::optional<Target> (Target::slot (2, 0)));
- check ("the overlay takes clicks only on elements", overlay->hitTest (spots.front().area.getCentreX(), spots.front().area.getCentreY()) && ! overlay->hitTest (2, ui.getHeight() - 2));
- check ("a pad assigns it", overlay->assignMidi ({ 0, lynx::linkNoteBase + 38, -1 }) && midiOf (offline.getSong(), Target::slot (2, 0)).number == lynx::linkNoteBase + 38);
- check ("the same pad again on track 0 is refused", ! (overlay->select (Target::slot (0, 2)), overlay->assignMidi ({ 0, lynx::linkNoteBase + 36, -1 })));
- overlay->select (Target::slot (2, 0));
- list->setMode (Mode::midi);
- list->selectRow (0);
- ui.resized();
- overlay->refresh();
- write (ui, "01-midi-map-mode");
- check ("Mapping Browser rows (MIDI): " + juce::String ((int) list->rowsShown().size()), list->rowsShown().size() == 7);
- write (*list, "02-mapping-browser-midi");
- saveMenus (juce::StringArray { "Row" }, std::vector<juce::PopupMenu> { list->rowMenu (0) }, prefix + "-03-row-menu.png");
- // Ctrl+K: Key Map Mode; a key assigns the selected element
- ui.keyPressed (juce::KeyPress ('K', juce::ModifierKeys::ctrlModifier, 0));
- check ("Ctrl+K switches to Key Map Mode", ui.getMapMode() == Mode::key && offline.getMapMode() == Mode::key);
- overlay->select (Target::sceneLaunch (0));
- ui.keyPressed (juce::KeyPress ('1', {}, '1'));
- check ("a key assigns the selected scene", keyOf (offline.getSong(), Target::sceneLaunch (0)).key == '1');
- overlay->select (Target::sceneLaunch (1));
- ui.keyPressed (juce::KeyPress ('A', {}, 'a'));
- check ("a key already on a slot is refused for a scene", ! keyOf (offline.getSong(), Target::sceneLaunch (1)).found);
- overlay->refresh();
- write (ui, "04-key-map-mode");
- write (*list, "05-mapping-browser-key");
- {
- // round 190em: Min / Max in the parameter's unit, Path "<track> | Mixer", Name "Track Volume" / "Slot n"
- const lynx::remotemap::Target volume = Target::parameter ({ lynx::AutomationTargetKind::mixerVolume, 2, 0, 0 });
- const auto [path, name] = lynx::mapmode::describe (offline, volume);
- check ("browser: volume row Path / Name = " + path + " / " + name, path == "Bass | Mixer" && name == "Track Volume");
- check ("browser: volume Min / Max = " + lynx::mapmode::rangeText (offline, volume, 0.0f) + " / " + lynx::mapmode::rangeText (offline, volume, 1.0f),
- lynx::mapmode::rangeText (offline, volume, 0.0f) == juce::String::fromUTF8 ("\xe2\x88\x92\xe2\x88\x9e dB")
- && lynx::mapmode::rangeText (offline, volume, 1.0f).endsWith (" dB"));
- const lynx::remotemap::Target pan = Target::parameter ({ lynx::AutomationTargetKind::mixerPan, 1, 0, 0 });
- check ("browser: pan Min / Max = " + lynx::mapmode::rangeText (offline, pan, 0.25f) + " / " + lynx::mapmode::rangeText (offline, pan, 0.5f),
- lynx::mapmode::rangeText (offline, pan, 0.25f) == "50L" && lynx::mapmode::rangeText (offline, pan, 0.5f) == "C"
- && lynx::mapmode::rangeText (offline, pan, 1.0f) == "100R");
- const auto typed = lynx::mapmode::rangeValueOf (offline, volume, "0 dB");
- check ("browser: typing 0 dB", typed.has_value() && std::abs (lynx::mapmode::rangeText (offline, volume, *typed).getDoubleValue()) < 0.15);
- check ("browser: typing 50L", lynx::mapmode::rangeValueOf (offline, pan, "50L") == std::optional<float> (0.25f));
- check ("browser: Key column = " + lynx::mapmode::listKeyText ('V') + ", " + lynx::mapmode::listKeyText ('3'),
- lynx::mapmode::listKeyText ('V') == "Key v" && lynx::mapmode::listKeyText ('3') == "Key 3");
- check ("browser: slot row Name = " + lynx::mapmode::describe (offline, Target::slot (0, 2)).second,
- lynx::mapmode::describe (offline, Target::slot (0, 2)) == std::pair<juce::String, juce::String> ("Drums", "Slot 3"));
- }
- // off again: the key mapping on a parameter toggles it between Min and Max
- ui.keyPressed (juce::KeyPress ('K', juce::ModifierKeys::ctrlModifier, 0));
- check ("Ctrl+K again ends it", ui.getMapMode() == Mode::off && ! overlay->isVisible() && ! list->isVisible());
- const lynx::AutomationTarget keysVolume { lynx::AutomationTargetKind::mixerVolume, 2, 0, 0 };
- // (round 190em, Live 12.4.16: the first press goes to Min, then Max, then Min)
- ui.keyPressed (juce::KeyPress ('V', {}, 'v'));
- check ("the mapped key V moves Bass's volume to Min first", std::abs (offline.currentTargetValue (keysVolume)) < 0.01f);
- ui.keyStateChanged (false); // (V is not down any more: its release)
- ui.keyPressed (juce::KeyPress ('V', {}, 'v'));
- check ("again: to Max", std::abs (offline.currentTargetValue (keysVolume) - 1.0f) < 0.01f);
- ui.keyStateChanged (false);
- ui.keyPressed (juce::KeyPress ('V', {}, 'v'));
- check ("again: to Min", std::abs (offline.currentTargetValue (keysVolume)) < 0.01f);
- ui.keyStateChanged (false);
- // the title bar switches
- ui.setMapMode (Mode::midi);
- write (ui, "06-switches-midi-on");
- ui.setMapMode (Mode::off);
- ui.setClipLaunchWorkflow (false);
- check ("leaving the Clip-launch layout ends the map mode", ui.getMapMode() == Mode::off);
- juce::File (prefix + "-checks.txt").replaceWithText (checks);
- }
- void runSceneShot190ef (const juce::String& prefix)
- {
- 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()));
- const auto write = [&prefix] (juce::Component& c, const char* name) {
- const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
- file.deleteFile();
- juce::FileOutputStream out (file);
- juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
- };
- juce::String checks;
- const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
- ui.setVisible (true);
- lynx::DetailView::shownSetting = false;
- ui.setClipLaunchWorkflow (true);
- ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist });
- offline.editSong ([] (lynx::Song& s) {
- const int channels = (int) s.channels.size();
- s.channels.resize ((std::size_t) channels + 3);
- const char* names[] { "Drum kit", "Bass synth", "Keys" };
- for (int k = 0; k < 3; ++k)
- {
- auto& ch = s.channels[(std::size_t) (channels + k)];
- ch.name = names[k];
- ch.instrument = k == 0 ? lynx::InstrumentKind::sampler : lynx::InstrumentKind::synth;
- }
- while (s.patterns.size() < 3)
- s.patterns.emplace_back();
- const char* patterns[] { "Beat", "Bassline", "Chords" };
- for (int p = 0; p < 3; ++p)
- {
- auto& pattern = s.patterns[(std::size_t) p];
- pattern.name = patterns[p];
- lynx::Note n;
- n.channel = channels + p;
- n.key = 48 + p * 5;
- pattern.notes = { n };
- pattern.lengthTicks = 4 * lynx::ppq;
- }
- s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 6));
- const char* tracks[] { "Drums", "Bass", "Keys" };
- const std::uint32_t colours[] { 0xFFE0533Bu, 0xFF3B8BE0u, 0xFF46C27Au };
- for (int t = 0; t < 3; ++t)
- {
- s.playlistTracks[(std::size_t) t].name = tracks[t];
- s.playlistTracks[(std::size_t) t].colour = colours[t];
- }
- for (int t = 0; t < 3; ++t)
- for (int r = 0; r < 3; ++r)
- if (! (t == 2 && r == 0))
- {
- lynx::Clip clip;
- clip.pattern = t;
- clip.length = 4 * lynx::ppq;
- lynx::launcher::setClip (s, t, r, clip);
- }
- auto& grid = lynx::launcher::ensureGrid (s);
- grid.scenes.resize (4);
- const char* scenes[] { "Intro", "Verse", "Drop" };
- for (int r = 0; r < 3; ++r)
- grid.scenes[(std::size_t) r].name = scenes[r];
- lynx::session::setSceneTempo (s, 1, 128.0);
- lynx::session::setSceneSignature (s, 1, 3, 4); // (as the live check's "Verse": 3 / 4)
- lynx::session::setSceneSignature (s, 2, 6, 8); // (round 190em: a denominator of its own)
- grid.scenes[2].colour = 0xFF8E5BD6u;
- }, false);
- offline.dispatchPendingMessages();
- ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
- offline.dispatchPendingMessages();
- ui.resized();
- auto* gridView = ui.getClipGridForSnapshot();
- if (gridView == nullptr)
- {
- juce::File (prefix + "-checks.txt").replaceWithText ("FAIL no grid\n");
- return;
- }
- lynx::clipGridSceneTempoShown() = true;
- lynx::refreshClipGrid (*gridView);
- lynx::selectClipGridScene (*gridView, 1);
- write (*gridView, "01-scene-fields");
- {
- // round 190em: a plain scene's launch triangle in Live's dark grey (#1E1E1E), scene 4 (row 3)
- const auto image = lynx::shot::snapshot (*gridView);
- int dark = 0;
- for (int y = 0; y < image.getHeight(); ++y)
- for (int x = image.getWidth() - 240; x < image.getWidth() - 180; ++x)
- if (const auto p = image.getPixelAt (x, y); y > 3 * 24 + 26 && y < 4 * 24 + 26 && std::abs (p.getRed() - 0x1e) <= 2
- && std::abs (p.getGreen() - 0x1e) <= 2 && std::abs (p.getBlue() - 0x1e) <= 2)
- ++dark;
- check ("plain scene triangle in Live's #1E1E1E (" + juce::String (dark) + " px)", dark >= 20);
- }
- saveMenus (juce::StringArray { "Scene menu (Verse)" }, std::vector<juce::PopupMenu> { lynx::clipGridSceneMenu (*gridView, 1) }, prefix + "-02-scene-menu.png");
- saveMenus (juce::StringArray { "Scene tempo field", "Scene time signature field" },
- std::vector<juce::PopupMenu> { lynx::clipGridSceneFieldMenu (*gridView, 1, 1), lynx::clipGridSceneFieldMenu (*gridView, 2, 2) },
- prefix + "-03-field-menus.png");
- saveMenus (juce::StringArray { "Column title (Bass)" }, std::vector<juce::PopupMenu> { lynx::clipGridHeaderMenu (*gridView, 1) }, prefix + "-04-title-menu.png");
- const auto clipsIn = [&offline] (int row) {
- int n = 0;
- if (const auto& g = offline.getSong().clipGrid)
- for (int t = 0; t < 8; ++t)
- n += lynx::launcher::clipAt (*g, t, row) != nullptr ? 1 : 0;
- return n;
- };
- const auto before = clipsIn (1);
- const auto dup = lynx::duplicateClipGridScene (*gridView, 1);
- offline.dispatchPendingMessages();
- const auto& scenesNow = offline.getSong().clipGrid->scenes;
- check ("duplicate: Verse's copy is row 2, with its clips and tempo", dup == 2 && clipsIn (2) == before && scenesNow.size() > 2
- && scenesNow[2].name == "Verse" && scenesNow[2].tempo == 128.0);
- write (*gridView, "05-scene-duplicated");
- const auto cap = lynx::captureClipGridScene (*gridView, 3, { 0, 2, 1 }); // Drums row 0, Bass row 2, Keys row 1
- offline.dispatchPendingMessages();
- check ("capture: a new row 4 with the three playing clips", cap == 4 && clipsIn (4) == 3);
- {
- const auto& sc = offline.getSong().clipGrid->scenes;
- check ("capture while playing: the new scene is plain (no name, fields off)", sc.size() > 4 && sc[4] == lynx::ClipGridScene {});
- }
- write (*gridView, "06-scene-captured");
- // round 190em: nothing plays: an empty scene like the selected one (name, tempo, signature), selected
- const auto empty = lynx::captureClipGridScene (*gridView, 1, { -1, -1 });
- offline.dispatchPendingMessages();
- {
- const auto& sc = offline.getSong().clipGrid->scenes;
- check ("capture with nothing playing: an empty row 2 named Verse, 128 BPM, 3 / 4", empty == 2 && clipsIn (2) == 0 && sc[2].name == "Verse"
- && sc[2].tempo == 128.0 && sc[2].beatsPerBar == 3 && sc[2].beatUnit == 4);
- }
- write (*gridView, "06b-scene-captured-stopped");
- // round 190em: Capture and Insert while clips play: playback moves to the new row (the runtime view shows what
- // the player reports once the published song holds the moved slots)
- {
- const auto rowsBefore = offline.getSong().clipGrid->scenes.size();
- lynx::selectClipGridScene (*gridView, 0);
- const auto at = lynx::captureClipGridScene (*gridView, 0, { 0, 0, -1 });
- offline.dispatchPendingMessages();
- const auto& g = *offline.getSong().clipGrid;
- check ("capture while playing: row 1 holds the moved playing slots", at == 1 && g.scenes.size() == rowsBefore + 1
- && clipsIn (1) == 2 && clipsIn (0) == 2 && g.scenes[1] == lynx::ClipGridScene {});
- if (auto* runtime = offline.launcherStateForSnapshot())
- for (int t = 0; t < 2; ++t)
- runtime->tracks[(std::size_t) t].playing.store (1);
- lynx::refreshClipGrid (*gridView);
- write (*gridView, "09-capture-playing-moves");
- if (auto* runtime = offline.launcherStateForSnapshot())
- for (int t = 0; t < 2; ++t)
- runtime->tracks[(std::size_t) t].playing.store (-1);
- }
- // round 190em: the fields as "n / d", a selected field, Del = Return to Default
- lynx::clipGridSceneTempoShown() = true;
- lynx::refreshClipGrid (*gridView);
- {
- const auto& sc = offline.getSong().clipGrid->scenes;
- int verse = -1;
- for (int r = 0; r < (int) sc.size() && verse < 0; ++r)
- if (sc[(std::size_t) r].name == "Verse" && sc[(std::size_t) r].tempo > 0.0)
- verse = r;
- lynx::selectClipGridSceneField (*gridView, verse, 1);
- write (*gridView, "10-field-selected");
- gridView->keyPressed (juce::KeyPress (juce::KeyPress::deleteKey));
- offline.dispatchPendingMessages();
- const auto& after = offline.getSong().clipGrid->scenes;
- check ("Del on a selected tempo field returns it to default (scene kept)", verse >= 0 && after.size() == sc.size()
- && after[(std::size_t) verse].tempo == 0.0 && after[(std::size_t) verse].beatsPerBar == 3);
- write (*gridView, "11-field-returned-to-default");
- }
- // round 190em: Capture MIDI to the armed track (Bass), the selected scene's slot, the tempo from the phrase
- {
- offline.stop();
- offline.setGridTrackArmed (1, true, true);
- lynx::selectClipGridScene (*gridView, 0);
- int empty = 0;
- while (lynx::launcher::clipAt (*offline.getSong().clipGrid, 1, empty) != nullptr)
- ++empty;
- const auto now = juce::Time::getMillisecondCounterHiRes();
- const auto beat = 60000.0 / 148.0;
- for (int i = 0; i < 8; ++i)
- {
- const auto at = now - 9.0 * beat + i * beat;
- offline.logPlayedNoteForTest (at, 0, 60 + (i % 4) * 2, 0.8f, true);
- offline.logPlayedNoteForTest (at + beat * 0.5, 0, 60 + (i % 4) * 2, 0.8f, false);
- }
- int placed = -1;
- bool into = true;
- const auto r = offline.captureMidiToSlot (1, empty, placed, into);
- offline.dispatchPendingMessages();
- check ("Capture MIDI: 8 notes into Bass row " + juce::String (placed) + ", tempo " + juce::String (offline.getSong().bpm, 2),
- r.notes == 8 && placed == empty && ! into && std::abs (offline.getSong().bpm - 148.0) < 0.5 && offline.getTransport().playing.load());
- const auto& capturedGrid = *offline.getSong().clipGrid;
- const auto* capturedClip = lynx::launcher::clipAt (capturedGrid, 1, placed);
- const auto* slot = capturedClip != nullptr ? &capturedGrid.slots[(std::size_t) capturedClip->gridSlot] : nullptr;
- check ("Capture MIDI: the clip has no name of its own (blank label, as Live)", slot != nullptr && slot->name.empty() && slot->blankName);
- if (auto* runtime = offline.launcherStateForSnapshot())
- runtime->tracks[1].playing.store (placed);
- lynx::refreshClipGrid (*gridView);
- write (*gridView, "12-capture-midi");
- if (auto* runtime = offline.launcherStateForSnapshot())
- runtime->tracks[1].playing.store (-1);
- offline.stop();
- }
- write (ui, "07-window");
- lynx::clipGridSceneTempoShown() = false;
- lynx::refreshClipGrid (*gridView);
- write (*gridView, "08-fields-off");
- juce::File (prefix + "-checks.txt").replaceWithText (checks);
- }
- void runDrawShot190ef (const juce::String& prefix)
- {
- 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()));
- const auto write = [&prefix] (juce::Component& c, const char* name) {
- const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
- file.deleteFile();
- juce::FileOutputStream out (file);
- juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
- };
- juce::String checks;
- const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
- ui.setVisible (true);
- ui.setClipLaunchWorkflow (true);
- ui.setClipGridView (lynx::PlaylistArea::GridView::song);
- ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist });
- lynx::autolanes::setShown (true);
- offline.editSong ([] (lynx::Song& s) {
- if (s.mixer.size() < 4)
- s.mixer.resize (4);
- s.mixer[1].name = "Bass";
- s.mixer[2].name = "Pad";
- s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 6));
- s.playlistTracks[0].name = "Bass";
- s.playlistTracks[0].mode = lynx::PlaylistTrackMode::audio;
- s.playlistTracks[0].mixerTrack = 1;
- s.playlistTracks[1].name = "Pad";
- s.playlistTracks[1].mode = lynx::PlaylistTrackMode::audio;
- s.playlistTracks[1].mixerTrack = 2;
- }, false);
- lynx::createAutomationLane (offline, { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, 0);
- lynx::createAutomationLane (offline, { lynx::AutomationTargetKind::mixerPan, 2, 0, 0 }, 1);
- offline.editSong ([] (lynx::Song& s) {
- for (int t = 0; t < 2; ++t)
- if (! s.playlistTracks[(std::size_t) t].lanes.empty())
- s.playlistTracks[(std::size_t) t].lanes[0].height = 110;
- }, false);
- offline.dispatchPendingMessages();
- auto& playlist = ui.getPlaylistForSnapshot();
- playlist.setViewForSnapshot (180.0, 0, 0);
- ui.resized();
- offline.dispatchPendingMessages();
- const auto& song = offline.getSong();
- const auto laneA = song.playlistTracks[0].lanes.empty() ? -1 : song.playlistTracks[0].lanes[0].automation;
- const auto laneB = song.playlistTracks[1].lanes.empty() ? -1 : song.playlistTracks[1].lanes[0].automation;
- check ("two lanes made", laneA >= 0 && laneB >= 0);
- if (laneA < 0 || laneB < 0)
- {
- juce::File (prefix + "-checks.txt").replaceWithText (checks);
- return;
- }
- write (ui, "00-lanes-before");
- const auto before = song.automations[(std::size_t) laneA].points;
- // a drag through the Playlist's own handlers (the events a real mouse sends)
- auto source = juce::Desktop::getInstance().getMainMouseSource();
- const auto now = juce::Time::getCurrentTime();
- const auto stroke = [&] (int track, const std::vector<juce::Point<float>>& path, juce::ModifierKeys extra) {
- const juce::ModifierKeys mods (juce::ModifierKeys::leftButtonModifier | extra.getRawFlags());
- const auto event = [&] (juce::Point<float> p, juce::ModifierKeys m, bool dragged) {
- return juce::MouseEvent (source, p, m, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, &playlist, &playlist, now, path.front(), now, 1, dragged);
- };
- juce::ignoreUnused (track);
- // (the engine joins the edits of one press into one undo step while a button is down)
- const auto held = juce::ModifierKeys::currentModifiers;
- juce::ModifierKeys::currentModifiers = mods;
- playlist.mouseDown (event (path.front(), mods, false));
- for (std::size_t i = 1; i < path.size(); ++i)
- playlist.mouseDrag (event (path[i], mods, true));
- juce::ModifierKeys::currentModifiers = held;
- playlist.mouseUp (event (path.back(), extra, true));
- };
- const auto bodyA = playlist.laneBodyForSnapshot (0, 0), bodyB = playlist.laneBodyForSnapshot (1, 0);
- const auto bar = (double) (4 * lynx::ppq);
- const auto x = [&] (double bars) { return (float) playlist.xOfTickForSnapshot (bars * bar); };
- const auto y = [] (juce::Rectangle<float> body, float v) { return body.getBottom() - v * body.getHeight(); };
- lynx::drawmode::set (true);
- // steps: a rise over bar 1 and a fall over bar 2, at the Playlist's grid (Line, at this zoom)
- std::vector<juce::Point<float>> steps;
- for (int k = 0; k <= 16; ++k)
- steps.push_back ({ x (1.0 + k / 16.0) + 2.0f, y (bodyA, 0.15f + 0.05f * (float) k) });
- for (int k = 0; k <= 16; ++k)
- steps.push_back ({ x (2.0 + k / 16.0) + 2.0f, y (bodyA, 0.95f - 0.05f * (float) k) });
- stroke (0, steps, {});
- const auto& afterSteps = offline.getSong().automations[(std::size_t) laneA].points;
- check ("Draw Mode drag made steps (" + juce::String ((int) afterSteps.size()) + " points)", afterSteps.size() > before.size() + 4);
- bool unchangedOutside = true;
- for (double t = 0.0; t < 6.0 * bar; t += 37.0)
- if ((t < bar - 1.0 || t > 3.1 * bar) && std::abs (lynx::automationCurveAt (before, t) - lynx::automationCurveAt (afterSteps, t)) > 1.0e-4f)
- unchangedOutside = false;
- check ("the curve outside the drawn bars is unchanged", unchangedOutside);
- {
- // flat inside each drawn cell: the values in a cell's first and last tick are the same
- int flatCells = 0, cells = 0;
- for (double t = bar; t < 3.0 * bar; t += lynx::ppq / 4.0)
- {
- ++cells;
- if (std::abs (lynx::automationCurveAt (afterSteps, t + 1.0) - lynx::automationCurveAt (afterSteps, t + lynx::ppq / 4.0 - 1.0)) < 1.0e-5f)
- ++flatCells;
- }
- check ("each sixteenth inside bars 2-3 is flat (" + juce::String (flatCells) + " / " + juce::String (cells) + ")", flatCells == cells);
- }
- // freehand: Alt (no grid) on the pad's pan lane, a wave over bars 1-4
- const auto panBefore = offline.getSong().automations[(std::size_t) laneB].points;
- // (off-screen every press has the same mouse-down time, which the undo history uses to join one press's edits:
- // an edit with no button down in between separates the two strokes, as a real second press does)
- offline.editSong ([] (lynx::Song&) {});
- std::vector<juce::Point<float>> wave;
- for (int k = 0; k <= 60; ++k)
- wave.push_back ({ x (1.0 + 3.0 * k / 60.0), y (bodyB, 0.5f + 0.4f * std::sin ((float) k * 0.3f)) });
- stroke (1, wave, juce::ModifierKeys (juce::ModifierKeys::altModifier));
- const auto& pan = offline.getSong().automations[(std::size_t) laneB].points;
- check ("Alt drag drew freehand (" + juce::String ((int) pan.size()) + " points)", pan.size() > 30);
- playlist.repaint();
- write (ui, "01-draw-mode-steps-and-freehand");
- if (auto* parent = playlist.getParentComponent())
- write (*parent, "01b-playlist");
- // one stroke is one undo step
- offline.undo();
- check ("one undo takes the whole freehand stroke back", offline.getSong().automations[(std::size_t) laneB].points == panBefore);
- // Draw Mode off: the same press adds one point, as before
- lynx::drawmode::set (false);
- const auto countOff = offline.getSong().automations[(std::size_t) laneA].points.size();
- stroke (0, { { x (4.5), y (bodyA, 0.8f) } }, {});
- check ("Draw Mode off: a press adds one point", offline.getSong().automations[(std::size_t) laneA].points.size() == countOff + 1);
- // the Options menu (Clip-launch layout) with the switch
- lynx::drawmode::set (true);
- {
- const auto names = ui.getMenuNamesForSnapshot();
- const auto index = names.indexOf (TRANS ("Options"));
- if (index >= 0)
- saveMenus (juce::StringArray { "Options" }, std::vector<juce::PopupMenu> { ui.getMenuForSnapshot (index) }, prefix + "-02-options-menu.png");
- check ("Options menu found", index >= 0);
- }
- lynx::drawmode::set (false);
- juce::File (prefix + "-checks.txt").replaceWithText (checks);
- }
- void runClipEnvShot190gi (const juce::String& prefix)
- {
- 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()));
- const auto write = [&prefix] (juce::Component& c, const char* name) {
- const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
- file.deleteFile();
- juce::FileOutputStream out (file);
- juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
- };
- juce::String checks;
- const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
- // two files: a sustained pad (4 s, a slow swell, for the envelope over its waveform) and a one-bar loop of clicks
- const auto writeWav = [] (const juce::File& file, int seconds, const std::function<float (int, double)>& fn) {
- const double rate = 48000.0;
- juce::AudioBuffer<float> buffer (2, (int) (rate * seconds));
- for (int ch = 0; ch < 2; ++ch)
- for (int i = 0; i < buffer.getNumSamples(); ++i)
- buffer.setSample (ch, i, fn (i, rate));
- file.deleteFile();
- if (auto out = std::unique_ptr<juce::FileOutputStream> (file.createOutputStream()))
- if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 2, 16, {}, 0))
- {
- out.release();
- std::unique_ptr<juce::AudioFormatWriter> owned (writer);
- owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
- }
- return file;
- };
- const auto pad = writeWav (juce::File (prefix + "-pad.wav"), 4, [] (int i, double rate) {
- const auto t = i / rate;
- return (float) (0.45 * (std::sin (juce::MathConstants<double>::twoPi * 220.0 * t) + 0.5 * std::sin (juce::MathConstants<double>::twoPi * 331.0 * t))
- * (0.7 + 0.3 * std::sin (juce::MathConstants<double>::twoPi * 1.5 * t)));
- });
- const auto loop = writeWav (juce::File (prefix + "-loop.wav"), 2, [] (int i, double) {
- const auto k = i % 12000;
- const auto hit = i / 12000;
- return k < 3000 ? (float) (std::sin (k * (hit % 4 == 0 ? 0.05 : 0.3)) * std::exp (-k / 500.0) * 0.8) : 0.0f;
- });
- ui.setVisible (true);
- ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist });
- offline.editSong ([&] (lynx::Song& s) {
- const auto add = [&s] (const char* name, const juce::File& file) {
- lynx::ChannelDef ch;
- ch.name = name;
- ch.instrument = lynx::InstrumentKind::audioClip;
- ch.samplePath = file.getFullPathName().toStdString();
- s.channels.push_back (ch);
- return (int) s.channels.size() - 1;
- };
- const auto padChannel = add ("Pad", pad), loopChannel = add ("Loop", loop);
- s.playlist.clear();
- lynx::Clip a;
- a.kind = lynx::ClipKind::audio;
- a.channel = padChannel;
- a.length = 8 * lynx::ppq;
- a.track = 0;
- s.playlist.push_back (a);
- a.track = 1;
- s.playlist.push_back (a);
- lynx::Clip b = a;
- b.channel = loopChannel;
- b.track = 2;
- b.length = 4 * lynx::ppq;
- s.playlist.push_back (b);
- // the first clip: a volume envelope (a swell, a dip, FL's curve modes on two segments)
- auto& e = lynx::clipenv::own (s, s.playlist[0]);
- e.shown = lynx::clipenv::volumeLane;
- e.volume = { { 0, 0.15f, 0.0f, 0 }, { lynx::ppq * 2, 1.0f, -0.6f, 0 }, { lynx::ppq * 4, 1.0f, 0.0f, 0 },
- { lynx::ppq * 5, 0.45f, 0.0f, 2 }, { lynx::ppq * 6, 0.9f, 0.0f, 0 }, { lynx::ppq * 8, 0.9f, 0.0f, 0 } };
- // the second: its pan lane shown (only pan made)
- lynx::clipenv::show (s, s.playlist[1], lynx::clipenv::panLane);
- auto& p = lynx::clipenv::own (s, s.playlist[1]);
- p.pan = { { 0, 0.5f, 0.0f, 0 }, { lynx::ppq * 2, 0.1f, 0.0f, 0 }, { lynx::ppq * 4, 0.9f, 0.0f, 0 }, { lynx::ppq * 6, 0.5f, 0.0f, 0 } };
- if (s.playlistTracks.size() < 3)
- s.playlistTracks.resize (3);
- for (int t = 0; t < 3; ++t)
- s.playlistTracks[(std::size_t) t].height = 96;
- }, false);
- offline.dispatchPendingMessages();
- auto& playlist = ui.getPlaylistForSnapshot();
- playlist.setViewForSnapshot (360.0, 0, 0);
- ui.resized();
- offline.dispatchPendingMessages();
- (void) lynx::shot::snapshot (ui); // (a paint starts the waveform analyses; the shot waits for them)
- lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
- offline.dispatchPendingMessages();
- write (ui, "01-playlist-envelopes");
- // the clip menu: LYNX's extras with Clip envelope ›, Auto-warp, Quantize audio (Auto-warp run from it on the loop)
- {
- const auto menu = playlist.getClipMenuForSnapshot (2);
- const juce::PopupMenu* envelopeMenu = nullptr;
- bool autoWarp = false, quantize = false;
- for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
- {
- if (it.getItem().text == lynx::tr ("Clip envelope") && it.getItem().subMenu != nullptr)
- envelopeMenu = it.getItem().subMenu.get();
- autoWarp = autoWarp || (it.getItem().text == lynx::tr ("Auto-warp") && it.getItem().isEnabled);
- quantize = quantize || (it.getItem().text == lynx::tr ("Quantize audio") && it.getItem().isEnabled);
- }
- check ("clip menu: Clip envelope submenu, Auto-warp, Quantize audio", envelopeMenu != nullptr && autoWarp && quantize);
- saveMenus (juce::StringArray { lynx::tr ("Audio clip"), lynx::tr ("Clip envelope") },
- std::vector<juce::PopupMenu> { menu, envelopeMenu != nullptr ? *envelopeMenu : juce::PopupMenu() }, prefix + "-02-clip-menu.png");
- check ("Auto-warp from the clip menu places markers", clickMenuItem (menu, lynx::tr ("Auto-warp")));
- offline.dispatchPendingMessages();
- const auto& s = offline.getSong();
- const auto& loopClip = s.playlist[2];
- check ("the loop's channel is warped", s.channels[(std::size_t) loopClip.channel].sampler.warp.size() >= 2
- && s.channels[(std::size_t) loopClip.channel].sampler.keepPitch);
- // the first clip's menu: Show volume envelope ticked
- const auto first = playlist.getClipMenuForSnapshot (0);
- bool ticked = false;
- for (juce::PopupMenu::MenuItemIterator it (first); it.next();)
- if (it.getItem().text == lynx::tr ("Clip envelope") && it.getItem().subMenu != nullptr)
- for (juce::PopupMenu::MenuItemIterator sub (*it.getItem().subMenu); sub.next();)
- ticked = ticked || (sub.getItem().text == lynx::tr ("Show volume envelope") && sub.getItem().isTicked);
- check ("Show volume envelope is ticked on the first clip", ticked);
- }
- // gestures through the Playlist's own handlers
- auto source = juce::Desktop::getInstance().getMainMouseSource();
- const auto now = juce::Time::getCurrentTime();
- const auto press = [&] (juce::Point<float> from, juce::Point<float> to, juce::ModifierKeys button, juce::ModifierKeys extra) {
- const juce::ModifierKeys mods (button.getRawFlags() | extra.getRawFlags());
- const auto event = [&] (juce::Point<float> p, juce::ModifierKeys m, bool dragged) {
- return juce::MouseEvent (source, p, m, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, &playlist, &playlist, now, from, now, 1, dragged);
- };
- const auto held = juce::ModifierKeys::currentModifiers;
- juce::ModifierKeys::currentModifiers = mods;
- playlist.mouseDown (event (from, mods, false));
- if (to != from)
- playlist.mouseDrag (event (to, mods, true));
- juce::ModifierKeys::currentModifiers = held;
- playlist.mouseUp (event (to, extra, to != from));
- };
- const auto x = [&] (double beats) { return (float) playlist.xOfTickForSnapshot (beats * lynx::ppq); };
- {
- const auto body = playlist.curveBodyForSnapshot (0);
- const auto points = offline.getSong().clipEnvelopes[(std::size_t) offline.getSong().playlist[0].envelope].volume.size();
- // [RMB] in the curve's area adds a point there (FL's in-Playlist automation editing, round 165)
- press ({ x (7.0), body.getBottom() - 0.3f * body.getHeight() }, { x (7.0), body.getBottom() - 0.3f * body.getHeight() },
- juce::ModifierKeys::rightButtonModifier, {});
- offline.dispatchPendingMessages();
- const auto& s = offline.getSong();
- const auto* e = lynx::clipenv::of (s, s.playlist[0]);
- check ("[RMB] on the clip's volume lane adds a point", e != nullptr && e->volume.size() == points + 1
- && std::abs (lynx::automationCurveAt (e->volume, 7.0 * lynx::ppq) - 0.3f) < 0.05f);
- // drag that point up with the Pencil
- press ({ x (7.0), body.getBottom() - 0.3f * body.getHeight() }, { x (7.0), body.getBottom() - 0.7f * body.getHeight() },
- juce::ModifierKeys::leftButtonModifier, {});
- offline.dispatchPendingMessages();
- const auto* moved = lynx::clipenv::of (offline.getSong(), offline.getSong().playlist[0]);
- check ("dragging the point moves it", moved != nullptr && std::abs (lynx::automationCurveAt (moved->volume, 7.0 * lynx::ppq) - 0.7f) < 0.05f);
- check ("the edits are undoable", offline.canUndo());
- }
- write (ui, "03-playlist-edited");
- {
- // warp: a double-click on the loop clip's flag strip adds a marker; Alt + drag on its line (mid clip) moves it
- const auto bounds = playlist.clipBoundsForSnapshot (2);
- const auto channelOf = [&] { return offline.getSong().playlist[2].channel; };
- const auto markers = [&] { return offline.getSong().channels[(std::size_t) channelOf()].sampler.warp; };
- const auto before = markers().size();
- const juce::Point<float> strip { x (1.5), (float) bounds.getY() + 13.0f + 3.0f };
- playlist.mouseDoubleClick (juce::MouseEvent (source, strip, juce::ModifierKeys::leftButtonModifier, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, &playlist, &playlist,
- now, strip, now, 2, false));
- offline.dispatchPendingMessages();
- check ("a double-click on the flag strip adds a warp marker", markers().size() == before + 1);
- if (markers().size() != before + 1)
- checks << " (strip seconds " << playlist.warpStripSecondsForSnapshot (2, strip.toInt()) << ", played markers "
- << (int) playlist.warpMarkerCountForSnapshot (2) << ", file seconds " << playlist.clipFileSecondsForSnapshot (2)
- << ", channel markers " << (int) before << ", clip at " << bounds.toString() << ", strip " << strip.toString() << ")\n";
- int added = -1;
- for (int k = 0; k < (int) markers().size(); ++k)
- if (std::abs (markers()[(std::size_t) k].beats - 1.5) < 0.05)
- added = k;
- check ("the marker sits on the beat it was added on", added > 0);
- if (added > 0)
- {
- const juce::Point<float> line { x (1.5), (float) bounds.getCentreY() + 10.0f };
- press (line, line.translated (x (1.75) - x (1.5), 0.0f), juce::ModifierKeys::leftButtonModifier, juce::ModifierKeys::altModifier);
- offline.dispatchPendingMessages();
- check ("Alt + drag on a marker's line moves it", added < (int) markers().size() && std::abs (markers()[(std::size_t) added].beats - 1.75) < 0.05);
- }
- }
- write (ui, "04-playlist-warp");
- // the Clip-launch layout: the Clip View's Envelopes tab of a grid audio clip
- offline.editSong ([&] (lynx::Song& s) {
- auto clip = s.playlist[0];
- clip.start = 0;
- lynx::launcher::setClip (s, 0, 0, clip);
- lynx::launcher::ensureGrid (s).scenes.resize (std::max<std::size_t> (1, lynx::launcher::ensureGrid (s).scenes.size()));
- }, false);
- offline.dispatchPendingMessages();
- const auto shootPanel = [&] (const char* name, bool envelopes, std::uint8_t lane) {
- auto panel = lynx::makeClipAudioPanel (offline, 0, 0);
- if (panel == nullptr)
- return false;
- panel->setSize (1100, 300);
- for (auto* child : panel->getChildren())
- if (auto* b = dynamic_cast<juce::TextButton*> (child); b != nullptr && b->getButtonText() == (envelopes ? lynx::tr ("Envelopes") : lynx::tr ("Sample")))
- if (b->onClick)
- b->onClick();
- if (lane != 0)
- offline.editSong ([lane] (lynx::Song& s) {
- if (s.clipGrid)
- if (auto* c = const_cast<lynx::Clip*> (lynx::launcher::clipAt (*s.clipGrid, 0, 0)); c != nullptr)
- lynx::clipenv::show (s, *c, lane);
- }, false);
- offline.dispatchPendingMessages();
- write (*panel, name);
- return true;
- };
- check ("Clip View: Sample tab", shootPanel ("05-clipview-sample", false, 0));
- check ("Clip View: Envelopes tab, Clip > Gain", shootPanel ("06-clipview-envelopes-gain", true, lynx::clipenv::volumeLane));
- check ("Clip View: Envelopes tab, Mixer > Track Panning", shootPanel ("07-clipview-envelopes-pan", true, lynx::clipenv::panLane));
- {
- const auto* c = offline.getSong().clipGrid ? lynx::launcher::clipAt (*offline.getSong().clipGrid, 0, 0) : nullptr;
- check ("the grid clip keeps the volume envelope", c != nullptr && lynx::clipenv::activeOf (offline.getSong(), *c) != nullptr);
- }
- shootPanel ("08-clipview-sample-again", false, 0); // (the tab choice back to Sample for the next run)
- juce::File (prefix + "-checks.txt").replaceWithText (checks);
- }
- void runLiveFactsShot190gx (const juce::String& prefix)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- lynx::AudioEngine offline (false);
- juce::String checks;
- const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
- // a 1 kHz sine, 20 s at 48 kHz (Live's 190gu clip-envelope stimulus), −9 dBFS
- const auto wav = juce::File (prefix + "-sine1k.wav");
- wav.deleteFile();
- {
- const double rate = 48000.0;
- juce::AudioBuffer<float> buffer (2, (int) (rate * 20.0));
- for (int k = 0; k < buffer.getNumSamples(); ++k)
- for (int ch = 0; ch < 2; ++ch)
- buffer.setSample (ch, k, (float) (0.3535 * std::sin (2.0 * juce::MathConstants<double>::pi * 1000.0 * k / rate)));
- if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
- if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 2, 16, {}, 0))
- {
- out.release();
- std::unique_ptr<juce::AudioFormatWriter> owned (writer);
- owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
- }
- }
- offline.editSong ([&wav] (lynx::Song& s) {
- s.bpm = 120.0;
- lynx::ChannelDef ch;
- ch.name = "sine1k";
- ch.instrument = lynx::InstrumentKind::audioClip;
- ch.samplePath = wav.getFullPathName().toStdString();
- s.channels.push_back (ch);
- const auto c = (int) s.channels.size() - 1;
- lynx::clipsample::setWarp (s, c, true, 20.0);
- lynx::warpmodes::setMode (s, c, (int) lynx::StretchMethod::beats);
- lynx::Clip audio;
- audio.kind = lynx::ClipKind::audio;
- audio.channel = c;
- audio.length = 40 * lynx::ppq;
- // Live's Clip Gain staircase of the 190gu render (−1 … 1 in 0.1 steps, 2 beats each), as LYNX lane values
- lynx::ClipEnvelope e;
- for (int k = 0; k <= 20; ++k)
- {
- const auto v = lynx::clipenv::fromLive (lynx::clipenv::volumeLane, -1.0 + 0.1 * k);
- for (const auto at : { 2 * k, 2 * k + 2 })
- {
- lynx::AutomationPoint p;
- p.tick = (std::int64_t) at * lynx::ppq;
- p.value = v;
- e.volume.push_back (p);
- }
- }
- e.shown = lynx::clipenv::volumeLane;
- s.clipEnvelopes.push_back (e);
- audio.envelope = (int) s.clipEnvelopes.size() - 1;
- lynx::launcher::setClip (s, 0, 0, audio);
- lynx::launcher::ensureGrid (s).scenes.resize (1);
- }, false);
- offline.dispatchPendingMessages();
- const auto channelOf = [&] {
- const auto* c = lynx::warpmodes::gridAudioClip (const_cast<lynx::Song&> (offline.getSong()), 0, 0);
- return c != nullptr ? c->channel : -1;
- };
- const auto shoot = [&] (const char* name, int w, int h, int tab) {
- auto panel = lynx::makeClipAudioPanel (offline, 0, 0);
- if (panel == nullptr)
- return std::unique_ptr<juce::Component>();
- panel->setSize (w, h);
- if (tab != 0)
- for (auto* child : panel->getChildren())
- if (auto* b = dynamic_cast<juce::TextButton*> (child); b != nullptr && b->getButtonText() == (tab == 2 ? lynx::tr ("Envelopes") : lynx::tr ("Sample")))
- if (b->onClick)
- b->onClick();
- offline.dispatchPendingMessages();
- const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
- file.deleteFile();
- juce::FileOutputStream out (file);
- juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (*panel), out);
- return panel;
- };
- const auto visibleText = [] (juce::Component& panel, const juce::String& text) {
- for (auto* child : panel.getChildren())
- if (auto* b = dynamic_cast<juce::TextButton*> (child); b != nullptr && b->getButtonText() == text)
- return b->isVisible();
- return false;
- };
- const auto setMode = [&] (int method) {
- offline.editSong ([&] (lynx::Song& s) { lynx::warpmodes::setMode (s, channelOf(), method); }, false);
- offline.dispatchPendingMessages();
- };
- check ("01 Beats (Preserve label + chooser, loop icon + Transient Envelope)", shoot ("01-audio-beats", 900, 250, 1) != nullptr);
- setMode ((int) lynx::StretchMethod::tones);
- check ("02 Tones (Grain Size 30.00)", shoot ("02-audio-tones", 900, 250, 1) != nullptr);
- setMode ((int) lynx::StretchMethod::texture);
- check ("03 Texture (Grain Size 65.00, Flux only when it plays)", shoot ("03-audio-texture", 900, 250, 1) != nullptr);
- if constexpr (lynx::warpmodes::complexProPlays)
- {
- offline.editSong ([&] (lynx::Song& s) { lynx::warpmodes::setComplexPro (s, channelOf()); }, false);
- offline.dispatchPendingMessages();
- check ("04 Complex Pro (Formants 100.00, Envelope 128)", shoot ("04-audio-complex-pro", 900, 250, 1) != nullptr);
- }
- else
- {
- setMode ((int) lynx::StretchMethod::complex);
- check ("04 Complex (nothing under the chooser)", shoot ("04-audio-complex", 900, 250, 1) != nullptr);
- }
- setMode ((int) lynx::StretchMethod::beats);
- {
- auto panel = shoot ("05-envelopes-clip-gain-staircase", 1390, 420, 2);
- check ("05 Envelopes tab shown on a warped clip", panel != nullptr && visibleText (*panel, lynx::tr ("Envelopes")));
- }
- offline.editSong ([&] (lynx::Song& s) { lynx::clipsample::setWarp (s, channelOf(), false, 20.0); }, false);
- offline.dispatchPendingMessages();
- {
- auto panel = shoot ("06-unwarped-sample-only", 1390, 420, 2);
- check ("06 an unwarped clip has no Envelopes tab (Live)", panel != nullptr && ! visibleText (*panel, lynx::tr ("Envelopes"))
- && visibleText (*panel, lynx::tr ("Sample")));
- }
- // the law: Live's staircase values round trip through the lane values
- bool law = true;
- for (int k = 0; k <= 20; ++k)
- {
- const auto L = -1.0 + 0.1 * k;
- law = law && std::abs (lynx::clipenv::toLive (lynx::clipenv::volumeLane, lynx::clipenv::fromLive (lynx::clipenv::volumeLane, L)) - L) < 2.0e-3;
- }
- check ("Clip Gain values round trip (Live → lane → Live)", law);
- juce::File (prefix + "-checks.txt").replaceWithText (checks);
- }
- void runWarpShot190fm (const juce::String& prefix)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- lynx::AudioEngine offline (false);
- juce::String checks;
- const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
- // a one-bar loop of clicks (2 s at 48 kHz) for the audio clips
- const auto wav = juce::File (prefix + "-loop.wav");
- wav.deleteFile();
- {
- const double rate = 48000.0;
- juce::AudioBuffer<float> buffer (2, (int) (rate * 2.0));
- buffer.clear();
- for (int hit = 0; hit < 8; ++hit)
- for (int k = 0; k < 3000; ++k)
- for (int ch = 0; ch < 2; ++ch)
- buffer.setSample (ch, hit * 12000 + k, (float) (std::sin (k * (hit % 4 == 0 ? 0.05 : 0.3)) * std::exp (-k / 500.0) * 0.8));
- if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
- if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 2, 16, {}, 0))
- {
- out.release();
- std::unique_ptr<juce::AudioFormatWriter> owned (writer);
- owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
- }
- }
- offline.editSong ([&wav] (lynx::Song& s) {
- lynx::ChannelDef ch;
- ch.name = "Loop";
- ch.instrument = lynx::InstrumentKind::audioClip;
- ch.samplePath = wav.getFullPathName().toStdString();
- s.channels.push_back (ch);
- const auto c = (int) s.channels.size() - 1;
- lynx::clipsample::setWarp (s, c, true, 2.0);
- lynx::warpmodes::setMode (s, c, (int) lynx::StretchMethod::beats); // (keeps the pitch: Beats, not Re-Pitch)
- lynx::Clip audio;
- audio.kind = lynx::ClipKind::audio;
- audio.channel = c;
- audio.length = 4 * lynx::ppq;
- lynx::launcher::setClip (s, 0, 0, audio);
- lynx::launcher::setClip (s, 0, 1, audio); // (a second clip on the same channel: O16)
- lynx::launcher::ensureGrid (s).scenes.resize (2);
- }, false);
- offline.dispatchPendingMessages();
- const auto shoot = [&] (const char* name) {
- auto panel = lynx::makeClipAudioPanel (offline, 0, 0);
- if (panel == nullptr)
- return false;
- panel->setSize (900, 250);
- const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
- file.deleteFile();
- juce::FileOutputStream out (file);
- juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (*panel), out);
- return true;
- };
- const auto channelOf = [&] (int scene) {
- const auto* c = lynx::warpmodes::gridAudioClip (const_cast<lynx::Song&> (offline.getSong()), 0, scene);
- return c != nullptr ? c->channel : -1;
- };
- const auto beatsOn = [&] { const auto& sm = offline.getSong().channels[(std::size_t) channelOf (0)].sampler; return sm.keepPitch && sm.stretchMethod == lynx::StretchMethod::beats; };
- check ("01 Beats panel (defaults: Transients, Back-and-Forth, 100)", beatsOn() && shoot ("01-beats-defaults"));
- offline.editSong ([&] (lynx::Song& s) {
- const auto c = lynx::warpmodes::ownChannelForGridClip (s, 0, 0);
- lynx::warpmodes::setPreserve (s, c, 3);
- lynx::warpmodes::setLoopMode (s, c, 0);
- lynx::warpmodes::setEnvelope (s, c, 40.0);
- }, false);
- offline.dispatchPendingMessages();
- check ("O16: the first clip moved to its own channel, the second kept the old one", channelOf (0) != channelOf (1) && channelOf (0) >= 0 && channelOf (1) >= 0);
- check ("02 Beats panel (1/8, Loop Off, 40)", beatsOn() && shoot ("02-beats-set"));
- offline.editSong ([&] (lynx::Song& s) { lynx::warpmodes::setMode (s, channelOf (0), (int) lynx::StretchMethod::tones); }, false);
- offline.dispatchPendingMessages();
- check ("03 Tones panel (Grain Size 30)", shoot ("03-tones"));
- offline.editSong ([&] (lynx::Song& s) {
- lynx::warpmodes::setMode (s, channelOf (0), (int) lynx::StretchMethod::texture);
- lynx::warpmodes::setGrain (s, channelOf (0), 120.0);
- }, false);
- offline.dispatchPendingMessages();
- check ("04 Texture panel (Grain Size 120)", shoot ("04-texture"));
- check ("Texture grain kept 120, Tones grain still 30", offline.getSong().channels[(std::size_t) channelOf (0)].sampler.warpModes.textureGrain == 120.0f
- && offline.getSong().channels[(std::size_t) channelOf (0)].sampler.warpModes.tonesGrain == 30.0f);
- offline.editSong ([&] (lynx::Song& s) { lynx::warpmodes::setMode (s, channelOf (0), (int) lynx::StretchMethod::complex); }, false);
- offline.dispatchPendingMessages();
- check ("05 Complex panel (no settings row)", shoot ("05-complex"));
- juce::File (prefix + "-checks.txt").replaceWithText (checks);
- }
- void runLiveShot190dr (const juce::String& prefix)
- {
- 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()));
- const auto write = [&prefix] (juce::Component& c, const char* name) {
- const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
- file.deleteFile();
- juce::FileOutputStream out (file);
- juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
- };
- juce::String checks;
- const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
- // a two-bar loop of clicks for the audio clip
- const auto wav = juce::File (prefix + "-loop.wav");
- wav.deleteFile();
- {
- const double rate = 48000.0;
- juce::AudioBuffer<float> buffer (2, (int) (rate * 4.0));
- buffer.clear();
- for (int hit = 0; hit < 16; ++hit)
- for (int k = 0; k < 3000 && hit * 12000 + k < buffer.getNumSamples(); ++k)
- for (int ch = 0; ch < 2; ++ch)
- buffer.setSample (ch, hit * 12000 + k, (float) (std::sin (k * (hit % 4 == 0 ? 0.05 : 0.3)) * std::exp (-k / 500.0) * 0.8));
- if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
- if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 2, 16, {}, 0))
- {
- out.release();
- std::unique_ptr<juce::AudioFormatWriter> owned (writer);
- owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
- }
- }
- ui.setVisible (true);
- lynx::DetailView::shownSetting = true;
- lynx::DetailView::devicesPage = false;
- ui.setClipLaunchWorkflow (true);
- ui.showPanelsForSnapshot ({ lynx::workspace::Panel::browser, lynx::workspace::Panel::playlist });
- ui.getPlaylistForSnapshot().addAudioClipAtPlayhead (wav);
- offline.dispatchPendingMessages();
- int audioChannel = -1;
- offline.editSong ([&audioChannel] (lynx::Song& s) {
- lynx::Clip audio;
- if (! s.playlist.empty())
- {
- audio = s.playlist.front();
- audioChannel = audio.channel;
- s.playlist.clear();
- }
- const int channels = (int) s.channels.size();
- s.channels.resize ((std::size_t) channels + 3);
- const char* names[] { "Drum kit", "Bass synth", "Keys" };
- for (int k = 0; k < 3; ++k)
- {
- auto& ch = s.channels[(std::size_t) (channels + k)];
- ch.name = names[k];
- ch.instrument = k == 0 ? lynx::InstrumentKind::sampler : lynx::InstrumentKind::synth;
- ch.mixerTrack = k + 1;
- }
- if (audioChannel >= 0)
- s.channels[(std::size_t) audioChannel].mixerTrack = 5;
- if (s.mixer.size() < 8)
- s.mixer.resize (8);
- const char* inserts[] { "Master", "Drums", "Bass", "Keys", "Vox", "Loop", "Reverb", "Delay" };
- for (int i = 1; i < 8; ++i)
- s.mixer[(std::size_t) i].name = inserts[i];
- s.mixer[1].volume = lynx::sessionmixer::positionForDb (-3.0);
- s.mixer[2].pan = 0.3f;
- s.mixer[2].effects.clear();
- for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor, lynx::EffectKind::delay })
- {
- lynx::EffectSlot fx;
- fx.kind = kind;
- const auto& info = lynx::effectInfo (kind);
- for (std::size_t k = 0; k < info.params.size() && k < fx.params.size(); ++k)
- fx.params[k] = info.params[k].defaultValue;
- s.mixer[2].effects.push_back (fx);
- }
- s.mixer[3].muted = true; // the Keys' activator off
- s.mixer[4].inputChannel = 0;
- s.mixer[4].inputStereo = true;
- s.mixer[4].monitor = lynx::InputMonitor::automatic;
- s.mixer[4].effects.clear();
- {
- lynx::EffectSlot fx;
- fx.kind = lynx::EffectKind::reverb;
- s.mixer[4].effects.push_back (fx);
- }
- s.mixer[5].solo = true;
- for (auto [from, to, level] : std::initializer_list<std::tuple<int, int, float>> { { 1, 6, 0.35f }, { 2, 6, 0.6f }, { 3, 6, 0.8f }, { 2, 7, 0.25f }, { 4, 7, 0.5f } })
- {
- lynx::MixerSend send;
- send.target = to;
- send.level = lynx::faderGain (level);
- s.mixer[(std::size_t) from].sends.push_back (send);
- }
- while (s.patterns.size() < 3)
- s.patterns.emplace_back();
- const char* patterns[] { "Beat", "Bassline", "Chords" };
- for (int p = 0; p < 3; ++p)
- {
- auto& pattern = s.patterns[(std::size_t) p];
- pattern.name = patterns[p];
- lynx::Note n;
- n.channel = channels + p;
- n.key = 48 + p * 5;
- pattern.notes = { n };
- pattern.lengthTicks = 4 * lynx::ppq;
- }
- s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 8));
- const char* tracks[] { "Drums", "Bass", "Keys", "Vox", "Loop", "FX" };
- for (int t = 0; t < 6; ++t)
- s.playlistTracks[(std::size_t) t].name = tracks[t];
- s.playlistTracks[3].mode = lynx::PlaylistTrackMode::audio;
- s.playlistTracks[3].mixerTrack = 4;
- for (int t = 0; t < 3; ++t)
- for (int r = 0; r < 3; ++r)
- if (! (t == 2 && r == 0))
- {
- lynx::Clip clip;
- clip.pattern = t;
- clip.length = 4 * lynx::ppq;
- lynx::launcher::setClip (s, t, r, clip);
- }
- if (audioChannel >= 0)
- {
- lynx::clipsample::setWarp (s, audioChannel, true, 4.0); // (Warp on, as a dropped loop in Live)
- audio.track = 4;
- audio.start = 0;
- lynx::launcher::setClip (s, 4, 0, audio);
- lynx::launcher::setClip (s, 4, 1, audio);
- }
- auto& grid = lynx::launcher::ensureGrid (s);
- const char* scenes[] { "Intro", "Verse", "Drop" };
- grid.scenes.resize (5);
- for (int r = 0; r < 3; ++r)
- grid.scenes[(std::size_t) r].name = scenes[r];
- }, false);
- offline.dispatchPendingMessages();
- offline.setGridTrackArmed (3, true);
- ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
- offline.dispatchPendingMessages();
- ui.resized();
- auto* gridView = ui.getClipGridForSnapshot();
- auto* mixer = gridView != nullptr ? lynx::clipGridMixer (*gridView) : nullptr;
- auto* detail = ui.getDetailViewForSnapshot();
- if (gridView == nullptr || mixer == nullptr || detail == nullptr)
- {
- juce::File (prefix + "-checks.txt").replaceWithText ("FAIL no grid, mixer or detail view\n");
- return;
- }
- // the meters: a level per insert, as a playing song leaves them (offscreen nothing plays), two ticks
- const auto levels = [&] {
- for (int k = 0; k < 2; ++k)
- {
- const float peaks[] { 0.9f, 0.5f, 0.7f, 0.0f, 0.3f, 0.45f, 0.2f, 0.12f };
- for (int i = 0; i < 8; ++i)
- offline.getMeters().accumulate (i, peaks[i], peaks[i] * 0.85f);
- mixer->tick();
- }
- };
- if (auto* runtime = offline.launcherStateForSnapshot())
- {
- runtime->tracks[0].playing.store (1);
- runtime->tracks[0].progress.store (0.3f);
- runtime->tracks[1].playing.store (1);
- runtime->tracks[1].progress.store (0.3f);
- runtime->tracks[4].playing.store (0);
- runtime->tracks[4].progress.store (0.5f);
- runtime->running.store (true);
- }
- levels();
- gridView->resized();
- write (ui, "01-session-mixer");
- write (*gridView, "01b-grid-alone");
- using Part = lynx::SessionMixerComponent::Part;
- check ("mixer: Sends rows are the two buses (Reverb 6, Delay 7)", mixer->sendTargets() == std::vector<int> { 6, 7 });
- check ("mixer: the arm buttons moved into the Volume section", mixer->armsShown());
- check ("mixer: Drums strip has activator, solo, arm, pan, volume", ! mixer->partBounds (0, Part::activator).isEmpty() && ! mixer->partBounds (0, Part::solo).isEmpty()
- && ! mixer->partBounds (0, Part::arm).isEmpty() && ! mixer->partBounds (0, Part::pan).isEmpty()
- && ! mixer->partBounds (0, Part::volume).isEmpty());
- check ("mixer: Vox strip (audio track) has Audio From, its channel, Monitor and Audio To", ! mixer->partBounds (3, Part::inType).isEmpty()
- && ! mixer->partBounds (3, Part::inChannel).isEmpty()
- && ! mixer->partBounds (3, Part::monAuto).isEmpty()
- && ! mixer->partBounds (3, Part::output).isEmpty());
- check ("mixer: Bass strip (instrument) shows MIDI From, no Monitor", mixer->partBounds (1, Part::monIn).isEmpty() && ! mixer->partBounds (1, Part::output).isEmpty());
- check ("mixer: FX strip (no clips) has no activator but an arm", mixer->partBounds (5, Part::activator).isEmpty() && ! mixer->partBounds (5, Part::arm).isEmpty());
- check ("mixer: Main strip has volume and pan, no activator", ! mixer->partBounds (-2, Part::volume).isEmpty() && mixer->partBounds (-2, Part::activator).isEmpty());
- {
- const auto hit = mixer->hitAt (mixer->partBounds (2, Part::solo).getCentre());
- check ("mixer: a click on the Keys' S is its solo", hit.column == 2 && hit.part == Part::solo);
- const auto send = mixer->hitAt (mixer->partBounds (1, Part::send, 1).getCentre());
- check ("mixer: the Bass' second knob is its send to Delay", send.column == 1 && send.part == Part::send && send.row == 1);
- }
- {
- juce::PopupMenu menu;
- mixer->addViewItems (menu);
- saveMenus (juce::StringArray { "Mixer (footer button)" }, std::vector<juce::PopupMenu> { menu }, prefix + "-02-mixer-view-menu.png");
- }
- offline.editSong ([] (lynx::Song& s) { lynx::launcher::ensureGrid (s).mixerView.trackOptions = true; }, false);
- offline.dispatchPendingMessages();
- gridView->resized();
- levels();
- write (*gridView, "03-mixer-track-options");
- offline.editSong ([] (lynx::Song& s) {
- auto& v = lynx::launcher::ensureGrid (s).mixerView;
- v.trackOptions = v.io = v.sends = false;
- }, false);
- offline.dispatchPendingMessages();
- gridView->resized();
- levels();
- write (*gridView, "04-mixer-volume-only");
- offline.editSong ([] (lynx::Song& s) { lynx::launcher::ensureGrid (s).mixerView.shown = false; }, false);
- offline.dispatchPendingMessages();
- gridView->resized();
- write (*gridView, "05-mixer-hidden");
- check ("mixer hidden: the arm buttons are back in the status row", ! mixer->armsShown() && mixer->getHeight() == 0);
- offline.editSong ([] (lynx::Song& s) { lynx::launcher::ensureGrid (s).mixerView = {}; }, false);
- offline.dispatchPendingMessages();
- gridView->resized();
- // the Clip page of the Loop clip (track 4, scene 0) while it plays: Warp on, the Set buttons lit, the title
- detail->showSelection (4, 0);
- detail->setPage (lynx::DetailView::Page::clip);
- offline.editSong ([] (lynx::Song&) {}, false); // (a change message: the Clip panel reads the playing state)
- offline.dispatchPendingMessages();
- write (ui, "06-clip-audio-warp-on");
- if (audioChannel >= 0)
- {
- const auto beforeLength = lynx::launcher::clipAt (*offline.getSong().clipGrid, 4, 0)->length;
- offline.editSong ([audioChannel] (lynx::Song& s) { lynx::clipsample::setWarp (s, audioChannel, false, 4.0); });
- offline.dispatchPendingMessages();
- write (ui, "07-clip-audio-warp-off");
- check ("warp off: the channel plays at its own speed", ! lynx::clipsample::isWarped (offline.getSong().channels[(std::size_t) audioChannel].sampler));
- offline.undo();
- offline.dispatchPendingMessages();
- check ("warp: undo gives the clip back as it was", lynx::launcher::clipAt (*offline.getSong().clipGrid, 4, 0)->length == beforeLength
- && lynx::clipsample::isWarped (offline.getSong().channels[(std::size_t) audioChannel].sampler));
- // Set (start) at the play position, half way: one undo step
- const auto clipBefore = *lynx::launcher::clipAt (*offline.getSong().clipGrid, 4, 0);
- offline.editSong ([] (lynx::Song& s) {
- for (auto& c : s.clipGrid->clips)
- if (c.track == 4 && c.gridSlot >= 0 && s.clipGrid->slots[(std::size_t) c.gridSlot].scene == 0)
- lynx::clipsample::setStartAt (c, lynx::clipsample::playPosition (c, 0.5f));
- });
- const auto& after = *lynx::launcher::clipAt (*offline.getSong().clipGrid, 4, 0);
- check ("set start: the clip starts half way and ends where it did", after.offset == clipBefore.offset + clipBefore.length / 2
- && after.offset + after.length == clipBefore.offset + clipBefore.length);
- offline.undo();
- offline.dispatchPendingMessages();
- }
- // a MIDI clip's Clip page too (the Set buttons are there for every clip), playing through a groove of the pool
- offline.editSong ([] (lynx::Song& s) {
- const auto& bank = lynx::groove::factoryBank();
- if (bank.size() > 9)
- lynx::groove::setClipGroove (s, 0, 1, lynx::groove::add (s.grooves, bank[9].groove));
- }, false);
- detail->showSelection (0, 1);
- offline.editSong ([] (lynx::Song&) {}, false);
- offline.dispatchPendingMessages();
- write (ui, "08-clip-midi-set-buttons");
- // the Device View of Bass (insert 2): its compressor dragged onto Keys (insert 3), then Ctrl-dragged onto Vox
- detail->showSelection (1, 0);
- detail->setPage (lynx::DetailView::Page::devices);
- offline.dispatchPendingMessages();
- write (ui, "09-devices-bass-before");
- lynx::setClipGridDeviceDropForSnapshot (*gridView, 2);
- write (ui, "10-device-dragged-over-keys");
- lynx::setClipGridDeviceDropForSnapshot (*gridView, -1);
- int fromId = 0;
- {
- const auto& s = offline.getSong();
- fromId = (int) (s.mixer[2].effects[1].instance.id & 0x7fffffff);
- }
- offline.editSongStructural ([] (lynx::Song& s) { lynx::detailchain::moveEffectToInsert (s, 2, 1, 3, false); });
- offline.dispatchPendingMessages();
- check ("drag to Keys: the compressor moved (same device)", offline.getSong().mixer[2].effects.size() == 2 && offline.getSong().mixer[3].effects.size() == 1
- && (int) (offline.getSong().mixer[3].effects[0].instance.id & 0x7fffffff) == fromId);
- detail->showSelection (2, 1);
- offline.dispatchPendingMessages();
- write (ui, "11-devices-keys-after-move");
- offline.editSongStructural ([] (lynx::Song& s) { lynx::detailchain::moveEffectToInsert (s, 2, 0, 4, true); });
- offline.dispatchPendingMessages();
- check ("Ctrl-drag to Vox: a copy of the EQ after its reverb, Bass keeps its own", offline.getSong().mixer[4].effects.size() == 2
- && offline.getSong().mixer[4].effects[1].kind == lynx::EffectKind::eq
- && offline.getSong().mixer[2].effects[0].kind == lynx::EffectKind::eq);
- offline.undo();
- offline.undo();
- offline.dispatchPendingMessages();
- check ("undo twice: Bass has its three devices again, Keys none", offline.getSong().mixer[2].effects.size() == 3 && offline.getSong().mixer[3].effects.empty()
- && offline.getSong().mixer[4].effects.size() == 1);
- juce::File (prefix + "-checks.txt").replaceWithText (checks);
- wav.deleteFile();
- }
- void runWarpShot (const juce::String& prefix)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- lynx::AudioEngine offline (false);
- lynx::MainComponent ui (offline, false);
- ui.setSize (1600, 900);
- const auto write = [&prefix] (juce::Component& c, const char* name) {
- const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
- file.deleteFile();
- juce::FileOutputStream out (file);
- juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
- };
- // a two-bar loop of clicks, a little off the grid (what Quantize is for)
- const auto wav = juce::File (prefix + "-loop.wav");
- wav.deleteFile();
- {
- const double rate = 44100.0;
- juce::AudioBuffer<float> buffer (1, (int) (rate * 4.0));
- buffer.clear();
- for (int hit = 0; hit < 8; ++hit)
- {
- const auto at = (int) ((hit * 0.5 + (hit % 3) * 0.035) * rate);
- for (int k = 0; k < 4000 && at + k < buffer.getNumSamples(); ++k)
- buffer.setSample (0, at + k, (float) (std::sin (k * (hit % 2 ? 0.25 : 0.06)) * std::exp (-k / 700.0) * 0.8));
- }
- if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
- if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 1, 16, {}, 0))
- {
- out.release();
- std::unique_ptr<juce::AudioFormatWriter> owned (writer);
- owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
- }
- }
- ui.setVisible (true);
- lynx::DetailView::shownSetting = true;
- ui.selectTabForSnapshot (2);
- ui.setLayoutStyle (lynx::layoutstyle::Style::clipLaunch);
- lynx::autolanes::setShown (true);
- ui.getPlaylistForSnapshot().addAudioClipAtPlayhead (wav);
- offline.dispatchPendingMessages();
- int channel = -1;
- offline.editSong ([&channel] (lynx::Song& s) {
- if (s.playlist.empty())
- return;
- auto audio = s.playlist.front();
- channel = audio.channel;
- audio.track = 1;
- s.playlist.front() = audio;
- for (int k = 1; k < 3; ++k)
- {
- auto more = audio;
- more.start = audio.start + k * 8 * lynx::ppq;
- s.playlist.push_back (more);
- }
- while (s.patterns.size() < 1)
- s.patterns.emplace_back();
- for (int t = 2; t < 5; ++t)
- for (int k = 0; k < 4; ++k)
- {
- lynx::Clip c;
- c.pattern = 0;
- c.track = t;
- c.start = k * 4 * lynx::ppq;
- c.length = 4 * lynx::ppq;
- s.playlist.push_back (c);
- }
- s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 6));
- s.playlistTracks[1].name = "Loop";
- s.playlistTracks[2].name = "Drums";
- s.playlistTracks[3].name = "Kick";
- s.playlistTracks[4].name = "Hats";
- s.playlistTracks[4].folded = true;
- lynx::noteedit::groupWithAbove (s, 3);
- lynx::noteedit::groupWithAbove (s, 4);
- lynx::arrange::makeGroupBus (s, 3);
- lynx::autolanes::addLane (s, 1, { lynx::AutomationTargetKind::tempo, 0, 0, 0 }, "Tempo", lynx::valueFromTempo (s.bpm));
- if (! s.automations.empty())
- s.automations.back().points = { { 0, lynx::valueFromTempo (120.0), 0.0f }, { 8 * lynx::ppq, lynx::valueFromTempo (120.0), 0.0f },
- { 12 * lynx::ppq, lynx::valueFromTempo (180.0), 0.0f }, { 16 * lynx::ppq, lynx::valueFromTempo (140.0), 0.0f } };
- s.addMarker ({ 4 * lynx::ppq, "Verse", 0, 0 });
- s.addMarker ({ 8 * lynx::ppq, {}, 3, 4 });
- s.addMarker ({ 14 * lynx::ppq, {}, 4, 4 });
- s.loopStart = 4 * lynx::ppq;
- s.loopEnd = 12 * lynx::ppq;
- s.loopOff = true;
- s.tempoViewLow = 60.0; // the tempo lane's range
- s.tempoViewHigh = 200.0;
- std::stable_sort (s.playlist.begin(), s.playlist.end(), [] (const lynx::Clip& a, const lynx::Clip& b) { return a.start < b.start; });
- // the same audio in the clip grid, for the Clip page
- lynx::Clip slot = audio;
- slot.start = 0;
- slot.pitch = -2.25f;
- slot.gain = 0.7f;
- lynx::launcher::setClip (s, 1, 0, slot);
- // a few warp markers, as Quantize leaves them
- if (channel >= 0 && channel < (int) s.channels.size())
- {
- auto& sampler = s.channels[(std::size_t) channel].sampler;
- lynx::warpedit::ensureMarkers (sampler, 4.0, s.bpm);
- std::vector<double> attacks;
- for (int hit = 1; hit < 8; ++hit)
- attacks.push_back (hit * 0.5 + (hit % 3) * 0.035);
- lynx::warptools::quantize (sampler, attacks, 0.0, 4.0, 0.5, 1.0);
- lynx::warpedit::syncLength (sampler, 4.0);
- }
- }, false);
- offline.dispatchPendingMessages();
- ui.resized();
- write (ui, "arrangement-loop-off");
- offline.editSong ([] (lynx::Song& s) { s.loopOff = false; }, false);
- offline.dispatchPendingMessages();
- write (ui, "arrangement-loop-on");
- juce::String facts;
- {
- const auto& s = offline.getSong();
- facts << "channel " << channel << ", warp markers " << (channel >= 0 ? (int) s.channels[(std::size_t) channel].sampler.warp.size() : -1)
- << ", group bus insert " << lynx::arrange::groupBus (s, 3) << ", folded track 4: " << (lynx::arrange::isFolded (s, 4) ? 1 : 0) << "\n";
- }
- if (auto* detail = ui.getDetailViewForSnapshot())
- {
- detail->showSelection (1, 0);
- detail->setPage (lynx::DetailView::Page::clip);
- offline.dispatchPendingMessages();
- write (ui, "clip-audio");
- }
- if (channel >= 0)
- if (auto editor = lynx::makeAudioEditorPanel (offline, channel, 0, true))
- {
- editor->setSize (1120, 600);
- write (*editor, "audio-editor-warp");
- // round 190cy (Live 12.4.16 live check 190cw shot 09): a plain drag of marker 3 holds it two sixteenths
- // later (its audio goes there); Shift + drag slides the audio under it. Round 190db: the Clip-launch
- // workflow draws the warped clip in beats, so the held drag shows the audio stretched around the marker
- // (plain) or slid under it, its attack later (Shift, to the right as in Live's shot)
- const auto& w = offline.getSong().channels[(std::size_t) channel].sampler.warp;
- if (w.size() > 4)
- {
- lynx::holdAudioEditorWarpDragForSnapshot (*editor, 3, w[3].beats + 0.5, false);
- write (*editor, "audio-editor-drag-stretch");
- lynx::holdAudioEditorWarpDragForSnapshot (*editor, 3, w[3].seconds - 0.12, true);
- write (*editor, "audio-editor-drag-slide");
- }
- // the same clip in file time (the Pattern workflow's view, or "Show the audio in beats" off)
- if (auto inFileTime = lynx::makeAudioEditorPanel (offline, channel, 0, true))
- {
- inFileTime->setSize (1120, 600);
- lynx::setAudioEditorBeatTimeForSnapshot (*inFileTime, 0);
- write (*inFileTime, "audio-editor-file-time");
- if (w.size() > 4)
- {
- lynx::holdAudioEditorWarpDragForSnapshot (*inFileTime, 3, w[3].beats + 0.5, false);
- write (*inFileTime, "audio-editor-file-time-drag");
- }
- }
- }
- // round 190cy (Live 12.4.16 live check 190cw shot 02): ÷2 from the editor of the first Playlist clip halves that
- // clip's length with the markers' beats; ÷2 on the grid clip's Clip page halves the grid clip
- {
- const auto lengthOf = [&offline] (int index) { return index < (int) offline.getSong().playlist.size() ? offline.getSong().playlist[(std::size_t) index].length : -1; };
- const auto gridLength = [&offline] {
- const auto& s = offline.getSong();
- const auto* c = s.clipGrid ? lynx::launcher::clipAt (*s.clipGrid, 1, 0) : nullptr;
- return c != nullptr ? c->length : (std::int64_t) -1;
- };
- const auto first = [&offline] {
- const auto& s = offline.getSong();
- for (int i = 0; i < (int) s.playlist.size(); ++i)
- if (s.playlist[(std::size_t) i].kind == lynx::ClipKind::audio)
- return i;
- return -1;
- }();
- facts << "halve: playlist clip " << first << " length " << lengthOf (first);
- if (first >= 0)
- if (auto editor = lynx::makeAudioEditorPanel (offline, offline.getSong().playlist[(std::size_t) first].channel, first, true))
- {
- lynx::scaleAudioEditorTempoForSnapshot (*editor, 0.5);
- offline.dispatchPendingMessages();
- }
- facts << " -> " << lengthOf (first) << "; grid clip length " << gridLength();
- if (channel >= 0)
- if (auto editor = lynx::makeAudioEditorPanel (offline, channel, -1, true))
- {
- lynx::setAudioEditorGridClip (*editor, 1, 0);
- lynx::scaleAudioEditorTempoForSnapshot (*editor, 0.5);
- offline.dispatchPendingMessages();
- }
- facts << " -> " << gridLength() << "\n";
- ui.resized();
- write (ui, "arrangement-halved");
- // Duplicate Time over beats 4-8 holding the locator "Verse" (beat 4): a second "Verse" at beat 8
- offline.editSong ([] (lynx::Song& s) { lynx::arrange::duplicateTime (s, 4 * lynx::ppq, 8 * lynx::ppq); });
- offline.dispatchPendingMessages();
- int verses = 0;
- for (const auto& m : offline.getSong().markers())
- verses += m.name == "Verse" ? 1 : 0;
- facts << "duplicate time: locators named Verse " << verses << "\n";
- write (ui, "arrangement-duplicated-time");
- }
- juce::File (prefix + "-facts.txt").replaceWithText (facts);
- lynx::autolanes::setShown (false);
- }
- void runMtShot190fm (const juce::String& prefix)
- {
- lynx::AudioEngine offline (false);
- offline.editSong ([] (lynx::Song& s) {
- if (s.patterns.empty())
- s.patterns.emplace_back();
- s.patterns[0].notes.clear();
- s.patterns[0].lengthTicks = 4 * lynx::ppq;
- s.currentPattern = 0;
- }, false);
- lynx::MidiToolsPanel panel (offline, [] {
- lynx::MidiToolsPanel::Target t;
- t.pattern = 0;
- t.grid = lynx::ppq / 4;
- t.channel = 0;
- t.length = 4 * lynx::ppq; // one bar, no time selection
- return t;
- });
- panel.setSize (lynx::MidiToolsPanel::panelWidth, lynx::MidiToolsPanel::panelHeight);
- panel.setSection (lynx::MidiToolsPanel::generateSection);
- panel.setGenerateShotSettingsForSnapshot();
- const auto write = [&prefix] (const juce::Image& image, const juce::String& name) {
- const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
- file.deleteFile();
- juce::FileOutputStream out (file);
- juce::PNGImageFormat().writeImageToStream (image, out);
- };
- std::vector<juce::Image> images;
- juce::String checks;
- for (int g = 0; g < lynx::midigen::Settings::toolCount; ++g)
- {
- panel.setGenerator (g);
- const auto name = juce::String (lynx::midigen::toolName (g)).toLowerCase();
- images.push_back (lynx::shot::paint (panel, lynx::theme::colour::bg2));
- write (images.back(), "generate-" + name);
- panel.generateNow();
- offline.dispatchPendingMessages();
- const auto made = (int) offline.getSong().patterns[0].notes.size();
- offline.undo();
- offline.dispatchPendingMessages();
- const auto after = (int) offline.getSong().patterns[0].notes.size();
- checks << name << ": generated " << made << " notes, after undo " << after << (made > 0 && after == 0 ? " OK" : " FAIL") << "\n";
- }
- // the five side by side (6 px apart, on the window's background)
- const auto gap = juce::roundToInt (6.0f * lynx::shot::scale());
- int width = gap, height = 0;
- for (const auto& image : images)
- {
- width += image.getWidth() + gap;
- height = std::max (height, image.getHeight());
- }
- juce::Image strip (juce::Image::RGB, width, height + 2 * gap, true);
- {
- juce::Graphics g (strip);
- g.fillAll (lynx::theme::colour::bg0);
- int x = gap;
- for (const auto& image : images)
- {
- g.drawImageAt (image, x, gap);
- x += image.getWidth() + gap;
- }
- }
- write (strip, "generate-panels");
- checks << "settings saved with the project: " << (offline.getSong().midiGenerate.stacksOptions.sequence.size() == 2 ? "OK" : "FAIL") << "\n";
- juce::File (prefix + "-checks.txt").replaceWithText (checks);
- }
- void runDetailShot (const juce::String& prefix)
- {
- 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()));
- const auto write = [&prefix, &ui] (const char* name) {
- const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
- file.deleteFile();
- juce::FileOutputStream out (file);
- juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
- };
- ui.setVisible (true); // (not on the desktop: only so the Clip page sees itself shown and docks the Piano roll)
- lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
- ui.selectTabForSnapshot (2); // the Playlist panel, maximized
- offline.editSong ([] (lynx::Song& s) {
- if (s.channels.size() < 2)
- s.channels.resize (2);
- s.channels[0].name = "Bass synth";
- s.channels[0].mixerTrack = 2;
- s.channels[1].mixerTrack = 3;
- if (s.mixer.size() < 4)
- s.mixer.resize (4);
- s.mixer[2].name = "Bass";
- s.mixer[2].effects.clear();
- for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor, lynx::EffectKind::reverb, lynx::EffectKind::delay })
- {
- lynx::EffectSlot fx;
- fx.kind = kind;
- const auto& info = lynx::effectInfo (kind);
- for (std::size_t k = 0; k < info.params.size() && k < fx.params.size(); ++k)
- fx.params[k] = info.params[k].defaultValue;
- fx.enabled = kind != lynx::EffectKind::compressor; // one switched off
- s.mixer[2].effects.push_back (fx);
- }
- while (s.patterns.size() < 2)
- s.patterns.emplace_back();
- s.patterns[0].name = "Bass line";
- s.patterns[0].notes.clear();
- for (int n = 0; n < 4; ++n)
- {
- lynx::Note note;
- note.channel = 0;
- note.start = n * lynx::ppq;
- note.key = 36 + (n % 2) * 7;
- s.patterns[0].notes.push_back (note);
- }
- s.patterns[0].lengthTicks = 4 * lynx::ppq;
- lynx::PatternEvents lane; // a volume swell for the Envelopes tab (slice 3)
- lane.target = lynx::AutomationTarget { lynx::AutomationTargetKind::channelVolume, 0 };
- for (int e = 0; e < 16; ++e)
- lane.events.push_back ({ e * lynx::ppq / 4, 0.3f + 0.6f * (float) e / 15.0f });
- s.patterns[0].events = { lane };
- s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 3));
- s.playlistTracks[1].name = "Bass";
- }, false);
- offline.dispatchPendingMessages();
- write ("pattern"); // Pattern workflow: no detail view exists
- ui.setClipLaunchWorkflow (true);
- offline.editSong ([] (lynx::Song& s) {
- lynx::Clip clip;
- clip.pattern = 0;
- clip.length = 4 * lynx::ppq;
- lynx::launcher::setClip (s, 1, 0, clip);
- }, false);
- offline.dispatchPendingMessages();
- juce::String counts;
- if (auto* detail = ui.getDetailViewForSnapshot())
- {
- detail->showSelection (1, 0);
- detail->setPage (lynx::DetailView::Page::devices);
- write ("devices");
- counts << "cards " << detail->cardCountForCheck() << ", insert " << detail->chainInsertForCheck() << ", channel " << detail->chainChannelForCheck() << "\n";
- detail->toggleFoldForCheck (3); // the reverb (card 0 is the instrument)
- write ("folded");
- counts << "folded card 3: " << (detail->isFoldedForCheck (3) ? 1 : 0) << "\n";
- detail->showSelection (2, 0); // an empty track
- write ("empty-track");
- detail->showSelection (1, 0);
- detail->setPage (lynx::DetailView::Page::clip);
- offline.dispatchPendingMessages();
- ui.getPianoRollForSnapshot().scrollToNotes(); // (the app does it on the message loop, which this shot doesn't run)
- write ("clip"); // slice 2: the Piano roll docked here
- {
- // round 190s: the Transform panel with each MIDI tool, then Arpeggiate applied (and undone again)
- auto& tools = detail->midiToolsForSnapshot();
- for (int t = 0; t < lynx::MidiToolsPanel::toolCount; ++t)
- {
- tools.setTool (t);
- write (("clip-mt-" + juce::String (lynx::MidiToolsPanel::toolName (t)).toLowerCase()).toRawUTF8());
- }
- // round 190aa: the pages again with the settings of the Live shots they are compared with
- tools.setAuto (false);
- tools.setLiveShotSettingsForSnapshot();
- for (int t : { (int) lynx::MidiToolsPanel::chop, (int) lynx::MidiToolsPanel::quantize, (int) lynx::MidiToolsPanel::timeWarp })
- {
- tools.setTool (t);
- write (("clip-mt-" + juce::String (lynx::MidiToolsPanel::toolName (t)).toLowerCase() + "-set").toRawUTF8());
- }
- tools.setAuto (true);
- tools.setTool (lynx::MidiToolsPanel::arpeggiate);
- tools.transformNow();
- offline.dispatchPendingMessages();
- write ("clip-mt-applied");
- counts << "midi tools: arpeggiate made " << (int) offline.getSong().patterns[0].notes.size() << " notes of 4\n";
- offline.undo();
- offline.dispatchPendingMessages();
- counts << "midi tools: undo gives " << (int) offline.getSong().patterns[0].notes.size() << " notes\n";
- }
- counts << "piano roll docked: " << (ui.getPianoRollForSnapshot().getParentComponent() != nullptr
- && ui.getPianoRollForSnapshot().getParentComponent()->getParentComponent() == detail ? 1 : 0) << "\n";
- detail->setClipTab (true); // slice 3: the pattern's events in the Envelopes tab
- offline.dispatchPendingMessages();
- write ("envelopes");
- detail->setClipTab (false);
- detail->setPage (lynx::DetailView::Page::devices);
- // round 183c-card: an Audio Effect Rack in the chain draws as its own card (the rack's view, Rand / Map in its
- // title bar), as Live's Device View shows a rack
- offline.editSong ([] (lynx::Song& s) { s.mixer[2].effects.insert (s.mixer[2].effects.begin() + 1, shotRack()); }, false);
- offline.dispatchPendingMessages();
- detail->showSelection (2, 0);
- detail->showSelection (1, 0);
- write ("devices-rack");
- counts << "rack card: cards " << detail->cardCountForCheck() << "\n";
- offline.editSong ([] (lynx::Song& s) { s.mixer[2].effects.erase (s.mixer[2].effects.begin() + 1); }, false);
- offline.dispatchPendingMessages();
- counts << "piano roll back in its panel: " << (ui.getPianoRollForSnapshot().getParentComponent() != nullptr
- && ui.getPianoRollForSnapshot().getParentComponent()->getParentComponent() != detail ? 1 : 0) << "\n";
- }
- else
- counts << "no detail view\n";
- ui.setClipLaunchWorkflow (false);
- offline.dispatchPendingMessages();
- write ("pattern-after");
- juce::File (prefix + "-counts.txt").replaceWithText (counts);
- }
- 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 (lynx::shot::snapshot (playlist), 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 (lynx::shot::snapshot (playlist), 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 (lynx::shot::snapshot (*c), 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 = lynx::shot::snapshot (*box);
- 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 runStabilityShot (const juce::String& folder)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- const juce::File dir (folder);
- dir.createDirectory();
- {
- lynx::AudioEngine offline (false);
- const auto save = [&dir] (std::unique_ptr<juce::Component> c, const juce::String& name) {
- juce::Component frame;
- frame.setSize (c->getWidth(), c->getHeight());
- frame.setOpaque (true);
- if (c->isOnDesktop()) // (an AlertWindow: never shown, so it takes no foreground)
- c->removeFromDesktop();
- frame.addAndMakeVisible (*c);
- c->setTopLeftPosition (0, 0);
- const auto image = lynx::shot::paint (frame, lynx::theme::panel);
- const auto file = dir.getChildFile (name);
- file.deleteFile();
- juce::PNGImageFormat png;
- if (auto out = file.createOutputStream())
- png.writeImageToStream (image, *out);
- };
- save (lynx::PluginWindows::makeCrashPromptPanel ("Serum", false), "crash-prompt.png");
- save (lynx::PluginWindows::makeCrashPromptPanel ("Serum", true), "crash-prompt-onload.png");
- save (lynx::PluginWindows::makeCrashNoticePanel ("Serum", true), "crash-notice.png");
- save (lynx::makePluginManagerPanel (offline, false), "plugin-manager.png");
- save (lynx::makePluginMonitorPanel (offline), "plugin-monitor.png");
- }
- setApplicationReturnValue (0);
- quit();
- }
- 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");
- {
- // View › Keyboard style › Piano keys (round 190j, discussion #136), also with tall keys
- auto& roll = ui.getPianoRollForSnapshot();
- lynx::PianoRollComponent::keyStyle = lynx::pianokeys::Style::piano;
- roll.repaint();
- saveSnapshot (ui, prefix + "-pianoroll-pianokeys.png");
- lynx::PianoRollComponent::keyStyle = lynx::pianokeys::Style::flat;
- roll.repaint();
- // round 190j (discussion #10): the toolbar in a narrow window: the chord stamp as an icon button, and
- // the menu button still there
- for (int narrower : { 150, 270, 330 })
- {
- roll.squeezeToolbarForSnapshot (narrower);
- saveSnapshot (ui, prefix + "-pianoroll-narrow" + juce::String (narrower) + ".png");
- roll.squeezeToolbarForSnapshot (-narrower);
- }
- }
- 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");
- {
- // a pattern with note Chance or a Velocity Range (round 187c): the Piano roll with those lanes
- const auto& song = offline.getSong();
- const auto& notes = song.patterns[(std::size_t) std::clamp (song.currentPattern, 0, (int) song.patterns.size() - 1)].notes;
- if (std::any_of (notes.begin(), notes.end(), [] (const lynx::Note& n) { return n.hasChance(); }))
- {
- auto& roll = ui.getPianoRollForSnapshot();
- ui.setHintForSnapshot ({});
- for (const auto& [lane, name] : { std::pair { lynx::PianoRollComponent::laneChance, "chance" },
- { lynx::PianoRollComponent::laneVelocityRange, "velrange" },
- { lynx::PianoRollComponent::laneVelocity, "velocity" } })
- {
- roll.setLaneForSnapshot (lane);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-pianoroll-" + name + ".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 177b: automation lanes on (two lanes under track 2: a volume ramp and a pan wobble)
- {
- const auto before = offline.getSong();
- offline.editSong ([] (lynx::Song& s) {
- s.loopStart = s.loopEnd = 0; // (no time selection in this one)
- const auto bar = s.barTicks();
- const auto vol = lynx::autolanes::addLane (s, 1, { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, "Insert 1 - Volume", 0.3f);
- s.automations[(std::size_t) vol].points = { { 0, 0.3f, 0.0f }, { bar * 2, 0.8f, 0.4f }, { bar * 4, 0.6f, 0.0f } };
- const auto pan = lynx::autolanes::addLane (s, 1, { lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }, "Insert 1 - Pan", 0.5f);
- s.automations[(std::size_t) pan].points = { { 0, 0.5f, 0.0f }, { bar, 0.2f, 0.0f }, { bar * 2, 0.8f, 0.0f }, { bar * 3, 0.5f, 0.0f } };
- }, false);
- lynx::autolanes::setShown (true);
- ui.getPlaylistForSnapshot().resized();
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-playlist-lanes.png");
- lynx::autolanes::setShown (false);
- offline.editSong ([before] (lynx::Song& s) { s = before; }, false);
- offline.dispatchPendingMessages();
- }
- // 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_ARRANGE=1 (round 186c): Mixer menu › "Arrange inserts like the Playlist" first
- if (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_ARRANGE", {}) == "1")
- {
- offline.editSong ([] (lynx::Song& s) { lynx::mixerops::arrangeLikePlaylist (s); });
- offline.dispatchPendingMessages();
- }
- // 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 190am: LYNX's two mixer extras, before and after (the demo project leaves most inserts unused). The
- // loudness panel shows a real measurement of 12 s of a test tone (a 1 kHz sine at -14 dBFS after a quieter
- // stretch, pushed through the Master's tap as the audio thread does)
- {
- auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
- saveSnapshot (ui, prefix + "-mixer190am-before.png");
- strips.setShowUsedOnly (true);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-mixer190am-usedonly.png");
- strips.setShowUsedOnly (false);
- strips.setShowLoudness (true);
- {
- const double sr = 48000.0;
- std::vector<float> tone (480);
- auto& tap = offline.getMeters().loudness;
- for (int block = 0; block < 1200; ++block)
- {
- const auto gain = std::pow (10.0, (block < 400 ? -20.0 : -14.0) / 20.0);
- for (int i = 0; i < 480; ++i)
- tone[(std::size_t) i] = (float) (gain * std::sin (2.0 * juce::MathConstants<double>::pi * 1000.0 * (block * 480 + i) / sr));
- tap.push (tone.data(), tone.data(), 480, sr);
- }
- }
- strips.refreshLoudnessForSnapshot();
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-mixer190am-loudness.png");
- for (const auto l : { lynx::mixerlayout::Layout::compact, lynx::mixerlayout::Layout::extraLarge })
- {
- const auto was = lynx::MixerStrips::layout;
- strips.setLayout (l);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-mixer190am-loudness-" + juce::String ((int) l) + ".png");
- strips.setLayout (was);
- }
- strips.setShowUsedOnly (true);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-mixer190am-both.png");
- strips.setShowUsedOnly (false);
- strips.setShowLoudness (false);
- offline.dispatchPendingMessages();
- }
- // 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");
- // round 190bf (fl190be Q3): the Channel Rack's "+" menu in FL's three views, with two root entries (plugins
- // at the top of the database, in no folder) and the Categories / Simple / Tree switch at the end
- {
- auto& host = offline.getPluginHost();
- const auto keep = host.databaseFolders();
- auto folders = keep;
- int added = 0;
- for (const auto& e : lynx::quickpick::generatorEntries (offline))
- if (e.folder == 3 && e.available && added < 2) // (installed plugins: FL's root entries are such)
- {
- folders.top.insert (e.key);
- ++added;
- }
- for (const auto& e : lynx::quickpick::generatorEntries (offline))
- if (e.folder != 3 && added < 2)
- {
- folders.top.insert (e.key);
- ++added;
- }
- static const char* const views[] { "categories", "simple", "tree" };
- for (int v = 0; v < 3; ++v)
- {
- folders.view = v;
- host.setDatabaseFolders (folders);
- juce::PopupMenu plus;
- lynx::quickpick::addGeneratorMenu (plus, offline, [] (lynx::ChannelDef) {}, {}, nullptr, nullptr);
- lynx::quickpick::addFolderViewItems (plus, offline);
- saveMenus (juce::StringArray { juce::String ("Channel Rack +: ") + views[v] }, { plus }, prefix + "-menus190bf-" + views[v] + ".png");
- }
- host.setDatabaseFolders (keep);
- }
- 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);
- // an AlertWindow is built on the desktop: shown there first, it would take the foreground from whoever has it
- // (TopLevelWindow::visibilityChanged calls toFront (true)). Off the desktop, its control that showing it would
- // have focused (what grabKeyboardFocus picks) is marked, so the picture keeps that control's focus ring
- if (c->isOnDesktop())
- {
- c->removeFromDesktop();
- auto* focus = c.get();
- for (int depth = 0; focus != nullptr && depth < 32; ++depth)
- {
- if (focus->getWantsKeyboardFocus() && (focus->isEnabled() || focus == c.get()))
- {
- focus->getProperties().set ("lynxSnapshotFocus", true);
- break;
- }
- auto traverser = focus->createKeyboardFocusTraverser();
- focus = traverser != nullptr ? traverser->getDefaultComponent (focus) : nullptr;
- }
- }
- frame.addAndMakeVisible (*c);
- c->setTopLeftPosition (0, 0);
- checkTextFit (*c, name.fromFirstOccurrenceOf ("-", false, false).upToLastOccurrenceOf (".", false, false));
- auto image = lynx::shot::paint (frame, lynx::theme::panel);
- const auto file = lynx::shot::file (juce::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");
- }
- // round 189e: the Playlist menu's Edit and Select submenus (FL's items and order) and the header drop question
- saveMenus (juce::StringArray { "Playlist: Edit", "Playlist: Select" },
- std::vector<juce::PopupMenu> { ui.getPlaylistForSnapshot().editMenu(), ui.getPlaylistForSnapshot().selectMenu() },
- prefix + "-playlist-edit189e.png");
- saveWindow (lynx::PlaylistComponent::makeHeaderDropDialog(), "-header-drop189e.png");
- {
- // round 189i: FL's fade handle menu (right-click on an audio clip's fade handle), on the song's first audio
- // clip, or on one added for the shot
- const auto before = offline.getSong();
- auto clipIndex = -1;
- for (std::size_t i = 0; i < before.playlist.size() && clipIndex < 0; ++i)
- if (before.playlist[i].kind == lynx::ClipKind::audio)
- clipIndex = (int) i;
- if (clipIndex < 0)
- {
- auto song = before;
- lynx::ChannelDef channel;
- channel.instrument = lynx::InstrumentKind::audioClip;
- channel.name = "Audio clip";
- song.channels.push_back (channel);
- lynx::Clip clip;
- clip.kind = lynx::ClipKind::audio;
- clip.channel = (int) song.channels.size() - 1;
- clip.length = lynx::ppq * 4;
- song.playlist.push_back (clip);
- clipIndex = (int) song.playlist.size() - 1;
- offline.setSong (song);
- offline.dispatchPendingMessages();
- }
- saveMenus (juce::StringArray { "Fade handle" },
- std::vector<juce::PopupMenu> { ui.getPlaylistForSnapshot().fadeHandleMenu (clipIndex, 1) },
- prefix + "-fade-handle189i.png");
- if (offline.getSong().playlist.size() != before.playlist.size())
- {
- offline.setSong (before);
- offline.dispatchPendingMessages();
- }
- }
- {
- // round 189n: FL's gain handle menu with two overlapping clips selected (Normalize selection individually / as a
- // group) and the later clip's fade in menu (Create crossfade enabled); FL shots in /mnt/e/lynx-work/flgap189n
- const auto before = offline.getSong();
- auto song = before;
- lynx::ChannelDef channel;
- channel.instrument = lynx::InstrumentKind::audioClip;
- channel.name = "Audio clip";
- song.channels.push_back (channel);
- int lane = 0;
- for (const auto& c : song.playlist)
- lane = std::max (lane, c.track + 1);
- for (int k = 0; k < 2; ++k)
- {
- lynx::Clip clip;
- clip.kind = lynx::ClipKind::audio;
- clip.channel = (int) song.channels.size() - 1;
- clip.track = lane;
- clip.start = k * lynx::ppq * 3;
- clip.length = lynx::ppq * 4;
- song.playlist.push_back (clip);
- }
- const auto second = (int) song.playlist.size() - 1;
- song.autoCrossfades = true; // FL's capture: Thief has Automatic crossfades on
- offline.setSong (song);
- offline.dispatchPendingMessages();
- auto& playlist = ui.getPlaylistForSnapshot();
- playlist.selectForSnapshot ({ second - 1, second });
- auto gain = playlist.gainMenu (second);
- auto fadeIn = playlist.fadeHandleMenu (second, 0); // (both selected, as in FL's capture)
- playlist.selectForSnapshot ({});
- saveMenus (juce::StringArray { "Gain handle, 2 selected", "Fade in, overlapping" },
- std::vector<juce::PopupMenu> { gain, fadeIn }, prefix + "-fade-gain189n.png");
- // round 189o: the audio clip menu with both overlapping clips selected (FL's Fades › Crossfade selected
- // shown) and with none selected (hidden)
- playlist.selectForSnapshot ({ second - 1, second });
- auto clipSelected = playlist.getClipMenuForSnapshot (second);
- playlist.selectForSnapshot ({});
- auto clipAlone = playlist.getClipMenuForSnapshot (second);
- saveMenus (juce::StringArray { "Audio clip, 2 selected", "Audio clip, none selected" },
- std::vector<juce::PopupMenu> { clipSelected, clipAlone }, prefix + "-xfadesel189o.png");
- offline.setSong (before);
- offline.dispatchPendingMessages();
- }
- {
- // 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 190as: the Piano roll's scripts (FL's Tools › Scripts column) and a script's form
- saveMenus (juce::StringArray { "Piano roll scripts" }, std::vector<juce::PopupMenu> { ui.getPianoRollForSnapshot().getScriptsMenuForSnapshot() },
- prefix + "-prscripts-menu.png");
- {
- lynx::prscript::Score score;
- const auto out = lynx::prscript::run (lynx::prscript::builtins().front().source, score, {});
- if (out.status == lynx::prscript::Outcome::Status::needsForm)
- {
- lynx::ScriptPanel::Options options;
- options.acceptText = lynx::tr ("Accept");
- saveWindow (std::make_unique<lynx::ScriptPanel> (out.form, [] (const lynx::scriptform::Form&) {}, [] (const lynx::scriptform::Form&) {},
- nullptr, options),
- "-prscript-form.png");
- }
- }
- // round 190j (discussion #10): the Piano roll menu's Chord stamp list
- saveMenus (juce::StringArray { "Chord stamp" }, std::vector<juce::PopupMenu> { ui.getPianoRollForSnapshot().getStampMenuForSnapshot() },
- prefix + "-stamp-menu.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::support::makeSupportWindow(), "-support.png"); // round 190fq: Help › Support LYNX SHARE...
- saveAlert (lynx::makeNameAndColourDialog (lynx::tr ("Rename pattern"), "Pattern 2", lynx::lynxPalette()[6]), "-rename.png");
- saveAlert (lynx::makeRecordChoiceDialog(), "-record-dialog.png");
- // round 190ah: Online Sessions — a guest's "go back in?" at start-up, the host's question at a guest's file limit
- saveAlert (lynx::liveui::makeRejoinDialog ("Ana", juce::Time (2026, 10, 10, 21, 40).toString (true, true, false, true)), "-live-rejoin.png");
- saveAlert (lynx::liveui::makeMediaLimitDialog ("Pedro", (juce::int64) 1010 << 20, (juce::int64) 1 << 30), "-live-media-limit.png");
- saveAlert (lynx::makeSamplePitchDialog (7.25f, true, true), "-sample-pitch.png"); // round 163c
- saveAlert (lynx::makeGradientColourDialog (juce::Colour (0xffe5383b), juce::Colour (0xff3a7bd5), 8), "-gradient.png"); // round 177a
- saveAlert (lynx::makeMidiImportDialog(), "-midi-import-dialog.png"); // File › Import › MIDI file (REA round 143)
- // round 186c: FL's mixer "Delete" questions and its Settings › General › Manage messages menu
- saveAlert (lynx::makeFlMessageDialog ({ lynx::tr ("Delete tracks"), lynx::tr ("This will |delete| {0} selected mixer track(s). Are you sure?", { "1" }),
- { lynx::tr ("Yes"), lynx::tr ("No") }, true }),
- "-delete-tracks.png");
- saveAlert (lynx::makeFlMessageDialog ({ lynx::tr ("Playlist tracks"),
- lynx::tr ("One or more mixer tracks that will be deleted are connected to instrument/audio tracks.") + "\n"
- + lynx::tr ("Do you want to unlink the tracks and channels or delete them?"),
- { lynx::tr ("Delete tracks and channels"), lynx::tr ("Unlink tracks and channels"), lynx::tr ("Cancel") }, false }),
- "-delete-tracks-linked.png");
- saveMenus (juce::StringArray { "Manage messages" }, std::vector<juce::PopupMenu> { lynx::messages::manageMenu() }, prefix + "-manage-messages.png");
- 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, 6 * (h + 6));
- for (int state = 0; state < 6; ++state) // (round 190gh: 4 going back, 5 went back)
- {
- bars[state].setBounds (0, state * (h + 6), getWidth(), h);
- bars[state].showForSnapshot (state);
- addAndMakeVisible (bars[state]);
- }
- }
- lynx::updater::UpdateBar bars[6];
- };
- saveWindow (std::make_unique<Bars>(), "-update-bar.png");
- saveWindow (lynx::updater::makeReleaseNotesForSnapshot(), "-update-notes.png");
- // round 190gh (B23): Help › Test audio output... in its states
- for (int state = 0; state < 5; ++state)
- saveWindow (lynx::makeAudioCheckForSnapshot (offline, state), "-audio-check-" + juce::String (state) + ".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");
- {
- // round 189o: the whole General page (the Editing and Plugins sections hold FL's "Monophonic painting in
- // piano roll" and "Limit the number of open plugin editors")
- auto tall = lynx::makeSettingsPanel (offline, lynx::SettingsPage::general);
- tall->setSize (tall->getWidth(), 3200);
- saveWindow (std::move (tall), "-settings-general-tall189o.png");
- }
- {
- // the whole General page (round 186a: the Startup section is below the first screen)
- auto tall = lynx::makeSettingsPanel (offline, lynx::SettingsPage::general);
- tall->setSize (tall->getWidth(), 1500);
- saveWindow (std::move (tall), "-settings-general-tall.png");
- }
- saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::theme), "-settings-theme.png");
- saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::extras), "-settings-extras.png"); // round 190am
- saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::audio), "-settings-audio.png");
- saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::midi), "-settings-midi.png");
- {
- // round 190bj (QA): the MIDI page in a small window keeps each row's switch and device name
- auto small = lynx::makeSettingsPanel (offline, lynx::SettingsPage::midi);
- small->setSize (390, 390);
- saveWindow (std::move (small), "-settings-midi-small.png");
- }
- {
- // round 190bj (QA): the Apex Limiter's window content at its default size, as sized before (JUCE's ratio
- // on the whole window: the status row cut off) and now
- lynx::AudioEngine apexEngine (false);
- 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 (lynx::EffectKind::apexLimiter));
- apexEngine.setSong (std::move (song));
- apexEngine.dispatchPendingMessages();
- savePng (lynx::ProEditorWindows::windowContentForSnapshot (apexEngine, 1, 0, true), prefix + "-apex-window-before190bj.png");
- savePng (lynx::ProEditorWindows::windowContentForSnapshot (apexEngine, 1, 0, false), prefix + "-apex-window.png");
- }
- saveWindow (lynx::makePluginManagerPanel (offline, false), "-plugin-manager.png");
- // round 190gg: the crash prompt and a plugin window's crash notice, with "Always run ... in a separate process"
- saveWindow (lynx::PluginWindows::makeCrashPromptPanel ("Serum", false), "-plugin-crash-prompt.png");
- saveWindow (lynx::PluginWindows::makeCrashNoticePanel ("Serum", true), "-plugin-crash-notice.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: FL's defaults, then one shaped state (the UI gate pairs)
- const auto before = offline.getSong().automations[0].lfo;
- const auto lfoShot = [&offline, &saveWindow] (std::function<void (lynx::AutomationLfo&)> set, const char* suffix) {
- offline.editSong ([&set] (lynx::Song& song) {
- auto& lfo = song.automations[0].lfo;
- lfo = lynx::AutomationLfo {};
- lfo.on = true;
- set (lfo);
- }, false);
- auto lfoEditor = lynx::makeAutomationEditor (offline, 0);
- lfoEditor->setSize (760, 346);
- saveWindow (std::move (lfoEditor), suffix);
- };
- lfoShot ([] (lynx::AutomationLfo&) {}, "-automation-lfo.png");
- lfoShot ([] (lynx::AutomationLfo& lfo) {
- // the state set through FL's own UI for the UI gate (TNS 50 %, SKEW 25 %, PW 25 %, two points), as FL saved it
- lfo.tension = 64;
- lfo.skew = 32;
- lfo.pulseWidth = 28;
- lfo.amp = { { 0, 0.6716f, 0.0f }, { (std::int64_t) (lynx::ppq * 1.4128), 0.9204f, 0.0f } };
- }, "-automation-lfo-shape.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;
- }
- // round 180c: Fruity Slicer's editor
- for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
- if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::fruityslicer)
- {
- saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-fruityslicer.png");
- // rounds 190f / 190m: its Envelope / instrument page, one picture per target
- saveWindow (lynx::makeChannelFrame (offline, c, 1), "-fruityslicer-envelope.png");
- for (const auto& [target, name] : std::vector<std::pair<int, const char*>> { { 0, "panning" }, { 2, "modx" }, { 3, "mody" }, { 4, "pitch" } })
- {
- auto frame = lynx::makeChannelFrame (offline, c, 1);
- lynx::showFlVoiceTarget (*frame, target);
- saveWindow (std::move (frame), juce::String ("-fruityslicer-envelope-") + name + ".png");
- }
- break;
- }
- // round 190r: Slicex's editor
- for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
- if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::slicex)
- {
- saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-slicex.png");
- break;
- }
- // round 190q: FPC's editor
- for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
- if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::fpc)
- {
- saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-fpc.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);
- // issue #86: the same editor on the Tempo target, with the project's own Tempo events (a sample ramp if none)
- const lynx::AutomationTarget tempo { lynx::AutomationTargetKind::tempo, 0 };
- offline.editSong ([&] (lynx::Song& s) {
- auto& lane = lynx::eventedit::laneFor (s.patterns[(std::size_t) s.currentPattern], tempo);
- if (lane.events.empty())
- lynx::eventedit::line (lane, 0, lynx::ppq * 2, 0.05f, 0.11f, lynx::ticksPerStep);
- }, false);
- saveWindow (lynx::makeEventEditor (offline, tempo), "-eventeditor-tempo.png");
- {
- auto compact = lynx::makeEventEditor (offline, tempo); // the toolbar in a small window
- compact->setSize (640, 300);
- saveWindow (std::move (compact), "-eventeditor-tempo-small.png");
- auto narrowest = lynx::makeEventEditor (offline, tempo); // the tool window's lower limit
- narrowest->setSize (400, 300);
- saveWindow (std::move (narrowest), "-eventeditor-tempo-narrowest.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");
- }
- // warp markers (round 175a, M3): the audio editor of the first audio clip whose channel has warp markers,
- // opened as the Playlist opens it, with its warp lane
- {
- const auto& song = offline.getSong();
- for (int i = 0; i < (int) song.playlist.size(); ++i)
- {
- const auto& c = song.playlist[(std::size_t) i];
- if (c.kind == lynx::ClipKind::audio && juce::isPositiveAndBelow (c.channel, (int) song.channels.size())
- && song.channels[(std::size_t) c.channel].sampler.warp.size() >= 3)
- {
- if (auto panel = lynx::makeAudioEditorPanel (offline, c.channel, i, true))
- saveWindow (std::move (panel), "-audioeditor-warp.png");
- break;
- }
- }
- }
- // 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");
- // issue #127 (PR #132 and our follow-up): the Playlist's pencil, brush and eraser on the blocks, driven
- // with real mouse events on the view. One picture per tool, and the gestures' results in
- // <prefix>-playlist-blocks-tools.txt ("OK", or the checks that failed).
- if (auto* blocks = ui.getPlaylistForSnapshot().getBlocksViewForSnapshot())
- {
- juce::StringArray failed;
- const auto expect = [&failed] (bool ok, const char* what) { if (! ok) failed.add (what); };
- const auto bar = offline.getSong().barTicks();
- offline.editSong ([bar] (lynx::Song& s) {
- s.blocks.clear();
- for (std::size_t r = 0; r < 4 && r < s.patterns.size(); ++r)
- s.patterns[r].lengthTicks = r == 1 ? 2 * bar : bar; // row 2 holds a 2-bar pattern
- }, false);
- offline.dispatchPendingMessages();
- const auto source = juce::Desktop::getInstance().getMainMouseSource();
- const juce::ModifierKeys left (juce::ModifierKeys::leftButtonModifier), right (juce::ModifierKeys::rightButtonModifier);
- juce::Point<float> pressedAt;
- const auto event = [&] (int row, std::int64_t tick, juce::ModifierKeys mods) {
- const auto at = blocks->pointForSnapshot (row, tick).toFloat();
- const auto now = juce::Time::getCurrentTime();
- return juce::MouseEvent (source, at, mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, blocks, blocks, now, pressedAt, now, 1, false);
- };
- const auto press = [&] (int row, std::int64_t tick, juce::ModifierKeys mods) {
- pressedAt = blocks->pointForSnapshot (row, tick).toFloat();
- blocks->mouseDown (event (row, tick, mods));
- };
- const auto dragTo = [&] (int row, std::int64_t tick, juce::ModifierKeys mods) { blocks->mouseDrag (event (row, tick, mods)); };
- const auto release = [&] (int row, std::int64_t tick) { blocks->mouseUp (event (row, tick, {})); };
- // the starts of row `row`'s blocks, as "0,2,5" (bars from 0)
- const auto rowBars = [&] (int row) {
- juce::StringArray bars;
- for (const auto& b : offline.getSong().blocks)
- if (b.pattern == row)
- bars.add (juce::String (b.start / bar) + (b.start % bar != 0 ? "+" : ""));
- return bars.joinIntoString (",");
- };
- auto& tools = ui.getPlaylistForSnapshot();
- // Pencil: a press on empty space places one block that follows the mouse along its row
- tools.setToolForSnapshot (lynx::EditTool::pencil);
- press (0, 2 * bar + 40, left);
- expect (rowBars (0) == "2", "pencil: a press places one block");
- dragTo (2, 5 * bar + 40, left); // (over another row: the block stays in its own)
- release (2, 5 * bar + 40);
- expect (rowBars (0) == "5" && rowBars (2).isEmpty(), "pencil: the placed block follows the drag in its row");
- // a 2-bar block grabbed by its second bar keeps that bar under the mouse (it used to jump a bar)
- press (1, 1 * bar + 40, left);
- release (1, 1 * bar + 40);
- expect (rowBars (1) == "1", "pencil: a click places the 2-bar block");
- press (1, 2 * bar + 40, left);
- dragTo (1, 2 * bar + bar / 2, left);
- expect (rowBars (1) == "1", "move: a small move on the grabbed bar leaves the block in place");
- dragTo (1, 4 * bar + 40, left);
- release (1, 4 * bar + 40);
- expect (rowBars (1) == "3", "move: the grabbed bar stays under the mouse");
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-playlist-blocks-pencil.png");
- // Brush: a drag over empty space paints a run; a press on a block moves it
- tools.setToolForSnapshot (lynx::EditTool::brush);
- press (2, 0, left);
- dragTo (2, 3 * bar + 40, left);
- release (2, 3 * bar + 40);
- expect (rowBars (2) == "0,1,2,3", "brush: a drag paints a run");
- press (2, 3 * bar + 40, left);
- dragTo (2, 6 * bar + 40, left);
- release (2, 6 * bar + 40);
- expect (rowBars (2) == "0,1,2,6", "brush: a press on a block moves it");
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-playlist-blocks-brush.png");
- // Eraser, and the right button with any tool: only the blocks under the mouse, row by row
- offline.editSong ([bar] (lynx::Song& s) {
- for (int r = 0; r < 4 && r < (int) s.patterns.size(); ++r)
- lynx::patternblocks::place (s, r, 8 * bar);
- }, false);
- offline.dispatchPendingMessages();
- expect (rowBars (0) == "5,8" && rowBars (3) == "8", "eraser: the column is set up");
- saveSnapshot (ui, prefix + "-playlist-blocks-eraser-before.png");
- tools.setToolForSnapshot (lynx::EditTool::eraser);
- press (0, 8 * bar + 40, left);
- expect (rowBars (0) == "5" && rowBars (1) == "3,8" && rowBars (2) == "0,1,2,6,8" && rowBars (3) == "8",
- "eraser: a click takes only the block under the mouse");
- dragTo (1, 8 * bar + 60, left); // down one row: that row's block goes too, the rows below stay
- release (1, 8 * bar + 60);
- expect (rowBars (1) == "3" && rowBars (2) == "0,1,2,6,8" && rowBars (3) == "8", "eraser: the drag erases the rows it crosses, no others");
- tools.setToolForSnapshot (lynx::EditTool::pencil);
- press (3, 8 * bar + 40, right);
- release (3, 8 * bar + 40);
- expect (rowBars (3).isEmpty() && rowBars (2) == "0,1,2,6,8", "right click: erases only the block under the mouse");
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-playlist-blocks-eraser.png");
- juce::File (prefix + "-playlist-blocks-tools.txt").replaceWithText (failed.isEmpty() ? juce::String ("OK\n") : "ERROR\n" + failed.joinIntoString ("\n") + "\n");
- }
- 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");
- // round 190bf (fl190be Q1): the Plugin database's right-click menus, a folder's and an entry's (FL's System group)
- saveMenus (juce::StringArray { "Plugin database: folder", "Plugin database: entry" }, ui.getBrowserForSnapshot().pluginDatabaseMenusForSnapshot(),
- prefix + "-browser190bf-menus.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();
- }
- {
- // round 190as: "Find similar samples" on a small library of kicks, hats and pads (LYNX_SNAPSHOT_SIMILAR =
- // "<folder>|<file>" lists a real folder instead)
- auto lib = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-snapshot-similar");
- auto query = lib.getChildFile ("Drums/Kicks/Kick 2.wav");
- const auto real = juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIMILAR", {});
- const auto made = real.isEmpty();
- if (made)
- {
- lib.deleteRecursively();
- juce::Random random (190);
- const auto write = [&] (const juce::String& path, char kind, int v) {
- const auto rate = 44100.0;
- const auto frames = (int) (rate * (kind == 'k' ? 0.35 : kind == 'h' ? 0.09 : 2.5));
- juce::AudioBuffer<float> audio (1, frames);
- double phase = 0.0;
- float last = 0.0f;
- for (int i = 0; i < frames; ++i)
- {
- const auto t = i / rate;
- float x = 0.0f;
- if (kind == 'k')
- {
- phase += juce::MathConstants<double>::twoPi * ((46.0 + 3.0 * v) + 150.0 * std::exp (-t * 35.0)) / rate;
- x = (float) (std::sin (phase) * std::exp (-t * (8.0 + v)));
- }
- else if (kind == 'h')
- {
- const auto n = random.nextFloat() * 2.0f - 1.0f;
- x = (n - last) * 0.5f * (float) std::exp (-t * (50.0 + 12.0 * v));
- last = n;
- }
- else
- {
- const auto base = 220.0 * std::pow (2.0, v / 12.0);
- x = (float) (0.25 * std::min (1.0, t / 0.4) * std::min (1.0, (2.5 - t) / 0.5)
- * (std::sin (juce::MathConstants<double>::twoPi * base * t) + std::sin (juce::MathConstants<double>::twoPi * base * 1.5 * t)));
- }
- audio.setSample (0, i, 0.8f * x);
- }
- const auto file = lib.getChildFile (path);
- file.getParentDirectory().createDirectory();
- juce::WavAudioFormat wav;
- if (auto out = file.createOutputStream())
- if (auto writer = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (out.release(), rate, 1, 16, {}, 0)))
- writer->writeFromAudioSampleBuffer (audio, 0, frames);
- };
- for (int v = 1; v <= 5; ++v)
- {
- write ("Drums/Kicks/Kick " + juce::String (v) + ".wav", 'k', v);
- write ("Drums/Hats/Hat " + juce::String (v) + ".wav", 'h', v);
- write ("Keys/Pad " + juce::String (v) + ".wav", 'p', v);
- }
- }
- else
- {
- lib = juce::File (real.upToFirstOccurrenceOf ("|", false, false));
- query = juce::File (real.fromFirstOccurrenceOf ("|", false, false));
- }
- ui.showDesktopForSnapshot (false);
- ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::all);
- ui.getBrowserForSnapshot().findSimilarForSnapshot (query, lib);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-browser-similar.png");
- ui.getBrowserForSnapshot().setSearchForSnapshot ({});
- if (made)
- 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 = s.barTicks();
- 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 = s.barTicks();
- 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;
- // (without the menu mnemonic's mark: FL's underlined letters, round 190dz)
- if (item.text.removeCharacters (juce::String::charToString (1)).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);
- }
- auto image = lynx::shot::canvas (totalWidth, totalHeight);
- {
- juce::Graphics g (image);
- lynx::shot::logical (g);
- 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 auto file = lynx::shot::file (juce::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 auto file = lynx::shot::file (juce::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 (lynx::shot::snapshot (splash), 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;
- auto strip = lynx::shot::canvas (4 * (w + 8) + 8, 2 * (h + 8) + 8);
- {
- juce::Graphics g (strip);
- lynx::shot::logical (g);
- g.fillAll (lynx::theme::colour::bg1);
- for (int i = 0; i < 8; ++i)
- {
- splash.setTimeForSnapshot (times[i]);
- const auto frame = lynx::shot::snapshot (splash);
- 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)
- {
- scale *= lynx::shot::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 auto file = lynx::shot::file (juce::File (path));
- file.deleteFile();
- juce::PNGImageFormat png;
- if (auto out = file.createOutputStream())
- png.writeImageToStream (lynx::shot::snapshot (c, area), *out);
- }
- static void savePng (const juce::Image& image, const juce::String& path)
- {
- const auto file = lynx::shot::file (juce::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 = lynx::shot::snapshot (ui, top);
- {
- juce::Graphics g (image);
- lynx::shot::logical (g);
- 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;
- }
- auto sheet = lynx::shot::canvas (width, y + 20 + 12);
- {
- juce::Graphics g (sheet);
- lynx::shot::logical (g);
- 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 auto file = lynx::shot::file (juce::File (path));
- file.deleteFile();
- juce::PNGImageFormat png;
- if (auto out = file.createOutputStream())
- png.writeImageToStream (lynx::shot::snapshot (c), *out);
- }
- class MainWindow final : public juce::DocumentWindow
- {
- public:
- MainWindow (const juce::String& name, lynx::AudioEngine& engine)
- : DocumentWindow (name, lynx::theme::window, DocumentWindow::allButtons, false)
- {
- // (round 190hd) one desktop window, made with the native title bar: before, JUCE made one with its own title
- // bar and setUsingNativeTitleBar made it again (~20-35 ms each, the Direct2D context included)
- setUsingNativeTitleBar (true);
- addToDesktop();
- setIcon (lynx::logoImage());
- startupTrace.mark (" window: its desktop window (native title bar), icon");
- content = new lynx::MainComponent (engine);
- setContentOwned (content, true);
- startupTrace.mark (" window: content set");
- 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();
- });
- }
- // Runs `then` once, right after the window's next frame (round 190go: the audio device opens behind the
- // window's first frame, not before it); at the latest after 300 ms (a window that paints nothing: minimised).
- void whenPainted (std::function<void()> then)
- {
- afterPaint = std::move (then);
- afterPaintPosted = false;
- repaint();
- juce::Timer::callAfterDelay (300, [safe = juce::Component::SafePointer<MainWindow> (this)] {
- if (safe != nullptr)
- safe->runAfterPaint();
- });
- }
- void runAfterPaint()
- {
- if (auto then = std::exchange (afterPaint, nullptr))
- then();
- }
- // 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 (afterPaint != nullptr && ! std::exchange (afterPaintPosted, true)) // (the frame is presented first)
- juce::MessageManager::callAsync ([safe = juce::Component::SafePointer<MainWindow> (this)] {
- if (safe != nullptr)
- safe->runAfterPaint();
- });
- 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;
- std::function<void()> afterPaint; // (whenPainted)
- bool afterPaintPosted = false;
- JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MainWindow)
- };
- lynx::theme::LookAndFeel lookAndFeel;
- std::unique_ptr<lynx::AudioEngine> engine;
- std::unique_ptr<lynx::RemoteControl> remoteControl;
- 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::StartupSplash> splash;
- static constexpr double landingSeconds = 1.05; // the logo's drop (SplashScreen::remainingDuration's `landing`)
- std::shared_future<std::pair<juce::Image, double>> graphicsDeviceJob; // (round 190hd) holds the graphics device
- bool graphicsDeviceMarked = false, windowRevealed = false;
- std::future<std::shared_ptr<const lynx::SampleData>> startupSampleJob; // (round 190go: the built-in start-up sound)
- bool startedAfterWindow = false, startupSoundPlayed = false;
- double splashDuration = lynx::SplashScreen::minimumDuration; // seconds of its clock (round 121: from the process start)
- lynx::StartupOptions startupOptions;
- juce::File fileToOpen;
- bool startupFileHandled = false;
- bool startWithoutPlugins = false; // --no-plugins project.lynx (round 190ap)
- juce::File openTimeReport; // --opentime
- int openTimeIdleSeconds = 10;
- };
- START_JUCE_APPLICATION (LynxApplication)
|