tests.cpp 314 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113
  1. // Core tests (no JUCE). Usage: lynx_tests [folder-with-flp-files]
  2. #include <atomic>
  3. #include <cctype>
  4. #include <cmath>
  5. #include <cstdio>
  6. #include <cstring>
  7. #include <filesystem>
  8. #include <map>
  9. #include <set>
  10. #include <sstream>
  11. #include <fstream>
  12. #include <functional>
  13. #include <iterator>
  14. #include <string>
  15. #include <tuple>
  16. #include <vector>
  17. #include "core/Dither.h"
  18. #include "core/DrumSynthLive.h"
  19. #include "core/Effects.h"
  20. #include "core/Effector.h"
  21. #include "core/FlpImport.h"
  22. #include "core/FlEffects.h"
  23. #include "core/FlPatcher.h"
  24. #include "core/FlSamplers.h"
  25. #include "core/FlSynths.h"
  26. #include "core/Inflate.h"
  27. #include "core/WavPack.h"
  28. #include "core/FlWrapper.h"
  29. #include "core/Harmless.h"
  30. #include "core/Harmor.h"
  31. #include "core/HarmlessFx.h"
  32. #include "core/LiveEventQueue.h"
  33. #include "core/RackRenderer.h"
  34. #include "core/Scheduler.h"
  35. #include "core/SnapshotExchange.h"
  36. #include "core/SoftClip.h"
  37. #include "core/Slicer.h"
  38. #include "core/SytrusEngine.h"
  39. #include "core/Templates.h"
  40. #include "core/Vocodex.h"
  41. #include "core/TimeStretch.h"
  42. #include "core/WorkerPool.h"
  43. #include "core/Song.h"
  44. #include "core/NoteEdit.h"
  45. #include "core/Recorder.h"
  46. #include "core/KeyMap.h"
  47. #include "core/RackOps.h"
  48. #include "core/ValueMath.h"
  49. #include "core/Workspace.h"
  50. #include "core/StartupSound.h"
  51. #include "flp/Flp.h"
  52. #include "ui/I18nData.h"
  53. namespace
  54. {
  55. int failures = 0;
  56. int checks = 0;
  57. std::vector<std::pair<const char*, std::function<void()>>>& registry()
  58. {
  59. static std::vector<std::pair<const char*, std::function<void()>>> r;
  60. return r;
  61. }
  62. struct Register
  63. {
  64. Register (const char* name, std::function<void()> fn) { registry().emplace_back (name, std::move (fn)); }
  65. };
  66. #define TEST(name) \
  67. static void name(); \
  68. static Register reg_##name (#name, name); \
  69. static void name()
  70. #define CHECK(cond) \
  71. do \
  72. { \
  73. ++checks; \
  74. if (! (cond)) \
  75. { \
  76. ++failures; \
  77. std::printf (" FAILED %s:%d: %s\n", __FILE__, __LINE__, #cond); \
  78. } \
  79. } while (false)
  80. std::string realFlpDir;
  81. // --- helpers for building synthetic .flp files -----------------------------
  82. struct FlpBuilder
  83. {
  84. std::vector<std::uint8_t> bytes;
  85. FlpBuilder (std::uint16_t ppq = 96)
  86. {
  87. put ("FLhd");
  88. u32 (6);
  89. u16 (0);
  90. u16 (1);
  91. u16 (ppq);
  92. put ("FLdt");
  93. u32 (0); // size is not used by the reader
  94. }
  95. void put (const char* s) { bytes.insert (bytes.end(), s, s + std::strlen (s)); }
  96. void u8 (std::uint8_t v) { bytes.push_back (v); }
  97. void u16 (std::uint16_t v) { u8 ((std::uint8_t) v); u8 ((std::uint8_t) (v >> 8)); }
  98. void u32 (std::uint32_t v) { u16 ((std::uint16_t) v); u16 ((std::uint16_t) (v >> 16)); }
  99. void varint (std::size_t n)
  100. {
  101. do
  102. {
  103. auto b = (std::uint8_t) (n & 0x7F);
  104. n >>= 7;
  105. u8 (n ? (std::uint8_t) (b | 0x80) : b);
  106. } while (n);
  107. }
  108. void data (std::uint8_t id, const std::vector<std::uint8_t>& payload)
  109. {
  110. u8 (id);
  111. varint (payload.size());
  112. bytes.insert (bytes.end(), payload.begin(), payload.end());
  113. }
  114. void ascii (std::uint8_t id, const std::string& s)
  115. {
  116. std::vector<std::uint8_t> p (s.begin(), s.end());
  117. p.push_back (0);
  118. data (id, p);
  119. }
  120. void utf16 (std::uint8_t id, const std::u16string& s)
  121. {
  122. std::vector<std::uint8_t> p;
  123. for (auto c : s)
  124. {
  125. p.push_back ((std::uint8_t) c);
  126. p.push_back ((std::uint8_t) (c >> 8));
  127. }
  128. p.push_back (0);
  129. p.push_back (0);
  130. data (id, p);
  131. }
  132. };
  133. std::vector<std::uint8_t> noteRecord (std::uint32_t pos, std::uint16_t channel, std::uint32_t len, std::uint16_t key,
  134. std::uint8_t velocity)
  135. {
  136. std::vector<std::uint8_t> r (24, 0);
  137. std::memcpy (&r[0], &pos, 4);
  138. std::memcpy (&r[6], &channel, 2);
  139. std::memcpy (&r[8], &len, 4);
  140. std::memcpy (&r[12], &key, 2);
  141. r[16] = 120;
  142. r[20] = 64;
  143. r[21] = velocity;
  144. return r;
  145. }
  146. } // namespace
  147. // ---------------------------------------------------------------------------
  148. // FLP
  149. TEST (flp_rejects_garbage)
  150. {
  151. std::vector<std::uint8_t> junk (64, 0x41);
  152. bool threw = false;
  153. try { flp::EventReader r (junk); } catch (const flp::Error&) { threw = true; }
  154. CHECK (threw);
  155. }
  156. TEST (flp_reads_size_classes_varint_and_extended_ids)
  157. {
  158. FlpBuilder b;
  159. b.u8 (0x15); b.u8 (2); // u8
  160. b.u8 (0x40); b.u16 (513); // u16
  161. b.u8 (0x9C); b.u32 (128500); // u32
  162. b.data (0xD5, std::vector<std::uint8_t> (300, 7)); // 2-byte varint
  163. b.u8 (0xAC); b.u32 (0xC0000100); b.varint (3); b.u8 (1); b.u8 (2); b.u8 (3); // extended ID
  164. flp::EventReader r (b.bytes);
  165. flp::Event e;
  166. CHECK (r.header().ppq == 96);
  167. CHECK (r.next (e) && e.id == 0x15 && e.value == 2);
  168. CHECK (r.next (e) && e.id == 0x40 && e.value == 513);
  169. CHECK (r.next (e) && e.id == 0x9C && e.value == 128500);
  170. CHECK (r.next (e) && e.id == 0xD5 && e.data.size() == 300 && e.data[299] == 7);
  171. CHECK (r.next (e) && e.id == 0xC0000100 && e.isData() && e.data.size() == 3 && e.data[2] == 3);
  172. CHECK (! r.next (e));
  173. }
  174. TEST (flp_truncated_file_throws)
  175. {
  176. FlpBuilder b;
  177. b.u8 (0x9C); b.u8 (1); // u32 with only 1 byte
  178. flp::EventReader r (b.bytes);
  179. flp::Event e;
  180. bool threw = false;
  181. try { r.next (e); } catch (const flp::Error&) { threw = true; }
  182. CHECK (threw);
  183. }
  184. TEST (flp_version_numbers)
  185. {
  186. CHECK (flp::parseVersionNumber ("25.2.5.5319") == 25002005u);
  187. CHECK (flp::parseVersionNumber ("20.99.3000.3031") == 20102000u);
  188. CHECK (flp::parseVersionNumber ("11.0.3") == 11000003u);
  189. }
  190. TEST (flp_playlist_record_size_by_version)
  191. {
  192. CHECK (flp::playlistRecordSize (12009003, 64) == 32);
  193. CHECK (flp::playlistRecordSize (21000000, 120) == 60);
  194. CHECK (flp::playlistRecordSize (25002005, 160) == 80);
  195. CHECK (flp::playlistRecordSize (25002005, 60) == 60); // size doesn't match the version -> tries the others
  196. CHECK (flp::playlistRecordSize (25002005, 7) == 0);
  197. }
  198. TEST (flp_parses_project_model)
  199. {
  200. FlpBuilder b (96);
  201. b.ascii (0xC7, "25.2.5.5319");
  202. b.u8 (0x9C); b.u32 (174500);
  203. b.utf16 (0xC2, u"Título");
  204. b.u8 (0x41); b.u16 (3);
  205. b.u8 (0x96); b.u32 (0x00A14547); // BGR in the file
  206. auto notes = noteRecord (96, 1, 48, 64, 100);
  207. auto n2 = noteRecord (0, 0, 0, 60, 128);
  208. notes.insert (notes.end(), n2.begin(), n2.end());
  209. b.data (0xE0, notes);
  210. b.u8 (0x40); b.u16 (0);
  211. b.u8 (0x15); b.u8 (0);
  212. b.utf16 (0xCB, u"Kick");
  213. {
  214. std::vector<std::uint8_t> levels (24, 0);
  215. const std::int32_t lv[] = { 3200, 12800, -150 };
  216. std::memcpy (levels.data(), lv, sizeof (lv));
  217. b.data (0xDB, levels);
  218. }
  219. b.u8 (0x68); b.u16 (5);
  220. b.u8 (0x40); b.u16 (1);
  221. b.u8 (0x15); b.u8 (2);
  222. b.utf16 (0xC9, u"FLEX");
  223. b.utf16 (0xCB, u"Lead");
  224. b.u8 (0x63); b.u16 (0);
  225. std::vector<std::uint8_t> item (80, 0);
  226. std::uint32_t pos = 384, len = 768;
  227. std::uint16_t base = 20480, idx = 20480 + 3, rv = 499 - 2;
  228. std::memcpy (&item[0], &pos, 4);
  229. std::memcpy (&item[4], &base, 2);
  230. std::memcpy (&item[6], &idx, 2);
  231. std::memcpy (&item[8], &len, 4);
  232. std::memcpy (&item[12], &rv, 2);
  233. b.data (0xE9, item);
  234. b.utf16 (0xCC, u"Drums");
  235. b.data (0xEC, std::vector<std::uint8_t> (12, 0));
  236. b.data (0xEC, std::vector<std::uint8_t> (12, 0));
  237. const auto p = flp::parseProject (b.bytes);
  238. CHECK (p.version == "25.2.5.5319");
  239. CHECK (std::abs (p.tempo - 174.5) < 1e-9);
  240. CHECK (p.title == "Título");
  241. CHECK (p.channels.size() == 2);
  242. CHECK (p.channels[0].name == "Kick" && p.channels[0].mixerTrack == 5);
  243. CHECK (p.channels[0].hasLevels && p.channels[0].pan == 3200 && p.channels[0].volume == 12800 && p.channels[0].pitchCents == -150);
  244. CHECK (p.channels[1].type == flp::ChannelType::instrument && p.channels[1].pluginName == "FLEX");
  245. CHECK (p.patterns.size() == 1 && p.patterns[0].index == 3);
  246. CHECK (p.patterns[0].colour && *p.patterns[0].colour == 0x4745A1);
  247. CHECK (p.patterns[0].notes.size() == 2 && p.patterns[0].notes[0].position == 0); // sorted
  248. CHECK (p.patterns[0].notes[1].key == 64 && p.patterns[0].notes[1].length == 48);
  249. CHECK (p.arrangements.size() == 1 && p.arrangements[0].items.size() == 1);
  250. const auto& it = p.arrangements[0].items[0];
  251. CHECK (it.kind == flp::PlaylistItem::Kind::pattern && it.index == 3 && it.track == 2 && it.position == 384);
  252. CHECK (p.mixer.size() == 2 && p.mixer[0].name == "Drums" && p.mixer[1].name.empty());
  253. CHECK (p.warnings.empty());
  254. }
  255. TEST (flp_fuzz_corrupted_files_do_not_crash)
  256. {
  257. if (realFlpDir.empty())
  258. return;
  259. // some real .flp files, corrupted in various ways: the parser may reject them (flp::Error), but
  260. // must never hang, read past the buffer or produce a Song with invalid indices
  261. std::vector<std::vector<std::uint8_t>> sources;
  262. for (auto& entry : std::filesystem::recursive_directory_iterator (realFlpDir))
  263. if (entry.path().extension() == ".flp" && sources.size() < 6 && std::filesystem::file_size (entry.path()) < 3'000'000)
  264. {
  265. std::ifstream in (entry.path(), std::ios::binary);
  266. sources.emplace_back ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  267. }
  268. std::uint32_t seed = 2024;
  269. auto rnd = [&] (std::uint32_t n) { seed = seed * 1664525u + 1013904223u; return n == 0 ? 0u : (seed >> 8) % n; };
  270. int parsed = 0, rejected = 0;
  271. for (int round = 0; round < 240 && ! sources.empty(); ++round)
  272. {
  273. auto bytes = sources[(std::size_t) rnd ((std::uint32_t) sources.size())];
  274. switch (round % 4)
  275. {
  276. case 0: bytes.resize (rnd ((std::uint32_t) bytes.size())); break; // truncated
  277. case 1: for (int k = 0; k < 20; ++k) bytes[(std::size_t) rnd ((std::uint32_t) bytes.size())] ^= (std::uint8_t) (1 + rnd (255)); break;
  278. case 2: // absurd event size
  279. for (int k = 0; k < 5; ++k)
  280. bytes[(std::size_t) rnd ((std::uint32_t) bytes.size())] = 0xFF;
  281. break;
  282. default: // shuffled block
  283. {
  284. const auto a = rnd ((std::uint32_t) bytes.size()), b = rnd ((std::uint32_t) bytes.size());
  285. std::reverse (bytes.begin() + std::min (a, b), bytes.begin() + std::max (a, b));
  286. break;
  287. }
  288. }
  289. try
  290. {
  291. const auto project = flp::parseProject (bytes);
  292. const auto song = lynx::importFlp (project);
  293. ++parsed;
  294. for (const auto& p : song.patterns)
  295. for (const auto& n : p.notes)
  296. CHECK (n.channel >= 0 && n.channel < (int) song.channels.size());
  297. for (const auto& c : song.playlist)
  298. CHECK (c.kind != lynx::ClipKind::pattern || (c.pattern >= 0 && c.pattern < (int) song.patterns.size()));
  299. }
  300. catch (const flp::Error&)
  301. {
  302. ++rejected;
  303. }
  304. }
  305. std::printf (" fuzz: %d imported, %d rejected\n", parsed, rejected);
  306. CHECK (parsed + rejected == 240);
  307. }
  308. TEST (plugin_state_decoders_survive_garbage)
  309. {
  310. // random blobs (varied sizes, including valid headers followed by garbage)
  311. std::uint32_t seed = 77;
  312. auto rnd = [&] { seed = seed * 1664525u + 1013904223u; return seed >> 8; };
  313. const char* plugins[] = { "Fruity Parametric EQ 2", "Fruity Limiter", "Fruity Reeverb 2", "Fruity Delay 2", "Fruity Delay 3",
  314. "Fruity Compressor", "Fruity Balance", "Fruity PanOMatic", "Fruity Stereo Shaper", "Fruity Phase Inverter" };
  315. int decoded = 0;
  316. for (int round = 0; round < 3000; ++round)
  317. {
  318. std::vector<std::uint8_t> blob ((std::size_t) (rnd() % 600));
  319. for (auto& b : blob)
  320. b = (std::uint8_t) rnd();
  321. if (blob.size() >= 4 && round % 3 == 0) // versions the readers accept
  322. {
  323. const std::uint32_t versions[] = { 8, 10001, 10000, 12, 14, 6, 1 };
  324. const auto v = versions[rnd() % 7];
  325. std::memcpy (blob.data(), &v, 4);
  326. }
  327. if (auto fx = lynx::effectFromFl (plugins[rnd() % 10], blob))
  328. {
  329. ++decoded;
  330. for (auto v : fx->params)
  331. CHECK (std::isfinite (v) && v >= 0.0f && v <= 1.0f);
  332. }
  333. lynx::SynthSettings synth;
  334. if (lynx::synthFrom3xOsc (blob, synth))
  335. for (const auto& o : synth.osc)
  336. CHECK (std::isfinite (o.level) && o.level >= 0.0f && o.level <= 1.0f);
  337. float harmlessGain = 1.0f;
  338. if (lynx::synthFromHarmless (blob, 120.0, synth, harmlessGain))
  339. CHECK (std::isfinite (harmlessGain) && std::isfinite (synth.cutoff) && std::isfinite (synth.attack));
  340. if (lynx::synthFromFruitKick (blob, synth))
  341. CHECK (std::isfinite (synth.decay) && std::isfinite (synth.pitchEnv.amount));
  342. if (lynx::synthFromGms (blob, 120.0, synth, harmlessGain) || lynx::synthFromHarmor (blob, synth, harmlessGain) || lynx::synthFromOgun (blob, synth, harmlessGain)
  343. || lynx::synthFromSakura (blob, synth) || lynx::synthFromKepler (blob, synth, harmlessGain))
  344. CHECK (std::isfinite (synth.cutoff) && std::isfinite (synth.attack) && std::isfinite (harmlessGain));
  345. if (auto sound = lynx::drumSynthLiveSound (blob))
  346. CHECK (sound->size() < 256);
  347. if (auto wave = lynx::waveTravellerSample (blob))
  348. CHECK (! wave->first.empty() && wave->second >= 0 && wave->second <= 127);
  349. lynx::synthFromBooBass (blob, synth);
  350. if (lynx::synthFromPoiZone (blob, synth, harmlessGain) || lynx::synthFromBassDrum (blob, synth, harmlessGain) || lynx::synthFromToxic (blob, synth, harmlessGain)
  351. || lynx::synthFromMorphine (blob, synth, harmlessGain))
  352. CHECK (std::isfinite (synth.cutoff) && std::isfinite (harmlessGain));
  353. if (auto patch = lynx::drumpadPatchName (blob))
  354. CHECK (patch->size() <= 0x30 && std::isfinite (lynx::drumToneForName (*patch).decay));
  355. if (auto flex = lynx::flexPresetName (blob))
  356. CHECK ((! flex->first.empty() || ! flex->second.empty()) && flex->second.size() <= 1024);
  357. if (lynx::synthFromSytrus (blob, 120.0, synth, harmlessGain))
  358. CHECK (std::isfinite (synth.cutoff) && std::isfinite (synth.attack));
  359. if (lynx::synthFromDX10 (blob, synth))
  360. CHECK (std::isfinite (synth.decay) && std::isfinite (synth.release) && std::isfinite (synth.osc[1].level));
  361. if (blob.size() >= 4 && round % 5 == 0) // MiniSynth header followed by garbage
  362. {
  363. std::memcpy (blob.data(), "SSLF", 4);
  364. if (blob.size() > 220)
  365. {
  366. std::memcpy (blob.data() + 40, "DATA", 4);
  367. std::memcpy (blob.data() + 48, "0rev", 4);
  368. }
  369. }
  370. if (lynx::synthFromMiniSynth (blob, 120.0, synth))
  371. CHECK (std::isfinite (synth.cutoff) && std::isfinite (synth.decay) && std::isfinite (synth.attack));
  372. lynx::ForeignPlugin foreign;
  373. lynx::parseFlWrapper (blob, foreign);
  374. std::vector<std::uint8_t> component, controller;
  375. lynx::splitFlVst3State (blob, component, controller);
  376. }
  377. CHECK (decoded == 3000); // every known name yields an effect (default when the blob is unusable)
  378. }
  379. TEST (inflate_zlib)
  380. {
  381. // fixed Huffman with back-references
  382. const std::uint8_t fixed[] = { 0x78, 0xda, 0x4b, 0x4c, 0x4a, 0x4e, 0xc4, 0x86, 0x22, 0x00, 0x7c, 0x69, 0x09, 0x89 };
  383. const auto a = lynx::inflateZlib (fixed, sizeof (fixed));
  384. CHECK (a && std::string (a->begin(), a->end()) == "abcabcabcabcabcabcabcabcX");
  385. // stored (uncompressed) block
  386. const std::uint8_t stored[] = { 0x78, 0x01, 0x01, 0x03, 0x00, 0xfc, 0xff, 'L', 'Y', 'N', 0x00, 0x00, 0x00, 0x00 };
  387. const auto b = lynx::inflateZlib (stored, sizeof (stored));
  388. CHECK (b && std::string (b->begin(), b->end()) == "LYN");
  389. // truncated, bad header and size limit
  390. CHECK (! lynx::inflateZlib (fixed, 6));
  391. const std::uint8_t bad[] = { 0x12, 0x34, 0x00 };
  392. CHECK (! lynx::inflateZlib (bad, sizeof (bad)));
  393. CHECK (! lynx::inflateZlib (fixed, sizeof (fixed), false, 10));
  394. }
  395. TEST (fl_round15_effects_convert_known_values)
  396. {
  397. auto blob = [] (std::vector<std::int32_t> words) {
  398. std::vector<std::uint8_t> b (words.size() * 4);
  399. std::memcpy (b.data(), words.data(), b.size());
  400. return b;
  401. };
  402. // Frequency Shifter "+800 Hz": frequency 51542 in the 20 kHz range, 100% wet
  403. const auto fs = lynx::effectFromFl ("Frequency Shifter", blob ({ 4, 10000, 0, 51542, 0, 10000, 10000, 5000, 10000, 0, 5000, 0, 0 }));
  404. CHECK (fs && fs->kind == lynx::EffectKind::freqShift);
  405. if (fs)
  406. {
  407. const auto x = (fs->params[0] - 0.5) * 2.0;
  408. CHECK (std::abs (2000.0 * x * std::abs (x) - 800.0) < 10.0);
  409. CHECK (std::abs (fs->params[1] - 1.0f) < 1e-4f);
  410. }
  411. // Emphasis: input 0.0625 (= +1.5 dB) and ceiling 0.9308 (≈ −1.6 dB) -> limiter
  412. const auto em = lynx::effectFromFl ("Emphasis", blob ({ 8, 0, 0, 2, 1, 0, 0, 625, 10000, 10000, 9308, 0, 2, 7, 0 }));
  413. CHECK (em && em->kind == lynx::EffectKind::limiter && em->enabled);
  414. if (em)
  415. {
  416. CHECK (std::abs (em->params[1] * 24.0f - 1.5f) < 0.05f);
  417. CHECK (std::abs (em->params[0] * 12.0f - 12.0f + 1.6f) < 0.1f);
  418. }
  419. // Pitch Shifter +12 st, mix 100%
  420. const auto ps = lynx::effectFromFl ("Pitch Shifter", blob ({ 7, 1200, 0, 0, 2400, 8500, 200, 0, 0, 768, 0, 0, 65536, 0, 65536, 0, 0, 0, 0 }));
  421. CHECK (ps && ps->kind == lynx::EffectKind::pitchShift && std::abs (ps->params[0] - (0.5f + 12.0f / 48.0f)) < 1e-4f);
  422. }
  423. TEST (frequency_shifter_moves_spectrum_by_hz)
  424. {
  425. auto fx = lynx::makeEffect (lynx::EffectKind::freqShift);
  426. fx->prepare (48000.0);
  427. auto slot = lynx::makeEffectSlot (lynx::EffectKind::freqShift);
  428. // +200 Hz: x·|x|·2000 = 200 -> x = sqrt(0.1)
  429. slot.params[0] = (float) (0.5 + std::sqrt (0.1) / 2.0);
  430. std::vector<float> l (48000), r (48000);
  431. for (int i = 0; i < 48000; ++i)
  432. l[(std::size_t) i] = r[(std::size_t) i] = (float) std::sin (2.0 * 3.141592653589793 * 1000.0 * i / 48000.0);
  433. for (int done = 0; done < 48000; done += 480)
  434. fx->process (l.data() + done, r.data() + done, 480, slot.params, 120.0);
  435. auto energy = [&] (double f) {
  436. const auto w = 2.0 * 3.141592653589793 * f / 48000.0, k = 2.0 * std::cos (w);
  437. double s1 = 0.0, s2 = 0.0;
  438. for (int i = 9600; i < 48000; ++i)
  439. {
  440. const auto s0 = l[(std::size_t) i] + k * s1 - s2;
  441. s2 = s1;
  442. s1 = s0;
  443. }
  444. return s1 * s1 + s2 * s2 - k * s1 * s2;
  445. };
  446. // the energy moves to 1200 Hz; little remains at 1000 and almost nothing at the image (800)
  447. CHECK (energy (1200.0) > 50.0 * energy (1000.0));
  448. CHECK (energy (1200.0) > 50.0 * energy (800.0));
  449. }
  450. TEST (pitch_shift_moves_frequency_keeps_length)
  451. {
  452. auto fx = lynx::makeEffect (lynx::EffectKind::pitchShift);
  453. fx->prepare (48000.0);
  454. auto slot = lynx::makeEffectSlot (lynx::EffectKind::pitchShift);
  455. auto crossingsAfter = [&] (float semitoneParam) {
  456. fx->reset();
  457. slot.params[0] = semitoneParam;
  458. std::vector<float> l (48000), r (48000);
  459. for (int i = 0; i < 48000; ++i)
  460. l[(std::size_t) i] = r[(std::size_t) i] = (float) std::sin (2.0 * 3.141592653589793 * 220.0 * i / 48000.0);
  461. for (int done = 0; done < 48000; done += 512)
  462. fx->process (l.data() + done, r.data() + done, std::min (512, 48000 - done), slot.params, 120.0);
  463. int crossings = 0;
  464. for (int i = 9600; i < 48000; ++i)
  465. crossings += (l[(std::size_t) i - 1] < 0.0f) != (l[(std::size_t) i] < 0.0f);
  466. for (auto v : l)
  467. CHECK (std::isfinite (v) && std::abs (v) < 1.6f);
  468. return crossings / 0.8 / 2.0; // cycles per second
  469. };
  470. CHECK (std::abs (crossingsAfter (0.5f) - 220.0) < 8.0); // 0 st
  471. CHECK (std::abs (crossingsAfter (0.5f + 12.0f / 48.0f) - 440.0) < 25.0); // +12 st
  472. CHECK (std::abs (crossingsAfter (0.5f - 12.0f / 48.0f) - 110.0) < 12.0); // −12 st
  473. }
  474. TEST (volume_gate_follows_bar_position)
  475. {
  476. auto fx = lynx::makeEffect (lynx::EffectKind::volumeGate);
  477. fx->prepare (48000.0);
  478. auto slot = lynx::makeEffectSlot (lynx::EffectKind::volumeGate);
  479. for (int i = 0; i < 32; ++i)
  480. slot.params[(std::size_t) i] = i < 16 ? 1.0f : 0.0f; // first two beats open, two closed
  481. slot.params[33] = slot.params[34] = 0.0f; // no smoothing
  482. // 120 BPM: one beat = 0.5 s = 24000 samples; the 4-beat bar starts at tick 0
  483. std::vector<float> l (96000, 1.0f), r (96000, 1.0f);
  484. fx->setSongPosition (0.0);
  485. for (int done = 0; done < 96000; done += 512)
  486. fx->process (l.data() + done, r.data() + done, std::min (512, 96000 - done), slot.params, 120.0);
  487. CHECK (l[10000] > 0.99f && l[40000] > 0.99f); // beats 1 and 2
  488. CHECK (l[60000] < 0.01f && l[90000] < 0.01f); // beats 3 and 4
  489. // starting mid-bar (beat 3): already closed
  490. std::vector<float> l2 (4800, 1.0f), r2 (4800, 1.0f);
  491. fx->reset();
  492. fx->setSongPosition (2.0 * lynx::ppq);
  493. fx->process (l2.data(), r2.data(), 4800, slot.params, 120.0);
  494. CHECK (l2[4000] < 0.01f);
  495. // mix 0: transparent
  496. slot.params[32] = 0.0f;
  497. std::vector<float> l3 (4800, 1.0f), r3 (4800, 1.0f);
  498. fx->setSongPosition (2.0 * lynx::ppq);
  499. fx->process (l3.data(), r3.data(), 4800, slot.params, 120.0);
  500. CHECK (l3[4000] > 0.99f);
  501. }
  502. TEST (patcher_branch_heads_follow_rea)
  503. {
  504. auto words = [] (std::vector<std::int32_t> v) {
  505. std::vector<std::uint8_t> b (v.size() * 4);
  506. std::memcpy (b.data(), v.data(), b.size());
  507. return b;
  508. };
  509. // Frequency Splitter, 2 bands, destinations 1/2/3, slope combo 3 (24 dB/oct), high send −6 dB
  510. std::vector<std::int32_t> fs (18, 0);
  511. fs[0] = 4;
  512. fs[1] = 32768;
  513. fs[3] = 3;
  514. fs[6] = 0;
  515. fs[11] = -600;
  516. fs[15] = 1;
  517. fs[16] = 2;
  518. fs[17] = 3;
  519. const auto split = words (fs);
  520. const auto low = lynx::patcherBranchHead ("Frequency Splitter", split, 1);
  521. CHECK (low.valid && low.slot && low.note.empty());
  522. if (low.slot)
  523. {
  524. // low band = just the Crossover low-pass, combo 3 (24 dB/oct)
  525. CHECK (low.slot->kind == lynx::EffectKind::crossover && low.slot->params[0] == 0.0f && low.slot->params[3] == 1.0f);
  526. CHECK (std::lround (low.slot->params[5] * 7.0f) == 3);
  527. }
  528. const auto mid = lynx::patcherBranchHead ("Frequency Splitter", split, 2);
  529. CHECK (mid.valid && mid.gain == 0.0f); // with 2 bands the mid is silent
  530. const auto high = lynx::patcherBranchHead ("Frequency Splitter", split, 3);
  531. CHECK (high.valid && std::abs (high.gain - std::pow (10.0f, -6.0f / 20.0f)) < 1e-4f);
  532. CHECK (! lynx::patcherBranchHead ("Frequency Splitter", split, 7).valid);
  533. // Stereo Shaper with identity matrix: the difference (destination 4) is zero
  534. const auto shaper = words ({ 3, 0, 12800, 12800, 0, 0, 0, 4, 0 });
  535. const auto diff = lynx::patcherBranchHead ("Fruity Stereo Shaper", shaper, 4);
  536. CHECK (diff.valid && diff.slot && std::abs (diff.slot->params[2] - 0.5f) < 1e-6f && std::abs (diff.slot->params[5] - 0.5f) < 1e-6f);
  537. CHECK (! lynx::patcherBranchHead ("Fruity Stereo Shaper", shaper, 2).valid);
  538. }
  539. TEST (parallel_container_sums_branches)
  540. {
  541. // two branches: dry with gain 0.5 and a utility that flips phase (matrix −1) with gain 0.5 -> silence
  542. auto slot = lynx::makeEffectSlot (lynx::EffectKind::parallel);
  543. lynx::EffectBranch dry;
  544. dry.gain = 0.5f;
  545. lynx::EffectBranch inverted;
  546. inverted.gain = 0.5f;
  547. auto flip = lynx::makeEffectSlot (lynx::EffectKind::utility);
  548. flip.params[2] = flip.params[5] = 0.25f; // (−1 + 2)/4
  549. inverted.chain.push_back (flip);
  550. slot.branches = { dry, inverted };
  551. auto fx = lynx::makeParallelEffect (slot);
  552. fx->prepare (48000.0);
  553. std::vector<float> l (9000, 0.8f), r (9000, -0.4f);
  554. fx->process (l.data(), r.data(), 9000, slot.params, 120.0);
  555. CHECK (std::abs (l[100]) < 1e-5f && std::abs (r[8999]) < 1e-5f);
  556. // only the dry branch with gain 2: doubles
  557. slot.branches = { lynx::EffectBranch { {}, 2.0f } };
  558. auto doubler = lynx::makeParallelEffect (slot);
  559. doubler->prepare (48000.0);
  560. std::fill (l.begin(), l.end(), 0.25f);
  561. doubler->process (l.data(), r.data(), 9000, slot.params, 120.0);
  562. CHECK (std::abs (l[5000] - 0.5f) < 1e-6f);
  563. }
  564. TEST (fl_controller_constant_outputs)
  565. {
  566. std::vector<std::int32_t> xy { 2, 32768, 0, 65536, 0, 16384, 0, 65536, 0, 1024, 256 };
  567. std::vector<std::uint8_t> blob (xy.size() * 4 + 8, 0);
  568. std::memcpy (blob.data(), xy.data(), xy.size() * 4);
  569. CHECK (std::abs (lynx::controllerConstantOutput ("Fruity X-Y Controller", blob, 0).value_or (-1.0f) - 0.5f) < 1e-4f);
  570. CHECK (std::abs (lynx::controllerConstantOutput ("Fruity X-Y Controller", blob, 1).value_or (-1.0f) - 0.25f) < 1e-4f);
  571. // Control Surface: version + group { 0x836: value 0.75, -, output 2 }
  572. std::vector<std::uint8_t> cs (4, 0);
  573. cs[0] = 1;
  574. auto chunk = [] (std::vector<std::uint8_t>& out, std::uint32_t id, const std::vector<std::uint8_t>& body) {
  575. const auto size = (std::uint64_t) body.size();
  576. out.insert (out.end(), reinterpret_cast<const std::uint8_t*> (&id), reinterpret_cast<const std::uint8_t*> (&id) + 4);
  577. out.insert (out.end(), reinterpret_cast<const std::uint8_t*> (&size), reinterpret_cast<const std::uint8_t*> (&size) + 8);
  578. out.insert (out.end(), body.begin(), body.end());
  579. };
  580. std::vector<std::uint8_t> value (12, 0);
  581. const float v = 0.75f;
  582. const std::int32_t out = 2;
  583. std::memcpy (value.data(), &v, 4);
  584. std::memcpy (value.data() + 8, &out, 4);
  585. std::vector<std::uint8_t> group;
  586. chunk (group, 0x836, value);
  587. chunk (cs, 0, group);
  588. CHECK (std::abs (lynx::controllerConstantOutput ("Control Surface", cs, 2).value_or (-1.0f) - 0.75f) < 1e-6f);
  589. CHECK (! lynx::controllerConstantOutput ("Control Surface", cs, 0).has_value());
  590. }
  591. TEST (flp_midi_out_notes_reach_wrapper_on_same_port)
  592. {
  593. auto record = [] (std::vector<std::uint8_t>& out, std::uint32_t id, std::vector<std::uint8_t> body) {
  594. const auto size = (std::uint64_t) body.size();
  595. out.insert (out.end(), reinterpret_cast<const std::uint8_t*> (&id), reinterpret_cast<const std::uint8_t*> (&id) + 4);
  596. out.insert (out.end(), reinterpret_cast<const std::uint8_t*> (&size), reinterpret_cast<const std::uint8_t*> (&size) + 8);
  597. out.insert (out.end(), body.begin(), body.end());
  598. };
  599. auto i32s = [] (std::vector<std::int32_t> v) {
  600. std::vector<std::uint8_t> b (v.size() * 4);
  601. std::memcpy (b.data(), v.data(), b.size());
  602. return b;
  603. };
  604. flp::Project p;
  605. flp::Channel midiOut;
  606. midiOut.index = 0;
  607. midiOut.type = flp::ChannelType::native;
  608. midiOut.pluginName = "MIDI Out";
  609. midiOut.pluginState = i32s ({ 7, 0, -1, -1, -1, 0, 3, 0 }); // channel 1, port 3 (@24)
  610. flp::Channel wrapper;
  611. wrapper.index = 1;
  612. wrapper.type = flp::ChannelType::native;
  613. wrapper.pluginName = "Fruity Wrapper";
  614. wrapper.pluginState = i32s ({ 9 });
  615. record (wrapper.pluginState, 0x32, i32s ({ 7 })); // VST3
  616. record (wrapper.pluginState, 0x01, i32s ({ 3, -1, 0, 0, 0 })); // input port 3
  617. p.channels = { midiOut, wrapper };
  618. flp::Pattern pattern;
  619. pattern.index = 1;
  620. flp::Note note;
  621. note.channel = 0;
  622. note.key = 64;
  623. note.length = 96;
  624. pattern.notes.push_back (note);
  625. p.patterns.push_back (pattern);
  626. const auto song = lynx::importFlp (p);
  627. CHECK (song.channels.size() == 2 && song.channels[0].muted);
  628. CHECK (song.channels[1].plugin.foreign.midiInPort == 3);
  629. int toWrapper = 0;
  630. for (const auto& pat : song.patterns)
  631. for (const auto& n : pat.notes)
  632. toWrapper += n.channel == 1 && n.key == 64;
  633. CHECK (toWrapper == 1);
  634. }
  635. TEST (flp_effect_automation_follows_slots_and_params)
  636. {
  637. // track 1: slot 0 with an effect that has no equivalent (dropped), slot 2 with Parametric EQ 2
  638. flp::Project p;
  639. flp::MixerInsert insert;
  640. insert.index = 1;
  641. insert.slots.push_back ({ 0, "Some Unknown FX", {} });
  642. insert.slots.push_back ({ 2, "Fruity Parametric EQ 2", {} });
  643. p.mixer.push_back (insert);
  644. auto clip = [&] (int index, std::uint32_t target) {
  645. flp::Channel c;
  646. c.index = index;
  647. c.type = flp::ChannelType::automationClip;
  648. c.automation = { { 0.0, 0.0 }, { 96.0, 1.0 } };
  649. p.channels.push_back (c);
  650. p.automationLinks.push_back ({ index, { target } });
  651. };
  652. const auto mixer = [] (int track, int slot, int param) { return 0x70000000u + ((std::uint32_t) track << 22) + ((std::uint32_t) slot << 16) + (std::uint32_t) param; };
  653. clip (0, mixer (1, 2, 0x8000 + 7)); // EQ band 1 frequency
  654. clip (1, mixer (1, 2, 0x1F01)); // EQ slot mix
  655. clip (2, mixer (1, 0, 0x8000)); // parameter of the dropped effect
  656. clip (3, mixer (1, 2, 0x8000 + 21)); // band type: no equivalent
  657. const auto song = lynx::importFlp (p);
  658. CHECK (song.automations.size() == 4);
  659. CHECK (song.mixer[1].effects.size() == 1 && song.mixer[1].effects[0].kind == lynx::EffectKind::parametricEq);
  660. const auto& freq = song.automations[0];
  661. CHECK (freq.target.kind == lynx::AutomationTargetKind::effectParam && freq.target.index == 1 && freq.target.slot == 0);
  662. CHECK (freq.target.param == lynx::peq::param (0, 1));
  663. // FL's 0..1 (20 Hz..20 kHz) becomes our frequency scale
  664. CHECK (std::abs (freq.points.front().value - lynx::peq::hzValue (20.0)) < 1e-4f);
  665. CHECK (std::abs (freq.points.back().value - lynx::peq::hzValue (20000.0)) < 1e-4f);
  666. CHECK (song.automations[1].target.kind == lynx::AutomationTargetKind::effectMix && song.automations[1].target.slot == 0);
  667. CHECK (song.automations[2].target.kind == lynx::AutomationTargetKind::none);
  668. CHECK (song.automations[3].target.kind == lynx::AutomationTargetKind::none);
  669. // the automated mix is read/written through the target
  670. auto copy = song;
  671. CHECK (copy.setTargetValue (song.automations[1].target, 0.25f) && std::abs (copy.mixer[1].effects[0].mix - 0.25f) < 1e-6f);
  672. CHECK (std::abs (copy.targetValue (song.automations[1].target) - 0.25f) < 1e-6f);
  673. }
  674. TEST (flp_real_files)
  675. {
  676. if (realFlpDir.empty())
  677. {
  678. std::printf (" (skipped: pass a folder with .flp files as argument)\n");
  679. return;
  680. }
  681. int files = 0, withNotes = 0, withPlaylist = 0, automations = 0, automationsWithTarget = 0, sends = 0;
  682. int threeOsc = 0, threeOscDecoded = 0, wrapped = 0, wrappedParsed = 0, markers = 0, signatures = 0, trackEqs = 0;
  683. int harmless = 0, harmlessDecoded = 0, harmlessParsed = 0, harmlessKind = 0, sytrus = 0, sytrusDecoded = 0, sytrusEngine = 0, sytrusRendered = 0,
  684. sytrusSounding = 0;
  685. int harmor = 0, harmorUsable = 0, harmorKind = 0, harmorSounding = 0;
  686. std::map<std::string, std::pair<int, int>> generators; // GMS/Ogun/Autogun/Sakura/DrumSynth: channels, decoded
  687. int ogunTrumpet = 0; // Ogun channels whose spectrum matches the REA "Trumpet" reference
  688. int peqSlots = 0, peqShaped = 0, reverbs = 0, reverbsDryless = 0, reverbsLowCut = 0;
  689. int dwChannels = 0, dwZones = 0, fpcKits = 0, padChannels = 0, padNotes = 0;
  690. int harmlessCompWanted = 0, harmlessCompLoaded = 0; // Harmless rack compressors / presets read from the installation
  691. // import with the installation's samples (realFlpDir is ...\Data): for DirectWave/FPC
  692. lynx::FlpImportOptions withFiles;
  693. const auto flRoot = std::filesystem::path (realFlpDir).parent_path().string();
  694. withFiles.roots = { flRoot, realFlpDir, "" };
  695. withFiles.fileExists = [] (const std::string& path) {
  696. auto local = path;
  697. std::replace (local.begin(), local.end(), '\\', '/');
  698. return std::filesystem::exists (local);
  699. };
  700. withFiles.readFile = [] (const std::string& path) {
  701. auto local = path;
  702. std::replace (local.begin(), local.end(), '\\', '/');
  703. std::ifstream in (local, std::ios::binary);
  704. return std::vector<std::uint8_t> ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  705. };
  706. int embeddedSaved = 0;
  707. withFiles.saveEmbedded = [&embeddedSaved] (const std::vector<std::uint8_t>& wav, const std::string&) {
  708. ++embeddedSaved;
  709. return wav.size() > 44 ? std::string ("embutido.wav") : std::string();
  710. };
  711. int slicedChannels = 0, flKeysChannels = 0;
  712. for (auto& entry : std::filesystem::recursive_directory_iterator (realFlpDir))
  713. {
  714. if (entry.path().extension() != ".flp")
  715. continue;
  716. std::ifstream in (entry.path(), std::ios::binary);
  717. std::vector<std::uint8_t> bytes ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  718. ++files;
  719. try
  720. {
  721. const auto p = flp::parseProject (bytes);
  722. CHECK (! p.version.empty());
  723. CHECK (p.tempo > 10.0 && p.tempo < 1000.0);
  724. const auto song = lynx::importFlp (p);
  725. CHECK (! song.patterns.empty());
  726. {
  727. const auto full = lynx::importFlp (p, withFiles);
  728. bool hasFpc = false;
  729. for (const auto& c : p.channels)
  730. hasFpc = hasFpc || c.pluginName == "FPC";
  731. for (const auto& c : full.channels)
  732. {
  733. if (c.instrument == lynx::InstrumentKind::harmless && c.modelParams.size() >= (std::size_t) lynx::harmlessParamCount
  734. && c.modelParams[(std::size_t) lynx::harmlessComboIndex + 3] > 0.5f)
  735. {
  736. ++harmlessCompWanted;
  737. harmlessCompLoaded += c.modelParams.size() > (std::size_t) lynx::harmlessCompIndex + 1000 ? 1 : 0;
  738. }
  739. flKeysChannels += c.zones.size() == 30 && c.zones.front().path.find ("CHANGPIANO") != std::string::npos ? 1 : 0;
  740. if (c.sampler.slices.size() >= 4)
  741. {
  742. ++slicedChannels;
  743. CHECK (std::is_sorted (c.sampler.slices.begin(), c.sampler.slices.end()));
  744. CHECK (c.sampler.slices.back() < 1.0f);
  745. }
  746. if (! c.zones.empty() && c.name.find (" - ") == std::string::npos)
  747. {
  748. ++dwChannels;
  749. dwZones += (int) c.zones.size();
  750. }
  751. padChannels += c.name.find (" - ") != std::string::npos && c.instrument == lynx::InstrumentKind::sampler ? 1 : 0;
  752. }
  753. fpcKits += hasFpc;
  754. for (const auto& pat : full.patterns)
  755. for (const auto& n : pat.notes)
  756. {
  757. CHECK (n.channel >= 0 && n.channel < (int) full.channels.size());
  758. padNotes += full.channels[(std::size_t) n.channel].name.find (" - ") != std::string::npos ? 1 : 0;
  759. }
  760. }
  761. const auto peqDefaults = lynx::makeEffectSlot (lynx::EffectKind::parametricEq).params;
  762. for (const auto& t : song.mixer)
  763. for (const auto& fx : t.effects)
  764. {
  765. if (fx.kind == lynx::EffectKind::parametricEq)
  766. {
  767. ++peqSlots;
  768. peqShaped += fx.params != peqDefaults;
  769. for (double hz : { 50.0, 1000.0, 10000.0 })
  770. CHECK (std::isfinite (lynx::peq::responseDb (fx.params, 48000.0, hz)));
  771. }
  772. if (fx.kind == lynx::EffectKind::reverb)
  773. {
  774. ++reverbs;
  775. reverbsDryless += fx.params[4] < 0.01f;
  776. reverbsLowCut += fx.params[5] > 0.0f;
  777. }
  778. }
  779. for (const auto& t : song.mixer)
  780. if (t.eq.active())
  781. {
  782. ++trackEqs;
  783. for (std::size_t b = 0; b < 3; ++b)
  784. CHECK (t.eq.hz[b] >= 10.0f && t.eq.hz[b] <= 16000.0f && std::abs (t.eq.gainDb[b]) <= 18.0f);
  785. }
  786. for (const auto& a : song.arrangements)
  787. for (const auto& m : a.markers)
  788. {
  789. ++markers;
  790. signatures += m.isSignature();
  791. CHECK (m.tick >= 0);
  792. }
  793. // Fruity Wrapper (channels and mixer slots): every blob in the demos is read
  794. auto countWrapper = [&] (const std::string& plugin, const std::vector<std::uint8_t>& state) {
  795. if (plugin != "Fruity Wrapper")
  796. return;
  797. ++wrapped;
  798. lynx::ForeignPlugin f;
  799. wrappedParsed += lynx::parseFlWrapper (state, f) && f.format != lynx::ForeignPlugin::Format::none && ! f.name.empty();
  800. };
  801. for (const auto& c : p.channels)
  802. countWrapper (c.pluginName, c.pluginState);
  803. for (const auto& insert : p.mixer)
  804. for (const auto& slot : insert.slots)
  805. countWrapper (slot.plugin, slot.state);
  806. // Harmless: every state in the demos becomes a synth, with finite values
  807. for (const auto& c : p.channels)
  808. if (c.pluginName == "Harmless")
  809. {
  810. ++harmless;
  811. lynx::SynthSettings hs;
  812. float g = 1.0f;
  813. if (lynx::synthFromHarmless (c.pluginState, 128.0, hs, g))
  814. {
  815. ++harmlessDecoded;
  816. CHECK (std::isfinite (g) && hs.cutoff >= 20.0f && hs.cutoff <= 20000.0f && std::isfinite (hs.decay) && std::isfinite (hs.release));
  817. }
  818. if (const auto hp = lynx::harmlessParams (c.pluginState))
  819. harmlessParsed += (int) hp->size() == lynx::harmlessParamCount ? 1 : 0;
  820. }
  821. for (const auto& c : song.channels)
  822. harmlessKind += c.instrument == lynx::InstrumentKind::harmless ? 1 : 0;
  823. // Harmor: every state in the demos plays on the exact engine (REA_rodada34) and sounds, with finite samples
  824. for (const auto& c : p.channels)
  825. if (c.pluginName == "Harmor")
  826. {
  827. ++harmor;
  828. harmorUsable += lynx::harmorStateUsable (c.pluginState) ? 1 : 0;
  829. }
  830. for (const auto& c : song.channels)
  831. if (c.instrument == lynx::InstrumentKind::harmor)
  832. {
  833. ++harmorKind;
  834. const auto y = lynx::harmor::renderReference (c.pluginState, { { 0, 60, 0.8, 1.0, 0.0, 6000 }, { 2000, 67, 0.6, 1.0, 0.0, 8000 } }, 44100.0, 11025);
  835. double e = 0.0;
  836. bool finite = ! y.empty();
  837. for (auto v : y)
  838. finite = finite && std::isfinite (v), e += (double) v * v;
  839. CHECK (finite);
  840. harmorSounding += e > 1e-6 ? 1 : 0;
  841. }
  842. // Sytrus: every state in the demos (zlib + 10 units) decodes, with finite values
  843. for (const auto& c : p.channels)
  844. if (c.pluginName == "Sytrus")
  845. {
  846. ++sytrus;
  847. lynx::SynthSettings ss;
  848. float g = 1.0f;
  849. // the Sytrus engine (REA_rodada31) reads every demo state; the first 24 play a short note (render settings)
  850. if (lynx::sytrus::stateUsable (c.pluginState))
  851. {
  852. ++sytrusEngine;
  853. if (sytrusRendered < 24)
  854. {
  855. ++sytrusRendered;
  856. lynx::sytrus::Engine e;
  857. e.prepare (44100.0, true, 512);
  858. e.setPatch (lynx::sytrus::parsePatch (c.pluginState));
  859. lynx::sytrus::NoteParams note;
  860. e.noteOn (note);
  861. std::vector<float> l (8192), r (8192);
  862. e.render (l.data(), r.data(), 8192, 0.551f, 0.0f);
  863. bool finite = true;
  864. double energy = 0.0;
  865. for (std::size_t k = 0; k < l.size(); ++k)
  866. finite = finite && std::isfinite (l[k]) && std::isfinite (r[k]), energy += (double) l[k] * l[k];
  867. CHECK (finite);
  868. sytrusSounding += energy > 1e-6;
  869. }
  870. }
  871. if (lynx::synthFromSytrus (c.pluginState, 128.0, ss, g))
  872. {
  873. ++sytrusDecoded;
  874. CHECK (std::isfinite (g) && ss.cutoff >= 20.0f && ss.cutoff <= 20000.0f && std::isfinite (ss.attack) && std::isfinite (ss.decay)
  875. && std::isfinite (ss.release) && ss.sustain >= 0.0f && ss.sustain <= 1.0f && std::isfinite (ss.filterEnv.amount));
  876. for (const auto& o : ss.osc)
  877. CHECK (o.level >= 0.0f && o.level <= 1.0f && o.octave >= -3 && o.octave <= 3);
  878. }
  879. }
  880. // round 12 generators
  881. for (const auto& c : p.channels)
  882. {
  883. lynx::SynthSettings gs;
  884. float g = 1.0f;
  885. int decoded = -1;
  886. if (c.pluginName == "Harmor")
  887. {
  888. decoded = lynx::synthFromHarmor (c.pluginState, gs, g);
  889. if (decoded)
  890. {
  891. // REA_rodada25 §4: most resonant settings stay below Q ≈ 3, a few saturate
  892. CHECK (gs.resonance >= 0.0f && gs.resonance <= 1.0f);
  893. static int resonant = 0, strong = 0, total = 0;
  894. resonant += gs.resonance > 0.0f;
  895. strong += gs.resonance > 0.9f;
  896. if (++total % 50 == 0)
  897. std::printf (" Harmor resonance: %d with a peak, %d with Q > ~5 (of %d)\n", resonant, strong, total);
  898. }
  899. static int saw = 0, square = 0, other = 0, total = 0;
  900. if (decoded && std::any_of (gs.osc.begin(), gs.osc.end(), [] (const lynx::SynthOscillator& o) { return o.wave == lynx::Waveform::spectral; }))
  901. {
  902. auto isSaw = true, isSquare = true;
  903. for (int n = 1; n <= 16; ++n)
  904. {
  905. isSaw = isSaw && std::abs (gs.spectrum[(std::size_t) n - 1] - 1.0f / n) < 1e-3f;
  906. isSquare = isSquare && std::abs (gs.spectrum[(std::size_t) n - 1] - (n % 2 == 1 ? 1.1535f / n : 0.0f)) < 2e-3f;
  907. }
  908. ++(isSaw ? saw : isSquare ? square : other);
  909. if (++total % 20 == 0 || total == 100)
  910. std::printf (" Harmor spectrum: %d saw, %d square, %d other (of %d)\n", saw, square, other, total);
  911. }
  912. }
  913. else if (c.pluginName == "GMS")
  914. decoded = lynx::synthFromGms (c.pluginState, 128.0, gs, g);
  915. else if (c.pluginName == "Ogun" || c.pluginName == "Autogun")
  916. {
  917. decoded = lynx::synthFromOgun (c.pluginState, gs, g);
  918. // REA_rodada24 §1.9: the "Trumpet" preset (richness 7, no seeds) has partials 0.9087, 0.8610,
  919. // 0.8151… at the fixed seed-3 phases 0.919, 0.380, 0.130
  920. if (decoded && gs.osc[0].wave == lynx::Waveform::spectral)
  921. {
  922. CHECK (std::all_of (gs.spectrum.begin(), gs.spectrum.end(), [] (float a) { return std::isfinite (a) && a >= 0.0f; }));
  923. static constexpr float trumpet[3] { 0.9087f, 0.8610f, 0.8151f }, phases[3] { 0.919f, 0.380f, 0.130f };
  924. auto match = true;
  925. for (std::size_t k = 0; k < 3; ++k)
  926. match = match && std::abs (gs.spectrum[k] * 2.0f / 3.14159265f - trumpet[k]) < 1e-3f && std::abs (gs.spectrumPhase[k] - phases[k]) < 1e-3f;
  927. ogunTrumpet += match ? 1 : 0;
  928. }
  929. }
  930. else if (c.pluginName == "Sakura")
  931. decoded = lynx::synthFromSakura (c.pluginState, gs);
  932. else if (c.pluginName == "Kepler")
  933. decoded = lynx::synthFromKepler (c.pluginState, gs, g);
  934. else if (c.pluginName == "Wave Traveller")
  935. decoded = lynx::waveTravellerSample (c.pluginState).has_value() ? 2 : 0;
  936. else if (c.pluginName == "PoiZone")
  937. decoded = lynx::synthFromPoiZone (c.pluginState, gs, g);
  938. else if (c.pluginName == "BassDrum")
  939. decoded = lynx::synthFromBassDrum (c.pluginState, gs, g);
  940. else if (c.pluginName == "Toxic Biohazard")
  941. decoded = lynx::synthFromToxic (c.pluginState, gs, g);
  942. else if (c.pluginName == "Morphine")
  943. decoded = lynx::synthFromMorphine (c.pluginState, gs, g);
  944. else if (c.pluginName == "BooBass")
  945. decoded = lynx::synthFromBooBass (c.pluginState, gs);
  946. else if (c.pluginName == "Drumpad" || c.pluginName == "DrumPad")
  947. decoded = lynx::drumpadPatchName (c.pluginState).has_value() ? 2 : 0;
  948. else if (c.pluginName == "Fruity Envelope Controller" && c.pluginState.size() >= 4 && c.pluginState[2] >= 6) // v >= 6
  949. decoded = lynx::parseEnvelopeController (c.pluginState).has_value() ? 2 : 0;
  950. else if (c.pluginName == "FLEX")
  951. decoded = lynx::flexPresetName (c.pluginState).has_value() ? 2 : 0;
  952. else if (c.pluginName == "Fruity DrumSynth Live")
  953. decoded = lynx::drumSynthLiveParams (c.pluginState).has_value() ? 2 : 0;
  954. if (decoded < 0)
  955. continue;
  956. auto& counter = generators[c.pluginName];
  957. ++counter.first;
  958. counter.second += decoded != 0;
  959. if (decoded == 1 && c.pluginName != "Fruity DrumSynth Live")
  960. {
  961. CHECK (std::isfinite (g) && g >= 0.0f && gs.cutoff >= 20.0f && gs.cutoff <= 20000.0f && gs.sustain >= 0.0f && gs.sustain <= 1.0f);
  962. CHECK (std::isfinite (gs.attack) && std::isfinite (gs.decay) && std::isfinite (gs.release) && std::isfinite (gs.filterEnv.amount) && std::isfinite (gs.lfo[lynx::lfoCutoff].amount));
  963. for (const auto& o : gs.osc)
  964. CHECK (o.level >= 0.0f && o.level <= 4.0f && std::isfinite (o.detune) && std::isfinite (o.pan));
  965. }
  966. }
  967. // 3x Osc: every state in the demos decodes, with levels summing to at most 1
  968. for (const auto& c : p.channels)
  969. if (c.pluginName == "3x Osc")
  970. {
  971. ++threeOsc;
  972. lynx::SynthSettings s;
  973. if (lynx::synthFrom3xOsc (c.pluginState, s))
  974. {
  975. ++threeOscDecoded;
  976. // with AM, osc 3 is the modulation depth and is left out of the sum
  977. const auto sum = s.osc[0].level + s.osc[1].level + (s.am ? 0.0f : s.osc[2].level);
  978. CHECK (sum <= 1.001f && s.osc[2].level <= 1.0f);
  979. for (const auto& o : s.osc)
  980. CHECK (o.octave >= -2 && o.octave <= 2 && std::abs (o.semitones) <= 11 && std::abs (o.pan) <= 1.0f);
  981. }
  982. }
  983. for (auto& pat : p.patterns)
  984. if (! pat.notes.empty())
  985. {
  986. ++withNotes;
  987. break;
  988. }
  989. for (auto& a : p.arrangements)
  990. for (auto& item : a.items)
  991. CHECK (item.track >= 0 && item.track < 500);
  992. for (auto& clip : song.playlist)
  993. {
  994. CHECK (clip.pattern >= 0 && clip.pattern < (int) song.patterns.size());
  995. CHECK (clip.length > 0 && clip.offset >= 0);
  996. if (clip.kind == lynx::ClipKind::automation)
  997. CHECK (clip.automation >= 0 && clip.automation < (int) song.automations.size());
  998. }
  999. for (auto& a : song.automations)
  1000. {
  1001. ++automations;
  1002. automationsWithTarget += a.target.kind != lynx::AutomationTargetKind::none;
  1003. CHECK (a.isLive() || ! a.points.empty());
  1004. for (std::size_t i = 1; i < a.points.size(); ++i)
  1005. CHECK (a.points[i].tick >= a.points[i - 1].tick);
  1006. }
  1007. // imported routing has no cycles and valid destinations
  1008. CHECK (song.mixerOrder().size() + 1 == song.mixer.size());
  1009. for (auto& t : song.mixer)
  1010. for (auto& s : t.sends)
  1011. {
  1012. ++sends;
  1013. CHECK (s.target > 0 && s.target < (int) song.mixer.size());
  1014. }
  1015. if (! song.playlist.empty())
  1016. ++withPlaylist;
  1017. }
  1018. catch (const flp::Error& e)
  1019. {
  1020. ++failures;
  1021. std::printf (" FAILED %s: %s\n", entry.path().string().c_str(), e.what());
  1022. }
  1023. }
  1024. CHECK (threeOscDecoded == threeOsc);
  1025. std::printf (" Harmless: %d channels, %d decoded\n", harmless, harmlessDecoded);
  1026. std::printf (" Sytrus: %d channels, %d decoded, %d by the engine (%d of %d rendered sound)\n", sytrus, sytrusDecoded, sytrusEngine,
  1027. sytrusSounding, sytrusRendered);
  1028. CHECK (sytrusEngine == sytrus);
  1029. CHECK (sytrusSounding >= sytrusRendered * 3 / 4);
  1030. for (const auto& [name, counter] : generators)
  1031. {
  1032. std::printf (" %s: %d channels, %d decoded\n", name.c_str(), counter.first, counter.second);
  1033. CHECK (counter.second == counter.first);
  1034. }
  1035. std::printf (" Ogun spectra matching the Trumpet reference: %d\n", ogunTrumpet);
  1036. CHECK (ogunTrumpet >= 1);
  1037. // demo Gross Beat: the volume slot becomes the gate (those using an envelope slot get steps < 1)
  1038. {
  1039. int vocodexes = 0, vocodexSides = 0;
  1040. int lovePhilterLinks[4] {}; // live links: cutoff, resonance; inside containers: cutoff, resonance
  1041. int embeddedZones = 0, lovePhilters = 0, lovePhiltersRead = 0, lovePhiltersConverted = 0, gates = 0, shaped = 0, effectors = 0, patchers = 0, serial = 0, parallel = 0, generatorPatchers = 0;
  1042. for (const auto& entry : std::filesystem::recursive_directory_iterator (std::filesystem::path (realFlpDir) / "Demo projects"))
  1043. if (entry.path().extension() == ".flp")
  1044. {
  1045. std::ifstream in (entry.path(), std::ios::binary);
  1046. const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1047. try
  1048. {
  1049. const auto project = flp::parseProject (file);
  1050. for (const auto& insert : project.mixer)
  1051. for (const auto& slot : insert.slots)
  1052. if (slot.plugin == "Gross Beat")
  1053. {
  1054. const auto fx = lynx::effectFromFl (slot.plugin, slot.state);
  1055. CHECK (fx && fx->kind == lynx::EffectKind::volumeGate);
  1056. ++gates;
  1057. if (fx && std::any_of (fx->params.begin(), fx->params.begin() + 32, [] (float v) { return v < 0.99f; }))
  1058. ++shaped;
  1059. }
  1060. else if (slot.plugin == "Fruity Love Philter")
  1061. {
  1062. ++lovePhilters;
  1063. lovePhiltersRead += lynx::parseLovePhilter (slot.state).has_value();
  1064. if (const auto conv = lynx::lovePhilterEffects (slot.state))
  1065. {
  1066. ++lovePhiltersConverted;
  1067. CHECK (! conv->slots.empty());
  1068. for (const auto& fx : conv->slots)
  1069. for (auto v : fx.params)
  1070. CHECK (std::isfinite (v) && v >= 0.0f && v <= 1.0f);
  1071. for (const auto& fx : conv->slots)
  1072. for (const auto& link : fx.links)
  1073. {
  1074. const auto& chain = fx.branches[(std::size_t) link.branch].chain;
  1075. CHECK (link.source < (int) chain.size() && chain[(std::size_t) link.target].kind == lynx::EffectKind::parametricEq);
  1076. lovePhilterLinks[2 + (link.param == lynx::peq::param (0, 3) ? 1 : 0)]++;
  1077. }
  1078. for (const auto& link : conv->links)
  1079. {
  1080. lovePhilterLinks[link.param == lynx::peq::param (0, 3) ? 1 : 0]++;
  1081. CHECK (link.curve.size() == 33);
  1082. for (auto v : link.curve)
  1083. CHECK (std::isfinite (v) && v >= 0.0f && v <= 1.0f);
  1084. }
  1085. }
  1086. }
  1087. else if (slot.plugin == "Vocodex")
  1088. {
  1089. const auto v = lynx::vocodexEffect (slot.state);
  1090. CHECK (v.has_value());
  1091. vocodexes += v.has_value();
  1092. vocodexSides += v && (v->modIn > 0 || v->carIn > 0);
  1093. }
  1094. else if (slot.plugin == "Effector")
  1095. effectors += lynx::effectFromFl (slot.plugin, slot.state).has_value();
  1096. else if (slot.plugin == "Patcher")
  1097. {
  1098. const auto graph = lynx::parsePatcher (slot.state);
  1099. CHECK (graph.has_value());
  1100. ++patchers;
  1101. if (graph && ! graph->serialChain.empty())
  1102. ++serial;
  1103. if (graph && graph->serialChain.empty() && graph->audio)
  1104. ++parallel;
  1105. }
  1106. for (const auto& c : project.channels)
  1107. if (c.pluginName == "DirectWave")
  1108. if (const auto program = lynx::directWaveProgram (c.pluginState))
  1109. for (const auto& wav : program->embeddedWav)
  1110. if (! wav.empty())
  1111. {
  1112. ++embeddedZones;
  1113. CHECK (wav.size() > 44 && std::memcmp (wav.data(), "RIFF", 4) == 0);
  1114. }
  1115. for (const auto& c : project.channels)
  1116. if (c.pluginName == "Patcher")
  1117. {
  1118. const auto graph = lynx::parsePatcher (c.pluginState);
  1119. CHECK (graph.has_value());
  1120. generatorPatchers += graph && graph->mainGenerator >= 0;
  1121. }
  1122. }
  1123. catch (const flp::Error&) {}
  1124. }
  1125. std::printf (" Gross Beat: %d slots, %d with gate; Effector: %d converted; Love Philter: %d, %d read\n", gates, shaped, effectors,
  1126. lovePhilters, lovePhiltersRead);
  1127. CHECK (lovePhiltersRead == lovePhilters && lovePhiltersConverted == lovePhilters);
  1128. std::printf (" Vocodex: %d converted, %d with side inputs\n", vocodexes, vocodexSides);
  1129. CHECK (vocodexes >= 9);
  1130. std::printf (" Love Philter live links: %d cutoff, %d resonance; in multi-unit containers: %d cutoff, %d resonance\n",
  1131. lovePhilterLinks[0], lovePhilterLinks[1], lovePhilterLinks[2], lovePhilterLinks[3]);
  1132. CHECK (lovePhilterLinks[2] + lovePhilterLinks[3] > 0);
  1133. std::printf (" DirectWave: %d zones with embedded audio\n", embeddedZones);
  1134. CHECK (embeddedZones == 12);
  1135. std::printf (" Patcher: %d in the mixer (%d serial, %d reduced to serial/parallel), %d as instrument with generator\n", patchers, serial,
  1136. parallel, generatorPatchers);
  1137. CHECK (gates == 0 || shaped > 0);
  1138. }
  1139. // Envelope Controller "Basic Sidechain" (Future House): drops on the note and returns to ~1 within ~1/3 s
  1140. {
  1141. const auto path = std::filesystem::path (realFlpDir) / "Demo projects" / "Demo songs" / "Asher Postman - Future House.flp";
  1142. if (std::filesystem::exists (path))
  1143. {
  1144. std::ifstream in (path, std::ios::binary);
  1145. const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1146. const auto song = lynx::importFlp (flp::parseProject (file));
  1147. const lynx::ChannelDef* controller = nullptr;
  1148. for (const auto& c : song.channels)
  1149. if (c.instrument == lynx::InstrumentKind::controller)
  1150. controller = &c;
  1151. CHECK (controller != nullptr);
  1152. if (controller != nullptr)
  1153. {
  1154. auto inst = lynx::makeInstrument (lynx::InstrumentKind::controller);
  1155. inst->prepare (48000.0);
  1156. inst->configure (*controller, song.bpm);
  1157. std::vector<float> l (480), r (480);
  1158. inst->render (l.data(), r.data(), 480, 1.0f, 1.0f);
  1159. inst->noteOn (60, 1.0f);
  1160. inst->render (l.data(), r.data(), 480, 1.0f, 1.0f); // 10 ms
  1161. const auto ducked = inst->controlOutput (0);
  1162. for (int i = 0; i < 100; ++i) // +1 s
  1163. inst->render (l.data(), r.data(), 480, 1.0f, 1.0f);
  1164. const auto recovered = inst->controlOutput (0);
  1165. std::printf (" Envelope Controller (Basic Sidechain): %.2f on the note, %.2f after 1 s\n", ducked, recovered);
  1166. CHECK (ducked < 0.3f && recovered > 0.9f);
  1167. }
  1168. }
  1169. }
  1170. // mutation fuzz: real states with flipped and truncated bytes must not crash the readers
  1171. {
  1172. std::map<std::string, std::vector<std::uint8_t>> samples; // one real blob per plugin
  1173. for (const auto& entry : std::filesystem::recursive_directory_iterator (std::filesystem::path (realFlpDir) / "Demo projects"))
  1174. {
  1175. if (entry.path().extension() != ".flp")
  1176. continue;
  1177. std::ifstream in (entry.path(), std::ios::binary);
  1178. const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1179. try
  1180. {
  1181. const auto project = flp::parseProject (file);
  1182. for (const auto& c : project.channels)
  1183. if (! c.pluginState.empty())
  1184. samples.emplace (c.pluginName, c.pluginState);
  1185. for (const auto& insert : project.mixer)
  1186. for (const auto& slot : insert.slots)
  1187. if (! slot.state.empty())
  1188. samples.emplace (slot.plugin, slot.state);
  1189. }
  1190. catch (const flp::Error&) {}
  1191. }
  1192. std::uint32_t seed = 12345;
  1193. auto rnd = [&seed] { seed = seed * 1664525u + 1013904223u; return seed >> 8; };
  1194. int mutations = 0;
  1195. for (const auto& [name, original] : samples)
  1196. for (int round = 0; round < 40; ++round)
  1197. {
  1198. auto blob = original;
  1199. if (round % 4 == 3 && ! blob.empty())
  1200. blob.resize (rnd() % blob.size()); // truncated
  1201. else
  1202. for (int k = 0; k < 1 + (int) (rnd() % 8) && ! blob.empty(); ++k)
  1203. blob[rnd() % blob.size()] = (std::uint8_t) rnd();
  1204. ++mutations;
  1205. lynx::SynthSettings synth;
  1206. float gain = 1.0f;
  1207. lynx::synthFromSytrus (blob, 120.0, synth, gain);
  1208. lynx::synthFromHarmor (blob, synth, gain);
  1209. lynx::synthFromGms (blob, 120.0, synth, gain);
  1210. lynx::synthFromOgun (blob, synth, gain);
  1211. lynx::synthFromMorphine (blob, synth, gain);
  1212. lynx::synthFromKepler (blob, synth, gain);
  1213. lynx::synthFromPoiZone (blob, synth, gain);
  1214. lynx::synthFromToxic (blob, synth, gain);
  1215. lynx::synthFromBassDrum (blob, synth, gain);
  1216. lynx::synthFromHarmless (blob, 120.0, synth, gain);
  1217. lynx::harmlessParams (blob);
  1218. if (lynx::harmorStateUsable (blob))
  1219. lynx::harmorFallbacks (blob);
  1220. lynx::parseEnvelopeController (blob);
  1221. lynx::parseKeyboardController (blob);
  1222. lynx::parseLovePhilter (blob);
  1223. lynx::parsePatcher (blob);
  1224. lynx::effectFromFl (name, blob);
  1225. lynx::fpcPads (blob);
  1226. lynx::directWaveProgram (blob);
  1227. CHECK (std::isfinite (gain) && std::isfinite (synth.cutoff));
  1228. }
  1229. std::printf (" mutation fuzz: %d blobs from %d plugins\n", mutations, (int) samples.size());
  1230. }
  1231. // WavPack (.wv) samples from FL packs: all decode, with finite, non-silent audio
  1232. {
  1233. int files = 0, decoded = 0, audible = 0;
  1234. double seconds = 0.0;
  1235. for (const auto& entry : std::filesystem::recursive_directory_iterator (std::filesystem::path (realFlpDir) / "Patches" / "Packs"))
  1236. if (entry.path().extension() == ".wv")
  1237. {
  1238. std::ifstream in (entry.path(), std::ios::binary);
  1239. const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1240. ++files;
  1241. lynx::DecodedAudio audio;
  1242. if (! lynx::decodeWavPack (file.data(), file.size(), audio))
  1243. continue;
  1244. ++decoded;
  1245. float peak = 0.0f;
  1246. bool finite = true;
  1247. for (const auto& ch : audio.channels)
  1248. for (auto v : ch)
  1249. {
  1250. finite = finite && std::isfinite (v);
  1251. peak = std::max (peak, std::abs (v));
  1252. }
  1253. CHECK (finite && peak <= 4.0f);
  1254. audible += peak > 1e-4f;
  1255. seconds += (double) audio.channels[0].size() / audio.sampleRate;
  1256. }
  1257. std::printf (" WavPack: %d .wv files, %d decoded, %d audible, %.0f s of audio\n", files, decoded, audible, seconds);
  1258. CHECK (decoded == files);
  1259. }
  1260. // native GMS presets (.gmsynth = the contents of 0xD5 without the "SSLF")
  1261. int gmsPresets = 0, gmsDecoded = 0;
  1262. const auto gmsFolder = std::filesystem::path (realFlpDir) / "Patches" / "Plugin presets" / "Generators" / "GMS";
  1263. if (std::filesystem::exists (gmsFolder))
  1264. for (const auto& entry : std::filesystem::recursive_directory_iterator (gmsFolder))
  1265. if (entry.path().extension() == ".gmsynth")
  1266. {
  1267. std::ifstream in (entry.path(), std::ios::binary);
  1268. std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1269. std::vector<std::uint8_t> blob { 'S', 'S', 'L', 'F' };
  1270. const auto n = (std::uint32_t) file.size();
  1271. blob.insert (blob.end(), reinterpret_cast<const std::uint8_t*> (&n), reinterpret_cast<const std::uint8_t*> (&n) + 4);
  1272. blob.insert (blob.end(), file.begin(), file.end());
  1273. lynx::SynthSettings gs;
  1274. float g = 1.0f;
  1275. ++gmsPresets;
  1276. if (lynx::synthFromGms (blob, 120.0, gs, g))
  1277. {
  1278. ++gmsDecoded;
  1279. CHECK (std::isfinite (g) && gs.cutoff >= 20.0f && std::isfinite (gs.pitchEnv.amount) && std::isfinite (gs.lfo[lynx::lfoPitch].period));
  1280. }
  1281. }
  1282. std::printf (" GMS presets: %d, %d decoded\n", gmsPresets, gmsDecoded);
  1283. // the synth's "FL presets" button: Sytrus/Harmor .fst and .gmsynth become synth settings
  1284. int presetFiles = 0, presetsRead = 0;
  1285. for (const auto* name : { "Sytrus", "Harmor", "GMS", "Harmless", "Ogun", "Sakura", "Fruit Kick", "Fruity DX10", "MiniSynth", "Kepler",
  1286. "PoiZone", "Toxic Biohazard", "BassDrum" })
  1287. {
  1288. const auto folder = std::filesystem::path (realFlpDir) / "Patches" / "Plugin presets" / "Generators" / name;
  1289. if (! std::filesystem::exists (folder))
  1290. continue;
  1291. for (const auto& entry : std::filesystem::recursive_directory_iterator (folder))
  1292. if (entry.path().extension() == ".fst" || entry.path().extension() == ".gmsynth")
  1293. {
  1294. std::ifstream in (entry.path(), std::ios::binary);
  1295. const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1296. ++presetFiles;
  1297. presetsRead += lynx::synthFromFlPreset (file).has_value();
  1298. }
  1299. }
  1300. std::printf (" FL synth presets: %d files, %d read\n", presetFiles, presetsRead);
  1301. CHECK (presetsRead >= presetFiles * 95 / 100);
  1302. CHECK (gmsDecoded == gmsPresets);
  1303. CHECK (sytrusDecoded == sytrus);
  1304. CHECK (harmlessDecoded == harmless && harmless > 100);
  1305. std::printf (" Harmless: %d states parsed for the engine, %d channels imported as Harmless\n", harmlessParsed, harmlessKind);
  1306. CHECK (harmlessParsed == harmless && harmlessKind >= harmless);
  1307. std::printf (" Harmor: %d channels, %d states usable by the engine, %d imported as Harmor (%d sounding)\n", harmor, harmorUsable, harmorKind, harmorSounding);
  1308. CHECK (harmorUsable == harmor && harmor > 90 && harmorKind >= harmor && harmorSounding >= harmorKind * 9 / 10);
  1309. std::printf (" Harmless rack compressor: %d of %d presets read from the installation\n", harmlessCompLoaded, harmlessCompWanted);
  1310. CHECK (harmlessCompLoaded == harmlessCompWanted && harmlessCompWanted > 100);
  1311. // 3x Osc channel presets shipped with FL (.fst): all become synth settings
  1312. int presets = 0, presetsDecoded = 0;
  1313. const auto presetDir = std::filesystem::path (realFlpDir) / "Patches" / "Channel presets" / "3x Osc";
  1314. if (std::filesystem::is_directory (presetDir))
  1315. for (auto& entry : std::filesystem::directory_iterator (presetDir))
  1316. if (entry.path().extension() == ".fst")
  1317. {
  1318. ++presets;
  1319. std::ifstream in (entry.path(), std::ios::binary);
  1320. std::vector<std::uint8_t> bytes ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  1321. if (auto synth = lynx::synthFromFlPreset (bytes))
  1322. {
  1323. ++presetsDecoded;
  1324. CHECK (synth->osc[0].level + synth->osc[1].level + (synth->am ? 0.0f : synth->osc[2].level) <= 1.001f);
  1325. }
  1326. }
  1327. std::printf (" %d 3x Osc presets, %d read\n", presets, presetsDecoded);
  1328. CHECK (presetsDecoded == presets);
  1329. // FL effect presets that become built-in effects
  1330. int fxPresets = 0, fxDecoded = 0;
  1331. for (auto kind : { lynx::EffectKind::parametricEq, lynx::EffectKind::limiter, lynx::EffectKind::reverb, lynx::EffectKind::delay,
  1332. lynx::EffectKind::utility })
  1333. for (const auto& plugin : lynx::flPluginsForEffect (kind))
  1334. {
  1335. const auto dir = std::filesystem::path (realFlpDir) / "Patches" / "Plugin presets" / "Effects" / plugin;
  1336. if (! std::filesystem::is_directory (dir))
  1337. continue;
  1338. for (auto& entry : std::filesystem::recursive_directory_iterator (dir))
  1339. if (entry.path().extension() == ".fst")
  1340. {
  1341. ++fxPresets;
  1342. std::ifstream in (entry.path(), std::ios::binary);
  1343. std::vector<std::uint8_t> bytes ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  1344. fxDecoded += lynx::effectFromFlPreset (bytes).has_value();
  1345. }
  1346. }
  1347. std::printf (" %d FL effect presets, %d read\n", fxPresets, fxDecoded);
  1348. CHECK (fxDecoded == fxPresets);
  1349. CHECK (wrappedParsed == wrapped);
  1350. std::printf (" %d plugins in Fruity Wrapper, %d read\n", wrapped, wrappedParsed);
  1351. std::printf (" %d markers, %d time signature changes, %d tracks with EQ\n", markers, signatures, trackEqs);
  1352. std::printf (" %d parametric EQs (%d with FL settings), %d reverbs (%d without dry)\n", peqSlots, peqShaped, reverbs, reverbsDryless);
  1353. std::printf (" DirectWave: %d channels, %d zones; FPC: %d projects, %d pad channels, %d pad notes\n", dwChannels, dwZones, fpcKits,
  1354. padChannels, padNotes);
  1355. CHECK (dwZones > 1000 && padChannels > 250 && padNotes > 500);
  1356. std::printf (" sliced channels (Slicer/Slicex): %d; embedded WAVs saved: %d\n", slicedChannels, embeddedSaved);
  1357. CHECK (slicedChannels >= 25 && embeddedSaved >= 10); // without decoding Ogg here, some loops have no duration
  1358. std::printf (" FL Keys (Grand Piano, 30 zones): %d channels\n", flKeysChannels);
  1359. CHECK (flKeysChannels >= 8);
  1360. CHECK (peqSlots > 1000 && peqShaped > 900 && reverbsDryless > 20 && reverbsLowCut > 250);
  1361. CHECK (markers > 300 && signatures > 60);
  1362. std::printf (" %d 3x Osc channels, %d decoded\n", threeOsc, threeOscDecoded);
  1363. std::printf (" %d .flp files read, %d with notes, %d with playlist, %d automations (%d with target), %d sends\n",
  1364. files, withNotes, withPlaylist, automations, automationsWithTarget, sends);
  1365. CHECK (files > 0);
  1366. CHECK (automations > 0 && sends > 0);
  1367. }
  1368. // ---------------------------------------------------------------------------
  1369. // Sequencer
  1370. TEST (pattern_toggle_step_and_length)
  1371. {
  1372. lynx::Pattern p;
  1373. CHECK (! p.hasStep (0, 4));
  1374. p.toggleStep (0, 4);
  1375. CHECK (p.hasStep (0, 4));
  1376. CHECK (p.notes.size() == 1 && p.notes[0].start == 4 * lynx::ticksPerStep);
  1377. CHECK (p.effectiveLength (4) == 4 * lynx::ppq); // one bar
  1378. p.toggleStep (1, 20); // second bar
  1379. CHECK (p.effectiveLength (4) == 8 * lynx::ppq);
  1380. p.toggleStep (0, 4);
  1381. CHECK (! p.hasStep (0, 4) && p.notes.size() == 1);
  1382. }
  1383. TEST (scheduler_places_events_at_exact_samples)
  1384. {
  1385. lynx::Pattern p;
  1386. p.toggleStep (0, 0);
  1387. p.toggleStep (0, 4); // tick 960 = 1 beat
  1388. const double sr = 48000.0, bpm = 120.0; // 1 beat = 0.5 s = 24000 samples
  1389. const auto tps = lynx::ticksPerSample (bpm, sr);
  1390. lynx::EventBuffer ev;
  1391. lynx::schedulePatternLoop (p, p.effectiveLength (4), 23900.0 * tps, 512, tps, ev);
  1392. // the beat-2 note starts at sample 24000 -> offset 100 in this block
  1393. int ons = 0;
  1394. for (auto& e : ev)
  1395. if (e.type == lynx::NoteEvent::Type::on)
  1396. {
  1397. ++ons;
  1398. CHECK (e.sampleOffset == 100);
  1399. }
  1400. CHECK (ons == 1);
  1401. }
  1402. TEST (scheduler_wraps_the_loop)
  1403. {
  1404. lynx::Pattern p;
  1405. p.toggleStep (2, 0);
  1406. const auto len = p.effectiveLength (4); // 3840 ticks
  1407. const double sr = 48000.0;
  1408. const auto tps = lynx::ticksPerSample (120.0, sr);
  1409. lynx::EventBuffer ev;
  1410. // block that crosses the loop end: starts 10 samples before
  1411. const auto start = (double) len - 10.0 * tps;
  1412. lynx::schedulePatternLoop (p, len, start, 64, tps, ev);
  1413. bool found = false;
  1414. for (auto& e : ev)
  1415. if (e.type == lynx::NoteEvent::Type::on && e.channel == 2)
  1416. {
  1417. found = true;
  1418. CHECK (e.sampleOffset == 10);
  1419. }
  1420. CHECK (found);
  1421. }
  1422. TEST (scheduler_off_before_on_at_same_sample)
  1423. {
  1424. lynx::Pattern p;
  1425. lynx::Note a;
  1426. a.start = 0; a.length = 240; a.channel = 0;
  1427. lynx::Note b = a;
  1428. b.start = 240;
  1429. p.notes = { a, b };
  1430. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  1431. lynx::EventBuffer ev;
  1432. lynx::schedulePatternLoop (p, p.effectiveLength (4), 200.0, 4000, tps, ev);
  1433. CHECK (ev.size() >= 2);
  1434. CHECK (ev[0].type == lynx::NoteEvent::Type::off);
  1435. CHECK (ev[1].type == lynx::NoteEvent::Type::on);
  1436. CHECK (ev[0].sampleOffset == ev[1].sampleOffset);
  1437. }
  1438. TEST (snapshot_exchange_hands_over_and_recycles)
  1439. {
  1440. struct Counted
  1441. {
  1442. int value;
  1443. int* alive;
  1444. Counted (int v, int* a) : value (v), alive (a) { ++*alive; }
  1445. ~Counted() { --*alive; }
  1446. };
  1447. int alive = 0;
  1448. {
  1449. lynx::SnapshotExchange<Counted> x;
  1450. CHECK (x.acquire() == nullptr);
  1451. x.publish (std::make_unique<Counted> (1, &alive));
  1452. CHECK (x.acquire()->value == 1);
  1453. x.publish (std::make_unique<Counted> (2, &alive));
  1454. x.publish (std::make_unique<Counted> (3, &alive)); // 2 was never read: freed immediately
  1455. CHECK (alive == 2);
  1456. CHECK (x.acquire()->value == 3);
  1457. CHECK (alive == 2); // 1 was returned, but only the UI frees it
  1458. x.collectGarbage();
  1459. CHECK (alive == 1);
  1460. // without collection, the return slots fill up and the audio side holds on to the current one
  1461. for (int i = 0; i < 20; ++i)
  1462. {
  1463. x.publish (std::make_unique<Counted> (10 + i, &alive));
  1464. CHECK (x.acquire() != nullptr);
  1465. }
  1466. }
  1467. CHECK (alive == 0);
  1468. }
  1469. TEST (rack_renderer_makes_sound_and_reuses_instruments)
  1470. {
  1471. auto song = lynx::Song::makeDefault();
  1472. song.bpm = 120.0;
  1473. const double sr = 48000.0;
  1474. auto state = lynx::RackState::build (song, nullptr, sr);
  1475. lynx::RackRenderer r;
  1476. r.prepare (sr);
  1477. std::vector<float> l (512), rr (512);
  1478. double tick = 0.0;
  1479. float peak = 0.0f;
  1480. int kicks = 0;
  1481. for (int block = 0; block < 93; ++block) // 47616 samples: just before 1 s
  1482. {
  1483. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  1484. for (auto& e : r.lastEvents())
  1485. if (e.type == lynx::NoteEvent::Type::on && e.channel == 0)
  1486. ++kicks;
  1487. for (int i = 0; i < 512; ++i)
  1488. {
  1489. CHECK (std::isfinite (l[(std::size_t) i]));
  1490. peak = std::max (peak, std::abs (l[(std::size_t) i]));
  1491. }
  1492. tick += 512 * lynx::ticksPerSample (song.bpm, sr);
  1493. }
  1494. CHECK (peak > 0.1f && peak < 4.0f);
  1495. CHECK (kicks == 2); // 120 BPM: beats at 0 and 0.5 s
  1496. // editing the song keeps the instruments of channels whose type didn't change
  1497. song.channels[4].instrument = lynx::InstrumentKind::kick;
  1498. auto next = lynx::RackState::build (song, state.get(), sr);
  1499. CHECK (next->instruments[0] == state->instruments[0]);
  1500. CHECK (next->instruments[4] != state->instruments[4]);
  1501. // stopping silences the synth and triggers no new notes
  1502. r.process (next.get(), false, tick, 512, l.data(), rr.data());
  1503. CHECK (r.lastEvents().size() == 0);
  1504. }
  1505. TEST (flp_import_maps_channels_and_rescales)
  1506. {
  1507. flp::Project p;
  1508. p.header.ppq = 96;
  1509. p.tempo = 150.0;
  1510. p.channels = { { 0, flp::ChannelType::sampler, "Kick 808", "", "", 1 },
  1511. { 1, flp::ChannelType::audioClip, "Vocal", "", "", 2 },
  1512. { 2, flp::ChannelType::instrument, "Lead", "FLEX", "", 3 } };
  1513. flp::Pattern pat;
  1514. pat.index = 1;
  1515. flp::Note n;
  1516. n.position = 96;
  1517. n.length = 0;
  1518. n.channel = 2;
  1519. n.key = 72;
  1520. n.velocity = 64;
  1521. pat.notes.push_back (n);
  1522. p.patterns.push_back (pat);
  1523. const auto s = lynx::importFlp (p);
  1524. CHECK (s.bpm == 150.0);
  1525. CHECK (s.channels.size() == 3); // audio clip channels stay in the rack, as in FL
  1526. CHECK (s.channels[0].instrument == lynx::InstrumentKind::kick);
  1527. CHECK (s.channels[1].instrument == lynx::InstrumentKind::audioClip);
  1528. CHECK (s.channels[2].instrument == lynx::InstrumentKind::synth);
  1529. CHECK (s.patterns.size() == 1);
  1530. CHECK (s.patterns[0].notes[0].start == lynx::ppq); // 96 @ PPQ 96 = 1 beat
  1531. CHECK (s.patterns[0].notes[0].channel == 2);
  1532. CHECK (s.patterns[0].notes[0].length == lynx::ticksPerStep); // step note
  1533. CHECK (std::abs (s.patterns[0].notes[0].velocity - 0.5f) < 1e-6f);
  1534. }
  1535. TEST (live_queue_is_fifo_and_bounded)
  1536. {
  1537. lynx::LiveEventQueue q;
  1538. lynx::NoteEvent e;
  1539. CHECK (! q.pop (e));
  1540. for (int i = 0; i < 10; ++i)
  1541. {
  1542. lynx::NoteEvent in;
  1543. in.key = i;
  1544. CHECK (q.push (in));
  1545. }
  1546. for (int i = 0; i < 10; ++i)
  1547. CHECK (q.pop (e) && e.key == i);
  1548. int pushed = 0;
  1549. while (q.push (e))
  1550. ++pushed;
  1551. CHECK (pushed == (int) lynx::LiveEventQueue::capacity - 1); // one slot stays free to tell full from empty
  1552. }
  1553. TEST (sampler_plays_pitched_one_shot)
  1554. {
  1555. // 1000-frame ramp sample: the position can be measured from the amplitude
  1556. auto data = std::make_shared<lynx::SampleData>();
  1557. data->sampleRate = 48000.0;
  1558. for (int i = 0; i < 1000; ++i)
  1559. data->left.push_back (1.0f);
  1560. auto sampler = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  1561. sampler->prepare (48000.0);
  1562. std::vector<float> l (2048, 0.0f), r (2048, 0.0f);
  1563. sampler->noteOn (60, 1.0f);
  1564. sampler->noteOff (60); // one-shot: noteOff doesn't cut
  1565. sampler->render (l.data(), r.data(), 2048, 1.0f, 1.0f);
  1566. int sounding = 0;
  1567. for (auto s : l)
  1568. sounding += s > 0.5f;
  1569. CHECK (sounding >= 995 && sounding <= 1000); // plays the whole sample at the original pitch
  1570. std::fill (l.begin(), l.end(), 0.0f);
  1571. sampler->noteOn (72, 1.0f); // one octave up: half the duration
  1572. sampler->render (l.data(), r.data(), 2048, 1.0f, 1.0f);
  1573. sounding = 0;
  1574. for (auto s : l)
  1575. sounding += s > 0.5f;
  1576. CHECK (sounding >= 495 && sounding <= 500);
  1577. CHECK (r[10] > 0.5f); // mono goes to both sides
  1578. auto silent = lynx::makeInstrument (lynx::InstrumentKind::sampler, nullptr);
  1579. silent->prepare (48000.0);
  1580. silent->noteOn (60, 1.0f);
  1581. std::fill (l.begin(), l.end(), 0.0f);
  1582. silent->render (l.data(), r.data(), 64, 1.0f, 1.0f);
  1583. CHECK (l[0] == 0.0f);
  1584. }
  1585. TEST (rack_live_notes_and_sample_provider)
  1586. {
  1587. lynx::Song song;
  1588. lynx::ChannelDef c;
  1589. c.name = "Smp";
  1590. c.instrument = lynx::InstrumentKind::sampler;
  1591. c.samplePath = "a.wav";
  1592. song.channels.push_back (c);
  1593. song.patterns.emplace_back();
  1594. int loads = 0;
  1595. auto provider = [&] (const std::string& path) -> std::shared_ptr<const lynx::SampleData> {
  1596. ++loads;
  1597. CHECK (path == "a.wav");
  1598. auto d = std::make_shared<lynx::SampleData>();
  1599. d->left.assign (4800, 0.5f);
  1600. return d;
  1601. };
  1602. auto state = lynx::RackState::build (song, nullptr, 48000.0, provider);
  1603. CHECK (loads == 1);
  1604. lynx::RackRenderer renderer;
  1605. renderer.prepare (48000.0);
  1606. lynx::LiveEventQueue live;
  1607. lynx::NoteEvent on;
  1608. on.channel = 0;
  1609. on.velocity = 1.0f;
  1610. live.push (on);
  1611. std::vector<float> l (256), r (256);
  1612. renderer.process (state.get(), false, 0.0, 256, l.data(), r.data(), &live); // stopped, but the live note plays
  1613. CHECK (l[0] > 0.1f);
  1614. // same sample: reused; different sample: reloaded
  1615. auto same = lynx::RackState::build (song, state.get(), 48000.0, provider);
  1616. CHECK (loads == 1 && same->instruments[0] == state->instruments[0]);
  1617. song.channels[0].samplePath = "b.wav";
  1618. auto other = lynx::RackState::build (song, state.get(), 48000.0, [&] (const std::string&) { ++loads; return nullptr; });
  1619. CHECK (loads == 2 && other->instruments[0] != state->instruments[0]);
  1620. }
  1621. TEST (flp_paths_resolve_and_samplers_import)
  1622. {
  1623. lynx::FlPathRoots roots { "C:\\FL", "C:\\FL\\Data", "D:\\User" };
  1624. CHECK (lynx::resolveFlPath ("%FLStudioFactoryData%\\Data\\x.wav", roots) == "C:\\FL\\Data\\x.wav");
  1625. CHECK (lynx::resolveFlPath ("%FLStudioData%\\Patches\\y.wav", roots) == "C:\\FL\\Data\\Patches\\y.wav");
  1626. CHECK (lynx::resolveFlPath ("%FLStudioUserData%\\z.wav", roots) == "D:\\User\\z.wav");
  1627. CHECK (lynx::resolveFlPath ("E:\\abs.wav", roots) == "E:\\abs.wav");
  1628. CHECK (lynx::resolveFlPath ("%FLStudioUserData%\\z.wav", {}) == "");
  1629. flp::Project p;
  1630. p.channels = { { 0, flp::ChannelType::sampler, "Kick", "", "%FLStudioData%\\k.wav", 1 },
  1631. { 1, flp::ChannelType::sampler, "Hat", "", "%FLStudioData%\\missing.wav", 1 } };
  1632. lynx::FlpImportOptions options;
  1633. options.roots = roots;
  1634. options.fileExists = [] (const std::string& path) { return path == "C:\\FL\\Data\\k.wav"; };
  1635. const auto s = lynx::importFlp (p, options);
  1636. CHECK (s.channels[0].instrument == lynx::InstrumentKind::sampler);
  1637. CHECK (s.channels[0].samplePath == "C:\\FL\\Data\\k.wav");
  1638. CHECK (s.channels[1].instrument == lynx::InstrumentKind::hat); // no file: built-in instrument
  1639. }
  1640. TEST (soft_clip_is_transparent_below_knee_and_bounded)
  1641. {
  1642. float s[] = { 0.5f, -0.89f, 1.5f, -3.0f, 0.95f };
  1643. lynx::softClip (s, 5);
  1644. CHECK (s[0] == 0.5f && s[1] == -0.89f);
  1645. CHECK (s[2] > 0.9f && s[2] <= 1.0f);
  1646. CHECK (s[3] < -0.9f && s[3] >= -1.0f);
  1647. CHECK (s[4] > 0.9f && s[4] < 0.95f);
  1648. }
  1649. TEST (song_scheduler_plays_clips_with_offset_and_cut)
  1650. {
  1651. lynx::Song s;
  1652. s.channels.resize (1);
  1653. auto& p = s.patterns.emplace_back();
  1654. for (int step : { 0, 4, 8, 12 }) // one note per beat
  1655. p.toggleStep (0, step);
  1656. // clip at bar 2 playing only the second half of the pattern (beats 3 and 4)
  1657. lynx::Clip c;
  1658. c.pattern = 0;
  1659. c.start = 4 * lynx::ppq;
  1660. c.length = 2 * lynx::ppq;
  1661. c.offset = 2 * lynx::ppq;
  1662. s.playlist.push_back (c);
  1663. CHECK (s.songLength() == 8 * lynx::ppq);
  1664. const double sr = 48000.0;
  1665. const auto tps = lynx::ticksPerSample (120.0, sr); // 1 beat = 24000 samples
  1666. lynx::EventBuffer ev;
  1667. // whole song in a single block (8 beats = 192000 samples)
  1668. lynx::scheduleSong (s, 0.0, 192000, tps, ev);
  1669. std::vector<int> ons;
  1670. for (auto& e : ev)
  1671. if (e.type == lynx::NoteEvent::Type::on)
  1672. ons.push_back (e.sampleOffset);
  1673. CHECK (ons.size() == 2);
  1674. CHECK (ons.size() == 2 && ons[0] == 4 * 24000 && ons[1] == 5 * 24000);
  1675. // crossing the loop: bar 1 is empty, so nothing at the start of the second pass
  1676. ev.clear();
  1677. lynx::scheduleSong (s, 8.0 * lynx::ppq - 100 * tps, 200, tps, ev);
  1678. CHECK (ev.size() == 0);
  1679. // a note longer than the clip is cut at the clip end
  1680. p.notes[3].length = 4 * lynx::ppq;
  1681. ev.clear();
  1682. lynx::scheduleSong (s, 0.0, 192000, tps, ev);
  1683. int lastOff = -1;
  1684. for (auto& e : ev)
  1685. if (e.type == lynx::NoteEvent::Type::off)
  1686. lastOff = std::max (lastOff, e.sampleOffset);
  1687. CHECK (lastOff == 6 * 24000);
  1688. }
  1689. TEST (remove_pattern_fixes_clips)
  1690. {
  1691. lynx::Song s;
  1692. s.patterns.resize (3);
  1693. s.currentPattern = 2;
  1694. s.playlist = { { 0, 0, 0, 100, 0 }, { 1, 0, 100, 100, 0 }, { 2, 1, 0, 100, 0 } };
  1695. s.removePattern (1);
  1696. CHECK (s.patterns.size() == 2);
  1697. CHECK (s.playlist.size() == 2 && s.playlist[1].pattern == 1);
  1698. CHECK (s.currentPattern == 1);
  1699. }
  1700. TEST (flp_import_3x_osc_state_and_channel_filter)
  1701. {
  1702. // new 3x Osc patch (version 14): osc 2 mix 64 coarse -12, osc 3 mix 32 coarse -24
  1703. std::vector<std::uint8_t> blob (460, 0);
  1704. auto put = [&] (std::size_t off, std::int32_t v) {
  1705. for (int b = 0; b < 4; ++b)
  1706. blob[off + (std::size_t) b] = (std::uint8_t) ((std::uint32_t) v >> (8 * b));
  1707. };
  1708. put (0x00, 14);
  1709. put (0x08, 3); // osc 1 saw
  1710. put (0x10, 7); // osc 1 fine +7
  1711. put (0x04, -32); // osc 1 pan -0.5
  1712. put (0x1C, 64); // osc 2 mix
  1713. put (0x28, -12); // osc 2 coarse
  1714. put (0x38, 32); // osc 3 mix
  1715. put (0x40, 2); // osc 3 square
  1716. put (0x44, -19); // osc 3 coarse: -1 octave and -7 semitones
  1717. lynx::SynthSettings s;
  1718. CHECK (lynx::synthFrom3xOsc (blob, s));
  1719. CHECK (std::abs (s.osc[0].level - 0.375f) < 1e-4f && std::abs (s.osc[1].level - 0.375f) < 1e-4f && std::abs (s.osc[2].level - 0.25f) < 1e-4f);
  1720. CHECK (s.osc[0].wave == lynx::Waveform::saw && s.osc[0].detune == 7.0f && s.osc[0].pan == -0.5f);
  1721. CHECK (s.osc[1].wave == lynx::Waveform::sine && s.osc[1].octave == -1 && s.osc[1].semitones == 0);
  1722. CHECK (s.osc[2].wave == lynx::Waveform::square && s.osc[2].octave == -1 && s.osc[2].semitones == -7);
  1723. CHECK (! lynx::synthFrom3xOsc (std::vector<std::uint8_t> (40, 0), s));
  1724. // channel filter: open by default; LP with Mod X 128 ~ 2.71 kHz; Fast LP with Mod X 128 ~ 280 Hz
  1725. float hz = 0.0f, res = 1.0f;
  1726. int mode = -1;
  1727. lynx::synthFilterFromChannel (256, 0, 0, hz, res, mode);
  1728. CHECK (hz >= 19999.0f && res == 0.0f);
  1729. lynx::synthFilterFromChannel (128, 0, 1, hz, res, mode);
  1730. CHECK (std::abs (hz - 2710.0f) < 30.0f && res == 0.0f);
  1731. lynx::synthFilterFromChannel (128, 0, 0, hz, res, mode);
  1732. CHECK (hz > 240.0f && hz < 320.0f);
  1733. lynx::synthFilterFromChannel (128, 256, 1, hz, res, mode);
  1734. CHECK (res > 0.8f);
  1735. CHECK (mode == 0);
  1736. lynx::synthFilterFromChannel (64, 0, 3, hz, res, mode); // high-pass at ~840 Hz
  1737. CHECK (mode == 2 && std::abs (hz - 840.0f) < 40.0f);
  1738. lynx::synthFilterFromChannel (128, 0, 2, hz, res, mode); // band-pass
  1739. CHECK (mode == 1);
  1740. }
  1741. TEST (synth_pitch_and_filter_envelopes)
  1742. {
  1743. auto render = [] (const lynx::SynthSettings& s, int frames) {
  1744. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  1745. inst->prepare (48000.0);
  1746. lynx::ChannelDef c;
  1747. c.synth = s;
  1748. inst->configure (c, 120.0);
  1749. inst->noteOn (45, 1.0f); // A2 = 110 Hz
  1750. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  1751. inst->render (l.data(), r.data(), frames, 1.0f, 1.0f);
  1752. return l;
  1753. };
  1754. auto crossings = [] (const std::vector<float>& b, int from, int to) {
  1755. int n = 0;
  1756. for (int i = from + 1; i < to; ++i)
  1757. n += (b[(std::size_t) i - 1] < 0.0f) != (b[(std::size_t) i] < 0.0f);
  1758. return n;
  1759. };
  1760. // 3x Osc "kick": sine with a +24 st pitch envelope falling fast
  1761. lynx::SynthSettings kick;
  1762. kick.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  1763. kick.cutoff = 20000.0f;
  1764. kick.pitchEnv = { 24.0f, 0.0f, 0.0f, 0.05f, 0.0f, 0.05f };
  1765. const auto k = render (kick, 48000);
  1766. const auto early = crossings (k, 0, 2400); // first 50 ms: well above 110 Hz
  1767. const auto late = crossings (k, 24000, 48000); // then back to 110 Hz (~110 crossings in 0.5 s)
  1768. CHECK (early > 20); // +24 st ramp over 50 ms: ~2.2x the average frequency (11 crossings without envelope)
  1769. CHECK (std::abs (late - 110) < 4);
  1770. // cutoff envelope: saw closed at 200 Hz opens +5 octaves on attack and closes again
  1771. lynx::SynthSettings pluck;
  1772. pluck.cutoff = 200.0f;
  1773. pluck.filterEnv = { 5.0f, 0.0f, 0.0f, 0.1f, 0.0f, 0.1f };
  1774. const auto p = render (pluck, 48000);
  1775. auto hf = [&] (int from, int to) { // energy of the difference (highs)
  1776. double e = 0.0;
  1777. for (int i = from + 1; i < to; ++i)
  1778. e += std::pow ((double) p[(std::size_t) i] - p[(std::size_t) i - 1], 2.0);
  1779. return e;
  1780. };
  1781. CHECK (hf (0, 2400) > 4.0 * hf (40000, 42400));
  1782. // Toxic Biohazard's envelope (REA_rodada33 §2): exponential towards 5 clipped at 1, so the cutoff is still near
  1783. // its base early in the attack, fully open at A = 0.2 s and back down after the exponential decay
  1784. lynx::SynthSettings toxic = pluck;
  1785. toxic.filterEnv = { 5.0f, 0.2f, 0.0f, 0.1f, 0.0f, 0.1f, 1 };
  1786. const auto t = render (toxic, 48000);
  1787. auto thf = [&] (int from, int to) {
  1788. double e = 0.0;
  1789. for (int i = from + 1; i < to; ++i)
  1790. e += std::pow ((double) t[(std::size_t) i] - t[(std::size_t) i - 1], 2.0);
  1791. return e;
  1792. };
  1793. CHECK (thf (9000, 9600) > 4.0 * thf (300, 900));
  1794. CHECK (thf (9000, 9600) > 4.0 * thf (40000, 40600));
  1795. }
  1796. TEST (synth_mono_reuses_the_sounding_voice)
  1797. {
  1798. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  1799. inst->prepare (48000.0);
  1800. lynx::ChannelDef c;
  1801. c.synth.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  1802. c.synth.cutoff = 20000.0f;
  1803. c.synth.mono = true;
  1804. inst->configure (c, 120.0);
  1805. std::vector<float> l (48000), r (48000);
  1806. inst->noteOn (57, 1.0f);
  1807. inst->render (l.data(), r.data(), 4800, 1.0f, 1.0f);
  1808. inst->noteOn (69, 1.0f); // A4 takes over the A3 voice: only one note sounding
  1809. inst->render (l.data() + 4800, r.data() + 4800, 43200, 1.0f, 1.0f);
  1810. int crossings = 0;
  1811. float peak = 0.0f;
  1812. for (std::size_t i = 24001; i < 48000; ++i)
  1813. {
  1814. crossings += (l[i - 1] < 0.0f) != (l[i] < 0.0f);
  1815. peak = std::max (peak, std::abs (l[i]));
  1816. }
  1817. CHECK (std::abs (crossings - 440) < 4); // 0.5 s of 440 Hz, without the A3 underneath
  1818. CHECK (peak < 0.35f); // one voice (0.3 level), not two summed
  1819. // no click on the handover: the jump between neighbouring samples stays sine-sized
  1820. float jump = 0.0f;
  1821. for (std::size_t i = 4790; i < 4810; ++i)
  1822. jump = std::max (jump, std::abs (l[i] - l[i - 1]));
  1823. CHECK (jump < 0.05f);
  1824. }
  1825. TEST (synth_porta_glides_and_am_modulates)
  1826. {
  1827. auto make = [] (const lynx::SynthSettings& s) {
  1828. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  1829. inst->prepare (48000.0);
  1830. lynx::ChannelDef c;
  1831. c.synth = s;
  1832. inst->configure (c, 120.0);
  1833. return inst;
  1834. };
  1835. auto crossings = [] (const std::vector<float>& b, std::size_t from, std::size_t to) {
  1836. int n = 0;
  1837. for (auto i = from + 1; i < to; ++i)
  1838. n += (b[i - 1] < 0.0f) != (b[i] < 0.0f);
  1839. return n;
  1840. };
  1841. // mono + 1-beat porta (0.5 s at 120 BPM): from A3 to A4, halfway ~E4 (329.6 Hz)
  1842. lynx::SynthSettings s;
  1843. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  1844. s.cutoff = 20000.0f;
  1845. s.mono = true;
  1846. s.porta = true;
  1847. s.portaBeats = 1.0f;
  1848. auto inst = make (s);
  1849. std::vector<float> l (96000), r (96000);
  1850. inst->noteOn (57, 1.0f);
  1851. inst->render (l.data(), r.data(), 4800, 1.0f, 1.0f);
  1852. inst->noteOn (69, 1.0f);
  1853. inst->render (l.data() + 4800, r.data() + 4800, 91200, 1.0f, 1.0f);
  1854. const auto middle = crossings (l, 4800 + 12000 - 2400, 4800 + 12000 + 2400); // 0.1 s around 0.25 s
  1855. CHECK (std::abs (middle - 66) < 6); // ~330 Hz * 0.1 s * 2
  1856. CHECK (std::abs (crossings (l, 48000, 96000) - 880) < 4); // reached A4 (1 s = 880 crossings)
  1857. // AM: osc 3 at level 1.0, slow sine, modulates osc 1 (the average level drops, the sum doesn't gain osc 3)
  1858. lynx::SynthSettings am;
  1859. am.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  1860. am.osc[2] = { lynx::Waveform::sine, -3, 0.0f, 1.0f };
  1861. am.cutoff = 20000.0f;
  1862. am.am = true;
  1863. auto modulated = make (am);
  1864. modulated->noteOn (69, 1.0f);
  1865. std::fill (l.begin(), l.end(), 0.0f);
  1866. modulated->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  1867. float peak = 0.0f;
  1868. for (std::size_t i = 4800; i < 48000; ++i)
  1869. peak = std::max (peak, std::abs (l[i]));
  1870. CHECK (peak > 0.45f && peak < 0.65f); // 0.3 · (1 + 1) at most: (1 − o3) goes up to 2
  1871. }
  1872. TEST (channel_lfo_vibrato_and_tremolo)
  1873. {
  1874. auto render = [] (const lynx::SynthSettings& s) {
  1875. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  1876. inst->prepare (48000.0);
  1877. lynx::ChannelDef c;
  1878. c.synth = s;
  1879. inst->configure (c, 120.0);
  1880. inst->noteOn (69, 1.0f);
  1881. std::vector<float> l (48000), r (48000);
  1882. inst->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  1883. return l;
  1884. };
  1885. lynx::SynthSettings s;
  1886. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  1887. s.cutoff = 20000.0f;
  1888. // tremolo: 100% volume LFO at 4 Hz (0.25 s period) -> the amplitude envelope goes from ~0 to ~2x
  1889. auto tremolo = s;
  1890. tremolo.lfo[lynx::lfoVolume] = { 1.0f, 0.25f, false, 0, 0.0f, 0.0f };
  1891. const auto t = render (tremolo);
  1892. float lowest = 1.0f, highest = 0.0f;
  1893. for (std::size_t w = 4800; w + 480 <= 48000; w += 480) // 10 ms windows (4.4 cycles of 440 Hz)
  1894. {
  1895. float peak = 0.0f;
  1896. for (auto i = w; i < w + 480; ++i)
  1897. peak = std::max (peak, std::abs (t[i]));
  1898. lowest = std::min (lowest, peak);
  1899. highest = std::max (highest, peak);
  1900. }
  1901. CHECK (lowest < 0.08f && highest > 0.5f);
  1902. // synced vibrato: ±1 semitone, 1-beat period (0.5 s at 120 BPM); the average stays at 440 Hz
  1903. auto vibrato = s;
  1904. vibrato.lfo[lynx::lfoPitch] = { 1.0f, 1.0f, true, 0, 0.0f, 0.0f };
  1905. const auto v = render (vibrato);
  1906. int crossings = 0;
  1907. for (std::size_t i = 1; i < 48000; ++i)
  1908. crossings += (v[i - 1] < 0.0f) != (v[i] < 0.0f);
  1909. CHECK (std::abs (crossings - 880) < 12);
  1910. int firstQuarter = 0; // first quarter of the cycle: rising sine -> higher than 440
  1911. for (std::size_t i = 1; i < 6000; ++i)
  1912. firstQuarter += (v[i - 1] < 0.0f) != (v[i] < 0.0f);
  1913. CHECK (firstQuarter > 112);
  1914. }
  1915. TEST (sampler_porta_glides_from_previous_note)
  1916. {
  1917. auto data = std::make_shared<lynx::SampleData>();
  1918. data->sampleRate = 48000.0;
  1919. data->left.resize (96000);
  1920. for (std::size_t i = 0; i < data->left.size(); ++i)
  1921. data->left[i] = 0.5f * (float) std::sin (6.283185307 * 220.0 * (double) i / 48000.0);
  1922. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  1923. inst->prepare (48000.0);
  1924. lynx::ChannelDef c;
  1925. c.sampler.cut = true;
  1926. c.sampler.porta = true;
  1927. c.sampler.portaBeats = 1.0f; // 0.5 s at 120 BPM
  1928. inst->configure (c, 120.0);
  1929. std::vector<float> l (24000), r (24000);
  1930. inst->noteOn (60, 1.0f);
  1931. inst->render (l.data(), r.data(), 2400, 1.0f, 1.0f);
  1932. inst->noteOn (72, 1.0f); // one octave up: starts at 220 Hz and rises
  1933. std::fill (l.begin(), l.end(), 0.0f);
  1934. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  1935. auto crossings = [&] (std::size_t from, std::size_t to) {
  1936. int n = 0;
  1937. for (auto i = from + 1; i < to; ++i)
  1938. n += (l[i - 1] < 0.0f) != (l[i] < 0.0f);
  1939. return n;
  1940. };
  1941. const auto start = crossings (600, 2400); // 37.5 ms still near 220 Hz: ~17 crossings (440 Hz would give 33)
  1942. const auto end = crossings (21600, 24000); // 50 ms at the end of the glide: near 440 Hz (~44; 220 Hz would give 22)
  1943. CHECK (start < 22);
  1944. CHECK (end > 36);
  1945. }
  1946. TEST (zoned_sampler_picks_zone_by_key_and_velocity)
  1947. {
  1948. auto sine = [] (double hz, float amp) {
  1949. auto d = std::make_shared<lynx::SampleData>();
  1950. d->sampleRate = 48000.0;
  1951. d->left.resize (48000);
  1952. for (std::size_t i = 0; i < d->left.size(); ++i)
  1953. d->left[i] = amp * (float) std::sin (6.283185307 * hz * (double) i / 48000.0);
  1954. return d;
  1955. };
  1956. // lows: 220 Hz sine recorded as A3 (57), up to key 69; highs: 880 Hz as A5 (81)
  1957. // hard layer on the highs: same tuning, louder
  1958. std::vector<lynx::LoadedZone> zones {
  1959. { { "graves.wav", 57, 0, 69, 0, 127, 0.0f, 1.0f }, sine (220.0, 0.5f) },
  1960. { { "agudos.wav", 81, 70, 127, 0, 99, 0.0f, 1.0f }, sine (880.0, 0.25f) },
  1961. { { "agudos forte.wav", 81, 70, 127, 100, 127, 0.0f, 1.0f }, sine (880.0, 0.9f) },
  1962. };
  1963. auto inst = lynx::makeZonedSampler (zones);
  1964. inst->prepare (48000.0);
  1965. inst->configure (lynx::ChannelDef {}, 120.0);
  1966. auto play = [&] (int key, float velocity) {
  1967. inst->allNotesOff();
  1968. std::vector<float> l (24000), r (24000);
  1969. inst->render (l.data(), r.data(), 2000, 1.0f, 1.0f); // let the old voices die out
  1970. std::fill (l.begin(), l.end(), 0.0f);
  1971. inst->noteOn (key, velocity);
  1972. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  1973. int crossings = 0;
  1974. float peak = 0.0f;
  1975. for (std::size_t i = 1; i < 24000; ++i)
  1976. {
  1977. crossings += (l[i - 1] < 0.0f) != (l[i] < 0.0f);
  1978. peak = std::max (peak, std::abs (l[i]));
  1979. }
  1980. return std::pair { crossings, peak };
  1981. };
  1982. const auto low = play (69, 0.5f); // A4 from root A3: 440 Hz -> 440 crossings in 0.5 s
  1983. CHECK (std::abs (low.first - 440) < 4);
  1984. const auto soft = play (81, 0.5f); // high zone at the root: 880 Hz
  1985. CHECK (std::abs (soft.first - 880) < 6);
  1986. const auto hard = play (81, 0.95f); // high velocity: hard layer
  1987. CHECK (hard.second > soft.second * 2.0f);
  1988. // overlapping layers round-robin: two identical zones at different levels, notes alternate
  1989. auto rr = lynx::makeZonedSampler ({ { { "a.wav", 60 }, sine (440.0, 0.2f) }, { { "b.wav", 60 }, sine (440.0, 0.8f) } });
  1990. rr->prepare (48000.0);
  1991. rr->configure (lynx::ChannelDef {}, 120.0);
  1992. float peaks[2] {};
  1993. for (int k = 0; k < 2; ++k)
  1994. {
  1995. rr->allNotesOff();
  1996. std::vector<float> l (4800), r (4800);
  1997. rr->render (l.data(), r.data(), 2000, 1.0f, 1.0f);
  1998. std::fill (l.begin(), l.end(), 0.0f);
  1999. rr->noteOn (60, 1.0f);
  2000. rr->render (l.data(), r.data(), 4800, 1.0f, 1.0f);
  2001. for (auto v : l)
  2002. peaks[k] = std::max (peaks[k], std::abs (v));
  2003. }
  2004. CHECK (std::abs (peaks[0] - peaks[1]) > 0.3f);
  2005. }
  2006. TEST (zoned_sampler_loops_while_held)
  2007. {
  2008. // 0.1 s sample with a loop in the middle: holding the note it keeps sounding well past the end of the file;
  2009. // on release, it leaves the loop and ends
  2010. auto data = std::make_shared<lynx::SampleData>();
  2011. data->sampleRate = 48000.0;
  2012. data->left.resize (4800);
  2013. for (std::size_t i = 0; i < data->left.size(); ++i)
  2014. data->left[i] = 0.5f * (float) std::sin (6.283185307 * 480.0 * (double) i / 48000.0); // 100 frames per cycle
  2015. lynx::SampleZone zone { "loop.wav", 60 };
  2016. zone.loopStart = 1000;
  2017. zone.loopEnd = 3000;
  2018. zone.loopMode = 2;
  2019. auto inst = lynx::makeZonedSampler ({ { zone, data } });
  2020. inst->prepare (48000.0);
  2021. lynx::ChannelDef c;
  2022. c.sampler.release = 0.01f;
  2023. inst->configure (c, 120.0);
  2024. inst->noteOn (60, 1.0f);
  2025. std::vector<float> l (48000), r (48000);
  2026. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f); // 0.5 s held
  2027. float held = 0.0f;
  2028. for (std::size_t i = 20000; i < 24000; ++i)
  2029. held = std::max (held, std::abs (l[i]));
  2030. CHECK (held > 0.3f);
  2031. inst->noteOff (60);
  2032. inst->render (l.data() + 24000, r.data() + 24000, 24000, 1.0f, 1.0f);
  2033. float after = 0.0f;
  2034. for (std::size_t i = 40000; i < 48000; ++i)
  2035. after = std::max (after, std::abs (l[i]));
  2036. CHECK (after == 0.0f);
  2037. }
  2038. TEST (global_lfo_follows_song_position)
  2039. {
  2040. // global volume LFO (1-beat period): a note mid-cycle starts mid-wave; the
  2041. // same note with a per-note LFO starts at phase 0
  2042. auto first = [] (bool global, double songTicks) {
  2043. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  2044. inst->prepare (48000.0);
  2045. lynx::ChannelDef c;
  2046. c.synth.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  2047. c.synth.cutoff = 20000.0f;
  2048. c.synth.lfo[lynx::lfoVolume] = { 1.0f, 1.0f, true, 2, 0.0f, 0.0f, global }; // pulse: +1 in the first half
  2049. inst->configure (c, 120.0);
  2050. inst->setSongPosition (songTicks);
  2051. inst->noteOn (69, 1.0f);
  2052. std::vector<float> l (4800), r (4800);
  2053. inst->render (l.data(), r.data(), 4800, 1.0f, 1.0f);
  2054. float peak = 0.0f;
  2055. for (std::size_t i = 2400; i < 4800; ++i)
  2056. peak = std::max (peak, std::abs (l[i]));
  2057. return peak;
  2058. };
  2059. // mid-cycle (phase 0.6) the pulse is at −1: volume ~0; per note (phase 0) it is at +1: ~2x
  2060. const auto globalLate = first (true, 0.6 * lynx::ppq);
  2061. const auto perNote = first (false, 0.6 * lynx::ppq);
  2062. CHECK (globalLate < 0.05f);
  2063. CHECK (perNote > 0.4f);
  2064. }
  2065. TEST (sampler_channel_filter_darkens_and_bypasses_when_open)
  2066. {
  2067. // white noise in the sampler: with a 300 Hz cutoff the energy drops a lot; open passes unchanged
  2068. auto data = std::make_shared<lynx::SampleData>();
  2069. data->sampleRate = 48000.0;
  2070. data->left.resize (48000);
  2071. std::uint32_t seed = 7;
  2072. for (auto& v : data->left)
  2073. {
  2074. seed = seed * 1664525u + 1013904223u;
  2075. v = ((float) (seed >> 8) / 16777216.0f - 0.5f);
  2076. }
  2077. data->right = data->left;
  2078. auto energy = [&] (float cutoff) {
  2079. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  2080. inst->prepare (48000.0);
  2081. lynx::ChannelDef c;
  2082. c.sampler.cutoff = cutoff;
  2083. inst->configure (c, 120.0);
  2084. inst->noteOn (60, 1.0f);
  2085. std::vector<float> l (24000), r (24000);
  2086. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  2087. double e = 0.0;
  2088. for (auto v : l)
  2089. e += (double) v * v;
  2090. return e;
  2091. };
  2092. const auto open = energy (20000.0f), dark = energy (300.0f);
  2093. {
  2094. // high-pass at 10 kHz: also removes most of the noise energy, but from the other side
  2095. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  2096. inst->prepare (48000.0);
  2097. lynx::ChannelDef hp;
  2098. hp.sampler.cutoff = 10000.0f;
  2099. hp.sampler.filterType = 2;
  2100. inst->configure (hp, 120.0);
  2101. inst->noteOn (60, 1.0f);
  2102. std::vector<float> l (24000), r (24000);
  2103. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  2104. double e = 0.0, lowE = 0.0;
  2105. float lp = 0.0f;
  2106. for (auto v : l)
  2107. {
  2108. e += (double) v * v;
  2109. lp += 0.01f * (v - lp); // crude low-pass: almost nothing should remain below
  2110. lowE += (double) lp * lp;
  2111. }
  2112. CHECK (e > 10.0 && e < 0.7 * energy (20000.0f));
  2113. CHECK (lowE < e * 0.01);
  2114. }
  2115. CHECK (open > 100.0);
  2116. CHECK (dark < open * 0.05);
  2117. // +12 st pitch envelope with sustain 1: the sample runs at double speed
  2118. // and ends in half the time (1 s of sample -> 0.5 s)
  2119. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  2120. inst->prepare (48000.0);
  2121. lynx::ChannelDef c;
  2122. c.sampler.pitchEnv = { 12.0f, 0.0f, 0.0f, 0.1f, 1.0f, 0.1f };
  2123. inst->configure (c, 120.0);
  2124. inst->noteOn (60, 1.0f);
  2125. std::vector<float> l (48000), r (48000);
  2126. inst->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  2127. float tail = 0.0f, body = 0.0f;
  2128. for (std::size_t i = 20000; i < 23000; ++i)
  2129. body = std::max (body, std::abs (l[i]));
  2130. for (std::size_t i = 25000; i < 48000; ++i)
  2131. tail = std::max (tail, std::abs (l[i]));
  2132. CHECK (body > 0.1f);
  2133. CHECK (tail == 0.0f);
  2134. }
  2135. TEST (synth_oscillator_pan_and_semitones)
  2136. {
  2137. auto render = [] (lynx::SynthSettings s, std::vector<float>& l, std::vector<float>& r) {
  2138. auto synth = lynx::makeInstrument (lynx::InstrumentKind::synth);
  2139. synth->prepare (48000.0);
  2140. lynx::ChannelDef c;
  2141. c.synth = s;
  2142. synth->configure (c, 120.0);
  2143. synth->noteOn (69, 1.0f);
  2144. l.assign (24000, 0.0f);
  2145. r.assign (24000, 0.0f);
  2146. synth->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  2147. };
  2148. lynx::SynthSettings s;
  2149. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f, 7, 1.0f }; // a fifth up, fully right
  2150. s.cutoff = 20000.0f;
  2151. std::vector<float> l, r;
  2152. render (s, l, r);
  2153. float peakL = 0.0f, peakR = 0.0f;
  2154. int crossings = 0;
  2155. for (std::size_t i = 4800; i < 24000; ++i)
  2156. {
  2157. peakL = std::max (peakL, std::abs (l[i]));
  2158. peakR = std::max (peakR, std::abs (r[i]));
  2159. crossings += (r[i - 1] < 0.0f) != (r[i] < 0.0f);
  2160. }
  2161. CHECK (peakL < 1e-4f && peakR > 0.1f);
  2162. // 440 * 2^(7/12) = 659.3 Hz; 0.4 s = 263.7 cycles = ~527 crossings
  2163. CHECK (std::abs (crossings - 527) < 6);
  2164. }
  2165. TEST (fl_wrapper_state_parses_records_and_vst3_state)
  2166. {
  2167. // Fruity Wrapper blob (version 12): VST3 generator type, class ID, name, path and state
  2168. std::vector<std::uint8_t> blob;
  2169. auto u32 = [] (std::vector<std::uint8_t>& b, std::uint32_t v) { for (int i = 0; i < 4; ++i) b.push_back ((std::uint8_t) (v >> (8 * i))); };
  2170. auto record = [&] (std::vector<std::uint8_t>& b, std::uint32_t id, const std::vector<std::uint8_t>& payload) {
  2171. u32 (b, id);
  2172. u32 (b, (std::uint32_t) payload.size());
  2173. u32 (b, 0);
  2174. b.insert (b.end(), payload.begin(), payload.end());
  2175. };
  2176. auto bytes = [] (const std::string& s) { return std::vector<std::uint8_t> (s.begin(), s.end()); };
  2177. std::vector<std::uint8_t> vst3State;
  2178. u32 (vst3State, 1);
  2179. record (vst3State, 1, std::vector<std::uint8_t> (64, 0));
  2180. record (vst3State, 3, bytes ("COMPONENTE"));
  2181. record (vst3State, 2, bytes ("CONTROLADOR"));
  2182. // record 4: 3 slots → ParamIDs 700, −1 (empty), 0xFFFFFF01
  2183. std::vector<std::uint8_t> slots;
  2184. for (auto v : { 3u, 700u, 0xFFFFFFFFu, 0xFFFFFF01u })
  2185. u32 (slots, v);
  2186. record (vst3State, 4, slots);
  2187. u32 (blob, 12);
  2188. record (blob, 0x01, std::vector<std::uint8_t> (20, 0xFF));
  2189. record (blob, 0x32, { 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });
  2190. std::vector<std::uint8_t> cid;
  2191. for (int i = 0; i < 16; ++i)
  2192. cid.push_back ((std::uint8_t) (0xA0 + i));
  2193. record (blob, 0x34, cid);
  2194. record (blob, 0x36, bytes ("Surge XT"));
  2195. record (blob, 0x37, bytes ("C:/Program Files/Common Files/VST3/Surge XT.vst3"));
  2196. record (blob, 0x35, vst3State);
  2197. lynx::ForeignPlugin p;
  2198. CHECK (lynx::parseFlWrapper (blob, p));
  2199. CHECK (p.format == lynx::ForeignPlugin::Format::vst3);
  2200. CHECK (p.hasClassId && p.classId[0] == 0xA0 && p.classId[15] == 0xAF);
  2201. CHECK (p.name == "Surge XT" && p.path.find ("Surge XT.vst3") != std::string::npos);
  2202. std::vector<std::uint8_t> component, controller;
  2203. CHECK (lynx::splitFlVst3State (p.state, component, controller));
  2204. CHECK (component == bytes ("COMPONENTE") && controller == bytes ("CONTROLADOR"));
  2205. const auto saved = lynx::flVst3ParamSlots (p.state);
  2206. CHECK (saved == (std::vector<std::int32_t> { 700, -1, (std::int32_t) 0xFFFFFF01u }));
  2207. // FL's slot assignment: saved slots keep their ParamID wherever it now sits; the empty slot stays empty;
  2208. // a vanished ParamID (0xFFFFFF01) leaves its slot dead; parameters without a slot get slots 3, 4… in list order
  2209. const auto positions = lynx::flVst3SlotPositions (saved, { 5u, 700u, 9u });
  2210. CHECK (positions == (std::vector<int> { 1, -1, -1, 0, 2 }));
  2211. CHECK (lynx::flVst3SlotPositions ({}, { 5u, 6u }) == (std::vector<int> { 0, 1 })); // new instance: slot = position
  2212. // version out of range or no type: not a usable wrapper
  2213. blob[0] = 13;
  2214. CHECK (! lynx::parseFlWrapper (blob, p));
  2215. CHECK (! lynx::parseFlWrapper ({ 12, 0, 0, 0 }, p));
  2216. }
  2217. TEST (schedule_index_matches_full_scan)
  2218. {
  2219. // random song (long notes, swing, clips with offset); indexed scheduling must yield
  2220. // exactly the same events as the full scan, including in the block that wraps around
  2221. lynx::Song s = lynx::Song::makeDefault();
  2222. s.swing = 0.6f;
  2223. std::uint32_t seed = 12345;
  2224. auto rnd = [&] (int n) { seed = seed * 1664525u + 1013904223u; return (int) ((seed >> 8) % (std::uint32_t) n); };
  2225. s.patterns.resize (3);
  2226. for (auto& p : s.patterns)
  2227. {
  2228. p.notes.clear();
  2229. for (int i = 0; i < 60; ++i)
  2230. {
  2231. lynx::Note n;
  2232. n.start = rnd (16 * lynx::ppq);
  2233. n.length = rnd (5) == 0 ? rnd (12 * lynx::ppq) + 1 : rnd (lynx::ppq) + 1;
  2234. n.channel = rnd (4);
  2235. n.key = 40 + rnd (40);
  2236. n.slide = rnd (20) == 0;
  2237. p.notes.push_back (n);
  2238. }
  2239. p.sortNotes();
  2240. }
  2241. s.playlist.clear();
  2242. for (int i = 0; i < 12; ++i)
  2243. {
  2244. lynx::Clip c;
  2245. c.pattern = rnd (3);
  2246. c.track = rnd (4);
  2247. c.start = rnd (40) * lynx::ppq;
  2248. c.length = (rnd (12) + 1) * lynx::ppq;
  2249. c.offset = rnd (4) * lynx::ppq;
  2250. s.playlist.push_back (c);
  2251. }
  2252. s.mode = lynx::PlayMode::song;
  2253. const auto index = lynx::makeScheduleIndex (s);
  2254. const auto tps = lynx::ticksPerSample (140.0, 48000.0);
  2255. const auto loop = (double) s.songLength();
  2256. int mismatches = 0, events = 0;
  2257. for (int block = 0; block < 400; ++block)
  2258. {
  2259. const auto start = block == 0 ? loop - 100.0 * tps : (double) rnd ((int) loop * 2);
  2260. const auto samples = 64 + rnd (24000); // up to ~1 beat per block
  2261. lynx::EventBuffer a, b;
  2262. lynx::scheduleSong (s, start, samples, tps, a, false, nullptr);
  2263. lynx::scheduleSong (s, start, samples, tps, b, false, &index);
  2264. events += a.size();
  2265. if (a.size() != b.size())
  2266. {
  2267. ++mismatches;
  2268. continue;
  2269. }
  2270. for (int i = 0; i < a.size(); ++i)
  2271. {
  2272. const auto& x = *(a.begin() + i);
  2273. const auto& y = *(b.begin() + i);
  2274. mismatches += x.sampleOffset != y.sampleOffset || x.type != y.type || x.key != y.key || x.channel != y.channel;
  2275. }
  2276. }
  2277. CHECK (events > 500);
  2278. CHECK (mismatches == 0);
  2279. }
  2280. TEST (mixer_track_eq_defaults_and_boost)
  2281. {
  2282. // FL defaults: 90 Hz, 1.5 kHz and 8 kHz; peak Q 0.632; shelf slope 0.607
  2283. lynx::TrackEq eq;
  2284. CHECK (std::abs (lynx::TrackEq::peakQ (eq.width[1]) - 0.632) < 0.01);
  2285. CHECK (std::abs (lynx::TrackEq::shelfSlope (eq.width[0]) - 0.607) < 0.01);
  2286. CHECK (! eq.active());
  2287. // +12 dB peak at 1.5 kHz on a track: a 1.5 kHz sine rises ~4x
  2288. lynx::Song song = lynx::Song::makeDefault();
  2289. song.mixer[1].eq.gainDb[1] = 12.0f;
  2290. for (auto& c : song.channels)
  2291. c.mixerTrack = 1;
  2292. song.channels[4].instrument = lynx::InstrumentKind::synth;
  2293. song.channels[4].synth = {};
  2294. song.channels[4].synth.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  2295. song.channels[4].synth.cutoff = 20000.0f;
  2296. auto render = [] (const lynx::Song& s) {
  2297. auto state = lynx::RackState::build (s, nullptr, 48000.0);
  2298. lynx::RackRenderer renderer;
  2299. renderer.prepare (48000.0);
  2300. lynx::LiveEventQueue live;
  2301. lynx::NoteEvent on; // 1.5 kHz ~ key 90.6: use 91 (1568 Hz), still within the wide peak
  2302. on.channel = 4;
  2303. on.key = 91;
  2304. on.velocity = 1.0f;
  2305. live.push (on);
  2306. std::vector<float> l (24000), r (24000);
  2307. for (int pos = 0; pos < 24000; pos += 480)
  2308. renderer.process (state.get(), false, 0.0, 480, l.data() + pos, r.data() + pos, pos == 0 ? &live : nullptr);
  2309. float peak = 0.0f;
  2310. for (std::size_t i = 12000; i < 24000; ++i)
  2311. peak = std::max (peak, std::abs (l[i]));
  2312. return peak;
  2313. };
  2314. const auto boosted = render (song);
  2315. song.mixer[1].eq.gainDb[1] = 0.0f;
  2316. const auto flat = render (song);
  2317. CHECK (flat > 0.01f);
  2318. CHECK (boosted / flat > 3.0f && boosted / flat < 4.2f);
  2319. }
  2320. TEST (bars_follow_time_signature_markers)
  2321. {
  2322. lynx::Song song;
  2323. song.beatsPerBar = 4;
  2324. const auto bar4 = (std::int64_t) lynx::ppq * 4;
  2325. auto bars = song.barsBetween (0, bar4 * 3);
  2326. CHECK (bars.size() == 3 && bars[2].tick == bar4 * 2 && bars[2].number == 3);
  2327. // 7/4 from bar 3, and 3/4 in the middle of a 7 bar (cuts and restarts)
  2328. song.addMarker ({ bar4 * 2, "Verso", 7, 4 });
  2329. song.addMarker ({ bar4, "Nome só", 0, 4 });
  2330. const auto seven = (std::int64_t) lynx::ppq * 7;
  2331. song.addMarker ({ bar4 * 2 + seven + lynx::ppq * 2, "", 3, 4 });
  2332. bars = song.barsBetween (0, bar4 * 2 + seven * 2);
  2333. CHECK (bars.size() >= 5);
  2334. CHECK (bars[1].length == bar4 && bars[2].tick == bar4 * 2 && bars[2].length == seven);
  2335. CHECK (bars[3].length == lynx::ppq * 2); // cut short by the change
  2336. CHECK (bars[4].length == lynx::ppq * 3 && bars[4].number == 5);
  2337. CHECK (song.markers()[0].name == "Nome só"); // sorted by tick
  2338. // from far away: starts at the right bar without losing the numbering
  2339. const auto far = song.barsBetween (lynx::ppq * 3000, lynx::ppq * 3001);
  2340. CHECK (far.size() == 1 && far[0].length == lynx::ppq * 3);
  2341. CHECK (song.barAt (lynx::ppq * 3000).number == far[0].number);
  2342. CHECK ((lynx::ppq * 3000 - far[0].tick) < far[0].length);
  2343. }
  2344. TEST (split_drum_channel_moves_notes_to_pads)
  2345. {
  2346. lynx::Song song = lynx::Song::makeDefault();
  2347. const auto channels = (int) song.channels.size();
  2348. song.patterns[0].notes.clear();
  2349. song.patterns[0].notes.push_back ({ 0, 240, 1, 36, 0.9f }); // kit kick (channel 1)
  2350. song.patterns[0].notes.push_back ({ 240, 240, 1, 38, 0.8f }); // snare
  2351. song.patterns[0].notes.push_back ({ 480, 240, 1, 50, 0.8f }); // key without a pad: dropped
  2352. song.patterns[0].notes.push_back ({ 480, 240, 3, 60, 0.8f }); // other channel: shifts by 1 position
  2353. lynx::Automation a;
  2354. a.target = { lynx::AutomationTargetKind::channelVolume, 3, 0, 0 };
  2355. song.automations.push_back (a);
  2356. std::vector<lynx::DrumPad> pads (2);
  2357. pads[0].name = "Kick";
  2358. pads[0].key = 36;
  2359. pads[0].layers = { { "kick.wav" } };
  2360. pads[1].name = "Snare";
  2361. pads[1].key = 38;
  2362. pads[1].layers = { { "snare soft.wav", 60, 0, 127, 0, 90 }, { "snare hard.wav", 60, 0, 127, 91, 127 } };
  2363. pads[1].cutGroup = 2;
  2364. pads[1].cutBy = 2;
  2365. lynx::splitDrumChannel (song, 1, pads);
  2366. CHECK ((int) song.channels.size() == channels + 1);
  2367. CHECK (song.channels[1].samplePath == "kick.wav" && song.channels[1].instrument == lynx::InstrumentKind::sampler);
  2368. CHECK (song.channels[2].zones.size() == 2 && song.channels[2].cutGroup == song.channels[2].cutBy && song.channels[2].cutGroup != 0);
  2369. const auto& notes = song.patterns[0].notes;
  2370. CHECK (notes.size() == 3);
  2371. CHECK (notes[0].channel == 1 && notes[0].key == 60);
  2372. CHECK (notes[1].channel == 2 && notes[1].key == 60);
  2373. CHECK (notes[2].channel == 4); // the old channel 3
  2374. CHECK (song.automations[0].target.index == 4);
  2375. }
  2376. TEST (flp_import_brings_playlist)
  2377. {
  2378. flp::Project p;
  2379. p.header.ppq = 96;
  2380. p.channels = { { 0, flp::ChannelType::sampler, "Kick", "", "", 1 } };
  2381. flp::Pattern empty;
  2382. empty.index = 1;
  2383. flp::Pattern full;
  2384. full.index = 2;
  2385. flp::Note n;
  2386. n.channel = 0;
  2387. full.notes.push_back (n);
  2388. p.patterns = { empty, full };
  2389. flp::Arrangement a;
  2390. flp::PlaylistItem item;
  2391. item.kind = flp::PlaylistItem::Kind::pattern;
  2392. item.index = 2;
  2393. item.position = 384;
  2394. item.length = 192;
  2395. item.track = 3;
  2396. item.patternStartTick = 96;
  2397. a.items.push_back (item);
  2398. item.index = 1; // empty pattern: discarded
  2399. a.items.push_back (item);
  2400. item.kind = flp::PlaylistItem::Kind::channelClip; // audio: not supported yet
  2401. a.items.push_back (item);
  2402. p.arrangements.push_back (a);
  2403. const auto s = lynx::importFlp (p);
  2404. CHECK (s.mode == lynx::PlayMode::song);
  2405. CHECK (s.playlist.size() == 1);
  2406. CHECK (s.playlist[0].pattern == 0 && s.playlist[0].track == 3);
  2407. CHECK (s.playlist[0].start == 4 * lynx::ppq && s.playlist[0].length == 2 * lynx::ppq && s.playlist[0].offset == lynx::ppq);
  2408. }
  2409. TEST (rack_releases_notes_on_position_jump)
  2410. {
  2411. lynx::Song s;
  2412. lynx::ChannelDef c;
  2413. c.instrument = lynx::InstrumentKind::synth;
  2414. s.channels.push_back (c);
  2415. auto& p = s.patterns.emplace_back();
  2416. lynx::Note n;
  2417. n.start = 0;
  2418. n.length = 4 * lynx::ppq; // long note
  2419. p.notes.push_back (n);
  2420. s.bpm = 120.0;
  2421. auto state = lynx::RackState::build (s, nullptr, 48000.0);
  2422. lynx::RackRenderer r;
  2423. r.prepare (48000.0);
  2424. std::vector<float> l (512), rr (512);
  2425. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  2426. double tick = 0.0;
  2427. for (int i = 0; i < 20; ++i, tick += 512 * tps)
  2428. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  2429. // jump to tick 2000 (mid-note, no new "on"): the synth must go silent
  2430. for (int i = 0; i < 40; ++i)
  2431. r.process (state.get(), true, 2000.0 + i * 512 * tps, 512, l.data(), rr.data());
  2432. float tail = 0.0f;
  2433. for (auto v : l)
  2434. tail = std::max (tail, std::abs (v));
  2435. CHECK (tail < 0.001f);
  2436. }
  2437. namespace
  2438. {
  2439. // Two samplers with a constant 0.5 signal on different inserts; returns the output peak.
  2440. float juce_db (float gain)
  2441. {
  2442. return 20.0f * std::log10 (gain);
  2443. }
  2444. float renderMixerCase (const std::function<void (lynx::Song&)>& tweak, lynx::MeterBank* meters = nullptr)
  2445. {
  2446. lynx::Song s;
  2447. s.mixer = lynx::Song::defaultMixer (4);
  2448. for (int i = 0; i < 2; ++i)
  2449. {
  2450. lynx::ChannelDef c;
  2451. c.instrument = lynx::InstrumentKind::sampler;
  2452. c.samplePath = "dc";
  2453. c.volume = 1.0f;
  2454. c.mixerTrack = i + 1;
  2455. s.channels.push_back (c);
  2456. }
  2457. s.patterns.emplace_back();
  2458. tweak (s);
  2459. auto provider = [] (const std::string&) {
  2460. auto d = std::make_shared<lynx::SampleData>();
  2461. d->left.assign (48000, 0.5f);
  2462. return std::shared_ptr<const lynx::SampleData> (d);
  2463. };
  2464. auto state = lynx::RackState::build (s, nullptr, 48000.0, provider);
  2465. lynx::RackRenderer r;
  2466. r.prepare (48000.0, 256);
  2467. lynx::LiveEventQueue live;
  2468. for (int ch = 0; ch < 2; ++ch)
  2469. {
  2470. lynx::NoteEvent on;
  2471. on.channel = ch;
  2472. on.velocity = 1.0f;
  2473. live.push (on);
  2474. }
  2475. std::vector<float> l (1000), rr (1000); // larger than the mixer block: tests the chunking
  2476. r.process (state.get(), false, 0.0, 1000, l.data(), rr.data(), &live, meters);
  2477. return std::max (std::abs (l[999]), std::abs (rr[999]));
  2478. }
  2479. } // namespace
  2480. TEST (mixer_routes_mutes_solos_and_meters)
  2481. {
  2482. // two 0.5 channels summed on the Master at 0 dB
  2483. CHECK (std::abs (renderMixerCase ([] (lynx::Song&) {}) - 1.0f) < 1e-4f);
  2484. // insert 1 muted: only channel 2 remains
  2485. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.mixer[1].muted = true; }) - 0.5f) < 1e-4f);
  2486. // solo on insert 2: same
  2487. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.mixer[2].solo = true; }) - 0.5f) < 1e-4f);
  2488. // FL fader curve: 0.8 = 0 dB, max ≈ +5.6 dB, half travel ≈ -12.7 dB
  2489. CHECK (std::abs (lynx::faderGain (0.8f) - 1.0f) < 1e-5f);
  2490. CHECK (std::abs (juce_db (lynx::faderGain (1.0f)) - 5.59f) < 0.05f);
  2491. CHECK (lynx::faderGain (0.0f) == 0.0f);
  2492. // Master fader at max
  2493. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.mixer[0].volume = 1.0f; }) - lynx::faderGain (1.0f)) < 1e-4f);
  2494. // both channels on the same insert, insert fader at 0.4
  2495. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) {
  2496. s.channels[1].mixerTrack = 1;
  2497. s.mixer[1].volume = 0.4f;
  2498. }) - lynx::faderGain (0.4f)) < 1e-4f);
  2499. // a route outside the mixer falls to the last existing insert, without crashing
  2500. CHECK (renderMixerCase ([] (lynx::Song& s) { s.channels[0].mixerTrack = 100; }) > 0.9f);
  2501. // no mixer: everything straight to the output at 0 dB
  2502. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.mixer.clear(); }) - 1.0f) < 1e-4f);
  2503. lynx::MeterBank meters;
  2504. renderMixerCase ([] (lynx::Song&) {}, &meters);
  2505. CHECK (std::abs (meters.takePeak (1, 0) - 0.5f) < 1e-4f);
  2506. CHECK (std::abs (meters.takePeak (0, 1) - 1.0f) < 1e-4f);
  2507. CHECK (meters.takePeak (1, 0) == 0.0f); // reading resets
  2508. CHECK (meters.takePeak (3, 0) == 0.0f); // insert with no channel
  2509. }
  2510. TEST (next_free_insert_and_flp_mixer_import)
  2511. {
  2512. auto s = lynx::Song::makeDefault();
  2513. CHECK (s.mixer.size() == 17 && s.mixer[0].name == "Master");
  2514. CHECK (s.nextFreeInsert() == 6); // the 5 default channels take 1..5
  2515. flp::Project p;
  2516. p.channels = { { 0, flp::ChannelType::sampler, "Kick", "", "", 30 } };
  2517. p.mixer = { { 0, "" }, { 30, "Drums" } };
  2518. const auto song = lynx::importFlp (p);
  2519. CHECK (song.channels[0].mixerTrack == 30);
  2520. CHECK (song.mixer.size() == 31);
  2521. CHECK (song.mixer[30].name == "Drums" && song.mixer[0].name == "Master");
  2522. }
  2523. namespace
  2524. {
  2525. float runEffectOnSine (lynx::EffectKind kind, const std::function<void (lynx::EffectSlot&)>& tweak, double hz, float amp,
  2526. int frames = 48000)
  2527. {
  2528. auto fx = lynx::makeEffect (kind);
  2529. fx->prepare (48000.0);
  2530. auto slot = lynx::makeEffectSlot (kind);
  2531. tweak (slot);
  2532. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  2533. for (int i = 0; i < frames; ++i)
  2534. l[(std::size_t) i] = r[(std::size_t) i] = amp * (float) std::sin (6.283185307 * hz * i / 48000.0);
  2535. for (int i = 0; i < frames; i += 480)
  2536. fx->process (l.data() + i, r.data() + i, std::min (480, frames - i), slot.params, 120.0);
  2537. float peak = 0.0f;
  2538. for (int i = frames / 2; i < frames; ++i) // second half: already settled
  2539. {
  2540. CHECK (std::isfinite (l[(std::size_t) i]));
  2541. peak = std::max (peak, std::abs (l[(std::size_t) i]));
  2542. }
  2543. return peak;
  2544. }
  2545. } // namespace
  2546. TEST (parametric_eq_bands_and_response)
  2547. {
  2548. // default: transparent
  2549. auto slot = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  2550. CHECK (std::abs (lynx::peq::responseDb (slot.params, 48000.0, 1000.0)) < 0.01);
  2551. CHECK (std::abs (runEffectOnSine (lynx::EffectKind::parametricEq, [] (auto&) {}, 1000.0, 0.5f) - 0.5f) < 0.005f);
  2552. // +12 dB peak at 1 kHz on band 4: the response and the signal agree
  2553. auto boost = [] (lynx::EffectSlot& s) {
  2554. s.params[(std::size_t) lynx::peq::param (3, 1)] = lynx::peq::hzValue (1000.0);
  2555. s.params[(std::size_t) lynx::peq::param (3, 2)] = lynx::peq::gainValue (12.0);
  2556. };
  2557. boost (slot);
  2558. CHECK (std::abs (lynx::peq::responseDb (slot.params, 48000.0, 1000.0) - 12.0) < 0.2);
  2559. CHECK (std::abs (lynx::peq::responseDb (slot.params, 48000.0, 100.0)) < 1.0);
  2560. const auto peak = runEffectOnSine (lynx::EffectKind::parametricEq, boost, 1000.0, 0.1f);
  2561. CHECK (std::abs (peak - 0.1f * std::pow (10.0f, 12.0f / 20.0f)) < 0.01f);
  2562. // low cut at 48 dB/oct at 200 Hz: 50 Hz (2 octaves below) drops ~96 dB; 2 kHz passes
  2563. auto cut = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  2564. cut.params[(std::size_t) lynx::peq::param (0, 0)] = lynx::peq::typeValue (lynx::peq::BandType::lowCut);
  2565. cut.params[(std::size_t) lynx::peq::param (0, 1)] = lynx::peq::hzValue (200.0);
  2566. cut.params[(std::size_t) lynx::peq::param (0, 3)] = lynx::peq::qValue (0.70710678); // Butterworth
  2567. cut.params[(std::size_t) (lynx::peq::slopeParam + 0)] = 1.0f;
  2568. CHECK (lynx::peq::responseDb (cut.params, 48000.0, 50.0) < -80.0);
  2569. CHECK (std::abs (lynx::peq::responseDb (cut.params, 48000.0, 200.0) + 3.0) < 0.5); // -3 dB at the cutoff (Butterworth)
  2570. CHECK (std::abs (lynx::peq::responseDb (cut.params, 48000.0, 2000.0)) < 0.1);
  2571. // round-trip conversions
  2572. CHECK (std::abs (lynx::peq::hz (lynx::peq::hzValue (440.0)) - 440.0) < 0.5);
  2573. CHECK (std::abs (lynx::peq::q (lynx::peq::qValue (2.5)) - 2.5) < 0.01);
  2574. CHECK (lynx::peq::type (lynx::peq::typeValue (lynx::peq::BandType::notch)) == lynx::peq::BandType::notch);
  2575. }
  2576. TEST (fl_parametric_eq2_state_maps_to_bands)
  2577. {
  2578. // v8 blob: band 1 low cut at 100 Hz "Steep 8", band 4 peak +6 dB at 1 kHz, output −3 dB
  2579. std::vector<std::uint8_t> blob (354, 0);
  2580. auto put = [&] (std::size_t off, std::int32_t v) { std::memcpy (blob.data() + off, &v, 4); };
  2581. put (0, 8);
  2582. auto param = [&] (int i, std::int32_t v) { put (4 + 4 * (std::size_t) i, v); };
  2583. auto hzRaw = [] (double hz) { return (std::int32_t) std::lround (std::log (hz / 20.0) / std::log (1000.0) * 65536.0); };
  2584. for (int b = 0; b < 7; ++b)
  2585. param (21 + b, 0); // all off
  2586. param (21 + 0, 3); // high pass (= low cut)
  2587. param (7 + 0, hzRaw (100.0));
  2588. param (14 + 0, 40124); // default width -> Q ~0.68
  2589. param (28 + 0, -3); // Steep 8 -> 4 biquads
  2590. param (21 + 3, 6); // peaking
  2591. param (7 + 3, hzRaw (1000.0));
  2592. param (3, 600); // +6 dB
  2593. param (14 + 3, 25412);
  2594. param (35, -300); // main level −3 dB
  2595. put (0x13E, 0x7F);
  2596. const auto slot = lynx::effectFromFl ("Fruity Parametric EQ 2", blob);
  2597. CHECK (slot.has_value() && slot->kind == lynx::EffectKind::parametricEq);
  2598. const auto& p = slot->params;
  2599. CHECK (lynx::peq::type (p[(std::size_t) lynx::peq::param (0, 0)]) == lynx::peq::BandType::lowCut);
  2600. CHECK (lynx::peq::slopeStages (p[(std::size_t) lynx::peq::slopeParam]) == 4);
  2601. CHECK (lynx::peq::type (p[(std::size_t) lynx::peq::param (3, 0)]) == lynx::peq::BandType::peak);
  2602. CHECK (lynx::peq::type (p[(std::size_t) lynx::peq::param (1, 0)]) == lynx::peq::BandType::off);
  2603. CHECK (std::abs (lynx::peq::responseDb (p, 48000.0, 1000.0) - 3.0) < 0.3); // +6 from the peak −3 from the output
  2604. CHECK (lynx::peq::responseDb (p, 48000.0, 30.0) < -40.0); // 48 dB/oct below 100 Hz
  2605. CHECK (std::abs (lynx::peq::responseDb (p, 48000.0, 8000.0) + 3.0) < 0.3);
  2606. // a band muted by the mask doesn't sound
  2607. put (0x13E, 0x7F & ~(1 << 3));
  2608. const auto muted = lynx::effectFromFl ("Fruity Parametric EQ 2", blob);
  2609. CHECK (lynx::peq::type (muted->params[(std::size_t) lynx::peq::param (3, 0)]) == lynx::peq::BandType::off);
  2610. }
  2611. TEST (reverb_low_cut_and_predelay)
  2612. {
  2613. // impulse: with 100 ms predelay the wet only starts later; with a 3 kHz low cut a
  2614. // 100 Hz sine barely enters the reverb
  2615. auto run = [] (const std::function<void (lynx::EffectSlot&)>& tweak, double hz, bool impulse) {
  2616. auto fx = lynx::makeEffect (lynx::EffectKind::reverb);
  2617. fx->prepare (48000.0);
  2618. auto slot = lynx::makeEffectSlot (lynx::EffectKind::reverb);
  2619. slot.params[4] = 0.0f; // wet only
  2620. slot.params[3] = 1.0f;
  2621. tweak (slot);
  2622. std::vector<float> l (48000), r (48000);
  2623. for (int i = 0; i < 48000; ++i)
  2624. l[(std::size_t) i] = r[(std::size_t) i] = impulse ? (i == 0 ? 1.0f : 0.0f) : 0.5f * (float) std::sin (6.283185307 * hz * i / 48000.0);
  2625. for (int i = 0; i < 48000; i += 480)
  2626. fx->process (l.data() + i, r.data() + i, 480, slot.params, 120.0);
  2627. return l;
  2628. };
  2629. const auto delayed = run ([] (auto& s) { s.params[7] = 0.1f; }, 0.0, true);
  2630. float early = 0.0f, later = 0.0f;
  2631. for (std::size_t i = 0; i < 4800; ++i)
  2632. early = std::max (early, std::abs (delayed[i]));
  2633. for (std::size_t i = 4800; i < 24000; ++i)
  2634. later = std::max (later, std::abs (delayed[i]));
  2635. CHECK (early == 0.0f && later > 0.0f);
  2636. auto energy = [] (const std::vector<float>& b) { double e = 0.0; for (std::size_t i = 24000; i < 48000; ++i) e += (double) b[i] * b[i]; return e; };
  2637. const auto open = energy (run ([] (auto&) {}, 100.0, false));
  2638. const auto cut = energy (run ([] (auto& s) { s.params[5] = 1.0f; }, 100.0, false));
  2639. CHECK (cut < open * 0.01);
  2640. }
  2641. TEST (utility_effect_and_fl_stereo_tools)
  2642. {
  2643. // transparent by default; balance fully right silences the left
  2644. CHECK (std::abs (runEffectOnSine (lynx::EffectKind::utility, [] (auto&) {}, 440.0, 0.5f) - 0.5f) < 0.001f);
  2645. CHECK (runEffectOnSine (lynx::EffectKind::utility, [] (auto& s) { s.params[1] = 1.0f; }, 440.0, 0.5f) < 0.001f);
  2646. // Stereo Shaper in "mono": each output = 0.5 L + 0.5 R
  2647. std::vector<std::uint8_t> blob (36, 0);
  2648. auto put = [&] (std::size_t off, std::int32_t v) { std::memcpy (blob.data() + off, &v, 4); };
  2649. put (4, 6400); put (8, 6400); put (12, 6400); put (16, 6400);
  2650. const auto slot = lynx::effectFromFl ("Fruity Stereo Shaper", blob);
  2651. CHECK (slot && slot->kind == lynx::EffectKind::utility);
  2652. auto fx = lynx::makeEffect (lynx::EffectKind::utility);
  2653. float l = 1.0f, r = 0.0f;
  2654. fx->process (&l, &r, 1, slot->params, 120.0);
  2655. CHECK (std::abs (l - 0.5f) < 1e-4f && std::abs (r - 0.5f) < 1e-4f);
  2656. // Balance: volume 256 = 0 dB, pan −128 = fully left
  2657. std::vector<std::uint8_t> bal (8, 0);
  2658. std::int32_t pan = -128, vol = 256;
  2659. std::memcpy (bal.data(), &pan, 4);
  2660. std::memcpy (bal.data() + 4, &vol, 4);
  2661. const auto b = lynx::effectFromFl ("Fruity Balance", bal);
  2662. l = 0.5f; r = 0.5f;
  2663. fx->process (&l, &r, 1, b->params, 120.0);
  2664. CHECK (std::abs (l - 0.5f) < 1e-3f && std::abs (r) < 1e-4f);
  2665. }
  2666. TEST (effects_eq_compressor_behave)
  2667. {
  2668. // EQ at default is transparent
  2669. CHECK (std::abs (runEffectOnSine (lynx::EffectKind::eq, [] (auto&) {}, 1000.0, 0.5f) - 0.5f) < 0.01f);
  2670. // +18 dB on the lows: 60 Hz rises a lot, 5 kHz barely
  2671. CHECK (runEffectOnSine (lynx::EffectKind::eq, [] (auto& s) { s.params[0] = 1.0f; }, 60.0, 0.05f) > 0.3f);
  2672. CHECK (runEffectOnSine (lynx::EffectKind::eq, [] (auto& s) { s.params[0] = 1.0f; }, 5000.0, 0.05f) < 0.06f);
  2673. // compressor: threshold -20 dB, ratio 20:1 flattens a 0 dBFS signal to near the threshold
  2674. const auto squashed = runEffectOnSine (lynx::EffectKind::compressor, [] (auto& s) {
  2675. s.params[0] = 40.0f / 60.0f;
  2676. s.params[1] = 1.0f;
  2677. }, 200.0, 1.0f);
  2678. CHECK (squashed < 0.2f && squashed > 0.05f);
  2679. // a signal below the threshold passes intact
  2680. CHECK (std::abs (runEffectOnSine (lynx::EffectKind::compressor, [] (auto& s) { s.params[0] = 1.0f; }, 200.0, 0.3f) - 0.3f) < 0.01f);
  2681. }
  2682. TEST (effects_delay_echoes_on_tempo_and_reverb_has_tail)
  2683. {
  2684. auto delay = lynx::makeEffect (lynx::EffectKind::delay);
  2685. delay->prepare (48000.0);
  2686. auto slot = lynx::makeEffectSlot (lynx::EffectKind::delay);
  2687. slot.params[0] = 3.5f / 8.0f; // index 3 = 1/4 = 0.5 s at 120 BPM
  2688. slot.params[1] = 0.0f; // no feedback: a single echo
  2689. slot.params[2] = 1.0f;
  2690. slot.params[4] = 0.0f; // no damping
  2691. std::vector<float> l (48000, 0.0f), r (48000, 0.0f);
  2692. l[0] = r[0] = 1.0f;
  2693. delay->process (l.data(), r.data(), 48000, slot.params, 120.0);
  2694. CHECK (std::abs (l[24000] - 1.0f) < 1e-4f);
  2695. CHECK (std::abs (l[12000]) < 1e-6f);
  2696. auto reverb = lynx::makeEffect (lynx::EffectKind::reverb);
  2697. reverb->prepare (48000.0);
  2698. auto rs = lynx::makeEffectSlot (lynx::EffectKind::reverb);
  2699. rs.params[3] = 1.0f;
  2700. std::fill (l.begin(), l.end(), 0.0f);
  2701. std::fill (r.begin(), r.end(), 0.0f);
  2702. l[0] = r[0] = 1.0f;
  2703. reverb->process (l.data(), r.data(), 48000, rs.params, 120.0);
  2704. float tail = 0.0f;
  2705. for (int i = 4800; i < 9600; ++i) // between 100 and 200 ms after the impulse
  2706. tail = std::max (tail, std::abs (l[(std::size_t) i]));
  2707. CHECK (tail > 1e-4f && tail < 1.0f);
  2708. CHECK (lynx::formatEffectParam (lynx::EffectKind::delay, 0, slot.params[0], 120.0) == "1/4 (500 ms)");
  2709. }
  2710. TEST (rack_runs_insert_effects_and_reuses_them)
  2711. {
  2712. // an insert with EQ at -inf doesn't exist; we use the EQ output at -18 dB to see the effect act
  2713. const auto quiet = renderMixerCase ([] (lynx::Song& s) {
  2714. auto eq = lynx::makeEffectSlot (lynx::EffectKind::eq);
  2715. eq.params[4] = 0.0f; // output -18 dB
  2716. s.mixer[1].effects.push_back (eq);
  2717. });
  2718. CHECK (quiet > 0.55f && quiet < 0.6f); // 0.5 from channel 2 + 0.5 * 0.126 from channel 1
  2719. const auto bypassed = renderMixerCase ([] (lynx::Song& s) {
  2720. auto eq = lynx::makeEffectSlot (lynx::EffectKind::eq);
  2721. eq.params[4] = 0.0f;
  2722. eq.enabled = false;
  2723. s.mixer[1].effects.push_back (eq);
  2724. });
  2725. CHECK (std::abs (bypassed - 1.0f) < 1e-4f);
  2726. auto s = lynx::Song::makeDefault();
  2727. s.mixer[2].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::reverb));
  2728. auto a = lynx::RackState::build (s, nullptr, 48000.0);
  2729. s.mixer[2].effects[0].params[0] = 0.9f; // turning a knob doesn't recreate the effect
  2730. auto b = lynx::RackState::build (s, a.get(), 48000.0);
  2731. CHECK (b->effects[2][0] == a->effects[2][0]);
  2732. s.mixer[2].effects[0] = lynx::makeEffectSlot (lynx::EffectKind::delay);
  2733. auto c = lynx::RackState::build (s, b.get(), 48000.0);
  2734. CHECK (c->effects[2][0] != b->effects[2][0]);
  2735. }
  2736. TEST (audio_clips_trigger_cut_and_resume)
  2737. {
  2738. lynx::Song s;
  2739. s.bpm = 120.0; // 1 beat = 0.5 s = 24000 samples at 48 kHz
  2740. lynx::ChannelDef c;
  2741. c.instrument = lynx::InstrumentKind::audioClip;
  2742. c.samplePath = "ramp";
  2743. c.volume = 1.0f;
  2744. s.channels.push_back (c);
  2745. s.patterns.emplace_back();
  2746. lynx::Clip clip;
  2747. clip.kind = lynx::ClipKind::audio;
  2748. clip.channel = 0;
  2749. clip.start = lynx::ppq; // starts at beat 2
  2750. clip.length = 2 * lynx::ppq; // lasts 2 beats
  2751. clip.offset = lynx::ppq; // skips the first beat of the audio
  2752. s.playlist.push_back (clip);
  2753. s.mode = lynx::PlayMode::song;
  2754. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  2755. lynx::EventBuffer ev;
  2756. lynx::scheduleSong (s, 0.0, 4 * 24000, tps, ev);
  2757. CHECK (ev.size() == 2);
  2758. CHECK (ev[0].type == lynx::NoteEvent::Type::on && ev[0].sampleOffset == 24000 && std::abs (ev[0].startSeconds - 0.5) < 1e-9);
  2759. CHECK (ev[1].type == lynx::NoteEvent::Type::off && ev[1].sampleOffset == 3 * 24000);
  2760. // seek to the middle of the clip (beat 2.5): with resume, starts at the block's first sample
  2761. ev.clear();
  2762. lynx::scheduleSong (s, 1.5 * lynx::ppq, 256, tps, ev, true);
  2763. CHECK (ev.size() == 1 && ev[0].sampleOffset == 0 && std::abs (ev[0].startSeconds - 0.75) < 1e-9);
  2764. ev.clear();
  2765. lynx::scheduleSong (s, 1.5 * lynx::ppq, 256, tps, ev, false);
  2766. CHECK (ev.size() == 0);
  2767. // sample whose value = position in seconds: lets us check where playback started
  2768. auto provider = [] (const std::string&) {
  2769. auto d = std::make_shared<lynx::SampleData>();
  2770. d->sampleRate = 48000.0;
  2771. for (int i = 0; i < 48000 * 3; ++i)
  2772. d->left.push_back ((float) i / 48000.0f);
  2773. return std::shared_ptr<const lynx::SampleData> (d);
  2774. };
  2775. auto state = lynx::RackState::build (s, nullptr, 48000.0, provider);
  2776. lynx::RackRenderer r;
  2777. r.prepare (48000.0, 512);
  2778. std::vector<float> l (256), rr (256);
  2779. // first block already playing mid-clip
  2780. r.process (state.get(), true, 1.5 * lynx::ppq, 256, l.data(), rr.data());
  2781. CHECK (std::abs (l[0] - 0.75f) < 0.001f);
  2782. // the clip ends at beat 3: after the short fade, silence (the sample would still have audio)
  2783. double tick = 3.0 * lynx::ppq - 10 * tps;
  2784. r.process (state.get(), false, tick, 256, l.data(), rr.data()); // stops (fade)
  2785. for (int i = 0; i < 4; ++i)
  2786. r.process (state.get(), false, tick, 256, l.data(), rr.data());
  2787. CHECK (std::abs (l[255]) < 1e-6f);
  2788. }
  2789. TEST (remove_channel_fixes_notes_and_audio_clips)
  2790. {
  2791. lynx::Song s;
  2792. s.channels.resize (3);
  2793. s.patterns.resize (1);
  2794. s.patterns[0].notes = { { 0, 240, 0, 60, 1.0f }, { 0, 240, 1, 60, 1.0f }, { 0, 240, 2, 60, 1.0f } };
  2795. lynx::Clip a;
  2796. a.kind = lynx::ClipKind::audio;
  2797. a.channel = 1;
  2798. a.length = 100;
  2799. lynx::Clip b = a;
  2800. b.channel = 2;
  2801. s.playlist = { a, b };
  2802. s.removeChannel (1);
  2803. CHECK (s.channels.size() == 2);
  2804. CHECK (s.patterns[0].notes.size() == 2 && s.patterns[0].notes[1].channel == 1);
  2805. CHECK (s.playlist.size() == 1 && s.playlist[0].channel == 1);
  2806. }
  2807. TEST (flp_import_audio_clips_with_offsets)
  2808. {
  2809. flp::Project p;
  2810. p.header.ppq = 96;
  2811. p.tempo = 120.0;
  2812. p.channels = { { 0, flp::ChannelType::audioClip, "Vocal", "", "%FLStudioData%\\v.wav", 2 },
  2813. { 1, flp::ChannelType::audioClip, "Loop", "", "%FLStudioData%\\l.wav", 3 } };
  2814. flp::Arrangement arr;
  2815. flp::PlaylistItem beats; // offset in beats: end - start = duration in beats
  2816. beats.kind = flp::PlaylistItem::Kind::channelClip;
  2817. beats.index = 0;
  2818. beats.position = 192;
  2819. beats.length = 384; // 4 beats
  2820. beats.startOffset = 2.0f;
  2821. beats.endOffset = 6.0f;
  2822. flp::PlaylistItem ms = beats; // offset in ms: 4 beats at 120 BPM = 2000 ms
  2823. ms.index = 1;
  2824. ms.startOffset = 500.0f;
  2825. ms.endOffset = 2500.0f;
  2826. arr.items = { beats, ms };
  2827. p.arrangements.push_back (arr);
  2828. lynx::FlpImportOptions options;
  2829. options.roots = { "C:\\FL", "C:\\FL\\Data", "" };
  2830. options.fileExists = [] (const std::string&) { return true; };
  2831. const auto s = lynx::importFlp (p, options);
  2832. CHECK (s.channels.size() == 2 && s.channels[0].instrument == lynx::InstrumentKind::audioClip);
  2833. CHECK (s.channels[0].samplePath == "C:\\FL\\Data\\v.wav");
  2834. CHECK (s.playlist.size() == 2);
  2835. CHECK (s.playlist[0].kind == lynx::ClipKind::audio && s.playlist[0].start == 2 * lynx::ppq);
  2836. CHECK (s.playlist[0].offset == 2 * lynx::ppq);
  2837. CHECK (s.playlist[1].offset == lynx::ppq); // 500 ms at 120 BPM = 1 beat
  2838. CHECK (s.mode == lynx::PlayMode::song);
  2839. }
  2840. TEST (plugin_factories_create_reuse_and_fallback)
  2841. {
  2842. lynx::Song s;
  2843. s.mixer = lynx::Song::defaultMixer (2);
  2844. lynx::ChannelDef c;
  2845. c.instrument = lynx::InstrumentKind::plugin;
  2846. c.plugin.id = "VST3-Synth-123";
  2847. c.mixerTrack = 1;
  2848. s.channels.push_back (c);
  2849. lynx::ChannelDef missing = c;
  2850. missing.plugin.id = "VST3-Ausente-0";
  2851. s.channels.push_back (missing);
  2852. lynx::EffectSlot fx;
  2853. fx.kind = lynx::EffectKind::plugin;
  2854. fx.plugin.id = "VST3-Reverb-9";
  2855. s.mixer[1].effects.push_back (fx);
  2856. s.patterns.emplace_back();
  2857. int instrumentsMade = 0, effectsMade = 0;
  2858. lynx::RackState::Factories f;
  2859. f.pluginInstruments = [&] (const lynx::PluginRef& ref, double) -> std::shared_ptr<lynx::Instrument> {
  2860. if (ref.id != "VST3-Synth-123")
  2861. return nullptr;
  2862. ++instrumentsMade;
  2863. auto synth = lynx::makeInstrument (lynx::InstrumentKind::synth);
  2864. synth->prepare (48000.0);
  2865. return synth;
  2866. };
  2867. f.pluginEffects = [&] (const lynx::PluginRef&, double) -> std::shared_ptr<lynx::Effect> {
  2868. ++effectsMade;
  2869. auto eq = lynx::makeEffect (lynx::EffectKind::eq);
  2870. eq->prepare (48000.0);
  2871. return eq;
  2872. };
  2873. auto a = lynx::RackState::build (s, nullptr, 48000.0, f);
  2874. CHECK (instrumentsMade == 1 && effectsMade == 1);
  2875. CHECK (a->instruments.size() == 2 && a->instruments[1] != nullptr); // missing: muted, but it exists
  2876. // changing the saved state doesn't recreate; swapping the plugin does
  2877. s.channels[0].plugin.state = "abc";
  2878. auto b = lynx::RackState::build (s, a.get(), 48000.0, f);
  2879. CHECK (instrumentsMade == 1 && b->instruments[0] == a->instruments[0] && b->effects[1][0] == a->effects[1][0]);
  2880. s.mixer[1].effects[0].plugin.id = "VST3-Outro-1";
  2881. auto c2 = lynx::RackState::build (s, b.get(), 48000.0, f);
  2882. CHECK (effectsMade == 2);
  2883. // rendering with a missing plugin and a plugin slot breaks nothing
  2884. lynx::RackRenderer r;
  2885. r.prepare (48000.0, 256);
  2886. lynx::LiveEventQueue live;
  2887. lynx::NoteEvent on;
  2888. on.channel = 0;
  2889. on.velocity = 1.0f;
  2890. live.push (on);
  2891. on.channel = 1;
  2892. live.push (on);
  2893. std::vector<float> l (256), rr (256);
  2894. r.process (c2.get(), false, 0.0, 256, l.data(), rr.data(), &live);
  2895. float peak = 0.0f;
  2896. for (auto v : l)
  2897. {
  2898. CHECK (std::isfinite (v));
  2899. peak = std::max (peak, std::abs (v));
  2900. }
  2901. CHECK (peak > 0.0f);
  2902. }
  2903. TEST (export_song_adds_silent_tail_and_never_restarts)
  2904. {
  2905. auto s = lynx::Song::makeDefault();
  2906. s.playlist.clear();
  2907. std::int64_t length = 0;
  2908. auto pat = lynx::makeExportSong (s, true, lynx::ppq * 8, length); // empty Playlist: uses the pattern
  2909. CHECK (length == lynx::ppq * 4);
  2910. CHECK (pat.mode == lynx::PlayMode::song && pat.playlist.size() == 2);
  2911. CHECK (pat.songLength() >= length + lynx::ppq * 8);
  2912. // no new notes after the song ends, only silence until the end of the tail
  2913. lynx::EventBuffer events;
  2914. const auto tps = lynx::ticksPerSample (pat.bpm, 48000.0);
  2915. int onsAfterEnd = 0, onsBefore = 0;
  2916. for (double tick = 0.0; tick < (double) (length + lynx::ppq * 8); tick += 512 * tps)
  2917. {
  2918. events.clear();
  2919. lynx::scheduleSong (pat, tick, 512, tps, events);
  2920. for (const auto& e : events)
  2921. if (e.type == lynx::NoteEvent::Type::on)
  2922. (tick + e.sampleOffset * tps >= (double) length ? onsAfterEnd : onsBefore)++;
  2923. }
  2924. CHECK (onsBefore == (int) s.patterns[0].notes.size());
  2925. CHECK (onsAfterEnd == 0);
  2926. // with Playlist: the end is the last clip's, without rounding
  2927. s.playlist.push_back ({ 0, 0, lynx::ppq * 2, lynx::ppq * 3, 0 });
  2928. auto song = lynx::makeExportSong (s, true, 0, length);
  2929. CHECK (length == lynx::ppq * 5 && song.playlist.size() == 1);
  2930. song = lynx::makeExportSong (s, false, 0, length);
  2931. CHECK (length == lynx::ppq * 4 && song.playlist[0].start == 0);
  2932. }
  2933. TEST (note_edit_selection_operations)
  2934. {
  2935. namespace ne = lynx::noteedit;
  2936. lynx::Pattern p;
  2937. p.notes = { { 0, 240, 0, 60 }, { 480, 240, 0, 64 }, { 960, 480, 1, 67 } };
  2938. // sorting keeps the indices in step
  2939. p.notes[0].start = 1200;
  2940. std::vector<int> tracked { 0, 2 };
  2941. ne::sortTracking (p, tracked);
  2942. CHECK (p.notes[2].start == 1200 && p.notes[(std::size_t) tracked[0]].start == 1200);
  2943. CHECK (p.notes[(std::size_t) tracked[1]].key == 67);
  2944. // group move respects the limits
  2945. std::int64_t dt = -5000;
  2946. int dk = 100;
  2947. ne::move (p, { 0, 1 }, dt, dk);
  2948. CHECK (dt == -480 && dk == 127 - 67 && p.notes[0].start == 0 && p.notes[1].key == 127);
  2949. // duplicate: right after the selection, rounded to the grid
  2950. lynx::Pattern q;
  2951. q.notes = { { 0, 240, 0, 60 }, { 240, 300, 0, 62 } }; // 540-tick selection
  2952. const auto added = ne::duplicate (q, { 0, 1 }, 960);
  2953. CHECK (added.size() == 2 && q.notes[(std::size_t) added[0]].start == 960 && q.notes[(std::size_t) added[1]].start == 1200);
  2954. // paste onto another channel with an offset
  2955. const auto pasted = ne::paste (q, ne::copy (q, { 1 }), 100, 3);
  2956. CHECK (pasted.size() == 1 && q.notes.back().channel == 3 && q.notes.back().start == 340);
  2957. // quantize rounds to the nearest
  2958. q.notes[0].start = 130;
  2959. q.notes[1].start = 100;
  2960. ne::quantize (q, { 0, 1 }, 240);
  2961. CHECK (q.notes[0].start == 240 && q.notes[1].start == 0);
  2962. // remove several (order and duplicates don't matter)
  2963. const auto before = q.notes.size();
  2964. ne::remove (q, { 1, 0, 1 });
  2965. CHECK (q.notes.size() == before - 2);
  2966. }
  2967. TEST (note_edit_quick_operations)
  2968. {
  2969. namespace ne = lynx::noteedit;
  2970. const std::int64_t step = lynx::ticksPerStep, bar = lynx::ppq * 4;
  2971. // split: only strictly inside; the tail is appended and does not slide again
  2972. lynx::Pattern p;
  2973. p.notes = { { 0, 4 * step, 0, 60 } };
  2974. p.notes[0].slide = true;
  2975. CHECK (ne::split (p, 0, 0) == -1 && ne::split (p, 0, 4 * step) == -1);
  2976. CHECK (ne::split (p, 0, step) == 1 && p.notes[0].length == step && p.notes[1].start == step && p.notes[1].length == 3 * step
  2977. && ! p.notes[1].slide);
  2978. // chop to grid: a 2.5-step note from half a step becomes 3 pieces cut on the step lines
  2979. lynx::Pattern c;
  2980. c.notes = { { step / 2, step * 5 / 2, 0, 60 }, { 0, step, 1, 50 } };
  2981. const auto pieces = ne::chop (c, { 0, 1 }, step);
  2982. CHECK (pieces.size() == 4 && c.notes.size() == 4);
  2983. CHECK (c.notes[0].length == step / 2 && c.notes[2].start == step && c.notes[2].length == step && c.notes[3].start == 2 * step
  2984. && c.notes[3].length == step);
  2985. // join: touching and overlapping notes of the same key and channel merge; others stay
  2986. lynx::Pattern j;
  2987. j.notes = { { 0, step, 0, 60 }, { step, step, 0, 60 }, { step * 3 / 2, step * 2, 0, 60 }, { 5 * step, step, 0, 60 },
  2988. { step, step, 0, 62 }, { step, step, 1, 60 } };
  2989. CHECK (ne::join (j, { 0, 1, 2, 3, 4, 5 }) == 2 && j.notes.size() == 4);
  2990. CHECK (j.notes[0].start == 0 && j.notes[0].length == step * 7 / 2);
  2991. // legato: each note reaches the next start (a chord ends together); the last keeps its length
  2992. lynx::Pattern l;
  2993. l.notes = { { 0, 10, 0, 60 }, { 0, 10, 0, 64 }, { step, 10, 0, 62 }, { 3 * step, 10, 0, 65 }, { step, 10, 1, 40 } };
  2994. ne::legato (l, { 0, 1, 2, 3, 4 });
  2995. CHECK (l.notes[0].length == step && l.notes[1].length == step && l.notes[2].length == 2 * step && l.notes[3].length == 10
  2996. && l.notes[4].length == 10);
  2997. // shrink to grid and full quantise (start and end)
  2998. ne::shrinkToGrid (l, { 3 }, step / 2);
  2999. CHECK (l.notes[3].length == step / 2);
  3000. lynx::Pattern q;
  3001. q.notes = { { 10, step - 30, 0, 60 }, { step + 100, 20, 0, 60 } };
  3002. ne::quantizeFull (q, { 0, 1 }, step);
  3003. CHECK (q.notes[0].start == 0 && q.notes[0].length == step && q.notes[1].start == step && q.notes[1].length == step);
  3004. // rotate inside the bar, wrapping
  3005. lynx::Pattern r;
  3006. r.notes = { { 0, step, 0, 60 }, { bar - step, step, 0, 62 } };
  3007. ne::rotate (r, { 0, 1 }, step, bar, 1);
  3008. CHECK (r.notes[0].start == step && r.notes[1].start == 0);
  3009. ne::rotate (r, { 0, 1 }, step, bar, -2);
  3010. CHECK (r.notes[0].start == bar - step && r.notes[1].start == bar - 2 * step);
  3011. r.notes.push_back ({ bar + step, step, 0, 64 }); // alone in the second bar: wraps inside that bar
  3012. ne::rotate (r, { 2 }, step, bar, -2);
  3013. CHECK (r.notes[2].start == 2 * bar - step);
  3014. }
  3015. TEST (note_edit_grid_and_time_text)
  3016. {
  3017. namespace ne = lynx::noteedit;
  3018. const std::int64_t step = lynx::ticksPerStep, bar = lynx::ppq * 4;
  3019. CHECK (ne::snapDown (250.0, step) == step && ne::snapDown (-1.0, step) == -step && ne::snapDown (17.9, 1) == 17);
  3020. CHECK (ne::snapNearest (1000.0, { 400, 1100, 980 }, 50.0, step) == 980);
  3021. CHECK (ne::snapNearest (1000.0, { 400 }, 50.0, step) == 960); // too far: falls back to the grid
  3022. // screen grid: 24 px per step shows steps; zoomed out it climbs to beats, bars and bar multiples
  3023. CHECK (ne::screenStep (24.0 / step, bar) == step);
  3024. CHECK (ne::screenStep (96.0 / bar, bar) == lynx::ppq);
  3025. CHECK (ne::screenStep (8.0 / bar, bar) == 2 * bar);
  3026. CHECK (ne::screenStep (200.0 / step, bar) == step / 4);
  3027. CHECK (ne::formatTime (0, 4) == "1:1:0" && ne::formatTime (bar + 5 * step + 7, 4) == "2:6:7");
  3028. CHECK (ne::formatTime (step * 2, 4, true) == "0:2:0");
  3029. std::int64_t t = 0;
  3030. CHECK (ne::parseTime ("2:6:7", 4, t) && t == bar + 5 * step + 7);
  3031. CHECK (ne::parseTime ("3", 4, t) && t == 2 * bar);
  3032. CHECK (ne::parseTime ("0:2:0", 4, t, true) && t == 2 * step);
  3033. CHECK (! ne::parseTime ("0:1:0", 4, t) && ! ne::parseTime ("1:17:0", 4, t) && ! ne::parseTime ("1:1:240", 4, t)
  3034. && ! ne::parseTime ("a", 4, t) && ! ne::parseTime ("", 4, t));
  3035. CHECK (ne::parseTime ("1:12:0", 3, t) && ! ne::parseTime ("1:13:0", 3, t)); // 3/4: 12 steps per bar
  3036. }
  3037. TEST (playlist_clip_edges_and_time_selection)
  3038. {
  3039. namespace ne = lynx::noteedit;
  3040. const std::int64_t beat = lynx::ppq;
  3041. // left-edge trim: content stays in place, cannot reveal what is before the content's start
  3042. lynx::Clip c { 0, 0, 4 * beat, 4 * beat, beat };
  3043. ne::trimStart (c, 5 * beat, beat);
  3044. CHECK (c.start == 5 * beat && c.offset == 2 * beat && c.length == 3 * beat);
  3045. ne::trimStart (c, 0, beat);
  3046. CHECK (c.start == 3 * beat && c.offset == 0 && c.length == 5 * beat);
  3047. ne::trimStart (c, 100 * beat, beat);
  3048. CHECK (c.length == beat && c.end() == 8 * beat);
  3049. // slip moves the content, not the clip
  3050. lynx::Clip s { 0, 0, 0, 2 * beat, beat };
  3051. ne::slip (s, beat / 2);
  3052. CHECK (s.offset == beat / 2 && s.start == 0 && s.length == 2 * beat);
  3053. ne::slip (s, beat);
  3054. CHECK (s.offset == 0);
  3055. ne::slip (s, -3 * beat);
  3056. CHECK (s.offset == 3 * beat);
  3057. // insert / delete time across all tracks, markers included
  3058. std::vector<lynx::Clip> clips { { 0, 0, 0, 2 * beat, 0 }, { 0, 1, 4 * beat, 2 * beat, 0 }, { 0, 2, beat, 6 * beat, 0 } };
  3059. std::vector<lynx::Marker> markers { { 5 * beat, "A" }, { beat / 2, "B" } };
  3060. ne::insertTime (clips, markers, 2 * beat, 4 * beat);
  3061. CHECK (clips[0].start == 0 && clips[1].start == 8 * beat && clips[2].start == beat && markers[0].tick == 9 * beat
  3062. && markers[1].tick == beat / 2);
  3063. std::vector<lynx::Clip> d { { 0, 0, 0, 2 * beat, 0 }, // before: kept
  3064. { 0, 1, 3 * beat, beat, 0 }, // inside: deleted
  3065. { 0, 2, beat, 6 * beat, 0 }, // spans the cut: head + tail
  3066. { 0, 3, 3 * beat, 4 * beat, 0 }, // tail outside: trimmed and moved
  3067. { 0, 4, 8 * beat, beat, 0 } }; // after: moved left
  3068. std::vector<lynx::Marker> dm { { 3 * beat, "in" }, { 9 * beat, "after" } };
  3069. ne::deleteTime (d, dm, 2 * beat, 5 * beat);
  3070. CHECK (d.size() == 5);
  3071. CHECK (d[1].track == 2 && d[1].start == beat && d[1].length == beat);
  3072. CHECK (d[2].track == 2 && d[2].start == 2 * beat && d[2].offset == 4 * beat && d[2].length == 2 * beat);
  3073. CHECK (d[3].track == 3 && d[3].start == 2 * beat && d[3].offset == 2 * beat && d[3].length == 2 * beat);
  3074. CHECK (d[4].start == 5 * beat && dm.size() == 1 && dm[0].tick == 6 * beat);
  3075. // time selection: overlapping clips; Ctrl+B repeats what starts inside it after itself
  3076. std::vector<lynx::Clip> r { { 0, 0, 0, beat, 0 }, { 0, 1, beat, 2 * beat, 0 }, { 0, 0, 4 * beat, beat, 0 } };
  3077. CHECK ((ne::clipsInTime (r, beat / 2, 2 * beat) == std::vector<int> { 0, 1 }));
  3078. const auto added = ne::repeatTime (r, 0, 4 * beat, {});
  3079. CHECK (added.size() == 2 && r[3].start == 4 * beat && r[4].start == 5 * beat && r[4].track == 1);
  3080. CHECK (ne::repeatTime (r, 0, 2 * beat, { 2 }).size() == 1 && r.back().start == 6 * beat);
  3081. }
  3082. TEST (recorder_builds_notes_in_pattern_and_song_mode)
  3083. {
  3084. auto song = lynx::Song::makeDefault();
  3085. const auto loop = song.patterns[0].effectiveLength (4); // 1 bar = 3840
  3086. lynx::NoteRecorder r;
  3087. r.add (song, { 100.0, 4, 60, 0.5f, true }); // no take: ignored
  3088. CHECK (r.takeFinished().empty());
  3089. r.begin (loop);
  3090. r.add (song, { 4000.0, 4, 60, 0.5f, true }); // second loop pass
  3091. r.add (song, { 4480.0, 4, 60, 0.0f, false });
  3092. r.add (song, { 5000.0, 4, 64, 0.9f, true }); // held until stop
  3093. r.end (song, 5240.0);
  3094. const auto notes = r.takeFinished();
  3095. CHECK (notes.size() == 2);
  3096. CHECK (notes[0].start == 4000 - 3840 && notes[0].length == 480 && notes[0].velocity == 0.5f && notes[0].channel == 4);
  3097. CHECK (notes[1].key == 64 && notes[1].start == 5000 - 3840 && notes[1].length == 240);
  3098. // song mode: position inside the current pattern's clip (with offset)
  3099. song.mode = lynx::PlayMode::song;
  3100. song.playlist = { { 0, 0, 7680, 3840, 960 } };
  3101. CHECK (lynx::patternPositionForTick (song, 7680.0 + 100.0, loop) == 1060);
  3102. CHECK (lynx::patternPositionForTick (song, 100.0, loop) == 100); // outside the clip: like loop
  3103. }
  3104. TEST (automation_curve_and_playback)
  3105. {
  3106. lynx::Automation a;
  3107. a.points = { { 0, 0.0f }, { 960, 1.0f }, { 1920, 0.5f, 0.0f } };
  3108. CHECK (a.valueAt (-10.0) == 0.0f && a.valueAt (480.0) == 0.5f && a.valueAt (5000.0) == 0.5f);
  3109. CHECK (a.length() == 1920);
  3110. a.points[0].tension = 1.0f; // curve: starts slow
  3111. CHECK (a.valueAt (480.0) < 0.2f && a.valueAt (480.0) > 0.0f);
  3112. // automated Master: silence in the first bar, sound in the second, and the last value
  3113. // keeps applying after the automation clip ends
  3114. auto song = lynx::Song::makeDefault();
  3115. song.bpm = 120.0;
  3116. song.mode = lynx::PlayMode::song;
  3117. const auto bar = (std::int64_t) lynx::ppq * 4;
  3118. for (int b = 0; b < 3; ++b)
  3119. song.playlist.push_back ({ 0, 0, bar * b, bar, 0 });
  3120. lynx::Automation master;
  3121. master.target = { lynx::AutomationTargetKind::mixerVolume, 0 };
  3122. master.points = { { 0, 0.0f }, { bar - 1, 0.0f }, { bar, 0.8f } };
  3123. song.automations.push_back (master);
  3124. lynx::Clip ac;
  3125. ac.kind = lynx::ClipKind::automation;
  3126. ac.automation = 0;
  3127. ac.track = 1;
  3128. ac.length = bar + bar / 2;
  3129. song.playlist.push_back (ac);
  3130. const double sr = 48000.0;
  3131. auto state = lynx::RackState::build (song, nullptr, sr);
  3132. CHECK (state->hasAutomation && state->mixerVolumeAuto[0] == 0 && state->automationClips[0].size() == 1);
  3133. lynx::RackRenderer r;
  3134. r.prepare (sr, 512);
  3135. std::vector<float> l (512), rr (512);
  3136. const auto tps = lynx::ticksPerSample (song.bpm, sr);
  3137. float peakBar1 = 0.0f, peakBar2 = 0.0f, peakBar3 = 0.0f;
  3138. for (double tick = 0.0; tick < (double) (bar * 3); tick += 512 * tps)
  3139. {
  3140. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  3141. auto& peak = tick < (double) bar - 512 * tps ? peakBar1 : tick < (double) bar * 2 ? peakBar2 : peakBar3;
  3142. for (auto v : l)
  3143. peak = std::max (peak, std::abs (v));
  3144. }
  3145. CHECK (peakBar1 < 1.0e-6f);
  3146. CHECK (peakBar2 > 0.05f);
  3147. CHECK (peakBar3 > 0.05f); // after the clip: keeps the last value
  3148. // target removed: automation disappears from the tables
  3149. song.removeChannel (0);
  3150. song.automations[0].target = { lynx::AutomationTargetKind::channelVolume, 0 };
  3151. song.removeChannel (0);
  3152. CHECK (song.automations[0].target.kind == lynx::AutomationTargetKind::none);
  3153. song.removeAutomation (0);
  3154. CHECK (song.automations.empty() && song.playlist.size() == 3);
  3155. }
  3156. TEST (mixer_sends_between_inserts)
  3157. {
  3158. // insert 1 goes only to 3; 3 goes to the Master: same sum (0.5 + 0.5)
  3159. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.setRoute (1, 3, true); s.setRoute (1, 0, false); }) - 1.0f) < 1e-4f);
  3160. // send at 50% and muted destination
  3161. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.setRoute (1, 3, true, 0.5f); s.setRoute (1, 0, false); }) - 0.75f) < 1e-4f);
  3162. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.setRoute (1, 3, true); s.setRoute (1, 0, false); s.mixer[3].muted = true; }) - 0.5f) < 1e-4f);
  3163. // going to the Master and to 3: the signal doubles
  3164. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.setRoute (1, 3, true); }) - 1.5f) < 1e-4f);
  3165. // solo on 3 lets what reaches it sound (insert 1), but not 2
  3166. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.setRoute (1, 3, true); s.setRoute (1, 0, false); s.mixer[3].solo = true; }) - 0.5f) < 1e-4f);
  3167. // solo on 1 lets the path to the Master (3) sound
  3168. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.setRoute (1, 3, true); s.setRoute (1, 0, false); s.mixer[1].solo = true; }) - 0.5f) < 1e-4f);
  3169. // order and cycles
  3170. auto song = lynx::Song::makeDefault();
  3171. song.setRoute (4, 2, true);
  3172. song.setRoute (2, 1, true);
  3173. CHECK (! song.canRoute (1, 4) && ! song.canRoute (1, 2) && song.canRoute (1, 5));
  3174. song.setRoute (1, 4, true); // ignored: would create a cycle
  3175. CHECK (! song.routes (1, 4));
  3176. const auto order = song.mixerOrder();
  3177. const auto pos = [&] (int t) { return std::find (order.begin(), order.end(), t) - order.begin(); };
  3178. CHECK ((int) order.size() == (int) song.mixer.size() - 1);
  3179. CHECK (pos (4) < pos (2) && pos (2) < pos (1));
  3180. song.setRoute (4, 2, false);
  3181. CHECK (! song.routes (4, 2) && song.routes (4, 0));
  3182. }
  3183. namespace
  3184. {
  3185. // Test effect: delays the signal by `latency` samples and reports that latency (like a lookahead plugin).
  3186. class LatentEffect final : public lynx::Effect
  3187. {
  3188. public:
  3189. explicit LatentEffect (int samples) : latency (samples), line (samples) {}
  3190. void prepare (double) noexcept override {}
  3191. void reset() noexcept override {}
  3192. void process (float* l, float* r, int n, const lynx::EffectParams&, double) noexcept override { line.process (l, r, n); }
  3193. int latencySamples() const noexcept override { return latency; }
  3194. private:
  3195. int latency;
  3196. lynx::DelayLine line;
  3197. };
  3198. } // namespace
  3199. TEST (delay_line_mix_into_matches_process_and_drains_tail)
  3200. {
  3201. // mixInto = process over source*level, added to the destination; in stretches that cross the ring
  3202. lynx::DelayLine a (37), b (37);
  3203. std::vector<float> sl (300), sr (300), dl (300, 0.5f), dr (300, -0.5f), xl (300), xr (300);
  3204. for (int i = 0; i < 300; ++i)
  3205. {
  3206. sl[(std::size_t) i] = (float) std::sin (i * 0.1);
  3207. sr[(std::size_t) i] = (float) std::cos (i * 0.07);
  3208. }
  3209. for (int start = 0; start < 300; start += 100)
  3210. {
  3211. b.mixInto (sl.data() + start, sr.data() + start, 0.25f, dl.data() + start, dr.data() + start, 100);
  3212. for (int i = start; i < start + 100; ++i)
  3213. {
  3214. xl[(std::size_t) i] = sl[(std::size_t) i] * 0.25f;
  3215. xr[(std::size_t) i] = sr[(std::size_t) i] * 0.25f;
  3216. }
  3217. a.process (xl.data() + start, xr.data() + start, 100);
  3218. }
  3219. float worst = 0.0f;
  3220. for (int i = 0; i < 300; ++i)
  3221. worst = std::max ({ worst, std::abs (dl[(std::size_t) i] - 0.5f - xl[(std::size_t) i]),
  3222. std::abs (dr[(std::size_t) i] + 0.5f - xr[(std::size_t) i]) });
  3223. CHECK (worst < 1e-6f);
  3224. // silenced source: the tail still in the line comes out, then nothing remains
  3225. std::vector<float> tl (64, 0.0f), tr (64, 0.0f);
  3226. b.mixInto (nullptr, nullptr, 1.0f, tl.data(), tr.data(), 64);
  3227. CHECK (std::abs (tl[0] - sl[263] * 0.25f) < 1e-6f);
  3228. std::vector<float> zl (64, 0.0f), zr (64, 0.0f);
  3229. b.mixInto (nullptr, nullptr, 1.0f, zl.data(), zr.data(), 64);
  3230. CHECK (*std::max_element (zl.begin(), zl.end()) == 0.0f && *std::min_element (zl.begin(), zl.end()) == 0.0f);
  3231. }
  3232. TEST (limiter_lookahead_holds_ceiling_on_bursts)
  3233. {
  3234. // short bursts over a low floor: the sliding maximum must see each peak before it leaves
  3235. auto fx = lynx::makeEffect (lynx::EffectKind::limiter);
  3236. fx->prepare (48000.0);
  3237. auto slot = lynx::makeEffectSlot (lynx::EffectKind::limiter);
  3238. slot.params[2] = 0.0f; // 10 ms release
  3239. std::vector<float> l (48000), r (48000);
  3240. std::uint32_t seed = 1;
  3241. for (int i = 0; i < 48000; ++i)
  3242. {
  3243. seed = seed * 1664525u + 1013904223u;
  3244. const auto noise = ((float) (seed >> 8) / 16777216.0f - 0.5f) * 0.1f;
  3245. l[(std::size_t) i] = noise + ((i % 9973) < 3 ? 3.0f : 0.0f);
  3246. r[(std::size_t) i] = -noise;
  3247. }
  3248. for (int i = 0; i < 48000; i += 333)
  3249. fx->process (l.data() + i, r.data() + i, std::min (333, 48000 - i), slot.params, 120.0);
  3250. float peak = 0.0f, quiet = 0.0f;
  3251. for (int i = 0; i < 48000; ++i)
  3252. peak = std::max (peak, std::abs (l[(std::size_t) i]));
  3253. for (int i = 9973 * 2 + 2000; i < 9973 * 2 + 2400; ++i) // 40 ms after the burst the gain has already recovered
  3254. quiet = std::max (quiet, std::abs (r[(std::size_t) i]));
  3255. const auto ceiling = 1.0f; // the default ceiling is at 0 dBFS or below
  3256. CHECK (peak <= ceiling + 1e-5f);
  3257. CHECK (quiet > 0.03f);
  3258. }
  3259. TEST (pdc_aligns_paths_through_latent_effects)
  3260. {
  3261. // plan: channel 0 -> insert 1 (effect of 100) -> insert 3; channel 1 -> insert 2 -> Master
  3262. lynx::Song s;
  3263. s.mixer = lynx::Song::defaultMixer (4);
  3264. s.channels.resize (3);
  3265. s.channels[0].mixerTrack = 1;
  3266. s.channels[1].mixerTrack = 2;
  3267. s.channels[2].mixerTrack = 3;
  3268. s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::eq));
  3269. s.setRoute (1, 3, true);
  3270. s.setRoute (1, 0, false);
  3271. auto plan = lynx::computePdc (s, { 0, 0, 30 }, { {}, { 100 } });
  3272. CHECK (plan.inAlign[1] == 0 && plan.outLat[1] == 100);
  3273. CHECK (plan.inAlign[3] == 100 && plan.channelDelay[2] == 70); // instrument of 30 on insert 3
  3274. CHECK (plan.sendDelay[1][1] == 0); // the slowest path isn't delayed
  3275. CHECK (plan.sendDelay[2][0] == 100 && plan.sendDelay[3][0] == 0 && plan.total == 100);
  3276. // bypass zeroes the slot's latency
  3277. s.mixer[1].effects[0].enabled = false;
  3278. CHECK (lynx::computePdc (s, { 0, 0, 30 }, { {}, { 100 } }).total == 30);
  3279. // rendered: two impulses played together come out together
  3280. lynx::Song r;
  3281. r.mixer = lynx::Song::defaultMixer (2);
  3282. for (int i = 0; i < 2; ++i)
  3283. {
  3284. lynx::ChannelDef c;
  3285. c.instrument = lynx::InstrumentKind::sampler;
  3286. c.samplePath = "impulso";
  3287. c.volume = 1.0f;
  3288. c.mixerTrack = i + 1;
  3289. r.channels.push_back (c);
  3290. }
  3291. r.patterns.emplace_back();
  3292. lynx::EffectSlot fx;
  3293. fx.kind = lynx::EffectKind::plugin;
  3294. fx.plugin.id = "latente";
  3295. r.mixer[1].effects.push_back (fx);
  3296. lynx::RackState::Factories f;
  3297. f.samples = [] (const std::string&) {
  3298. auto d = std::make_shared<lynx::SampleData>();
  3299. d->left.assign (64, 0.0f);
  3300. d->left[0] = 1.0f;
  3301. return std::shared_ptr<const lynx::SampleData> (d);
  3302. };
  3303. f.pluginEffects = [] (const lynx::PluginRef&, double) -> std::shared_ptr<lynx::Effect> { return std::make_shared<LatentEffect> (100); };
  3304. auto state = lynx::RackState::build (r, nullptr, 48000.0, f);
  3305. CHECK (state->pdc.total == 100 && state->sendDelays[2][0] != nullptr && state->sendDelays[2][0]->length() == 100);
  3306. lynx::RackRenderer renderer;
  3307. renderer.prepare (48000.0, 256);
  3308. lynx::LiveEventQueue live;
  3309. for (int ch = 0; ch < 2; ++ch)
  3310. {
  3311. lynx::NoteEvent on;
  3312. on.channel = ch;
  3313. on.key = 60;
  3314. on.velocity = 1.0f;
  3315. live.push (on);
  3316. }
  3317. std::vector<float> l (256), rr (256);
  3318. renderer.process (state.get(), false, 0.0, 256, l.data(), rr.data(), &live);
  3319. int first = -1;
  3320. for (int i = 0; i < 256 && first < 0; ++i)
  3321. if (std::abs (l[(std::size_t) i]) > 0.01f)
  3322. first = i;
  3323. CHECK (first == 100 && std::abs (l[100] - 2.0f) < 1e-3f); // both impulses arrive together, summed
  3324. // editing without changing latencies reuses the lines
  3325. r.channels[0].volume = 0.5f;
  3326. auto next = lynx::RackState::build (r, state.get(), 48000.0, f);
  3327. CHECK (next->sendDelays[2][0] == state->sendDelays[2][0]);
  3328. }
  3329. TEST (mixer_mute_fades_instead_of_clicking)
  3330. {
  3331. lynx::Song s;
  3332. s.mixer = lynx::Song::defaultMixer (2);
  3333. lynx::ChannelDef c;
  3334. c.instrument = lynx::InstrumentKind::sampler;
  3335. c.samplePath = "dc";
  3336. c.volume = 1.0f;
  3337. c.mixerTrack = 1;
  3338. s.channels.push_back (c);
  3339. s.patterns.emplace_back();
  3340. auto provider = [] (const std::string&) {
  3341. auto d = std::make_shared<lynx::SampleData>();
  3342. d->left.assign (48000, 0.5f);
  3343. return std::shared_ptr<const lynx::SampleData> (d);
  3344. };
  3345. auto on = lynx::RackState::build (s, nullptr, 48000.0, provider);
  3346. s.mixer[1].muted = true;
  3347. auto off = lynx::RackState::build (s, on.get(), 48000.0, provider);
  3348. lynx::RackRenderer r;
  3349. r.prepare (48000.0, 256);
  3350. lynx::LiveEventQueue live;
  3351. lynx::NoteEvent note;
  3352. note.velocity = 1.0f;
  3353. live.push (note);
  3354. std::vector<float> l (256), rr (256);
  3355. r.process (on.get(), false, 0.0, 256, l.data(), rr.data(), &live);
  3356. CHECK (std::abs (l[255] - 0.5f) < 1e-3f);
  3357. r.process (off.get(), false, 0.0, 256, l.data(), rr.data());
  3358. CHECK (l[0] > 0.45f && l[128] > 0.2f && l[128] < 0.3f && std::abs (l[255]) < 1e-6f); // ramp down to zero
  3359. r.process (off.get(), false, 0.0, 256, l.data(), rr.data());
  3360. CHECK (std::abs (l[0]) < 1e-9f);
  3361. }
  3362. TEST (dither_quantizes_to_lsb_grid_with_small_error)
  3363. {
  3364. lynx::Dither d (16);
  3365. std::vector<float> x (4800);
  3366. for (std::size_t i = 0; i < x.size(); ++i)
  3367. x[i] = 0.25f * std::sin ((float) i * 0.05f);
  3368. auto y = x;
  3369. d.process (y.data(), (int) y.size(), 0);
  3370. double errorSum = 0.0;
  3371. bool onGrid = true;
  3372. for (std::size_t i = 0; i < x.size(); ++i)
  3373. {
  3374. const auto steps = y[i] * 32768.0f;
  3375. onGrid = onGrid && std::abs (steps - std::round (steps)) < 1e-3f;
  3376. errorSum += std::abs (y[i] - x[i]);
  3377. }
  3378. CHECK (onGrid);
  3379. CHECK (errorSum / (double) x.size() < 4.0 / 32768.0); // a few LSBs of noise on average
  3380. }
  3381. TEST (parallel_rendering_matches_sequential)
  3382. {
  3383. // 32 channels (worth parallelizing), inserts with chained sends
  3384. auto song = lynx::Song::makeDefault();
  3385. song.mixer = lynx::Song::defaultMixer (16);
  3386. for (int i = 5; i < 32; ++i)
  3387. {
  3388. lynx::ChannelDef c;
  3389. c.instrument = i % 2 ? lynx::InstrumentKind::synth : lynx::InstrumentKind::hat;
  3390. c.mixerTrack = 1 + i % 12;
  3391. c.volume = 0.3f;
  3392. song.channels.push_back (c);
  3393. for (int step = i % 4; step < 16; step += 3)
  3394. song.patterns[0].notes.push_back ({ (std::int64_t) step * lynx::ticksPerStep, 200, i, 48 + i, 0.7f });
  3395. }
  3396. song.patterns[0].sortNotes();
  3397. song.setRoute (3, 7, true, 0.6f);
  3398. song.setRoute (7, 9, true, 0.5f);
  3399. song.setRoute (2, 9, true);
  3400. song.mixer[9].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::reverb));
  3401. auto seqState = lynx::RackState::build (song, nullptr, 48000.0);
  3402. auto parState = lynx::RackState::build (song, nullptr, 48000.0);
  3403. CHECK (parState->parallel && parState->mixerLayers.size() == 3);
  3404. lynx::WorkerPool pool (3);
  3405. lynx::RackRenderer seq, par;
  3406. seq.prepare (48000.0, 512);
  3407. par.prepare (48000.0, 512);
  3408. par.setWorkerPool (&pool);
  3409. std::vector<float> l1 (512), r1 (512), l2 (512), r2 (512);
  3410. const auto tps = lynx::ticksPerSample (song.bpm, 48000.0);
  3411. bool same = true;
  3412. float peak = 0.0f;
  3413. for (int block = 0; block < 200; ++block)
  3414. {
  3415. seq.process (seqState.get(), true, block * 512 * tps, 512, l1.data(), r1.data());
  3416. par.process (parState.get(), true, block * 512 * tps, 512, l2.data(), r2.data());
  3417. same = same && l1 == l2 && r1 == r2;
  3418. for (auto v : l1)
  3419. peak = std::max (peak, std::abs (v));
  3420. }
  3421. CHECK (same);
  3422. CHECK (peak > 0.05f);
  3423. // the pool handles many small rounds in a row
  3424. std::atomic<int> sum { 0 };
  3425. auto add = [&sum] (int i) { sum.fetch_add (i + 1); };
  3426. for (int round = 0; round < 2000; ++round)
  3427. pool.parallelFor (5, add);
  3428. CHECK (sum.load() == 2000 * 15);
  3429. }
  3430. TEST (arrangements_switch_and_keep_clip_indices)
  3431. {
  3432. auto s = lynx::Song::makeDefault();
  3433. s.patterns.emplace_back().name = "B";
  3434. s.playlist = { { 1, 0, 0, 960, 0 } };
  3435. s.loopEnd = 960;
  3436. CHECK (s.arrangements.size() == 1 && s.currentArrangement == 0);
  3437. const auto second = s.addArrangement ("Versão curta", true);
  3438. CHECK (second == 1 && s.currentArrangement == 1 && s.playlist.size() == 1 && s.loopEnd == 960);
  3439. s.playlist.push_back ({ 0, 1, 960, 960, 0 });
  3440. s.loopEnd = 0;
  3441. s.selectArrangement (0);
  3442. CHECK (s.playlist.size() == 1 && s.loopEnd == 960 && s.arrangements[1].clips.size() == 2);
  3443. // removing pattern 0 fixes the clips stored in the other arrangement
  3444. s.removePattern (0);
  3445. CHECK (s.playlist.size() == 1 && s.playlist[0].pattern == 0);
  3446. CHECK (s.arrangements[1].clips.size() == 1 && s.arrangements[1].clips[0].pattern == 0);
  3447. s.removeArrangement (0);
  3448. CHECK (s.arrangements.size() == 1 && s.currentArrangement == 0 && s.playlist.size() == 1 && s.loopEnd == 0);
  3449. }
  3450. namespace
  3451. {
  3452. // Test effect that inverts the signal and counts how many times it processed.
  3453. class CountingInverter final : public lynx::Effect
  3454. {
  3455. public:
  3456. void prepare (double) noexcept override {}
  3457. void reset() noexcept override {}
  3458. void process (float* l, float* r, int n, const lynx::EffectParams&, double) noexcept override
  3459. {
  3460. ++calls;
  3461. for (int i = 0; i < n; ++i)
  3462. {
  3463. l[i] = -l[i];
  3464. r[i] = -r[i];
  3465. }
  3466. }
  3467. int calls = 0;
  3468. };
  3469. } // namespace
  3470. TEST (keyboard_controller_outputs_key_value)
  3471. {
  3472. std::vector<std::uint8_t> blob (554, 0);
  3473. const std::uint32_t version = 3;
  3474. std::memcpy (blob.data(), &version, 4);
  3475. const float key60 = 0.7f, off = 0.2f;
  3476. std::memcpy (blob.data() + 12 + 60 * 4, &key60, 4);
  3477. std::memcpy (blob.data() + 548, &off, 4);
  3478. blob[552] = 1; // auto release
  3479. lynx::ChannelDef c;
  3480. c.instrument = lynx::InstrumentKind::controller;
  3481. c.controllerState = blob;
  3482. auto inst = lynx::makeInstrument (lynx::InstrumentKind::controller);
  3483. inst->prepare (48000.0);
  3484. inst->configure (c, 120.0);
  3485. std::vector<float> l (64), r (64);
  3486. inst->noteOn (60, 1.0f);
  3487. inst->render (l.data(), r.data(), 64, 1.0f, 1.0f);
  3488. CHECK (std::abs (inst->controlOutput (0) - 0.7f) < 1e-6f);
  3489. inst->noteOff (60);
  3490. CHECK (std::abs (inst->controlOutput (0) - 0.2f) < 1e-6f);
  3491. }
  3492. TEST (envelope_controller_ducks_on_each_note)
  3493. {
  3494. // a unipolar articulator like "Basic Sidechain": base 0.05, drops to 0 on the note and rises to 1 in 0.3 s
  3495. lynx::ControllerArticulator a;
  3496. a.envOn = true;
  3497. a.base = 0.05f;
  3498. a.envLevel = 1.0f;
  3499. a.count = 3;
  3500. a.time = { 0.0f, 0.2f, 0.3f };
  3501. a.level = { 0.0f, 0.75f, 1.0f };
  3502. CHECK (std::abs (lynx::controllerValue (a, 0.0, -1.0) - 0.05f) < 1e-4f);
  3503. CHECK (std::abs (lynx::controllerValue (a, 0.1, -1.0) - 0.425f) < 1e-3f);
  3504. CHECK (lynx::controllerValue (a, 1.0, -1.0) > 0.99f); // no sustain: runs to the end and stays
  3505. a.sustain = 1;
  3506. CHECK (std::abs (lynx::controllerValue (a, 1.0, -1.0) - 0.8f) < 1e-3f); // held at sustain
  3507. CHECK (lynx::controllerValue (a, 1.0, 0.5) > 0.99f); // released: continues to the end
  3508. a.bipolar = true;
  3509. a.base = 0.5f;
  3510. a.sustain = -1;
  3511. CHECK (std::abs (lynx::controllerValue (a, 0.0, -1.0) - 0.0f) < 1e-4f); // bipolar: 0.5 + (0 − 0.5)
  3512. }
  3513. TEST (peak_controller_drives_live_automation)
  3514. {
  3515. // track 1: source (DC 0.5) with Peak Controller; track 2: DC 0.5 with volume linked to the controller
  3516. auto render = [] (bool linked) {
  3517. lynx::Song s;
  3518. s.mixer = lynx::Song::defaultMixer (2);
  3519. for (int t = 1; t <= 2; ++t)
  3520. {
  3521. lynx::ChannelDef c;
  3522. c.instrument = lynx::InstrumentKind::sampler;
  3523. c.samplePath = "dc";
  3524. c.volume = 1.0f;
  3525. c.mixerTrack = t;
  3526. s.channels.push_back (c);
  3527. }
  3528. s.patterns.emplace_back();
  3529. auto peak = lynx::makeEffectSlot (lynx::EffectKind::peakController);
  3530. peak.params[0] = 1.0f; // base 1
  3531. peak.params[1] = 0.0f; // amount −1: 1 − peak
  3532. peak.params[2] = 0.5f; // no tension
  3533. s.mixer[1].effects.push_back (peak);
  3534. if (linked)
  3535. {
  3536. lynx::Automation a;
  3537. a.name = "Peak";
  3538. a.target = { lynx::AutomationTargetKind::mixerVolume, 2 };
  3539. a.source = { 1, 0, 0 };
  3540. s.automations.push_back (a);
  3541. }
  3542. lynx::RackState::Factories f;
  3543. f.samples = [] (const std::string&) {
  3544. auto d = std::make_shared<lynx::SampleData>();
  3545. d->left.assign (48000, 0.5f);
  3546. return std::shared_ptr<const lynx::SampleData> (d);
  3547. };
  3548. auto state = lynx::RackState::build (s, nullptr, 48000.0, f);
  3549. lynx::RackRenderer r;
  3550. r.prepare (48000.0, 512);
  3551. lynx::LiveEventQueue live;
  3552. for (int ch = 0; ch < 2; ++ch)
  3553. {
  3554. lynx::NoteEvent on;
  3555. on.channel = ch;
  3556. on.velocity = 1.0f;
  3557. live.push (on);
  3558. }
  3559. std::vector<float> l (4800), rr (4800);
  3560. r.process (state.get(), false, 0.0, 4800, l.data(), rr.data(), &live);
  3561. return l[4000];
  3562. };
  3563. const auto free = render (false), ducked = render (true);
  3564. CHECK (std::isfinite (ducked) && ducked > 0.0f);
  3565. CHECK (ducked < free - 0.05f); // the 0.5 peak on track 1 lowers track 2's volume
  3566. }
  3567. TEST (effect_slot_dry_wet_and_smart_disable)
  3568. {
  3569. lynx::Song s;
  3570. s.mixer = lynx::Song::defaultMixer (1);
  3571. lynx::ChannelDef c;
  3572. c.instrument = lynx::InstrumentKind::sampler;
  3573. c.samplePath = "dc";
  3574. c.volume = 1.0f;
  3575. c.mixerTrack = 1;
  3576. s.channels.push_back (c);
  3577. s.patterns.emplace_back();
  3578. lynx::EffectSlot fx;
  3579. fx.kind = lynx::EffectKind::plugin;
  3580. fx.plugin.id = "inversor";
  3581. fx.mix = 0.25f; // 75% dry (+0.5) and 25% wet (-0.5) = +0.25
  3582. s.mixer[1].effects.push_back (fx);
  3583. auto inverter = std::make_shared<CountingInverter>();
  3584. lynx::RackState::Factories f;
  3585. f.samples = [] (const std::string&) {
  3586. auto d = std::make_shared<lynx::SampleData>();
  3587. d->left.assign (4800, 0.5f);
  3588. return std::shared_ptr<const lynx::SampleData> (d);
  3589. };
  3590. f.pluginEffects = [inverter] (const lynx::PluginRef&, double) -> std::shared_ptr<lynx::Effect> { return inverter; };
  3591. auto state = lynx::RackState::build (s, nullptr, 48000.0, f);
  3592. lynx::RackRenderer r;
  3593. r.prepare (48000.0, 512);
  3594. lynx::LiveEventQueue live;
  3595. lynx::NoteEvent on;
  3596. on.velocity = 1.0f;
  3597. live.push (on);
  3598. std::vector<float> l (480), rr (480);
  3599. r.process (state.get(), false, 0.0, 480, l.data(), rr.data(), &live);
  3600. CHECK (std::abs (l[100] - 0.25f) < 1e-4f);
  3601. // after the sample ends: 4 s of silence and the plugin stops being called
  3602. for (int i = 0; i < 100 * 6; ++i) // 6 s
  3603. r.process (state.get(), false, 0.0, 480, l.data(), rr.data());
  3604. const auto callsAfterSilence = inverter->calls;
  3605. for (int i = 0; i < 100; ++i)
  3606. r.process (state.get(), false, 0.0, 480, l.data(), rr.data());
  3607. CHECK (inverter->calls == callsAfterSilence);
  3608. CHECK (callsAfterSilence < 100 * 6);
  3609. // sound again: processing resumes in the same block
  3610. live.push (on);
  3611. r.process (state.get(), false, 0.0, 480, l.data(), rr.data(), &live);
  3612. CHECK (inverter->calls == callsAfterSilence + 1 && std::abs (l[100] - 0.25f) < 1e-4f);
  3613. }
  3614. TEST (swing_delays_offbeat_sixteenths)
  3615. {
  3616. CHECK (lynx::swingDelay (0, 1.0f) == 0);
  3617. CHECK (lynx::swingDelay (lynx::ticksPerStep, 1.0f) == lynx::ticksPerStep / 2);
  3618. CHECK (lynx::swingDelay (lynx::ticksPerStep * 2, 1.0f) == 0);
  3619. CHECK (lynx::swingDelay (lynx::ticksPerStep + 10, 1.0f) == (lynx::ticksPerStep - 20) / 2); // off the grid: triangular weight (FL)
  3620. CHECK (lynx::swingDelay (lynx::ticksPerStep, 1.0f, 0.5f) == lynx::ticksPerStep / 4); // channel mix
  3621. CHECK (lynx::swingDelay (lynx::ticksPerStep * 3, 0.5f) == lynx::ticksPerStep / 4);
  3622. lynx::Pattern p;
  3623. p.notes = { { 0, 100, 0, 60 }, { lynx::ticksPerStep, 100, 0, 62 } };
  3624. lynx::EventBuffer ev;
  3625. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  3626. lynx::schedulePatternLoop (p, p.effectiveLength (4), 0.0, 12000, tps, ev, 1.0f);
  3627. int onOffset = -1;
  3628. for (auto& e : ev)
  3629. if (e.type == lynx::NoteEvent::Type::on && e.key == 62)
  3630. onOffset = e.sampleOffset;
  3631. CHECK (onOffset == (int) std::floor ((lynx::ticksPerStep * 1.5) / tps));
  3632. }
  3633. TEST (sampler_settings_pitch_reverse_envelope_cut)
  3634. {
  3635. auto ramp = std::make_shared<lynx::SampleData>();
  3636. for (int i = 0; i < 48000; ++i)
  3637. ramp->left.push_back ((float) i / 48000.0f); // ramp: the value tells where the read position is
  3638. ramp->sampleRate = 48000.0;
  3639. auto play = [&] (const lynx::SamplerSettings& s, int key, int frames, bool releaseAfterHalf) {
  3640. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  3641. inst->prepare (48000.0);
  3642. lynx::ChannelDef c;
  3643. c.sampler = s;
  3644. inst->configure (c, 120.0);
  3645. inst->noteOn (key, 1.0f);
  3646. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  3647. inst->render (l.data(), r.data(), frames / 2, 1.0f, 1.0f);
  3648. if (releaseAfterHalf)
  3649. inst->noteOff (key);
  3650. inst->render (l.data() + frames / 2, r.data() + frames / 2, frames - frames / 2, 1.0f, 1.0f);
  3651. return l;
  3652. };
  3653. // +12 semitones: reads twice as fast
  3654. lynx::SamplerSettings up;
  3655. up.pitch = 12.0f;
  3656. CHECK (std::abs (play (up, 60, 1000, false)[999] - 2.0f * 999.0f / 48000.0f) < 1e-3f);
  3657. // reversed: starts from the end
  3658. lynx::SamplerSettings back;
  3659. back.reverse = true;
  3660. CHECK (play (back, 60, 100, false)[10] > 0.99f);
  3661. // 10 ms attack: starts silent and reaches full level
  3662. lynx::SamplerSettings slow;
  3663. slow.attack = 0.01f;
  3664. const auto a = play (slow, 60, 2000, false);
  3665. CHECK (a[10] < 0.2f * (10.0f / 48000.0f) + 1e-6f && std::abs (a[1500] - 1500.0f / 48000.0f) < 1e-4f);
  3666. // 5 ms release: gone right after release; without release it plays in full
  3667. lynx::SamplerSettings rel;
  3668. rel.release = 0.005f;
  3669. CHECK (play (rel, 60, 2000, true)[1999] == 0.0f);
  3670. CHECK (play (lynx::SamplerSettings {}, 60, 2000, true)[1999] > 0.0f);
  3671. // cut itself: the second note cuts the first (one voice remains)
  3672. lynx::SamplerSettings cut;
  3673. cut.cut = true;
  3674. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  3675. inst->prepare (48000.0);
  3676. lynx::ChannelDef cutChannel;
  3677. cutChannel.sampler = cut;
  3678. inst->configure (cutChannel, 120.0);
  3679. inst->noteOn (60, 1.0f);
  3680. std::vector<float> l (2000), r (2000);
  3681. inst->render (l.data(), r.data(), 1000, 1.0f, 1.0f);
  3682. inst->noteOn (60, 1.0f);
  3683. std::fill (l.begin(), l.end(), 0.0f);
  3684. inst->render (l.data(), r.data(), 2000, 1.0f, 1.0f);
  3685. CHECK (std::abs (l[1999] - 1999.0f / 48000.0f) < 1e-4f); // only the new note
  3686. }
  3687. TEST (playlist_split_and_track_mute)
  3688. {
  3689. lynx::Clip c { 0, 3, 960, 3840, 480 };
  3690. const auto rest = lynx::splitClip (c, 2000);
  3691. CHECK (c.start == 960 && c.length == 1040 && c.offset == 480);
  3692. CHECK (rest.start == 2000 && rest.length == 2800 && rest.offset == 480 + 1040 && rest.track == 3);
  3693. auto s = lynx::Song::makeDefault();
  3694. s.mode = lynx::PlayMode::song;
  3695. s.playlist = { { 0, 0, 0, 3840, 0 } };
  3696. lynx::EventBuffer ev;
  3697. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  3698. lynx::scheduleSong (s, 0.0, 48000, tps, ev);
  3699. CHECK (ev.size() > 0);
  3700. s.playlistTracks.resize (1);
  3701. s.playlistTracks[0].muted = true;
  3702. ev.clear();
  3703. lynx::scheduleSong (s, 0.0, 48000, tps, ev);
  3704. CHECK (ev.size() == 0);
  3705. }
  3706. TEST (note_pan_pitch_and_mute)
  3707. {
  3708. lynx::Pattern p;
  3709. lynx::Note a { 0, 240, 0, 60 };
  3710. a.pan = -1.0f;
  3711. a.finePitch = 50.0f;
  3712. lynx::Note b { 240, 240, 0, 62 };
  3713. b.muted = true;
  3714. p.notes = { a, b };
  3715. lynx::EventBuffer ev;
  3716. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  3717. lynx::schedulePatternLoop (p, p.effectiveLength (4), 0.0, 48000, tps, ev);
  3718. int ons = 0;
  3719. for (auto& e : ev)
  3720. if (e.type == lynx::NoteEvent::Type::on)
  3721. {
  3722. ++ons;
  3723. CHECK (e.key == 60 && e.pan == -1.0f && e.cents == 50.0f);
  3724. }
  3725. CHECK (ons == 1); // the muted one doesn't play
  3726. // note pan in the sampler: fully left
  3727. auto dc = std::make_shared<lynx::SampleData>();
  3728. dc->left.assign (4800, 0.5f);
  3729. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, dc);
  3730. inst->prepare (48000.0);
  3731. inst->setNextNoteExpression (-1.0f, 0.0f);
  3732. inst->noteOn (60, 1.0f);
  3733. std::vector<float> l (100), r (100);
  3734. inst->render (l.data(), r.data(), 100, 1.0f, 1.0f);
  3735. CHECK (l[50] > 0.6f && std::abs (r[50]) < 1e-6f);
  3736. }
  3737. TEST (tempo_automation_changes_speed_and_duration)
  3738. {
  3739. auto song = lynx::Song::makeDefault();
  3740. song.bpm = 120.0;
  3741. song.mode = lynx::PlayMode::song;
  3742. const auto bar = (std::int64_t) lynx::ppq * 4;
  3743. song.playlist = { { 0, 0, 0, bar, 0 }, { 0, 0, bar, bar, 0 } };
  3744. lynx::Automation tempo;
  3745. tempo.target = { lynx::AutomationTargetKind::tempo, 0 };
  3746. const auto v120 = lynx::valueFromTempo (120.0), v240 = lynx::valueFromTempo (240.0);
  3747. tempo.points = { { 0, v120 }, { bar - 1, v120 }, { bar, v240 } }; // step: 120 -> 240 at bar 2
  3748. song.automations.push_back (tempo);
  3749. lynx::Clip clip;
  3750. clip.kind = lynx::ClipKind::automation;
  3751. clip.automation = 0;
  3752. clip.track = 1;
  3753. clip.length = bar * 2;
  3754. song.playlist.push_back (clip);
  3755. CHECK (std::abs (song.tempoAt (100.0) - 120.0) < 0.01 && std::abs (song.tempoAt ((double) bar + 100.0) - 240.0) < 0.01);
  3756. // 1 bar at 120 (2 s) + 1 at 240 (1 s)
  3757. CHECK (std::abs (song.secondsForTicks (bar * 2) - 3.0) < 0.01);
  3758. auto state = lynx::RackState::build (song, nullptr, 48000.0);
  3759. CHECK (state->tempoAutomation == 0);
  3760. lynx::RackRenderer r;
  3761. r.prepare (48000.0, 512);
  3762. std::vector<float> l (512), rr (512);
  3763. r.process (state.get(), true, 10.0, 512, l.data(), rr.data());
  3764. CHECK (std::abs (r.currentBpm() - 120.0) < 0.01);
  3765. r.process (state.get(), true, (double) bar + 10.0, 512, l.data(), rr.data());
  3766. CHECK (std::abs (r.currentBpm() - 240.0) < 0.01);
  3767. }
  3768. TEST (bounce_insert_song_and_apply)
  3769. {
  3770. auto s = lynx::Song::makeDefault();
  3771. s.setRoute (3, 7, true, 0.5f);
  3772. s.mixer[0].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::reverb));
  3773. s.mixer[2].solo = true;
  3774. const auto b = lynx::makeBounceSong (s, 3);
  3775. CHECK (b.mixer[3].solo && ! b.mixer[2].solo && b.mixer[3].toMaster && b.mixer[3].sends.empty());
  3776. CHECK (b.mixer[0].effects.empty() && b.mode == lynx::PlayMode::song);
  3777. const auto audible = b.soloAudible();
  3778. CHECK (audible[3] && ! audible[1] && ! audible[7]);
  3779. const auto channels = s.channels.size();
  3780. const auto inserts = s.mixer.size();
  3781. const auto created = lynx::applyBounce (s, 3, "C:/x.wav", 3840);
  3782. CHECK (created == (int) inserts && s.mixer.size() == inserts + 1 && s.mixer[3].muted);
  3783. CHECK (s.mixer[(std::size_t) created].sends.size() == 1 && s.mixer[(std::size_t) created].sends[0].target == 7);
  3784. CHECK (s.channels.size() == channels + 1 && s.channels.back().mixerTrack == created);
  3785. CHECK (s.playlist.back().kind == lynx::ClipKind::audio && s.playlist.back().length == 3840);
  3786. }
  3787. TEST (mixer_stereo_separation_phase_swap)
  3788. {
  3789. lynx::MixerTrack t;
  3790. std::vector<float> l { 1.0f }, r { 0.0f };
  3791. t.stereo = 1.0f; // mono
  3792. lynx::RackRenderer::applyStereoForTest (t, l.data(), r.data(), 1);
  3793. CHECK (std::abs (l[0] - 0.5f) < 1e-6f && std::abs (r[0] - 0.5f) < 1e-6f);
  3794. l = { 1.0f };
  3795. r = { 0.0f };
  3796. t.stereo = -1.0f; // doubled side: 1.5 L - 0.5 R
  3797. lynx::RackRenderer::applyStereoForTest (t, l.data(), r.data(), 1);
  3798. CHECK (std::abs (l[0] - 1.5f) < 1e-6f && std::abs (r[0] + 0.5f) < 1e-6f);
  3799. l = { 1.0f };
  3800. r = { 0.25f };
  3801. t.stereo = 0.0f;
  3802. t.swapChannels = true;
  3803. t.invertPhase = true;
  3804. lynx::RackRenderer::applyStereoForTest (t, l.data(), r.data(), 1);
  3805. CHECK (l[0] == -0.25f && r[0] == -1.0f);
  3806. }
  3807. TEST (effects_limiter_filter_distortion_chorus)
  3808. {
  3809. const double sr = 48000.0;
  3810. auto sine = [] (float hz, float amp, int n) {
  3811. std::vector<float> v ((std::size_t) n);
  3812. for (int i = 0; i < n; ++i)
  3813. v[(std::size_t) i] = amp * std::sin (2.0f * 3.14159265f * hz * (float) i / 48000.0f);
  3814. return v;
  3815. };
  3816. auto peak = [] (const std::vector<float>& v, int from) {
  3817. float p = 0.0f;
  3818. for (std::size_t i = (std::size_t) from; i < v.size(); ++i)
  3819. p = std::max (p, std::abs (v[i]));
  3820. return p;
  3821. };
  3822. // limiter: +12 dB on a 0.9 sine never exceeds the ceiling (-1 dB) and reports the latency
  3823. auto lim = lynx::makeEffect (lynx::EffectKind::limiter);
  3824. lim->prepare (sr);
  3825. auto slot = lynx::makeEffectSlot (lynx::EffectKind::limiter);
  3826. slot.params[0] = 11.0f / 12.0f; // -1 dB
  3827. slot.params[1] = 0.5f; // +12 dB
  3828. auto l = sine (100.0f, 0.9f, 48000), r = l;
  3829. lim->process (l.data(), r.data(), 48000, slot.params, 120.0);
  3830. CHECK (peak (l, 0) <= std::pow (10.0f, -1.0f / 20.0f) + 1e-4f);
  3831. CHECK (peak (l, 4800) > 0.8f);
  3832. CHECK (lim->latencySamples() == 72);
  3833. // low-pass filter at 500 Hz knocks down an 8 kHz sine
  3834. auto lp = lynx::makeEffect (lynx::EffectKind::filter);
  3835. lp->prepare (sr);
  3836. auto fs = lynx::makeEffectSlot (lynx::EffectKind::filter);
  3837. fs.params[1] = std::log (500.0f / 20.0f) / std::log (1000.0f);
  3838. l = sine (8000.0f, 1.0f, 9600);
  3839. r = l;
  3840. lp->process (l.data(), r.data(), 9600, fs.params, 120.0);
  3841. CHECK (peak (l, 4800) < 0.05f);
  3842. // distortion and chorus: finite, audible output
  3843. for (auto kind : { lynx::EffectKind::distortion, lynx::EffectKind::chorus })
  3844. {
  3845. auto fx = lynx::makeEffect (kind);
  3846. fx->prepare (sr);
  3847. auto ps = lynx::makeEffectSlot (kind);
  3848. l = sine (220.0f, 0.5f, 9600);
  3849. r = l;
  3850. fx->process (l.data(), r.data(), 9600, ps.params, 120.0);
  3851. bool finite = true;
  3852. for (auto v : l)
  3853. finite = finite && std::isfinite (v);
  3854. CHECK (finite && peak (l, 2400) > 0.1f && peak (l, 0) < 2.0f);
  3855. }
  3856. }
  3857. TEST (slide_notes_glide_without_retrigger)
  3858. {
  3859. // sampler with a ramp: the read speed doubles after a one-octave slide
  3860. auto ramp = std::make_shared<lynx::SampleData>();
  3861. for (int i = 0; i < 96000; ++i)
  3862. ramp->left.push_back ((float) i / 96000.0f);
  3863. ramp->sampleRate = 48000.0;
  3864. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  3865. inst->prepare (48000.0);
  3866. inst->noteOn (60, 1.0f);
  3867. std::vector<float> l (2000), r (2000);
  3868. inst->render (l.data(), r.data(), 1000, 1.0f, 1.0f);
  3869. const auto stepBefore = l[999] - l[998];
  3870. inst->slideTo (72, 0.0f, 100.0f);
  3871. std::fill (l.begin(), l.end(), 0.0f);
  3872. inst->render (l.data(), r.data(), 1000, 1.0f, 1.0f);
  3873. const auto stepAfter = l[999] - l[998];
  3874. CHECK (std::abs (stepAfter / stepBefore - 2.0f) < 0.01f);
  3875. // the sequencer sends "slide" (no off) for the slide note
  3876. lynx::Pattern p;
  3877. lynx::Note base { 0, 960, 0, 48 };
  3878. lynx::Note glide { 480, 240, 0, 55 };
  3879. glide.slide = true;
  3880. p.notes = { base, glide };
  3881. lynx::EventBuffer ev;
  3882. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  3883. lynx::schedulePatternLoop (p, p.effectiveLength (4), 0.0, 30000, tps, ev);
  3884. int ons = 0, offs = 0, slides = 0;
  3885. for (auto& e : ev)
  3886. {
  3887. ons += e.type == lynx::NoteEvent::Type::on;
  3888. offs += e.type == lynx::NoteEvent::Type::off;
  3889. if (e.type == lynx::NoteEvent::Type::slide)
  3890. {
  3891. ++slides;
  3892. CHECK (e.key == 55 && std::abs (e.slideSamples - 240.0f / (float) tps) < 1.0f);
  3893. }
  3894. }
  3895. CHECK (ons == 1 && offs == 1 && slides == 1);
  3896. }
  3897. TEST (synth_fm_phase_modulation)
  3898. {
  3899. auto render = [] (const lynx::SynthSettings& s) {
  3900. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  3901. inst->prepare (48000.0);
  3902. lynx::ChannelDef c;
  3903. c.synth = s;
  3904. inst->configure (c, 120.0);
  3905. inst->noteOn (69, 1.0f); // 440 Hz
  3906. std::vector<float> l (48000), r (48000);
  3907. inst->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  3908. return l;
  3909. };
  3910. // energy (Goertzel) at frequency f over frames [from, to)
  3911. auto energy = [] (const std::vector<float>& x, double f, int from, int to) {
  3912. const auto w = 2.0 * 3.141592653589793 * f / 48000.0, k = 2.0 * std::cos (w);
  3913. double s1 = 0.0, s2 = 0.0;
  3914. for (int i = from; i < to; ++i)
  3915. {
  3916. const auto s0 = x[(std::size_t) i] + k * s1 - s2;
  3917. s2 = s1;
  3918. s1 = s0;
  3919. }
  3920. return s1 * s1 + s2 * s2 - k * s1 * s2;
  3921. };
  3922. lynx::SynthSettings plain;
  3923. plain.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  3924. plain.osc[2] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  3925. plain.cutoff = 20000.0f;
  3926. auto fm = plain;
  3927. fm.fm = 1.0f;
  3928. const auto a = render (plain), b = render (fm);
  3929. // no FM: osc 3 adds (same pitch) and there's no 2nd harmonic; with FM the sidebands appear
  3930. CHECK (energy (a, 880.0, 4800, 24000) < 1e-3 * energy (a, 440.0, 4800, 24000));
  3931. CHECK (energy (b, 880.0, 4800, 24000) > 0.1 * energy (b, 440.0, 4800, 24000));
  3932. CHECK (energy (b, 1320.0, 4800, 24000) > 0.01 * energy (b, 440.0, 4800, 24000));
  3933. for (auto v : b)
  3934. CHECK (std::isfinite (v) && std::abs (v) < 1.0f);
  3935. // index decaying to 0: the start is bright, the end is nearly a sine again
  3936. auto decaying = fm;
  3937. decaying.fmDecay = 0.1f;
  3938. decaying.fmSustain = 0.0f;
  3939. const auto c = render (decaying);
  3940. const auto early = energy (c, 880.0, 0, 2400) / energy (c, 440.0, 0, 2400);
  3941. const auto late = energy (c, 880.0, 36000, 48000) / energy (c, 440.0, 36000, 48000);
  3942. CHECK (early > 0.05 && late < 1e-3);
  3943. }
  3944. TEST (synth_three_oscillators_adsr_filter)
  3945. {
  3946. auto render = [] (const lynx::SynthSettings& s, int frames, int releaseAt) {
  3947. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  3948. inst->prepare (48000.0);
  3949. lynx::ChannelDef c;
  3950. c.synth = s;
  3951. inst->configure (c, 120.0);
  3952. inst->noteOn (69, 1.0f); // A4 = 440 Hz
  3953. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  3954. inst->render (l.data(), r.data(), releaseAt, 1.0f, 1.0f);
  3955. inst->noteOff (69);
  3956. inst->render (l.data() + releaseAt, r.data() + releaseAt, frames - releaseAt, 1.0f, 1.0f);
  3957. return l;
  3958. };
  3959. auto peakIn = [] (const std::vector<float>& v, int from, int to) {
  3960. float p = 0.0f;
  3961. for (int i = from; i < to; ++i)
  3962. p = std::max (p, std::abs (v[(std::size_t) i]));
  3963. return p;
  3964. };
  3965. // default: sounds and fades after the release
  3966. const lynx::SynthSettings standard;
  3967. const auto a = render (standard, 48000, 24000);
  3968. CHECK (peakIn (a, 1000, 20000) > 0.05f && peakIn (a, 40000, 48000) < 1e-3f);
  3969. // pure sine with an open filter: zero-crossing count gives ~440 Hz
  3970. lynx::SynthSettings sine;
  3971. sine.osc[0].wave = lynx::Waveform::sine;
  3972. sine.cutoff = 20000.0f;
  3973. const auto b = render (sine, 48000, 47000);
  3974. int crossings = 0;
  3975. for (int i = 4800; i < 4800 + 48000 / 2; ++i)
  3976. crossings += (b[(std::size_t) i - 1] < 0.0f) != (b[(std::size_t) i] < 0.0f);
  3977. CHECK (std::abs (crossings - 440) < 6); // half a second = 220 cycles = 440 crossings
  3978. float sinePeak = 0.0f;
  3979. for (int i = 4800; i < 9600; ++i)
  3980. sinePeak = std::max (sinePeak, std::abs (b[(std::size_t) i]));
  3981. CHECK (sinePeak > 0.2f && sinePeak < 0.35f); // 0.3 level, approximated sine without clipping
  3982. // second oscillator an octave up adds energy; sustain 0 makes the note decay on its own
  3983. lynx::SynthSettings two = sine;
  3984. two.osc[1] = { lynx::Waveform::sine, 1, 0.0f, 1.0f };
  3985. two.sustain = 0.0f;
  3986. two.decay = 0.1f;
  3987. const auto c = render (two, 48000, 47000);
  3988. CHECK (peakIn (c, 100, 2000) > peakIn (b, 100, 2000) && peakIn (c, 30000, 40000) < 1e-3f);
  3989. }
  3990. TEST (set_target_value_round_trips)
  3991. {
  3992. auto s = lynx::Song::makeDefault();
  3993. s.mixer[2].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay));
  3994. const lynx::AutomationTarget targets[] = {
  3995. { lynx::AutomationTargetKind::channelVolume, 1 }, { lynx::AutomationTargetKind::channelPan, 2 },
  3996. { lynx::AutomationTargetKind::mixerVolume, 3 }, { lynx::AutomationTargetKind::mixerPan, 0 },
  3997. { lynx::AutomationTargetKind::effectParam, 2, 0, 1 }, { lynx::AutomationTargetKind::tempo, 0 },
  3998. };
  3999. for (const auto& t : targets)
  4000. {
  4001. CHECK (s.setTargetValue (t, 0.25f));
  4002. CHECK (std::abs (s.targetValue (t) - 0.25f) < 1e-5f);
  4003. }
  4004. CHECK (! s.setTargetValue ({ lynx::AutomationTargetKind::channelParam, 0, 0, 3 }, 0.5f)); // lives in the plugin
  4005. }
  4006. TEST (cut_groups_stretch_and_envelope_import)
  4007. {
  4008. // open hat (cut by 1) is cut when the closed one (group 1) plays
  4009. lynx::Song s;
  4010. s.mixer = lynx::Song::defaultMixer (2);
  4011. for (int i = 0; i < 2; ++i)
  4012. {
  4013. lynx::ChannelDef c;
  4014. c.instrument = lynx::InstrumentKind::sampler;
  4015. c.samplePath = "dc";
  4016. c.volume = 1.0f;
  4017. c.mixerTrack = i + 1;
  4018. s.channels.push_back (c);
  4019. }
  4020. s.channels[0].cutBy = 1; // open
  4021. s.channels[1].cutGroup = 1; // closed
  4022. auto& p = s.patterns.emplace_back();
  4023. p.notes = { { 0, 100, 0, 60 }, { 960, 100, 1, 60 } };
  4024. auto provider = [] (const std::string&) {
  4025. auto d = std::make_shared<lynx::SampleData>();
  4026. d->left.assign (96000, 0.5f);
  4027. return std::shared_ptr<const lynx::SampleData> (d);
  4028. };
  4029. auto state = lynx::RackState::build (s, nullptr, 48000.0, provider);
  4030. CHECK (state->hasCutGroups && state->cutTargets[1].size() == 1 && state->cutTargets[1][0] == 0);
  4031. lynx::RackRenderer r;
  4032. r.prepare (48000.0, 512);
  4033. std::vector<float> l (512), rr (512);
  4034. const auto tps = lynx::ticksPerSample (s.bpm, 48000.0);
  4035. float afterCut = 0.0f;
  4036. for (double tick = 0.0; tick < 960.0 * 3; tick += 512 * tps)
  4037. {
  4038. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  4039. if (tick > 960.0 * 2) // the closed one continues; the open one has stopped
  4040. afterCut = std::max (afterCut, std::abs (l[256]));
  4041. }
  4042. CHECK (std::abs (afterCut - 0.5f * 0.78f) < 0.01f); // only the closed one (default velocity 0.78)
  4043. // resampling stretch: 1 s of sample stretched to 4 beats at 120 BPM = 2 s
  4044. auto ramp = std::make_shared<lynx::SampleData>();
  4045. for (int i = 0; i < 48000; ++i)
  4046. ramp->left.push_back ((float) i / 48000.0f);
  4047. ramp->sampleRate = 48000.0;
  4048. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  4049. inst->prepare (48000.0);
  4050. lynx::ChannelDef c;
  4051. c.sampler.stretchBeats = 4.0f;
  4052. inst->configure (c, 120.0);
  4053. inst->noteOn (72, 1.0f); // the note pitch doesn't change the speed
  4054. std::vector<float> a (48000), b (48000);
  4055. inst->render (a.data(), b.data(), 48000, 1.0f, 1.0f);
  4056. CHECK (std::abs (a[47999] - 0.5f) < 0.01f); // after 1 s it has read half
  4057. // FL envelope time: 32950 = 2 s; < 101 = 0
  4058. CHECK (std::abs (flp::Channel::envelopeTime (32950) - 2.0) < 0.01 && flp::Channel::envelopeTime (50) == 0.0);
  4059. }
  4060. TEST (time_stretch_keeps_pitch)
  4061. {
  4062. lynx::SampleData sine;
  4063. sine.sampleRate = 48000.0;
  4064. for (int i = 0; i < 48000; ++i)
  4065. sine.left.push_back (0.5f * std::sin (2.0f * 3.14159265f * 440.0f * (float) i / 48000.0f));
  4066. auto crossingsPerSecond = [] (const lynx::SampleData& d) {
  4067. int c = 0;
  4068. const auto n = (int) d.frames();
  4069. for (int i = 4800; i < n - 4800; ++i)
  4070. c += (d.left[(std::size_t) i - 1] < 0.0f) != (d.left[(std::size_t) i] < 0.0f);
  4071. return (double) c / ((double) (n - 9600) / d.sampleRate);
  4072. };
  4073. for (double ratio : { 2.0, 0.5, 1.37 })
  4074. {
  4075. const auto out = lynx::timeStretch (sine, ratio);
  4076. CHECK (std::abs ((double) out->frames() - 48000.0 * ratio) < 2.0);
  4077. CHECK (std::abs (crossingsPerSecond (*out) - 880.0) < 15.0); // 440 Hz stays 440 Hz
  4078. float peak = 0.0f;
  4079. for (std::size_t i = 4800; i + 4800 < out->frames(); ++i)
  4080. peak = std::max (peak, std::abs (out->left[i]));
  4081. CHECK (peak > 0.4f && peak < 0.6f); // no gaps or clipping in the overlap
  4082. }
  4083. }
  4084. TEST (sampler_region_start_and_end)
  4085. {
  4086. auto ramp = std::make_shared<lynx::SampleData>();
  4087. for (int i = 0; i < 10000; ++i)
  4088. ramp->left.push_back ((float) i / 10000.0f);
  4089. ramp->sampleRate = 48000.0;
  4090. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  4091. inst->prepare (48000.0);
  4092. lynx::ChannelDef c;
  4093. c.sampler.regionStart = 0.25f;
  4094. c.sampler.regionEnd = 0.5f;
  4095. inst->configure (c, 120.0);
  4096. inst->noteOn (60, 1.0f);
  4097. std::vector<float> l (6000), r (6000);
  4098. inst->render (l.data(), r.data(), 6000, 1.0f, 1.0f);
  4099. CHECK (std::abs (l[0] - 0.25f) < 0.001f); // starts at the beginning of the slice
  4100. CHECK (l[2400] > 0.48f && l[2600] == 0.0f); // and stops at its end
  4101. }
  4102. TEST (arpeggiator_plays_held_chord_in_steps)
  4103. {
  4104. auto song = lynx::Song::makeDefault();
  4105. song.bpm = 120.0;
  4106. song.patterns[0].notes.clear();
  4107. for (int key : { 60, 64, 67 })
  4108. song.patterns[0].notes.push_back ({ 0, lynx::ppq * 4, 4, key, 0.8f }); // chord held for 1 bar
  4109. song.channels[4].arp.direction = 1; // up
  4110. song.channels[4].arp.stepBeats = 0.25f;
  4111. auto state = lynx::RackState::build (song, nullptr, 48000.0);
  4112. CHECK (state->arpeggiators[4] != nullptr && state->arpeggiators[0] == nullptr);
  4113. // the arpeggiator generates the notes; we count what it hands to the instrument
  4114. auto& arp = *state->arpeggiators[4];
  4115. const auto tps = lynx::ticksPerSample (song.bpm, 48000.0);
  4116. std::vector<int> keys;
  4117. lynx::EventBuffer ev;
  4118. for (double tick = 0.0; tick < lynx::ppq * 2.0; tick += 512 * tps)
  4119. {
  4120. ev.clear();
  4121. lynx::schedulePatternLoop (song.patterns[0], song.patterns[0].effectiveLength (4), tick, 512, tps, ev);
  4122. int in = 0, out = 0;
  4123. for (auto& e : ev)
  4124. if (e.channel == 4)
  4125. arp.input[(std::size_t) in++] = e;
  4126. arp.process (4, arp.input.data(), in, tick, tps, 512, song.channels[4].arp, arp.output.data(), out);
  4127. for (int i = 0; i < out; ++i)
  4128. if (arp.output[(std::size_t) i].type == lynx::NoteEvent::Type::on)
  4129. keys.push_back (arp.output[(std::size_t) i].key);
  4130. }
  4131. // 2 beats = 8 sixteenth steps: 60 64 67 60 64 67 60 64
  4132. CHECK (keys.size() >= 8); // the last block goes slightly past 2 beats
  4133. const int expected[] = { 60, 64, 67, 60, 64, 67, 60, 64 };
  4134. for (std::size_t i = 0; i < keys.size() && i < 8; ++i)
  4135. CHECK (keys[i] == expected[i]);
  4136. // actually rendering also makes sound
  4137. lynx::RackRenderer r;
  4138. r.prepare (48000.0, 512);
  4139. std::vector<float> l (512), rr (512);
  4140. float peak = 0.0f;
  4141. for (double tick = 0.0; tick < lynx::ppq; tick += 512 * tps)
  4142. {
  4143. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  4144. for (auto v : l)
  4145. peak = std::max (peak, std::abs (v));
  4146. }
  4147. CHECK (peak > 0.01f);
  4148. }
  4149. TEST (audio_clip_fades_and_gain)
  4150. {
  4151. lynx::Song s;
  4152. s.bpm = 120.0;
  4153. s.mode = lynx::PlayMode::song;
  4154. s.mixer = lynx::Song::defaultMixer (1);
  4155. lynx::ChannelDef c;
  4156. c.instrument = lynx::InstrumentKind::audioClip;
  4157. c.samplePath = "dc";
  4158. c.volume = 1.0f;
  4159. c.mixerTrack = 1;
  4160. s.channels.push_back (c);
  4161. s.patterns.emplace_back();
  4162. lynx::Clip clip;
  4163. clip.kind = lynx::ClipKind::audio;
  4164. clip.channel = 0;
  4165. clip.length = lynx::ppq * 4; // 2 s at 120 BPM
  4166. clip.fadeIn = lynx::ppq; // 0.5 s
  4167. clip.fadeOut = lynx::ppq;
  4168. clip.gain = 0.5f;
  4169. s.playlist.push_back (clip);
  4170. auto provider = [] (const std::string&) {
  4171. auto d = std::make_shared<lynx::SampleData>();
  4172. d->left.assign (48000 * 4, 1.0f);
  4173. return std::shared_ptr<const lynx::SampleData> (d);
  4174. };
  4175. auto state = lynx::RackState::build (s, nullptr, 48000.0, provider);
  4176. lynx::RackRenderer r;
  4177. r.prepare (48000.0, 512);
  4178. std::vector<float> all;
  4179. std::vector<float> l (512), rr (512);
  4180. const auto tps = lynx::ticksPerSample (s.bpm, 48000.0);
  4181. for (double tick = 0.0; tick < lynx::ppq * 4.0; tick += 512 * tps)
  4182. {
  4183. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  4184. all.insert (all.end(), l.begin(), l.end());
  4185. }
  4186. CHECK (all[100] < 0.01f); // fade-in start
  4187. CHECK (std::abs (all[12000] - 0.25f) < 0.02f); // fade-in midpoint: half of 0.5
  4188. CHECK (std::abs (all[48000] - 0.5f) < 0.01f); // body: the clip gain
  4189. CHECK (std::abs (all[96000 - 12000] - 0.25f) < 0.02f); // fade-out midpoint
  4190. }
  4191. TEST (slicer_detects_hits_and_plays_slices_by_key)
  4192. {
  4193. // 4 hits (decaying noise) every 0.25 s
  4194. lynx::SampleData loop;
  4195. loop.sampleRate = 48000.0;
  4196. loop.left.assign (48000, 0.0f);
  4197. lynx::Noise noise;
  4198. for (int hit = 0; hit < 4; ++hit)
  4199. for (int i = 0; i < 6000; ++i)
  4200. loop.left[(std::size_t) (hit * 12000 + i)] = noise.next() * 0.8f * std::exp (-(float) i / 1500.0f);
  4201. const auto slices = lynx::detectSlices (loop, 0.5f);
  4202. CHECK (slices.size() == 4);
  4203. for (std::size_t i = 0; i < slices.size(); ++i)
  4204. CHECK (std::abs (slices[i] - 0.25f * (float) i) < 0.01f);
  4205. // key 61 plays the second slice, which starts at 0.25 and ends before 0.5
  4206. auto ramp = std::make_shared<lynx::SampleData>();
  4207. for (int i = 0; i < 48000; ++i)
  4208. ramp->left.push_back ((float) i / 48000.0f);
  4209. ramp->sampleRate = 48000.0;
  4210. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  4211. inst->prepare (48000.0);
  4212. lynx::ChannelDef c;
  4213. c.sampler.slices = slices;
  4214. inst->configure (c, 120.0);
  4215. inst->noteOn (61, 1.0f);
  4216. std::vector<float> l (20000), r (20000);
  4217. inst->render (l.data(), r.data(), 20000, 1.0f, 1.0f);
  4218. CHECK (std::abs (l[0] - 0.25f) < 0.01f && l[11000] > 0.45f && l[13000] == 0.0f);
  4219. }
  4220. TEST (project_templates_render_sound)
  4221. {
  4222. const auto names = lynx::templateNames();
  4223. CHECK (names.size() == 4);
  4224. for (int t = 1; t < (int) names.size(); ++t)
  4225. {
  4226. auto song = lynx::makeTemplate (t);
  4227. auto state = lynx::RackState::build (song, nullptr, 48000.0);
  4228. lynx::RackRenderer r;
  4229. r.prepare (48000.0, 512);
  4230. std::vector<float> l (512), rr (512);
  4231. const auto tps = lynx::ticksPerSample (song.bpm, 48000.0);
  4232. float peak = 0.0f;
  4233. for (double tick = 0.0; tick < lynx::ppq * 4.0; tick += 512 * tps)
  4234. {
  4235. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  4236. for (auto v : l)
  4237. peak = std::max (peak, std::abs (v));
  4238. }
  4239. CHECK (peak > 0.05f && peak < 4.0f);
  4240. }
  4241. CHECK (lynx::makeTemplate (0).patterns[0].notes.empty());
  4242. }
  4243. // --- interface translations (resources/i18n) -------------------------------------------------------
  4244. namespace i18ntest
  4245. {
  4246. std::string readFile (const std::filesystem::path& path)
  4247. {
  4248. std::ifstream in (path, std::ios::binary);
  4249. return { std::istreambuf_iterator<char> (in), std::istreambuf_iterator<char>() };
  4250. }
  4251. std::string unescape (const std::string& s)
  4252. {
  4253. std::string out;
  4254. for (std::size_t i = 0; i < s.size(); ++i)
  4255. {
  4256. if (s[i] == '\\' && i + 1 < s.size())
  4257. {
  4258. const auto n = s[++i];
  4259. out += n == 'n' ? '\n' : n == 't' ? '\t' : n;
  4260. }
  4261. else
  4262. out += s[i];
  4263. }
  4264. return out;
  4265. }
  4266. // reads a quoted string starting at s[pos] == '"'; returns the raw (escaped) contents and moves pos past the closing quote
  4267. bool quoted (const std::string& s, std::size_t& pos, std::string& raw)
  4268. {
  4269. if (pos >= s.size() || s[pos] != '"')
  4270. return false;
  4271. raw.clear();
  4272. for (++pos; pos < s.size() && s[pos] != '"' && s[pos] != '\n'; ++pos)
  4273. {
  4274. if (s[pos] == '\\' && pos + 1 < s.size())
  4275. raw += s[pos++];
  4276. raw += s[pos];
  4277. }
  4278. if (pos >= s.size() || s[pos] != '"')
  4279. return false;
  4280. ++pos;
  4281. return true;
  4282. }
  4283. // JUCE LocalisedStrings format: "english" = "translation"; duplicates are reported in `duplicates`
  4284. std::map<std::string, std::string> parseTable (const std::string& text, std::vector<std::string>& duplicates)
  4285. {
  4286. std::map<std::string, std::string> table;
  4287. std::istringstream lines (text);
  4288. std::string line;
  4289. while (std::getline (lines, line))
  4290. {
  4291. std::size_t pos = line.find_first_not_of (" \t");
  4292. std::string key, value;
  4293. if (pos == std::string::npos || ! quoted (line, pos, key))
  4294. continue;
  4295. pos = line.find ('"', pos);
  4296. if (pos == std::string::npos || ! quoted (line, pos, value))
  4297. value.clear();
  4298. const auto k = unescape (key);
  4299. if (table.count (k) != 0)
  4300. duplicates.push_back (k);
  4301. table[k] = unescape (value);
  4302. }
  4303. return table;
  4304. }
  4305. // string literals passed to tr() / TR_NOOP() in the sources (adjacent literals are concatenated)
  4306. std::map<std::string, std::string> sourceKeys (const std::filesystem::path& srcDir)
  4307. {
  4308. std::map<std::string, std::string> keys;
  4309. for (const auto& entry : std::filesystem::recursive_directory_iterator (srcDir))
  4310. {
  4311. const auto ext = entry.path().extension().string();
  4312. if (! entry.is_regular_file() || (ext != ".cpp" && ext != ".h"))
  4313. continue;
  4314. // drop // comment lines (they may quote tr ("...") as an example)
  4315. std::string text, line;
  4316. std::istringstream in (readFile (entry.path()));
  4317. while (std::getline (in, line))
  4318. {
  4319. const auto first = line.find_first_not_of (" \t");
  4320. text += (first != std::string::npos && line.compare (first, 2, "//") == 0) ? std::string() : line;
  4321. text += '\n';
  4322. }
  4323. auto isIdent = [] (char c) { return std::isalnum ((unsigned char) c) || c == '_'; };
  4324. for (const std::string name : { "tr", "TR_NOOP" })
  4325. for (auto at = text.find (name); at != std::string::npos; at = text.find (name, at + 1))
  4326. {
  4327. if ((at > 0 && isIdent (text[at - 1])) || isIdent (text[at + name.size()]))
  4328. continue;
  4329. auto pos = text.find_first_not_of (" \t\n", at + name.size());
  4330. if (pos == std::string::npos || text[pos] != '(')
  4331. continue;
  4332. pos = text.find_first_not_of (" \t\n", pos + 1);
  4333. std::string key, raw;
  4334. bool any = false;
  4335. while (pos != std::string::npos && quoted (text, pos, raw))
  4336. {
  4337. key += raw;
  4338. any = true;
  4339. pos = text.find_first_not_of (" \t\n", pos);
  4340. }
  4341. if (any)
  4342. keys.emplace (unescape (key), entry.path().filename().string());
  4343. }
  4344. }
  4345. return keys;
  4346. }
  4347. std::set<std::string> placeholders (const std::string& s)
  4348. {
  4349. std::set<std::string> found;
  4350. for (auto open = s.find ('{'); open != std::string::npos; open = s.find ('{', open + 1))
  4351. if (const auto close = s.find ('}', open); close != std::string::npos && close - open <= 3)
  4352. found.insert (s.substr (open, close - open + 1));
  4353. return found;
  4354. }
  4355. } // namespace i18ntest
  4356. TEST (translations_cover_every_ui_string)
  4357. {
  4358. using namespace i18ntest;
  4359. const auto text = readFile ("resources/i18n/pt-BR.txt");
  4360. CHECK (! text.empty());
  4361. std::vector<std::string> duplicates;
  4362. const auto table = parseTable (text, duplicates);
  4363. CHECK (table.size() > 300);
  4364. CHECK (duplicates.empty());
  4365. for (const auto& d : duplicates)
  4366. std::printf (" duplicate pt-BR entry: \"%s\"\n", d.c_str());
  4367. const auto keys = sourceKeys ("src");
  4368. CHECK (keys.size() > 300);
  4369. int missing = 0;
  4370. for (const auto& [key, file] : keys)
  4371. if (auto it = table.find (key); it == table.end() || it->second.empty())
  4372. {
  4373. ++missing;
  4374. std::printf (" no pt-BR translation for \"%s\" (%s)\n", key.c_str(), file.c_str());
  4375. }
  4376. CHECK (missing == 0);
  4377. // no empty values, and every {n} placeholder survives the translation
  4378. int empty = 0, badPlaceholders = 0;
  4379. for (const auto& [english, portuguese] : table)
  4380. {
  4381. empty += portuguese.empty() ? 1 : 0;
  4382. if (placeholders (english) != placeholders (portuguese))
  4383. {
  4384. ++badPlaceholders;
  4385. std::printf (" placeholders differ: \"%s\"\n", english.c_str());
  4386. }
  4387. }
  4388. CHECK (empty == 0);
  4389. CHECK (badPlaceholders == 0);
  4390. }
  4391. TEST (translations_embedded_table_is_up_to_date)
  4392. {
  4393. // src/ui/I18nData.h must be regenerated (tools/make_i18n.py) whenever the .txt changes
  4394. const auto text = i18ntest::readFile ("resources/i18n/pt-BR.txt");
  4395. CHECK (text.size() == sizeof (lynx::i18n::data::ptBR));
  4396. CHECK (std::memcmp (text.data(), lynx::i18n::data::ptBR, std::min (text.size(), sizeof (lynx::i18n::data::ptBR))) == 0);
  4397. }
  4398. // --- workflow shell: pattern/channel operations, key map, workspace layout, control math -------------
  4399. TEST (workflow_pattern_navigation_and_insert)
  4400. {
  4401. auto song = lynx::Song::makeDefault();
  4402. song.patterns.resize (3);
  4403. song.patterns[1].name = "B";
  4404. song.patterns[2].name = "C";
  4405. song.patterns[2].notes.push_back ({});
  4406. song.currentPattern = 0;
  4407. CHECK (lynx::stepPattern (song, 1) == 1 && lynx::stepPattern (song, -1) == 0 && lynx::stepPattern (song, 10) == 2);
  4408. // pattern 0 has the default notes, 1 is empty, 2 has a note
  4409. CHECK (! lynx::isPatternEmpty (song.patterns[0]) && lynx::isPatternEmpty (song.patterns[1]));
  4410. CHECK (lynx::findNextEmptyPattern (song, 0) == 1 && lynx::findNextEmptyPattern (song, 1) == -1);
  4411. CHECK (lynx::gotoNextEmptyPattern (song) == 1 && song.currentPattern == 1);
  4412. song.patterns[1].notes.push_back ({});
  4413. const auto before = song.patterns.size();
  4414. CHECK (lynx::gotoNextEmptyPattern (song) == (int) before && song.patterns.size() == before + 1);
  4415. CHECK (song.patterns.back().name == "Pattern 1" || song.patterns.back().name.rfind ("Pattern ", 0) == 0);
  4416. // insert keeps Playlist clips on their patterns
  4417. lynx::Clip clip;
  4418. clip.pattern = 2;
  4419. song.playlist = { clip };
  4420. song.arrangements.push_back ({ "Other", { clip }, 0, 0, {} });
  4421. CHECK (lynx::insertPattern (song, 1, "New") == 1 && song.currentPattern == 1);
  4422. CHECK (song.patterns[1].name == "New" && song.patterns[1].notes.empty() && song.patterns[3].name == "C");
  4423. CHECK (song.playlist[0].pattern == 3 && song.arrangements[1].clips[0].pattern == 3);
  4424. }
  4425. TEST (workflow_split_pattern_by_channel)
  4426. {
  4427. auto song = lynx::Song::makeDefault();
  4428. song.patterns.resize (1);
  4429. auto& p = song.patterns[0];
  4430. p.name = "Beat";
  4431. p.notes.clear();
  4432. for (int i = 0; i < 4; ++i)
  4433. p.notes.push_back ({ (std::int64_t) i * lynx::ticksPerStep, lynx::ticksPerStep, i % 2 == 0 ? 0 : 2, 60 });
  4434. song.channels[2].colour = 0xff112233;
  4435. lynx::Clip clip;
  4436. clip.pattern = 0;
  4437. song.playlist = { clip };
  4438. const auto created = lynx::splitPatternByChannel (song, 0);
  4439. CHECK (created == 2 && song.patterns.size() == 3);
  4440. CHECK (song.patterns[0].notes.size() == 4); // the original is unchanged
  4441. CHECK (song.patterns[1].name == "Beat - " + song.channels[0].name && song.patterns[1].notes.size() == 2);
  4442. CHECK (song.patterns[2].colour == 0xff112233u && song.patterns[2].notes.size() == 2 && song.patterns[2].notes[0].channel == 2);
  4443. CHECK (song.playlist[0].pattern == 0);
  4444. CHECK (lynx::splitPatternByChannel (song, 99) == 0);
  4445. }
  4446. TEST (workflow_channel_selection)
  4447. {
  4448. lynx::ChannelSelection s;
  4449. s.selectOnly (2);
  4450. s.toggle (5);
  4451. s.toggle (0);
  4452. CHECK ((s.rows == std::vector<int> { 0, 2, 5 }) && s.contains (5) && ! s.contains (3));
  4453. s.toggle (2);
  4454. CHECK ((s.rows == std::vector<int> { 0, 5 }));
  4455. s.selectOnly (3);
  4456. s.extendTo (6);
  4457. CHECK ((s.rows == std::vector<int> { 3, 4, 5, 6 }));
  4458. s.extendTo (1);
  4459. CHECK ((s.rows == std::vector<int> { 1, 2, 3 }));
  4460. s.selectOnly (4);
  4461. s.toggle (4); // the last one stays
  4462. CHECK ((s.rows == std::vector<int> { 4 }));
  4463. s.selectAll (3);
  4464. CHECK ((s.rows == std::vector<int> { 0, 1, 2 }));
  4465. s.rows = { 7, 9 };
  4466. s.clamp (5);
  4467. CHECK (s.rows.size() == 1 && s.rows[0] < 5);
  4468. }
  4469. TEST (workflow_move_clone_insert_channels)
  4470. {
  4471. auto song = lynx::Song::makeDefault();
  4472. const auto names = [&] {
  4473. std::vector<std::string> n;
  4474. for (const auto& c : song.channels)
  4475. n.push_back (c.name);
  4476. return n;
  4477. };
  4478. const auto original = names();
  4479. const auto count = (int) song.channels.size();
  4480. CHECK (count >= 4);
  4481. // references that must follow their channel
  4482. song.patterns[0].notes.push_back ({ 0, 240, 1, 64 });
  4483. lynx::Automation a;
  4484. a.target = { lynx::AutomationTargetKind::channelVolume, 1 };
  4485. song.automations.push_back (a);
  4486. song.midiLinks.push_back ({ 7, -1, { lynx::AutomationTargetKind::channelPan, 3 } });
  4487. lynx::Clip audio;
  4488. audio.kind = lynx::ClipKind::audio;
  4489. audio.channel = 3;
  4490. song.playlist.push_back (audio);
  4491. std::vector<int> selection { 1, 3 };
  4492. CHECK (lynx::moveChannels (song, selection, -1));
  4493. CHECK ((selection == std::vector<int> { 0, 2 }));
  4494. CHECK (song.channels[0].name == original[1] && song.channels[1].name == original[0] && song.channels[2].name == original[3]
  4495. && song.channels[3].name == original[2]);
  4496. CHECK (song.automations[0].target.index == 0 && song.midiLinks[0].target.index == 2 && song.playlist.back().channel == 2);
  4497. CHECK (std::any_of (song.patterns[0].notes.begin(), song.patterns[0].notes.end(),
  4498. [] (const lynx::Note& n) { return n.channel == 0 && n.key == 64; }));
  4499. CHECK (! lynx::moveChannels (song, selection, -1)); // the block is at the top
  4500. CHECK (lynx::moveChannels (song, selection, 1) && (selection == std::vector<int> { 1, 3 }) && names() == original);
  4501. // clone: settings, not notes, right below, with a new name
  4502. song.channels[1].volume = 0.33f;
  4503. const auto notesBefore = song.patterns[0].notes.size();
  4504. const auto clone = lynx::cloneChannel (song, 1);
  4505. CHECK (clone == 2 && (int) song.channels.size() == count + 1);
  4506. CHECK (song.channels[2].name == original[1] + " #2" && song.channels[2].volume == 0.33f);
  4507. CHECK (song.patterns[0].notes.size() == notesBefore);
  4508. CHECK (song.channels[3].name == original[2] && song.automations[0].target.index == 1);
  4509. CHECK (lynx::cloneChannel (song, 1) == 2 && song.channels[2].name == original[1] + " #3");
  4510. // remove several
  4511. CHECK (lynx::removeChannels (song, { 2, 3, 2 }) == 2 && (int) song.channels.size() == count);
  4512. CHECK (names() == original);
  4513. }
  4514. TEST (workflow_send_channels_to_free_inserts)
  4515. {
  4516. auto song = lynx::Song::makeDefault();
  4517. for (auto& c : song.channels)
  4518. c.mixerTrack = 0;
  4519. song.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay)); // not free: has effects
  4520. song.channels[0].mixerTrack = 2; // not free: used
  4521. song.setRoute (5, 3, true); // 3 is not free: receives a send
  4522. CHECK (! lynx::isInsertFree (song, 1) && ! lynx::isInsertFree (song, 2) && ! lynx::isInsertFree (song, 3) && lynx::isInsertFree (song, 4));
  4523. song.channels[1].colour = 0xff445566;
  4524. const auto tracks = lynx::sendChannelsToFreeInserts (song, { 1, 2 });
  4525. CHECK ((tracks == std::vector<int> { 4, 5 }) || (tracks == std::vector<int> { 4, 6 }));
  4526. CHECK (song.channels[1].mixerTrack == 4 && song.mixer[4].name == song.channels[1].name && song.mixer[4].colour == 0xff445566u);
  4527. CHECK (song.mixer[(std::size_t) tracks[1]].name == song.channels[2].name);
  4528. // with no free insert left, a new one is added at the end
  4529. auto full = lynx::Song::makeDefault();
  4530. full.mixer = lynx::Song::defaultMixer (1);
  4531. full.channels[0].mixerTrack = 1;
  4532. const auto added = lynx::sendChannelsToFreeInserts (full, { 1 });
  4533. CHECK (added.size() == 1 && added[0] == 2 && full.mixer.size() == 3 && full.channels[1].mixerTrack == 2);
  4534. }
  4535. TEST (workflow_palette_random_colour)
  4536. {
  4537. const auto& palette = lynx::lynxPalette();
  4538. for (std::uint32_t seed = 0; seed < 50; ++seed)
  4539. {
  4540. const auto current = palette[seed % palette.size()];
  4541. const auto c = lynx::randomPaletteColour (current, seed);
  4542. CHECK (c != current && std::find (palette.begin(), palette.end(), c) != palette.end());
  4543. }
  4544. }
  4545. TEST (workflow_key_map)
  4546. {
  4547. using namespace lynx::keys;
  4548. KeyMap map;
  4549. const auto global = Context::global, rack = Context::channelRack;
  4550. CHECK (map.find ({ space, none }, global, true) == "transport.playStop");
  4551. CHECK (map.find ({ space, ctrl }, global, true) == "transport.pause");
  4552. CHECK (map.find ({ f6, none }, global, true) == "panel.channelRack");
  4553. CHECK (map.find ({ f8, alt }, global, false) == "panel.browser");
  4554. CHECK (map.find ({ insert, ctrl | shift }, global, false) == "pattern.insert");
  4555. CHECK (map.find ({ numpadPlus, none }, rack, true) == "pattern.next");
  4556. // panel context: only while focused
  4557. CHECK (map.find ({ 'L', ctrl }, rack, true) == "rack.sendToInserts");
  4558. CHECK (map.find ({ 'L', ctrl }, global, true).empty());
  4559. CHECK (map.find ({ up, alt }, rack, false) == "rack.moveUp");
  4560. // typing piano: note keys play, other plain keys only for whilePiano actions; chords always work
  4561. CHECK (KeyMap::playsNote ({ 'Z', none }, true) && ! KeyMap::playsNote ({ 'Z', none }, false) && ! KeyMap::playsNote ({ 'Z', ctrl }, true));
  4562. CHECK (map.find ({ 'L', none }, global, true) == "transport.toggleMode");
  4563. CHECK (map.find ({ '1', none }, rack, false) == "rack.mute1" && map.find ({ '0', none }, rack, false) == "rack.mute10");
  4564. CHECK (map.find ({ '1', none }, rack, true).empty()); // a plain digit is not a shortcut while the piano is on
  4565. CHECK (map.find ({ '2', ctrl }, rack, true) == "rack.solo2");
  4566. CHECK (typingPianoNote ('Z') == 60 && typingPianoNote ('q') == 72 && typingPianoNote ('P') == 88 && typingPianoNote ('L') == -1);
  4567. CHECK (map.conflicts().empty());
  4568. // chord text
  4569. CHECK (toString ({ f4, ctrl | shift }) == "Ctrl+Shift+F4" && toString ({ numpadMinus, none }) == "Numpad -");
  4570. CHECK (parseChord ("Shift+Ctrl+Ins") == (Chord { insert, ctrl | shift }));
  4571. CHECK (parseChord ("alt+up") == (Chord { up, alt }) && parseChord ("k") == (Chord { 'K', none }));
  4572. CHECK (parseChord ("Numpad +") == (Chord { numpadPlus, none }) && ! parseChord ("F13") && ! parseChord ("Ctrl+"));
  4573. for (const auto& a : actions())
  4574. for (const auto& c : a.defaults)
  4575. CHECK (parseChord (toString (c)) == c);
  4576. // JSON overrides
  4577. std::vector<std::string> errors;
  4578. CHECK (map.loadJson (R"({ "pattern.next": "Ctrl+Right", "rack.clone": ["Alt+D", "Ctrl+D"], "help.shortcuts": "", "nope": "F1", "file.open": "Hyper+Q" })", &errors));
  4579. CHECK (errors.size() == 2);
  4580. CHECK (map.find ({ right, ctrl }, global, false) == "pattern.next" && map.find ({ numpadPlus, none }, global, false).empty());
  4581. CHECK (map.find ({ 'D', ctrl }, rack, false) == "rack.clone" && map.find ({ f1, none }, global, false).empty());
  4582. map.setChords ("pattern.previous", { { right, ctrl } });
  4583. CHECK (map.conflicts().size() == 1);
  4584. KeyMap reloaded;
  4585. CHECK (reloaded.loadJson (map.toJson()) && reloaded.chordsFor ("rack.clone") == map.chordsFor ("rack.clone"));
  4586. CHECK (! map.loadJson ("[1, 2]") && ! map.loadJson ("{\"a\": }"));
  4587. map.resetToDefaults();
  4588. CHECK (map.find ({ numpadPlus, none }, global, false) == "pattern.next");
  4589. }
  4590. TEST (workflow_workspace_layout)
  4591. {
  4592. using namespace lynx::workspace;
  4593. auto l = Layout::makeDefault (1280, 620);
  4594. // every visible panel is inside the desktop; the default shows Browser, Playlist and Channel Rack
  4595. for (const auto& p : l.panels)
  4596. CHECK (p.bounds.x >= 0 && p.bounds.y >= 0 && p.bounds.right() <= 1280 && p.bounds.bottom() <= 620 && p.bounds.w >= minWidth);
  4597. CHECK (l[Panel::browser].visible && l[Panel::playlist].visible && l[Panel::channelRack].visible);
  4598. CHECK (! l[Panel::pianoRoll].visible && ! l[Panel::mixer].visible);
  4599. CHECK (l[Panel::playlist].bounds.x == l[Panel::browser].bounds.right() && l[Panel::playlist].bounds.right() == 1280);
  4600. CHECK (l.isFrontmost (Panel::channelRack) && l.focused == Panel::channelRack);
  4601. // toggle: show+focus, focus, hide
  4602. CHECK (l.toggle (Panel::mixer) && l.focused == Panel::mixer && l.isFrontmost (Panel::mixer));
  4603. CHECK (l.toggle (Panel::channelRack) && l.focused == Panel::channelRack && l.isFrontmost (Panel::channelRack));
  4604. CHECK (! l.toggle (Panel::channelRack) && ! l[Panel::channelRack].visible && l.focused == Panel::mixer);
  4605. l.toggleMaximised (Panel::playlist);
  4606. CHECK (l[Panel::playlist].maximised && l.focused == Panel::playlist);
  4607. // save and load at another size: positions scale
  4608. l[Panel::mixer].detached = true;
  4609. l[Panel::mixer].windowBounds = { 100, 50, 900, 500 };
  4610. const auto text = l.serialise();
  4611. const auto big = Layout::parse (text, 2560, 1240);
  4612. CHECK (big.has_value());
  4613. if (big)
  4614. {
  4615. CHECK ((*big)[Panel::playlist].maximised && (*big)[Panel::mixer].detached && (*big)[Panel::mixer].windowBounds.w == 900);
  4616. CHECK (std::abs ((*big)[Panel::playlist].bounds.x - 2 * l[Panel::playlist].bounds.x) <= 1);
  4617. CHECK (big->order == l.order && big->focused == l.focused);
  4618. }
  4619. CHECK (! Layout::parse ("garbage", 100, 100) && ! Layout::parse ("lynx-layout 1\npanel nowhere 1 0 0 0 0 1 1 0 0 0 0\n", 100, 100));
  4620. // resize keeps panels inside and edges glued to the border
  4621. l.resize (1000, 500);
  4622. CHECK (l[Panel::playlist].bounds.right() == 1000 && l[Panel::browser].bounds.bottom() == 500);
  4623. for (const auto& p : l.panels)
  4624. CHECK (p.bounds.right() <= 1000 && p.bounds.bottom() <= 500);
  4625. // off-screen panels come back
  4626. l[Panel::pianoRoll].bounds = { 5000, -300, 400, 300 };
  4627. CHECK (l.bringBackOffscreen() == 1 && l[Panel::pianoRoll].bounds.x + 400 <= 1000 && l[Panel::pianoRoll].bounds.y == 0);
  4628. // snapping: to the desktop, to another panel, and resizing one edge
  4629. CHECK ((snap ({ 5, 6, 200, 100 }, {}, 1000, 500) == Rect { 0, 0, 200, 100 }));
  4630. CHECK ((snap ({ 304, 50, 200, 100 }, { { 0, 0, 300, 400 } }, 1000, 500) == Rect { 300, 50, 200, 100 }));
  4631. CHECK ((snap ({ 304, 50, 200, 100 }, { { 0, 0, 300, 400 } }, 1000, 500, 2) == Rect { 304, 50, 200, 100 })); // out of range
  4632. CHECK ((snap ({ 100, 100, 195, 100 }, { { 300, 0, 300, 400 } }, 1000, 500, 8, right) == Rect { 100, 100, 200, 100 }));
  4633. CHECK ((snap ({ 100, 100, 195, 100 }, { { 300, 1000, 300, 400 } }, 2000, 2000, 8, right) == Rect { 100, 100, 195, 100 })); // not facing
  4634. }
  4635. TEST (workflow_control_math)
  4636. {
  4637. using namespace lynx::controls;
  4638. CHECK (std::abs (dragValue (0.5, 75, 0, 1, 150, false) - 1.0) < 1e-9);
  4639. CHECK (std::abs (dragValue (0.5, 75, 0, 1, 150, true) - 0.55) < 1e-9);
  4640. CHECK (dragValue (0.5, -1000, -1, 1, 150, false) == -1.0);
  4641. CHECK (std::abs (wheelValue (0.5, 1, 0, 1, false) - 0.52) < 1e-9 && std::abs (wheelValue (0.5, -1, 0, 1, true) - 0.498) < 1e-9);
  4642. CHECK (wheelValue (3, 1, 0, 10, true, 1) == 4.0); // integer controls move at least one step
  4643. CHECK (std::abs (snapToInterval (0.234, 0, 0.1) - 0.2) < 1e-9);
  4644. CHECK (tempoDrag (130.0, 8, false, false) == 132.0 && tempoDrag (130.0, -3, false, false) == 130.0);
  4645. CHECK (std::abs (tempoDrag (130.0, 25, true, false) - 130.25) < 1e-9);
  4646. CHECK (std::abs (tempoDrag (130.0, 8, false, true) - 130.2) < 1e-9);
  4647. CHECK (tempoDrag (520.0, 400, false, false) == lynx::maxTempo && halfTempo (15.0) == lynx::minTempo && doubleTempo (130.0) == 260.0);
  4648. TapTempo tap;
  4649. CHECK (! tap.tap (1000.0));
  4650. CHECK (tap.tap (1500.0) == 120.0);
  4651. CHECK (tap.tap (2000.0) == 120.0 && tap.count() == 3);
  4652. CHECK (std::abs (*tap.tap (2400.0) - 128.57) < 0.01); // average of 500, 500, 400 ms
  4653. CHECK (! tap.tap (9000.0) && tap.count() == 1); // a long pause starts over
  4654. }
  4655. int main (int argc, char** argv)
  4656. {
  4657. if (argc > 1)
  4658. realFlpDir = argv[1];
  4659. for (auto& [name, fn] : registry())
  4660. {
  4661. std::printf ("%s\n", name);
  4662. fn();
  4663. }
  4664. std::printf ("\n%d checks, %d failures\n", checks, failures);
  4665. return failures == 0 ? 0 : 1;
  4666. }
  4667. TEST (synth_cutoff_keytrack)
  4668. {
  4669. // the cutoff follows the note from key 48 (130.81 Hz), like Harmor's "Key to filter frequency"
  4670. auto rms = [] (float keyTrack, int key) {
  4671. lynx::SynthSettings s;
  4672. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  4673. s.cutoff = 130.81f;
  4674. s.keyTrack = keyTrack;
  4675. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  4676. inst->prepare (48000.0);
  4677. lynx::ChannelDef c;
  4678. c.synth = s;
  4679. inst->configure (c, 120.0);
  4680. inst->noteOn (key, 1.0f);
  4681. std::vector<float> l (24000), r (24000);
  4682. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  4683. double e = 0.0;
  4684. for (int i = 4800; i < 24000; ++i)
  4685. e += (double) l[(std::size_t) i] * l[(std::size_t) i];
  4686. return std::sqrt (e / 19200.0);
  4687. };
  4688. const auto fixed = rms (0.0f, 72), tracked = rms (1.0f, 72);
  4689. CHECK (tracked > 4.0 * fixed); // 2 octaves up: without keytrack the low-pass cuts
  4690. CHECK (std::abs (rms (1.0f, 48) - rms (0.0f, 48)) < 0.05 * rms (0.0f, 48)); // unchanged at the reference key
  4691. }
  4692. namespace
  4693. {
  4694. std::vector<float> renderSynthNote (const lynx::SynthSettings& s, int key, int frames)
  4695. {
  4696. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  4697. inst->prepare (48000.0);
  4698. lynx::ChannelDef c;
  4699. c.synth = s;
  4700. inst->configure (c, 120.0);
  4701. inst->noteOn (key, 1.0f);
  4702. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  4703. inst->render (l.data(), r.data(), frames, 1.0f, 1.0f);
  4704. return l;
  4705. }
  4706. double goertzel (const std::vector<float>& x, double f, int from, int to)
  4707. {
  4708. const auto w = 2.0 * 3.141592653589793 * f / 48000.0, k = 2.0 * std::cos (w);
  4709. double s1 = 0.0, s2 = 0.0;
  4710. for (int i = from; i < to; ++i)
  4711. {
  4712. const auto s0 = x[(std::size_t) i] + k * s1 - s2;
  4713. s2 = s1;
  4714. s1 = s0;
  4715. }
  4716. return s1 * s1 + s2 * s2 - k * s1 * s2;
  4717. }
  4718. } // namespace
  4719. TEST (synth_pitch_sweep_ring_and_bands)
  4720. {
  4721. lynx::SynthSettings sine;
  4722. sine.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  4723. sine.cutoff = 20000.0f;
  4724. // sweep: starts at f·(1 + sweep) and returns to f (time constant s = 10 ms; s⁴ falls 4× faster)
  4725. auto sweep = sine;
  4726. sweep.sweep = 1.0f;
  4727. sweep.sweepTime = 0.01f;
  4728. const auto a = renderSynthNote (sweep, 69, 24000);
  4729. auto crossings = [] (const std::vector<float>& x, int to) {
  4730. int n = 0;
  4731. for (int i = 1; i < to; ++i)
  4732. n += (x[(std::size_t) i - 1] < 0.0f) != (x[(std::size_t) i] < 0.0f);
  4733. return n;
  4734. };
  4735. CHECK (crossings (a, 480) > 1.3 * crossings (renderSynthNote (sine, 69, 480), 480)); // 10 ms: much higher
  4736. CHECK (goertzel (a, 440.0, 12000, 24000) > 100.0 * goertzel (a, 880.0, 12000, 24000));
  4737. // ring with |a| = 1: carrier 440 × modulator 110 -> only 330 and 550, no 440
  4738. auto ring = sine;
  4739. ring.am = ring.ring = true;
  4740. ring.osc[2] = { lynx::Waveform::sine, -2, 0.0f, 1.0f };
  4741. const auto b = renderSynthNote (ring, 69, 24000);
  4742. CHECK (goertzel (b, 330.0, 4800, 24000) > 100.0 * goertzel (b, 440.0, 4800, 24000));
  4743. CHECK (goertzel (b, 550.0, 4800, 24000) > 100.0 * goertzel (b, 440.0, 4800, 24000));
  4744. // 3 bands: muting the high knocks down a 4 kHz note and barely touches an 80 Hz one
  4745. auto bands = sine;
  4746. bands.bandGain = { 1.0f, 1.0f, 0.0f };
  4747. auto rms = [] (const std::vector<float>& x) {
  4748. double e = 0.0;
  4749. for (std::size_t i = 4800; i < x.size(); ++i)
  4750. e += (double) x[i] * x[i];
  4751. return std::sqrt (e / (double) (x.size() - 4800));
  4752. };
  4753. CHECK (rms (renderSynthNote (bands, 107, 24000)) < 0.3 * rms (renderSynthNote (sine, 107, 24000)));
  4754. CHECK (rms (renderSynthNote (bands, 28, 24000)) > 0.85 * rms (renderSynthNote (sine, 28, 24000)));
  4755. }
  4756. TEST (love_philter_map_evaluation)
  4757. {
  4758. lynx::LovePhilterMap line { { { 0.0, 0.0 }, { 1.0, 1.0 } } };
  4759. CHECK (std::abs (lynx::lovePhilterMapAt (line, 0.5) - 0.5) < 1e-9);
  4760. CHECK (std::abs (lynx::lovePhilterMapAt (line, 1.0) - 1.0) < 1e-9);
  4761. // steps (Δx = 0): 1 until 0.4375, ramp to 0 at 0.5, then 0
  4762. lynx::LovePhilterMap steps { { { 0.0, 1.0 }, { 0.4375, 1.0 }, { 0.0625, 0.0 }, { 0.5, 0.0 } } };
  4763. CHECK (lynx::lovePhilterMapAt (steps, 0.27) == 1.0);
  4764. CHECK (lynx::lovePhilterMapAt (steps, 0.75) == 0.0);
  4765. CHECK (std::abs (lynx::lovePhilterMapAt (steps, 0.46875) - 0.5) < 1e-9);
  4766. CHECK (lynx::lovePhilterMapAt ({}, 0.3) == 1.0);
  4767. }
  4768. TEST (lofi_holds_and_quantizes)
  4769. {
  4770. auto fx = lynx::makeEffect (lynx::EffectKind::lofi);
  4771. fx->prepare (48000.0);
  4772. auto slot = lynx::makeEffectSlot (lynx::EffectKind::lofi);
  4773. slot.params[0] = 0.5f; // 128·0.125 + 1 = 17 samples
  4774. slot.params[1] = 1.0f; // 65536/2049 ≈ 32 levels
  4775. std::vector<float> l (170), r (170);
  4776. for (std::size_t i = 0; i < l.size(); ++i)
  4777. l[i] = r[i] = 0.9f * (float) std::sin (0.05 * (double) i);
  4778. const auto original = l;
  4779. fx->process (l.data(), r.data(), 170, slot.params, 120.0);
  4780. for (int i = 0; i < 17; ++i)
  4781. CHECK (l[(std::size_t) i] == l[0]);
  4782. CHECK (l[17] != l[16]);
  4783. const auto step = 2.0f * 2049.0f / 65536.0f;
  4784. for (auto v : l)
  4785. CHECK (std::abs (v / step - std::round (v / step)) < 1e-3f);
  4786. CHECK (std::abs (l[0] - original[0]) <= step);
  4787. CHECK (lynx::formatEffectParam (lynx::EffectKind::lofi, 1, 0.0f, 120.0) == "16.0 bits");
  4788. }
  4789. namespace
  4790. {
  4791. lynx::EffectParams effectorParams (int type, float x, float y)
  4792. {
  4793. auto slot = lynx::makeEffectSlot (lynx::EffectKind::effector);
  4794. slot.params[0] = (float) type / 11.0f;
  4795. slot.params[3] = x;
  4796. slot.params[4] = y;
  4797. return slot.params;
  4798. }
  4799. } // namespace
  4800. TEST (effector_algorithms)
  4801. {
  4802. CHECK (lynx::effector::typeOf (8.0f / 11.0f) == 8);
  4803. CHECK (std::string (lynx::effector::typeName (11)) == "Ring");
  4804. CHECK (std::abs (lynx::effector::rateBeats (0.5f, 0.0f) - 0.75) < 1e-9); // trunc(8·0.5 + 0.5) = 4 -> 3/4
  4805. CHECK (std::abs (lynx::effector::rateBeats (1.0f, 0.5f) - 2.0) < 1e-9); // 8 × (1 − 0.5)²
  4806. auto run = [] (const lynx::EffectParams& p, std::vector<float> in, double bpm = 120.0) {
  4807. auto fx = lynx::makeEffect (lynx::EffectKind::effector);
  4808. fx->prepare (48000.0);
  4809. fx->setSongPosition (0.0);
  4810. auto r = in;
  4811. fx->process (in.data(), r.data(), (int) in.size(), p, bpm);
  4812. return in;
  4813. };
  4814. // Distort with Y = 1 (everything goes to the cascade): 0.5 comes out 0.5 (compensation G = 0.5/F(0.5))
  4815. {
  4816. auto p = effectorParams (0, 0.5f, 1.0f);
  4817. const auto out = run (p, std::vector<float> (4800, 0.5f));
  4818. CHECK (std::abs (out.back() - 0.5f) < 1e-3f);
  4819. const auto small = run (p, std::vector<float> (4800, 0.05f));
  4820. CHECK (small.back() > 0.45f && small.back() < 0.5f); // saturates near ±0.5
  4821. }
  4822. // Ring: DC 1 becomes the carrier sine, 2^(8.7·0 + 5) = 32 Hz -> 32 cycles per second
  4823. {
  4824. auto p = effectorParams (11, 0.0f, 0.0f);
  4825. const auto out = run (p, std::vector<float> (48000, 1.0f));
  4826. int crossings = 0;
  4827. for (std::size_t i = 4800; i < out.size(); ++i)
  4828. crossings += (out[i - 1] < 0.0f) != (out[i] < 0.0f);
  4829. CHECK (crossings >= 56 && crossings <= 60); // 0.9 s × 32 Hz × 2
  4830. }
  4831. // Trancer, Y = 0: at the start of the period the gain drops to zero; X = 1 returns only at the end of the period
  4832. {
  4833. auto p = effectorParams (8, 1.0f, 0.0f);
  4834. p[5] = 1.0f; // 8/1 = 8 beats = 4 s at 120 BPM
  4835. const auto out = run (p, std::vector<float> (48000, 1.0f));
  4836. CHECK (out[100] > 0.3f); // still rising on the "and" (1% of the period = 40 ms)
  4837. CHECK (out[24000] < 0.05f); // 0.5 s: trough
  4838. }
  4839. // Reverb with Wet = 0: the dry passes intact
  4840. {
  4841. auto p = effectorParams (6, 0.5f, 0.5f);
  4842. p[2] = 0.0f;
  4843. std::vector<float> in (4800);
  4844. for (std::size_t i = 0; i < in.size(); ++i)
  4845. in[i] = (float) std::sin (0.01 * (double) i);
  4846. const auto out = run (p, in);
  4847. for (std::size_t i = 0; i < in.size(); ++i)
  4848. CHECK (std::abs (out[i] - in[i]) < 1e-6f);
  4849. }
  4850. // Delay: the echo arrives after the Mod Rate period (1/4 beat at 120 BPM = 125 ms), at level X²
  4851. {
  4852. auto p = effectorParams (5, 0.7f, 0.5f);
  4853. p[5] = 1.0f / 8.0f; // index 1 = 1/4
  4854. std::vector<float> in (12000, 0.0f);
  4855. in[0] = 1.0f;
  4856. const auto out = run (p, in);
  4857. CHECK (std::abs (out[6000] - 0.49f) < 0.02f);
  4858. CHECK (std::abs (out[3000]) < 1e-6f);
  4859. }
  4860. // Stutter: repeats the recorded start every period
  4861. {
  4862. auto p = effectorParams (9, 0.0f, 0.0f);
  4863. p[5] = 0.0f; // 1/8 beat = 62.5 ms = 3000 samples
  4864. std::vector<float> in (9000);
  4865. for (std::size_t i = 0; i < in.size(); ++i)
  4866. in[i] = (float) i / 9000.0f;
  4867. const auto out = run (p, in);
  4868. CHECK (std::abs (out[3000 + 500] - in[500]) < 0.01f); // after the crossfade, it's the start again
  4869. CHECK (std::abs (out[1000] - in[1000]) < 1e-6f);
  4870. }
  4871. }
  4872. TEST (crossover_linkwitz_riley_sums_flat)
  4873. {
  4874. // low band + high band of the same crossover: sum with magnitude 1 (Linkwitz-Riley; for 12 and 36 dB the HP is inverted)
  4875. for (const auto combo : { 1, 3, 4, 5, 6, 7 })
  4876. for (const auto testHz : { 200.0, 1000.0, 5000.0 })
  4877. {
  4878. auto run = [&] (bool high) {
  4879. auto fx = lynx::makeEffect (lynx::EffectKind::crossover);
  4880. fx->prepare (48000.0);
  4881. auto slot = lynx::makeEffectSlot (lynx::EffectKind::crossover);
  4882. const auto value = (float) (std::log2 (1000.0 / 30.0) / 9.0589);
  4883. slot.params[high ? 0 : 3] = 1.0f;
  4884. slot.params[high ? 1 : 4] = value;
  4885. slot.params[high ? 2 : 5] = (float) combo / 7.0f;
  4886. std::vector<float> l (24000), r (24000);
  4887. for (std::size_t i = 0; i < l.size(); ++i)
  4888. l[i] = r[i] = (float) std::sin (2.0 * 3.141592653589793 * testHz * (double) i / 48000.0);
  4889. fx->process (l.data(), r.data(), 24000, slot.params, 120.0);
  4890. return l;
  4891. };
  4892. const auto low = run (false), high = run (true);
  4893. double peak = 0.0;
  4894. for (std::size_t i = 12000; i < low.size(); ++i)
  4895. peak = std::max (peak, (double) std::abs (low[i] + high[i]));
  4896. CHECK (std::abs (peak - 1.0) < 0.02);
  4897. }
  4898. // 96 dB/oct: two octaves above the cutoff the low-pass is already below −150 dB... in practice, very low
  4899. auto fx = lynx::makeEffect (lynx::EffectKind::crossover);
  4900. fx->prepare (48000.0);
  4901. auto slot = lynx::makeEffectSlot (lynx::EffectKind::crossover);
  4902. slot.params[3] = 1.0f;
  4903. slot.params[4] = (float) (std::log2 (500.0 / 30.0) / 9.0589);
  4904. slot.params[5] = 1.0f;
  4905. std::vector<float> l (24000), r (24000);
  4906. for (std::size_t i = 0; i < l.size(); ++i)
  4907. l[i] = r[i] = (float) std::sin (2.0 * 3.141592653589793 * 2000.0 * (double) i / 48000.0);
  4908. fx->process (l.data(), r.data(), 24000, slot.params, 120.0);
  4909. float peak = 0.0f;
  4910. for (std::size_t i = 12000; i < l.size(); ++i)
  4911. peak = std::max (peak, std::abs (l[i]));
  4912. CHECK (peak < 1e-4f);
  4913. }
  4914. TEST (rhythm_gain_and_autopan)
  4915. {
  4916. // 1-beat gate: 1 → 0 at 0.5 beat (linear) → 1 at the end; at 120 BPM 1 beat = 24000 samples at 48 kHz
  4917. auto slot = lynx::makeEffectSlot (lynx::EffectKind::rhythmGain);
  4918. slot.params[0] = 1.0f / 64.0f;
  4919. slot.params[1] = 3.0f / 12.0f;
  4920. const float pts[3][3] = { { 0.0f, 1.0f, 0.5f }, { 0.5f, 0.0f, 0.5f }, { 1.0f, 1.0f, 0.5f } };
  4921. for (int k = 0; k < 3; ++k)
  4922. for (int j = 0; j < 3; ++j)
  4923. slot.params[(std::size_t) (2 + 3 * k + j)] = pts[k][j];
  4924. auto fx = lynx::makeEffect (lynx::EffectKind::rhythmGain);
  4925. fx->prepare (48000.0);
  4926. fx->setSongPosition (960.0 * 2.0); // beat 2: phase 0
  4927. std::vector<float> l (24000, 1.0f), r (24000, 1.0f);
  4928. fx->process (l.data(), r.data(), 24000, slot.params, 120.0);
  4929. CHECK (std::abs (l[0] - 1.0f) < 1e-3f);
  4930. CHECK (std::abs (l[6000] - 0.5f) < 1e-3f);
  4931. CHECK (l[12000] < 1e-3f);
  4932. CHECK (std::abs (l[18000] - 0.5f) < 1e-3f);
  4933. // positive tension: changes quickly at the start of the segment
  4934. CHECK (lynx::effectInfo (lynx::EffectKind::rhythmGain).params.size() == 39);
  4935. // auto-pan: 1-beat period, full depth; start phase 0.75 -> W = 0 rising (pan centered)
  4936. auto pan = lynx::makeEffectSlot (lynx::EffectKind::autoPan);
  4937. pan.params[0] = 1.0f / 64.0f;
  4938. pan.params[1] = 1.0f;
  4939. auto ap = lynx::makeEffect (lynx::EffectKind::autoPan);
  4940. ap->prepare (48000.0);
  4941. ap->setSongPosition (0.0);
  4942. std::vector<float> a (24000, 1.0f), b (24000, 1.0f);
  4943. ap->process (a.data(), b.data(), 24000, pan.params, 120.0);
  4944. CHECK (std::abs (a[0] - 1.0f) < 1e-3f && std::abs (b[0] - 1.0f) < 1e-3f);
  4945. CHECK (a[6000] < 0.01f && std::abs (b[6000] - 1.0f) < 1e-3f); // ¼ cycle later: fully right
  4946. }
  4947. TEST (vocoder_side_inputs_split_modulator_and_carrier)
  4948. {
  4949. // "Side inputs" mode (Vocodex): modulator from side input 1 (noise in the first half), carrier from side input 2
  4950. // (saw), own input silent → the output follows the side modulator; with input 1 silent, the output is silent
  4951. auto slot = lynx::makeEffectSlot (lynx::EffectKind::vocoder);
  4952. slot.params[16] = 1.0f;
  4953. auto fx = lynx::makeEffect (lynx::EffectKind::vocoder);
  4954. fx->prepare (48000.0);
  4955. std::vector<float> modL (48000), car (48000), l (48000, 0.0f), r (48000, 0.0f);
  4956. std::uint32_t seed = 1;
  4957. for (std::size_t i = 0; i < modL.size(); ++i)
  4958. {
  4959. seed = seed * 1664525u + 1013904223u;
  4960. modL[i] = i < 24000 ? ((float) (seed >> 8) / 16777216.0f - 0.5f) : 0.0f;
  4961. car[i] = (float) (2.0 * std::fmod ((double) i * 220.0 / 48000.0, 1.0) - 1.0) * 0.5f;
  4962. }
  4963. for (int done = 0; done < 48000; done += 480)
  4964. {
  4965. fx->setSidechain (modL.data() + done, modL.data() + done);
  4966. fx->setSidechain2 (car.data() + done, car.data() + done);
  4967. fx->process (l.data() + done, r.data() + done, 480, slot.params, 120.0);
  4968. }
  4969. auto rms = [&] (int from, int to) {
  4970. double e = 0.0;
  4971. for (int i = from; i < to; ++i)
  4972. e += (double) l[(std::size_t) i] * l[(std::size_t) i];
  4973. return std::sqrt (e / (to - from));
  4974. };
  4975. CHECK (rms (6000, 20000) > 0.01);
  4976. CHECK (rms (40000, 48000) < 0.1 * rms (6000, 20000));
  4977. // the side modulator configured but silent: nothing comes out (the own input is not used instead)
  4978. std::vector<float> a (4800, 0.3f), b (4800, 0.3f);
  4979. for (int done = 0; done < 4800; done += 480)
  4980. {
  4981. fx->setSidechain (nullptr, nullptr);
  4982. fx->setSidechain2 (car.data() + done, car.data() + done);
  4983. fx->process (a.data() + done, b.data() + done, 480, slot.params, 120.0);
  4984. }
  4985. CHECK (std::abs (a[4700]) < 0.05f);
  4986. }
  4987. TEST (vocoder_follows_modulator)
  4988. {
  4989. // modulator (L) plays only in the first half; carrier (R) is a continuous saw: the wet follows the modulator
  4990. auto slot = lynx::makeEffectSlot (lynx::EffectKind::vocoder);
  4991. auto fx = lynx::makeEffect (lynx::EffectKind::vocoder);
  4992. fx->prepare (48000.0);
  4993. std::vector<float> l (48000), r (48000);
  4994. std::uint32_t seed = 1;
  4995. for (std::size_t i = 0; i < l.size(); ++i)
  4996. {
  4997. seed = seed * 1664525u + 1013904223u;
  4998. l[i] = i < 24000 ? ((float) (seed >> 8) / 16777216.0f - 0.5f) : 0.0f;
  4999. r[i] = (float) (2.0 * std::fmod ((double) i * 220.0 / 48000.0, 1.0) - 1.0) * 0.5f;
  5000. }
  5001. fx->process (l.data(), r.data(), 48000, slot.params, 120.0);
  5002. auto rms = [&] (int from, int to) {
  5003. double e = 0.0;
  5004. for (int i = from; i < to; ++i)
  5005. e += (double) l[(std::size_t) i] * l[(std::size_t) i];
  5006. return std::sqrt (e / (to - from));
  5007. };
  5008. CHECK (rms (6000, 20000) > 0.01);
  5009. CHECK (rms (40000, 48000) < 0.1 * rms (6000, 20000)); // modulator silent: the vocoder fades out (100 ms release)
  5010. for (std::size_t i = 0; i < l.size(); ++i)
  5011. CHECK (l[i] == r[i] && std::isfinite (l[i])); // mono output
  5012. }
  5013. // Vocodex (REA_rodada35): a synthetic state in FL's layout (version 8, 13 maps, 20 parameters, the 0x24 block,
  5014. // 13 map-axis bytes, tone, notes)
  5015. struct VocodexSpec
  5016. {
  5017. // Wet, SG, ModVol, ModHP, CarVol, CarLP, CarNoise, CarNoiseHP, Hold, Att, AttCurve, Rel, RelCurve, Freeze, BW,
  5018. // Flatness, ModBW, ModPitch, FatPitch, FatPan
  5019. std::array<std::int32_t, 20> params { 1000, 0, 0, 0, 0, 65536, 0, 0, 0, 2000, 0, 3000, 0, 0, 1000, 0, 2000, 0, 0, 0 };
  5020. std::array<std::int32_t, 7> block { 0, 2, 0, 24, 1, 1, 2 }; // hold mode, order, unison, bands, draft field, ModIn, CarIn
  5021. std::array<std::uint8_t, 8> flags { 0, 1, 0, 1, 1, 0, 0, 0 }; // L-R, MIN TIMES, TO MOD, THREADED, subtractive, TO NOISE, FROM CAR, FROM CONS
  5022. std::vector<std::uint8_t> bytes() const
  5023. {
  5024. std::vector<std::uint8_t> d;
  5025. auto put = [&d] (const void* p, std::size_t n) { d.insert (d.end(), (const std::uint8_t*) p, (const std::uint8_t*) p + n); };
  5026. auto i32 = [&] (std::int32_t v) { put (&v, 4); };
  5027. i32 (8 << 16);
  5028. for (int m = 0; m < 13; ++m)
  5029. {
  5030. const double y0 = m == 8 ? 0.1429 : (m == 3 || m == 4 || m == 11) ? 0.0 : 0.5;
  5031. const double y1 = m == 8 ? 0.9918 : y0;
  5032. i32 (1), i32 (0), i32 (2);
  5033. for (const auto& [dx, y] : { std::pair { 0.0, y0 }, std::pair { 1.0, y1 } })
  5034. {
  5035. put (&dx, 8), put (&y, 8);
  5036. i32 (0), i32 (0); // tension (f32 0), flags
  5037. }
  5038. const std::array<std::uint8_t, 20> tail {};
  5039. put (tail.data(), tail.size());
  5040. }
  5041. for (auto v : params)
  5042. i32 (v);
  5043. for (auto v : block)
  5044. i32 (v);
  5045. put (flags.data(), flags.size());
  5046. const std::array<std::uint8_t, 13> axis {};
  5047. put (axis.data(), axis.size());
  5048. d.push_back (3), put ("PWM", 3);
  5049. i32 (1), i32 (60);
  5050. return d;
  5051. }
  5052. };
  5053. std::vector<float> vocodexSaw (int n, double hz, double fs)
  5054. {
  5055. std::vector<float> out ((std::size_t) n);
  5056. for (int i = 0; i < n; ++i)
  5057. out[(std::size_t) i] = (float) (2.0 * std::fmod (i * hz / fs, 1.0) - 1.0) * 0.4f;
  5058. return out;
  5059. }
  5060. TEST (vocodex_state_parse_and_conversion)
  5061. {
  5062. VocodexSpec spec;
  5063. spec.block = { 1, 3, 2, 40, 0, 2, 1 };
  5064. spec.params[17] = -1200;
  5065. const auto raw = spec.bytes();
  5066. const auto s = lynx::vocodex::parseState (raw);
  5067. CHECK (s.has_value());
  5068. if (! s)
  5069. return;
  5070. CHECK (s->version == 8 && s->holdMode == 1 && s->order == 3 && s->unison == 2 && s->bands == 40);
  5071. CHECK (s->draft() && s->modIn == 2 && s->carIn == 1 && s->minTimes && s->subtractiveGate && ! s->lrEncoding);
  5072. CHECK (s->params[lynx::vocodex::modPitch] == -1200 && s->params[lynx::vocodex::carLp] == 65536);
  5073. CHECK (s->maps[8].x.size() == 2 && std::abs (s->maps[8].y[1] - 0.9918) < 1e-12 && s->maps[8].x[1] == 1.0);
  5074. CHECK (s->tone == "PWM" && s->notes.size() == 1 && s->notes[0] == 60);
  5075. const auto v = lynx::vocodexEffect (raw);
  5076. CHECK (v && v->slot.kind == lynx::EffectKind::vocodex && v->slot.state == raw && v->modIn == 2 && v->carIn == 1 && v->notes.empty());
  5077. spec.block[6] = -1; // internal synth carrier: not available yet → reported
  5078. spec.params[1] = 150; // Soundgoodizer stage
  5079. const auto w = lynx::vocodexEffect (spec.bytes());
  5080. CHECK (w && w->carIn == -1 && w->notes.size() == 2);
  5081. CHECK (! lynx::vocodex::parseState ({ 1, 2, 3 }).has_value());
  5082. }
  5083. TEST (vocodex_vocodes_side_inputs)
  5084. {
  5085. // modulator on side input 1 (noise in the first half), carrier on side input 2 (saw), own input silent: the
  5086. // output follows the modulator's envelope and fades after it stops
  5087. VocodexSpec spec;
  5088. lynx::EffectSlot slot = lynx::makeEffectSlot (lynx::EffectKind::vocodex);
  5089. slot.state = spec.bytes();
  5090. auto fx = lynx::makeEffect (slot);
  5091. fx->prepare (48000.0);
  5092. CHECK (fx->latencySamples() == 0);
  5093. const auto car = vocodexSaw (48000, 110.0, 48000.0);
  5094. std::vector<float> mod (48000), l (48000, 0.0f), r (48000, 0.0f);
  5095. std::uint32_t seed = 7;
  5096. for (std::size_t i = 0; i < mod.size(); ++i)
  5097. {
  5098. seed = seed * 1664525u + 1013904223u;
  5099. mod[i] = i < 24000 ? ((float) (seed >> 8) / 16777216.0f - 0.5f) : 0.0f;
  5100. }
  5101. for (int done = 0; done < 48000; done += 512)
  5102. {
  5103. const int n = std::min (512, 48000 - done);
  5104. fx->setSidechain (mod.data() + done, mod.data() + done);
  5105. fx->setSidechain2 (car.data() + done, car.data() + done);
  5106. fx->process (l.data() + done, r.data() + done, n, slot.params, 120.0);
  5107. }
  5108. auto rms = [&] (int from, int to) {
  5109. double e = 0.0;
  5110. for (int i = from; i < to; ++i)
  5111. e += (double) l[(std::size_t) i] * l[(std::size_t) i] + (double) r[(std::size_t) i] * r[(std::size_t) i];
  5112. return std::sqrt (e / (2.0 * (to - from)));
  5113. };
  5114. CHECK (rms (6000, 20000) > 0.02);
  5115. CHECK (rms (40000, 48000) < 0.01 * rms (6000, 20000));
  5116. CHECK (std::abs (l[0]) < 1e-6f); // the gains ramp up from 0 when the plugin is created
  5117. }
  5118. TEST (vocodex_draft_latency_and_pass_through)
  5119. {
  5120. // carrier pass-through at unit gain only (Wet 0): after a Flush the gains snap, so the output is the carrier,
  5121. // 16 samples late in Draft
  5122. VocodexSpec spec;
  5123. spec.params[0] = 0; // Wet
  5124. spec.params[4] = 12800; // CarVol = 1
  5125. for (const int draftField : { 1, 0 })
  5126. {
  5127. spec.block[4] = draftField;
  5128. const auto s = lynx::vocodex::parseState (spec.bytes());
  5129. CHECK (s.has_value());
  5130. lynx::vocodex::Engine engine;
  5131. engine.prepare (*s, 44100.0, 300, s->draft());
  5132. CHECK (engine.latencySamples() == (draftField == 0 ? 16 : 0));
  5133. engine.flush();
  5134. const auto saw = vocodexSaw (3000, 220.0, 44100.0);
  5135. std::vector<float> car (6000), mod (6000, 0.0f), out (6000);
  5136. for (int i = 0; i < 3000; ++i)
  5137. car[(std::size_t) (2 * i)] = car[(std::size_t) (2 * i + 1)] = saw[(std::size_t) i];
  5138. static constexpr int sizes[] { 300, 37, 128, 1, 255, 16, 299 }; // uneven blocks exercise the FIFOs
  5139. for (int done = 0, k = 0, n = 0; done < 3000; done += n, ++k)
  5140. {
  5141. n = std::min (sizes[k % 7], 3000 - done);
  5142. engine.process (mod.data() + 2 * done, mod.data() + 2 * done, car.data() + 2 * done, out.data() + 2 * done, n);
  5143. }
  5144. const int lag = engine.latencySamples();
  5145. auto maxError = 0.0f;
  5146. for (int i = lag; i < 3000; ++i)
  5147. maxError = std::max (maxError, std::abs (out[(std::size_t) (2 * i)] - saw[(std::size_t) (i - lag)]));
  5148. CHECK (maxError == 0.0f);
  5149. }
  5150. }
  5151. TEST (vocodex_soundgoodizer_stage_limits_the_output)
  5152. {
  5153. // SG > 0: the vocoder's output (loud here: Wet 2000) goes through the Soundgoodizer approximation, whose
  5154. // master limiter keeps the peaks under −0.2 dBFS; its look-ahead is reported as latency
  5155. VocodexSpec spec;
  5156. spec.params[0] = 2000;
  5157. spec.params[1] = 250;
  5158. lynx::EffectSlot slot = lynx::makeEffectSlot (lynx::EffectKind::vocodex);
  5159. slot.state = spec.bytes();
  5160. auto fx = lynx::makeEffect (slot);
  5161. fx->prepare (48000.0);
  5162. CHECK (fx->latencySamples() == 72); // 1.5 ms at 48 kHz
  5163. const auto car = vocodexSaw (48000, 110.0, 48000.0);
  5164. std::vector<float> mod (48000), l (48000, 0.0f), r (48000, 0.0f);
  5165. for (std::size_t i = 0; i < mod.size(); ++i)
  5166. mod[i] = 0.9f * (float) std::sin (0.07 * (double) i) * (float) std::sin (0.0003 * (double) i);
  5167. auto peak = 0.0f;
  5168. for (int done = 0; done < 48000; done += 512)
  5169. {
  5170. const int n = std::min (512, 48000 - done);
  5171. fx->setSidechain (mod.data() + done, mod.data() + done);
  5172. fx->setSidechain2 (car.data() + done, car.data() + done);
  5173. fx->process (l.data() + done, r.data() + done, n, slot.params, 120.0);
  5174. }
  5175. for (std::size_t i = 0; i < l.size(); ++i)
  5176. peak = std::max ({ peak, std::abs (l[i]), std::abs (r[i]) });
  5177. CHECK (peak > 0.5f && peak <= 0.9775f);
  5178. }
  5179. TEST (vocodex_tail_bypass_and_noise)
  5180. {
  5181. // both inputs silent for longer than 0.5 s + hold + release: the own input passes unchanged
  5182. VocodexSpec spec;
  5183. const auto s = lynx::vocodex::parseState (spec.bytes());
  5184. CHECK (s.has_value());
  5185. lynx::vocodex::Engine engine;
  5186. engine.prepare (*s, 44100.0, 512, false);
  5187. std::vector<float> zero (1024, 0.0f), own (1024), out (1024);
  5188. for (std::size_t i = 0; i < own.size(); ++i)
  5189. own[i] = 0.25f * (float) std::sin (0.01 * (double) i);
  5190. for (int b = 0; b < 80; ++b)
  5191. engine.process (own.data(), zero.data(), zero.data(), out.data(), 512);
  5192. CHECK (out == own);
  5193. // carrier noise: the IPP-compatible generator restarts from the same seed after a Flush
  5194. spec.params[6] = 9000;
  5195. const auto noisy = lynx::vocodex::parseState (spec.bytes());
  5196. lynx::vocodex::Engine a;
  5197. a.prepare (*noisy, 44100.0, 512, false);
  5198. std::vector<float> mod (1024), first (1024), second (1024);
  5199. for (std::size_t i = 0; i < mod.size(); ++i)
  5200. mod[i] = 0.3f * (float) std::sin (0.05 * (double) i);
  5201. a.flush();
  5202. a.process (own.data(), mod.data(), zero.data(), first.data(), 512);
  5203. a.flush();
  5204. a.process (own.data(), mod.data(), zero.data(), second.data(), 512);
  5205. CHECK (first == second);
  5206. auto energy = 0.0;
  5207. for (auto v : first)
  5208. energy += (double) v * v;
  5209. CHECK (energy > 1e-6 && std::isfinite (energy));
  5210. }
  5211. TEST (synth_spectral_oscillator)
  5212. {
  5213. // 1/n spectrum = saw: same harmonic proportions and same level as LYNX's saw
  5214. lynx::SynthSettings saw;
  5215. saw.osc[0] = { lynx::Waveform::saw, 0, 0.0f, 1.0f };
  5216. saw.cutoff = 20000.0f;
  5217. auto spectral = saw;
  5218. spectral.osc[0].wave = lynx::Waveform::spectral;
  5219. for (int n = 1; n <= lynx::SynthSettings::spectrumSize; ++n)
  5220. spectral.spectrum[(std::size_t) n - 1] = 1.0f / (float) n;
  5221. const auto a = renderSynthNote (saw, 57, 24000), b = renderSynthNote (spectral, 57, 24000); // 220 Hz
  5222. for (const auto h : { 1, 2, 3, 5 })
  5223. {
  5224. const auto ea = goertzel (a, 220.0 * h, 4800, 24000), eb = goertzel (b, 220.0 * h, 4800, 24000);
  5225. CHECK (std::abs (10.0 * std::log10 (eb / ea)) < 0.5); // within 0.5 dB
  5226. }
  5227. // odd only: no 2nd harmonic
  5228. auto odd = spectral;
  5229. for (int n = 2; n <= lynx::SynthSettings::spectrumSize; n += 2)
  5230. odd.spectrum[(std::size_t) n - 1] = 0.0f;
  5231. const auto c = renderSynthNote (odd, 57, 24000);
  5232. CHECK (goertzel (c, 440.0, 4800, 24000) < 1e-4 * goertzel (c, 220.0, 4800, 24000));
  5233. // high note: the band-limited tables don't pass Nyquist (no aliasing below the fundamental)
  5234. const auto d = renderSynthNote (spectral, 105, 24000); // 3520 Hz
  5235. CHECK (goertzel (d, 1000.0, 4800, 24000) < 1e-3 * goertzel (d, 3520.0, 4800, 24000));
  5236. }
  5237. TEST (compressor_sidechain_ducks_and_orders_mixer)
  5238. {
  5239. // the detector listens to the side input: quiet signal on the track, loud kick on the sidechain -> reduction
  5240. auto slot = lynx::makeEffectSlot (lynx::EffectKind::compressor);
  5241. slot.params[0] = 0.5f; // threshold
  5242. slot.params[1] = 1.0f; // high ratio
  5243. slot.params[4] = 0.0f;
  5244. auto run = [&] (bool withSidechain) {
  5245. auto fx = lynx::makeEffect (lynx::EffectKind::compressor);
  5246. fx->prepare (48000.0);
  5247. std::vector<float> l (4800, 0.1f), r (4800, 0.1f), kick (4800, 1.0f);
  5248. if (withSidechain)
  5249. fx->setSidechain (kick.data(), kick.data());
  5250. fx->process (l.data(), r.data(), 4800, slot.params, 120.0);
  5251. return l.back();
  5252. };
  5253. const auto alone = run (false), ducked = run (true);
  5254. CHECK (ducked < 0.5f * alone);
  5255. // order: track 5 listens to 7 via sidechain -> 7 comes before 5
  5256. auto song = lynx::Song::makeDefault();
  5257. while (song.mixer.size() < 8)
  5258. song.mixer.push_back ({});
  5259. auto comp = lynx::makeEffectSlot (lynx::EffectKind::compressor);
  5260. comp.sidechain = 7;
  5261. song.mixer[5].effects.push_back (comp);
  5262. const auto order = song.mixerOrder();
  5263. const auto at = [&] (int t) { return std::find (order.begin(), order.end(), t) - order.begin(); };
  5264. CHECK (at (7) < at (5));
  5265. }
  5266. TEST (pitch_correction_pulls_to_allowed_note)
  5267. {
  5268. auto run = [] (const lynx::EffectParams& p, double hz) {
  5269. auto fx = lynx::makeEffect (lynx::EffectKind::pitchCorrect);
  5270. fx->prepare (48000.0);
  5271. std::vector<float> l (48000 * 2), r;
  5272. for (std::size_t i = 0; i < l.size(); ++i)
  5273. l[i] = 0.5f * (float) std::sin (2.0 * 3.141592653589793 * hz * (double) i / 48000.0);
  5274. r = l;
  5275. fx->process (l.data(), r.data(), (int) l.size(), p, 120.0);
  5276. // frequency from zero crossings in the last second
  5277. int crossings = 0;
  5278. for (std::size_t i = 48000 + 1; i < l.size(); ++i)
  5279. crossings += (l[i - 1] < 0.0f) != (l[i] < 0.0f);
  5280. return crossings / 2.0;
  5281. };
  5282. auto slot = lynx::makeEffectSlot (lynx::EffectKind::pitchCorrect); // chromatic, instant, A 440
  5283. CHECK (std::abs (run (slot.params, 452.0) - 440.0) < 4.0);
  5284. for (int k = 0; k < 12; ++k)
  5285. slot.params[(std::size_t) (5 + k)] = k == 0 ? 1.0f : 0.0f; // only C
  5286. CHECK (std::abs (run (slot.params, 452.0) - 523.25) < 5.0); // C5 (523 Hz) is closer than C4 (262)
  5287. slot.params[2] = 1.0f; // turn everything off: passes unchanged
  5288. CHECK (std::abs (run (slot.params, 452.0) - 452.0) < 4.0);
  5289. }
  5290. TEST (pitch_correction_bypass_is_a_pure_delay)
  5291. {
  5292. // FL's Pitcher with Bypass All still runs its shifter: the plain path is an exact 9-sample delay, the formant
  5293. // path (256-Hann overlap-add) an exact 257-sample delay, and Gender changes nothing without a shift
  5294. // (REA_rodada30 §2.4/2.5); both are reported as latency
  5295. std::vector<float> in (48000);
  5296. for (std::size_t i = 0; i < in.size(); ++i)
  5297. in[i] = 0.5f * (float) std::sin (2.0 * 3.141592653589793 * 440.0 * (double) i / 48000.0)
  5298. + 0.2f * (float) std::sin (2.0 * 3.141592653589793 * 1234.5 * (double) i / 48000.0);
  5299. auto run = [&] (bool formant, float gender, int& latency) {
  5300. auto fx = lynx::makeEffect (lynx::EffectKind::pitchCorrect);
  5301. fx->prepare (48000.0);
  5302. auto slot = lynx::makeEffectSlot (lynx::EffectKind::pitchCorrect);
  5303. slot.params[2] = 1.0f;
  5304. slot.params[29] = formant ? 1.0f : 0.0f;
  5305. slot.params[30] = gender;
  5306. auto l = in, r = in;
  5307. for (std::size_t i = 0; i < l.size(); i += 480)
  5308. fx->process (l.data() + i, r.data() + i, 480, slot.params, 120.0);
  5309. latency = fx->latencySamples();
  5310. return l;
  5311. };
  5312. int latency = 0;
  5313. auto plain = run (false, 0.5f, latency);
  5314. CHECK (latency == 9);
  5315. auto worst = 0.0f;
  5316. for (std::size_t i = 4000; i < in.size(); ++i)
  5317. worst = std::max (worst, std::abs (plain[i] - in[i - 9]));
  5318. CHECK (worst < 1e-5f);
  5319. auto formant = run (true, 0.8f, latency);
  5320. CHECK (latency == 257);
  5321. worst = 0.0f;
  5322. for (std::size_t i = 4000; i < in.size(); ++i)
  5323. worst = std::max (worst, std::abs (formant[i] - in[i - 257]));
  5324. CHECK (worst < 1e-5f);
  5325. }
  5326. TEST (pitch_correction_formant_path)
  5327. {
  5328. // Formant on: PSOLA keeps the correction (output pitch = grain spacing) while Gender resamples the grains:
  5329. // the spectrum of a saw moves up with Gender > 0.5 and down with Gender < 0.5
  5330. auto run = [] (float gender) {
  5331. auto fx = lynx::makeEffect (lynx::EffectKind::pitchCorrect);
  5332. fx->prepare (48000.0);
  5333. auto slot = lynx::makeEffectSlot (lynx::EffectKind::pitchCorrect); // chromatic, instant, A 440
  5334. slot.params[29] = 1.0f;
  5335. slot.params[30] = gender;
  5336. std::vector<float> l (48000 * 2), r;
  5337. for (std::size_t i = 0; i < l.size(); ++i)
  5338. l[i] = 0.5f * (float) (2.0 * std::fmod (452.0 * (double) i / 48000.0, 1.0) - 1.0); // saw
  5339. r = l;
  5340. fx->process (l.data(), r.data(), (int) l.size(), slot.params, 120.0);
  5341. l.erase (l.begin(), l.begin() + 48000);
  5342. return l;
  5343. };
  5344. // period by autocorrelation (lags 60…160 = 300…800 Hz)
  5345. auto pitch = [] (const std::vector<float>& x) {
  5346. auto best = 0.0, bestLag = 0.0;
  5347. for (int lag = 60; lag <= 160; ++lag)
  5348. {
  5349. auto sum = 0.0;
  5350. for (std::size_t i = 0; i + (std::size_t) lag < x.size(); ++i)
  5351. sum += (double) x[i] * x[i + (std::size_t) lag];
  5352. if (sum > best)
  5353. {
  5354. best = sum;
  5355. bestLag = lag;
  5356. }
  5357. }
  5358. return 48000.0 / bestLag;
  5359. };
  5360. // brightness: energy of the first difference relative to the energy
  5361. auto brightness = [] (const std::vector<float>& x) {
  5362. auto e = 0.0, d = 0.0;
  5363. for (std::size_t i = 1; i < x.size(); ++i)
  5364. {
  5365. e += (double) x[i] * x[i];
  5366. d += (double) (x[i] - x[i - 1]) * (x[i] - x[i - 1]);
  5367. }
  5368. return d / e;
  5369. };
  5370. const auto neutral = run (0.5f), up = run (0.8f), down = run (0.3f);
  5371. CHECK (std::abs (pitch (neutral) - 440.0) < 5.0); // 452 Hz pulled to A
  5372. CHECK (std::abs (pitch (up) - 440.0) < 5.0); // Gender does not move the pitch
  5373. CHECK (brightness (up) > 1.5 * brightness (neutral));
  5374. CHECK (brightness (down) < 0.7 * brightness (neutral));
  5375. }
  5376. TEST (parallel_container_inner_links_modulate)
  5377. {
  5378. // one branch: utility (gain) + a control-only auto-pan LFO (1 beat); the link maps the LFO 0..1 onto the
  5379. // utility gain −24 dB..0 dB, so the level must swing; without the link it stays put
  5380. auto container = lynx::makeEffectSlot (lynx::EffectKind::parallel);
  5381. auto gain = lynx::makeEffectSlot (lynx::EffectKind::utility);
  5382. auto lfo = lynx::makeEffectSlot (lynx::EffectKind::autoPan);
  5383. lfo.params[0] = 1.0f / 64.0f;
  5384. lfo.params[4] = 1.0f; // control only: audio passes unchanged
  5385. container.branches.push_back ({ { gain, lfo }, 1.0f });
  5386. lynx::EffectLink link;
  5387. link.source = 1;
  5388. link.param = 0;
  5389. for (int i = 0; i <= 32; ++i)
  5390. link.curve.push_back (0.5f * (float) i / 32.0f);
  5391. auto levels = [&] (bool linked) {
  5392. auto slot = container;
  5393. if (linked)
  5394. slot.links.push_back (link);
  5395. auto fx = lynx::makeParallelEffect (slot);
  5396. fx->prepare (48000.0);
  5397. float lo = 1e9f, hi = 0.0f;
  5398. for (int block = 0; block < 94; ++block) // ~1 beat at 120 BPM in 256-sample blocks
  5399. {
  5400. std::vector<float> l (256, 1.0f), r (256, 1.0f);
  5401. fx->setSongPosition (block * 256.0 / 48000.0 * 2.0 * 960.0); // the engine positions every block
  5402. fx->process (l.data(), r.data(), 256, slot.params, 120.0);
  5403. lo = std::min (lo, std::abs (l[128]));
  5404. hi = std::max (hi, std::abs (l[128]));
  5405. }
  5406. return std::pair { lo, hi };
  5407. };
  5408. const auto [lo, hi] = levels (true);
  5409. CHECK (hi > 0.8f && lo < 0.12f);
  5410. const auto [lo0, hi0] = levels (false);
  5411. CHECK (std::abs (hi0 - lo0) < 1e-4f);
  5412. }
  5413. TEST (synth_spectrum_decays_per_harmonic)
  5414. {
  5415. // harmonic 1 holds, harmonic 3 falls 60 dB in 0.2 s: early the 3rd is as loud as the 1st, later it is gone
  5416. lynx::SynthSettings s;
  5417. s.osc[0] = { lynx::Waveform::spectral, 0, 0.0f, 1.0f };
  5418. s.cutoff = 20000.0f;
  5419. s.decay = 0.0f;
  5420. s.sustain = 1.0f;
  5421. s.spectrum[0] = 1.0f;
  5422. s.spectrum[2] = 1.0f;
  5423. s.spectrumDecay[2] = 0.2f;
  5424. const auto x = renderSynthNote (s, 57, 48000); // 220 Hz, 48 kHz, 1 s
  5425. // equal 2400-sample windows (Goertzel power grows with the window): 10…60 ms and 500…550 ms
  5426. const auto early1 = goertzel (x, 220.0, 480, 2880), early3 = goertzel (x, 660.0, 480, 2880);
  5427. const auto late1 = goertzel (x, 220.0, 24000, 26400), late3 = goertzel (x, 660.0, 24000, 26400);
  5428. CHECK (early3 > 0.05 * early1); // ≈ −9 dB on average over 10…60 ms
  5429. CHECK (late3 < 1e-4 * late1);
  5430. CHECK (std::abs (10.0 * std::log10 (late1 / early1)) < 1.0); // the 1st holds
  5431. // without per-harmonic decay the spectrum stays as it is
  5432. s.spectrumDecay[2] = 0.0f;
  5433. const auto y = renderSynthNote (s, 57, 48000);
  5434. CHECK (std::abs (10.0 * std::log10 (goertzel (y, 660.0, 24000, 26400) / goertzel (y, 660.0, 480, 2880))) < 1.0);
  5435. }
  5436. TEST (worker_pool_runs_each_index_once_per_round)
  5437. {
  5438. // rounds of alternating sizes (a stalled worker must never run an index of a later round), each index
  5439. // exactly once, and nothing running after parallelFor returns
  5440. lynx::WorkerPool pool (3);
  5441. std::vector<std::atomic<int>> hits (64);
  5442. std::atomic<int> round { 0 }, outside { 0 }, wrongRound { 0 };
  5443. std::atomic<bool> open { false };
  5444. int failures = 0;
  5445. for (int r = 1; r <= 20000; ++r)
  5446. {
  5447. const auto n = (r % 3 == 0) ? 64 : (r % 3 == 1 ? 2 : 9);
  5448. for (int i = 0; i < n; ++i)
  5449. hits[(std::size_t) i].store (0);
  5450. round.store (r);
  5451. open.store (true);
  5452. auto fn = [&, r] (int i) {
  5453. if (! open.load())
  5454. outside.fetch_add (1);
  5455. if (round.load() != r)
  5456. wrongRound.fetch_add (1);
  5457. hits[(std::size_t) i].fetch_add (1);
  5458. };
  5459. pool.parallelFor (n, fn);
  5460. open.store (false);
  5461. for (int i = 0; i < n; ++i)
  5462. failures += hits[(std::size_t) i].load() != 1;
  5463. }
  5464. CHECK (failures == 0);
  5465. CHECK (outside.load() == 0);
  5466. CHECK (wrongRound.load() == 0);
  5467. }
  5468. TEST (ladder_filter_follows_toxic_law)
  5469. {
  5470. // the 4-pole ladder: −24 dB/oct far above the cutoff (vs −12 for the SVF), resonance raises the corner, and
  5471. // the input saturation keeps it bounded even at full resonance
  5472. auto level = [] (bool ladder, float res, double hz) {
  5473. lynx::SynthSettings s;
  5474. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  5475. s.cutoff = 500.0f;
  5476. s.resonance = res;
  5477. s.ladder = ladder;
  5478. const auto key = (int) std::lround (69.0 + 12.0 * std::log2 (hz / 440.0));
  5479. const auto x = renderSynthNote (s, key, 48000);
  5480. double e = 0.0, peak = 0.0;
  5481. for (std::size_t i = 24000; i < 48000; ++i)
  5482. e += (double) x[i] * x[i], peak = std::max (peak, (double) std::abs (x[i]));
  5483. return std::pair { std::sqrt (e / 24000.0), peak };
  5484. };
  5485. const auto low = level (true, 0.0f, 110.0).first, high = level (true, 0.0f, 3520.0).first; // 3 octaves above 500 Hz… 2.8
  5486. const auto svfHigh = level (false, 0.0f, 3520.0).first / level (false, 0.0f, 110.0).first;
  5487. CHECK (20.0 * std::log10 (high / low) < -55.0); // ≈ 24 dB/oct over ~2.8 octaves
  5488. CHECK (20.0 * std::log10 (svfHigh) > -45.0); // the 2-pole SVF falls much less
  5489. const auto corner0 = level (true, 0.0f, 523.25).first, corner1 = level (true, 0.6f, 523.25).first;
  5490. CHECK (corner1 > 1.5 * corner0); // resonance boosts near the cutoff
  5491. const auto loud = level (true, 1.0f, 523.25);
  5492. CHECK (std::isfinite (loud.first) && loud.second < 20.0); // self-oscillation stays bounded
  5493. }
  5494. TEST (synth_spectrum_settles_on_target)
  5495. {
  5496. // ALT DECAY-like morph: harmonic 3 starts at 1 and settles on 0.25 (−12 dB) instead of fading out
  5497. lynx::SynthSettings s;
  5498. s.osc[0] = { lynx::Waveform::spectral, 0, 0.0f, 1.0f };
  5499. s.cutoff = 20000.0f;
  5500. s.decay = 0.0f;
  5501. s.sustain = 1.0f;
  5502. s.spectrum[0] = 1.0f;
  5503. s.spectrum[2] = 1.0f;
  5504. s.spectrumDecay[2] = 0.1f;
  5505. s.spectrumTarget[2] = 0.25f;
  5506. const auto x = renderSynthNote (s, 57, 48000);
  5507. const auto ratio = goertzel (x, 660.0, 24000, 26400) / goertzel (x, 220.0, 24000, 26400);
  5508. CHECK (std::abs (10.0 * std::log10 (ratio) - 20.0 * std::log10 (0.25)) < 1.0);
  5509. }
  5510. TEST (kepler_chorus_is_stereo_and_keeps_level)
  5511. {
  5512. // chorus I on a sine: L and R differ (opposite LFO phases), the level stays close to the dry one
  5513. lynx::SynthSettings s;
  5514. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  5515. s.cutoff = 20000.0f;
  5516. auto dry = s;
  5517. s.chorus = 1;
  5518. auto render = [] (const lynx::SynthSettings& set) {
  5519. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  5520. inst->prepare (48000.0);
  5521. lynx::ChannelDef c;
  5522. c.synth = set;
  5523. inst->configure (c, 120.0);
  5524. inst->noteOn (69, 1.0f);
  5525. std::vector<float> l (96000), r (96000);
  5526. inst->render (l.data(), r.data(), 96000, 1.0f, 1.0f);
  5527. return std::pair { l, r };
  5528. };
  5529. const auto [l, r] = render (s);
  5530. const auto [dl, dr] = render (dry);
  5531. double diff = 0.0, e = 0.0, ed = 0.0;
  5532. for (std::size_t i = 48000; i < 96000; ++i)
  5533. diff += std::abs (l[i] - r[i]), e += (double) l[i] * l[i], ed += (double) dl[i] * dl[i];
  5534. CHECK (diff / 48000.0 > 1e-3);
  5535. CHECK (std::abs (10.0 * std::log10 (e / ed)) < 3.0);
  5536. }
  5537. TEST (fl_pan_law_matches_love_philter_dll)
  5538. {
  5539. // values printed by the installation's Love Philter pan routine for vol 0.8 (REA_rodada27 §3.1, lppan.txt)
  5540. struct Row { double pan, ll, rr, rl, lr; };
  5541. const Row rows[] = { { -1.5, 0.239782482, -0.432956904, 0.805467963, 0.0 }, { -0.5, 0.805467963, 0.432956904, 0.239782482, 0.0 },
  5542. { 0.0, 0.8, 0.8, 0.0, 0.0 }, { 0.75, 0.220719516, 0.707889318, 0.0, 0.401742548 },
  5543. { 1.0, 0.0, 0.565685451, 0.0, 0.565685451 } };
  5544. for (const auto& row : rows)
  5545. {
  5546. float ll, rl, lr, rr;
  5547. lynx::flPanMatrix (row.pan, ll, rl, lr, rr);
  5548. CHECK (std::abs (0.8 * ll - row.ll) < 1e-6 && std::abs (0.8 * rr - row.rr) < 1e-6);
  5549. CHECK (std::abs (0.8 * rl - row.rl) < 1e-6 && std::abs (0.8 * lr - row.lr) < 1e-6);
  5550. }
  5551. }
  5552. TEST (effector_units_match_fl_dll_impulse_responses)
  5553. {
  5554. // impulse responses of the installation's Effector engine (REA_rodada27 §2, eu_<kind>_<X>_<Y>.txt; LFO off,
  5555. // wet 1, blocks of 256): samples 1, 10, 100 and 1000
  5556. struct Case { int kind; float x, y; double v[4]; };
  5557. const Case cases[] = { { 3, 0.5f, 0.5f, { -0.603055418, 0.159798339, -0.0055043716, -1.06241259e-06 } },
  5558. { 4, 0.2f, 0.5f, { 4.68885949e-26, 4.20032622e-19, 0.000487731799, 2.27715846e-09 } },
  5559. { 4, 0.8f, 0.3f, { -0.293783396, -0.0306414738, -0.00068128563, 1.358577e-15 } } };
  5560. for (const auto& c : cases)
  5561. {
  5562. auto fx = lynx::effector::make();
  5563. fx->prepare (44100.0);
  5564. lynx::EffectParams p {};
  5565. p[lynx::effector::type] = c.kind / 11.0f;
  5566. p[lynx::effector::wetMix] = 1.0f;
  5567. p[lynx::effector::paramX] = c.x;
  5568. p[lynx::effector::paramY] = c.y;
  5569. p[lynx::effector::modX] = p[lynx::effector::modY] = 0.5f;
  5570. p[lynx::effector::modRate] = 0.5f;
  5571. p[lynx::effector::inputLevel] = 1.0f;
  5572. p[lynx::effector::outputGain] = 0.5f;
  5573. std::vector<float> l (1024, 0.0f), r (1024, 0.0f);
  5574. l[0] = r[0] = 1.0f;
  5575. for (int d = 0; d < 1024; d += 256)
  5576. fx->process (l.data() + d, r.data() + d, 256, p, 120.0);
  5577. const int at[4] { 1, 10, 100, 1000 };
  5578. for (int k = 0; k < 4; ++k)
  5579. CHECK (std::abs (l[(std::size_t) at[k]] - c.v[k]) < 2e-7 + 1e-5 * std::abs (c.v[k]));
  5580. }
  5581. }
  5582. TEST (harmless_stereo_tremolo_and_vibrato)
  5583. {
  5584. // tremolo d = 1: each side swings between 0 and 1.25 at 5 Hz, L and R in anti-phase; vibrato modulates the pitch
  5585. lynx::SynthSettings s;
  5586. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  5587. s.cutoff = 20000.0f;
  5588. s.stereoTremolo = 1.0f;
  5589. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  5590. inst->prepare (48000.0);
  5591. lynx::ChannelDef c;
  5592. c.synth = s;
  5593. inst->configure (c, 120.0);
  5594. inst->noteOn (69, 1.0f);
  5595. std::vector<float> l (48000), r (48000);
  5596. inst->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  5597. auto envelope = [] (const std::vector<float>& x, int at) { float m = 0.0f; for (int i = at; i < at + 120; ++i) m = std::max (m, std::abs (x[(std::size_t) i])); return m; };
  5598. // θ = 2π·2.5·t: at t = 0.4 s cos = 1 (L peak 1.25×), sin = 0 (R near 0); at t = 0.5 s the opposite
  5599. CHECK (envelope (l, 19200) > 4.0f * envelope (r, 19200));
  5600. CHECK (envelope (r, 24000) > 4.0f * envelope (l, 24000));
  5601. // vibrato 100 cents: zero crossings vary in spacing; without it they are regular
  5602. auto crossingsSpread = [] (float cents) {
  5603. lynx::SynthSettings v;
  5604. v.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  5605. v.cutoff = 20000.0f;
  5606. v.vibratoCents = cents;
  5607. const auto x = renderSynthNote (v, 69, 48000);
  5608. std::vector<int> zc;
  5609. for (int i = 24000; i < 48000; ++i)
  5610. if (x[(std::size_t) i - 1] < 0.0f && x[(std::size_t) i] >= 0.0f)
  5611. zc.push_back (i);
  5612. int lo = 1 << 30, hi = 0;
  5613. for (std::size_t k = 1; k < zc.size(); ++k)
  5614. lo = std::min (lo, zc[k] - zc[k - 1]), hi = std::max (hi, zc[k] - zc[k - 1]);
  5615. return hi - lo;
  5616. };
  5617. CHECK (crossingsSpread (0.0f) <= 1);
  5618. CHECK (crossingsSpread (100.0f) >= 4);
  5619. }
  5620. TEST (physical_models_sound_and_end)
  5621. {
  5622. // Sakura: a plucked string with default-ish parameters rings and fades after the release; Drumpad: a hit decays
  5623. for (const auto kind : { lynx::InstrumentKind::sakura, lynx::InstrumentKind::drumpad })
  5624. {
  5625. lynx::ChannelDef c;
  5626. c.instrument = kind;
  5627. if (kind == lynx::InstrumentKind::sakura)
  5628. {
  5629. c.modelParams.assign (146, 0.5f);
  5630. c.modelParams[111] = 3.0f; // both strings at the note
  5631. c.modelParams[113] = 0.5f; // octave ×1
  5632. c.modelParams[6] = c.modelParams[11] = 0.99f; // long decay
  5633. c.modelParams[31] = 0.0f; // noise exciter
  5634. }
  5635. else
  5636. {
  5637. c.modelParams.assign (38, 0.5f);
  5638. c.modelParams[0] = 1.0f; // retrigger noise
  5639. c.modelParams[30] = c.modelParams[31] = c.modelParams[32] = c.modelParams[33] = 0.0f; // no velocity morph
  5640. }
  5641. auto inst = lynx::makeInstrument (kind);
  5642. inst->prepare (48000.0);
  5643. inst->configure (c, 120.0);
  5644. inst->noteOn (60, 0.8f);
  5645. std::vector<float> l (48000), r (48000);
  5646. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  5647. inst->noteOff (60);
  5648. inst->render (l.data() + 24000, r.data() + 24000, 24000, 1.0f, 1.0f);
  5649. double early = 0.0;
  5650. for (int i = 0; i < 12000; ++i)
  5651. early += (double) l[(std::size_t) i] * l[(std::size_t) i];
  5652. CHECK (early > 1e-6);
  5653. CHECK (std::all_of (l.begin(), l.end(), [] (float v) { return std::isfinite (v); }));
  5654. std::vector<float> tail (480000), tailR (480000);
  5655. inst->render (tail.data(), tailR.data(), 480000, 1.0f, 1.0f); // 10 s later the voice has ended
  5656. CHECK (inst->idle());
  5657. }
  5658. }
  5659. TEST (squeeze_matches_fl_model)
  5660. {
  5661. // Fruity Squeeze: Steps quantises, Mix 0 passes the input dry ×Volume/127; a silent block is left untouched
  5662. auto slot = lynx::makeEffectSlot (lynx::EffectKind::squeeze);
  5663. slot.params[1] = 0.0f; // mix 0: dry only
  5664. auto fx = lynx::makeEffect (lynx::EffectKind::squeeze);
  5665. fx->prepare (44100.0);
  5666. std::vector<float> l (512, 0.3f), r (512, -0.2f);
  5667. fx->process (l.data(), r.data(), 512, slot.params, 120.0);
  5668. CHECK (std::abs (l[100] - 0.3f) < 1e-6f && std::abs (r[100] + 0.2f) < 1e-6f); // Volume 127/127
  5669. slot.params[1] = 1.0f; // wet only
  5670. slot.params[2] = 32000.0f / 32768.0f; // 32768^(1 − 32000/32768) ≈ 1.27 levels per unit → heavy quantisation
  5671. std::vector<float> a (512), b (512);
  5672. for (int i = 0; i < 512; ++i)
  5673. a[(std::size_t) i] = b[(std::size_t) i] = 0.4f * (float) std::sin (i * 0.05);
  5674. fx->process (a.data(), b.data(), 512, slot.params, 120.0);
  5675. const auto levels = std::pow (32768.0f, 1.0f - 32000.0f / 32768.0f);
  5676. for (int i = 0; i < 512; i += 37)
  5677. CHECK (std::abs (a[(std::size_t) i] * levels - std::nearbyint (a[(std::size_t) i] * levels)) < 1e-3f);
  5678. std::vector<float> z (512, 0.0f), z2 (512, 0.0f);
  5679. fx->process (z.data(), z2.data(), 512, slot.params, 120.0);
  5680. CHECK (z[10] == 0.0f);
  5681. }
  5682. TEST (sakura_matrix_and_effects)
  5683. {
  5684. // REA_rodada29 §1: velocity → level follows 10^(2m)·0.05 (vel 1 vs 0.5 → ×10 in amplitude); the delay leaves
  5685. // an echo after the note has ended and keeps the instrument from going idle until its tail is silent
  5686. auto base = [] {
  5687. lynx::ChannelDef c;
  5688. c.instrument = lynx::InstrumentKind::sakura;
  5689. c.modelParams.assign (146, 0.0f);
  5690. const std::pair<int, float> values[] { { 0, 0.375f }, { 1, 0.5f }, { 3, 0.5f }, { 4, 1.0f }, { 6, 0.95f }, { 9, 0.3f },
  5691. { 11, 0.95f }, { 14, 0.3f }, { 18, 0.5f }, { 19, 0.5f }, { 27, 0.5f }, { 28, 1.0f },
  5692. { 29, 0.7f }, { 31, 1.0f }, { 32, 0.5f }, { 111, 3.0f }, { 113, 0.5f } };
  5693. for (const auto& [i, v] : values)
  5694. c.modelParams[(std::size_t) i] = v;
  5695. return c;
  5696. };
  5697. auto render = [] (const lynx::ChannelDef& c, float velocity, int held, int total) {
  5698. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sakura);
  5699. inst->prepare (48000.0);
  5700. inst->configure (c, 120.0);
  5701. inst->noteOn (60, velocity);
  5702. std::vector<float> l ((std::size_t) total), r ((std::size_t) total);
  5703. for (int s = 0; s < total; s += 256)
  5704. {
  5705. if (s == held)
  5706. inst->noteOff (60);
  5707. inst->render (l.data() + s, r.data() + s, std::min (256, total - s), 1.0f, 1.0f);
  5708. }
  5709. return std::make_pair (l, std::move (inst));
  5710. };
  5711. auto energy = [] (const std::vector<float>& x, int from, int to) {
  5712. double e = 0.0;
  5713. for (int i = from; i < to; ++i)
  5714. e += (double) x[(std::size_t) i] * x[(std::size_t) i];
  5715. return e;
  5716. };
  5717. auto c = base();
  5718. c.modelParams[79] = 6.0f; // slot 1: velocity → level, amount 1
  5719. c.modelParams[80] = 1.0f;
  5720. c.modelParams[82] = 1.0f;
  5721. const auto loud = energy (render (c, 1.0f, 24064, 24064).first, 0, 24064);
  5722. const auto soft = energy (render (c, 0.5f, 24064, 24064).first, 0, 24064);
  5723. CHECK (loud > 1e-6 && std::abs (loud / soft - 100.0) < 1.0);
  5724. auto d = base();
  5725. auto [dry, dryInst] = render (d, 0.8f, 4864, 72000);
  5726. d.modelParams[63] = 1.0f; // delay on: time 0.5 → ≈ 0.52 s, wet 1, no feedback: one echo
  5727. d.modelParams[64] = 0.5f;
  5728. d.modelParams[69] = 1.0f;
  5729. auto [wet, wetInst] = render (d, 0.8f, 4864, 72000);
  5730. CHECK (energy (wet, 26000, 40000) > 100.0 * energy (dry, 26000, 40000) + 1e-9); // the note ends near 0.2 s
  5731. CHECK (dryInst->idle() || energy (dry, 70000, 72000) < 1e-12);
  5732. CHECK (! wetInst->idle()); // the echo tail has not been silent for 3 s yet
  5733. }
  5734. TEST (drumsynth_live_engine)
  5735. {
  5736. // REA_rodada30 §1: key → patch slot, state parsing, the engine against our reference model (no DLL: synthesised
  5737. // sources only, noise from the fallback seed), voice modes, patch level/pan
  5738. CHECK (lynx::drumSynthKeyToSlot (48) == 0 && lynx::drumSynthKeyToSlot (71) == 23 && lynx::drumSynthKeyToSlot (0) == 24);
  5739. CHECK (lynx::drumSynthKeyToSlot (47) == 71 && lynx::drumSynthKeyToSlot (72) == 72 && lynx::drumSynthKeyToSlot (119) == 119);
  5740. CHECK (lynx::drumSynthKeyToSlot (120) == -1);
  5741. // a version 3 state: 120 names, 120 × 38 ints (send track −1 becomes 0 below version 4), flags
  5742. std::vector<std::uint8_t> blob;
  5743. auto put = [&] (std::uint32_t v) { for (int k = 0; k < 4; ++k) blob.push_back ((std::uint8_t) (v >> (8 * k))); };
  5744. put (3);
  5745. put (66);
  5746. for (int i = 0; i < 120; ++i)
  5747. blob.push_back (2), blob.push_back ('a'), blob.push_back ((std::uint8_t) ('0' + i % 10));
  5748. for (int i = 0; i < 120 * 38; ++i)
  5749. put ((std::uint32_t) (i % 38 == 36 ? -1 : i % 38 == 4 ? 300 : 0));
  5750. put (0);
  5751. const auto parsed = lynx::drumSynthLiveParams (blob);
  5752. CHECK (parsed && (int) parsed->size() == lynx::drumSynthParamCount);
  5753. CHECK (parsed && (*parsed)[36] == 0.0f && (*parsed)[38 * 7 + 4] == 300.0f && (*parsed)[(std::size_t) lynx::drumSynthEditorKeyIndex] == 66.0f);
  5754. blob.resize (500);
  5755. CHECK (! lynx::drumSynthLiveParams (blob));
  5756. // patch on key 60 (slot 12): tone-mode Osc1 with sweep and click, noise-band Osc2, ring, 2 retriggers
  5757. const int patch[38] { 100, 0, 10, -20, 300, 40, 50, 70, 90, 30, 600, 60, 10, 60, 80, -1, 0, 0, 2, 40, 60, 127, 0, 20, 0, 0, 0,
  5758. 0, 0, 0, 0, 0, 0, 30, -1, 0, 0, 64 };
  5759. lynx::ChannelDef c;
  5760. c.instrument = lynx::InstrumentKind::drumsynth;
  5761. c.modelParams.assign ((std::size_t) lynx::drumSynthParamCount, 0.0f);
  5762. for (int s = 0; s < 120; ++s)
  5763. c.modelParams[(std::size_t) (38 * s + 15)] = c.modelParams[(std::size_t) (38 * s + 34)] = -1.0f;
  5764. for (int i = 0; i < 38; ++i)
  5765. c.modelParams[(std::size_t) (38 * 12 + i)] = (float) patch[i];
  5766. auto render = [] (const lynx::ChannelDef& def, std::vector<int> keys, int total, float gl = 1.0f, float gr = 1.0f) {
  5767. auto inst = lynx::makeInstrument (lynx::InstrumentKind::drumsynth);
  5768. inst->configure (def, 120.0);
  5769. inst->prepare (48000.0);
  5770. std::vector<float> l ((std::size_t) total), r ((std::size_t) total);
  5771. for (int s = 0; s < total; s += 512)
  5772. {
  5773. for (std::size_t k = 0; k + 1 < keys.size(); k += 2)
  5774. if (keys[k + 1] == s)
  5775. inst->noteOn (keys[k], 100.0f / 128.0f);
  5776. inst->render (l.data() + s, r.data() + s, std::min (512, total - s), gl, gr);
  5777. }
  5778. return std::make_tuple (l, r, std::move (inst));
  5779. };
  5780. {
  5781. auto [l, r, inst] = render (c, { 60, 0 }, 9600);
  5782. // reference model (REA round 30 dsl_model.py, seed 0x56CE, FL velocity 100, V = 1, centre: × g(100)·cos(π/4))
  5783. const std::pair<int, float> golden[] { { 0, -0.0074092713f }, { 10, -0.13961405f }, { 100, -0.47290668f }, { 1000, -0.29188696f },
  5784. { 3000, -0.22130175f }, { 6000, -0.049537566f }, { 9599, 0.010392102f } };
  5785. for (const auto& [i, v] : golden)
  5786. CHECK (std::abs (l[(std::size_t) i] - v) < 2e-6f && std::abs (r[(std::size_t) i] - v) < 2e-6f);
  5787. std::vector<float> tail (48000 * 4), tailR (tail.size());
  5788. inst->render (tail.data(), tailR.data(), (int) tail.size(), 1.0f, 1.0f);
  5789. CHECK (inst->idle()); // the engine reported the voice finished
  5790. }
  5791. auto energy = [] (const std::vector<float>& x, int from, int to) {
  5792. double e = 0.0;
  5793. for (int i = from; i < to; ++i)
  5794. e += (double) x[(std::size_t) i] * x[(std::size_t) i];
  5795. return e;
  5796. };
  5797. // a key without a patch level (slot 0, level 0) and a key outside the 120 patches are silent
  5798. CHECK (energy (std::get<0> (render (c, { 48, 0, 125, 0 }, 4096)), 0, 4096) == 0.0);
  5799. // mono: a second hit on the same key cuts the first; poly: both ring together (Osc2 off: no noise, deterministic)
  5800. auto tone = c;
  5801. tone.modelParams[38 * 12 + 14] = 0.0f;
  5802. const auto single = std::get<0> (render (tone, { 60, 0 }, 8192));
  5803. const auto mono = std::get<0> (render (tone, { 60, 0, 60, 2048 }, 8192));
  5804. auto poly = tone;
  5805. poly.modelParams[38 * 12 + 24] = 1.0f;
  5806. const auto both = std::get<0> (render (poly, { 60, 0, 60, 2048 }, 8192));
  5807. double monoDiff = 0.0, polyDiff = 0.0;
  5808. for (int i = 2048 + 300; i < 8192; ++i) // after the cut fade: mono = only the second hit, a copy of the first
  5809. monoDiff += std::abs (mono[(std::size_t) i] - single[(std::size_t) i - 2048]), polyDiff += std::abs (both[(std::size_t) i] - single[(std::size_t) i - 2048]);
  5810. CHECK (monoDiff < 1e-3 && polyDiff > 1.0);
  5811. // patch pan +64 → right only; channel volume counts twice (FL applies Final.Vol in the engine and at the host)
  5812. auto right = c;
  5813. right.modelParams[38 * 12 + 1] = 64.0f;
  5814. const auto [pl, pr, pi] = render (right, { 60, 0 }, 4096);
  5815. CHECK (energy (pl, 0, 4096) < 1e-12 * energy (pr, 0, 4096) && energy (pr, 0, 4096) > 1.0);
  5816. const auto full = std::get<0> (render (tone, { 60, 0 }, 4096));
  5817. const auto half = std::get<0> (render (tone, { 60, 0 }, 4096, 0.5f, 0.5f));
  5818. CHECK (std::abs (half[100] - 0.25f * full[100]) < 1e-6f && std::abs (full[100]) > 0.01f);
  5819. }
  5820. TEST (kepler_lfo_bpm_sync)
  5821. {
  5822. // REA_rodada33 §3.4: with BPM Sync (k6 ≥ 0.5) the LFO1 period is n/192 beats, n = trunc((2^(7(1 − x)) − 1)·48.370079 + 1.1)
  5823. std::vector<std::uint8_t> state (0x21 + 34 * 4, 0);
  5824. auto putU32 = [&] (std::size_t o, std::uint32_t v) { std::memcpy (state.data() + o, &v, 4); };
  5825. putU32 (12, 9);
  5826. std::memcpy (state.data() + 16, "Kepler-1", 9);
  5827. putU32 (0x19, 4);
  5828. putU32 (0x1D, 34);
  5829. float k[34] {};
  5830. k[5] = 0.602085769f; // "Pads - Kepler" demo: n = 286
  5831. k[6] = 1.0f;
  5832. k[10] = 1.0f; // vibrato on
  5833. k[33] = 1.0f;
  5834. std::memcpy (state.data() + 0x21, k, sizeof k);
  5835. lynx::SynthSettings s;
  5836. float gain = 0.0f;
  5837. CHECK (lynx::synthFromKepler (state, s, gain));
  5838. CHECK (s.lfo[lynx::lfoPitch].sync && s.lfo[lynx::lfoPitch].secondsTiming);
  5839. CHECK (std::abs (s.lfo[lynx::lfoPitch].period - 286.0f / 192.0f) < 1e-6f);
  5840. k[5] = 0.0f; // slowest: 32 beats
  5841. std::memcpy (state.data() + 0x21, k, sizeof k);
  5842. CHECK (lynx::synthFromKepler (state, s, gain) && std::abs (s.lfo[lynx::lfoPitch].period - 32.0f) < 1e-6f);
  5843. k[6] = 0.0f; // free rate in seconds
  5844. std::memcpy (state.data() + 0x21, k, sizeof k);
  5845. CHECK (lynx::synthFromKepler (state, s, gain) && ! s.lfo[lynx::lfoPitch].sync);
  5846. }
  5847. namespace
  5848. {
  5849. // A Harmor state written from scratch (REA_rodada11 §4.1 layout, version 18): part A only — a decaying-harmonics
  5850. // timbre, low-pass + resonance, filter envelope, 3-voice unison, vibrato, pluck, tremolo, volume envelope with a
  5851. // velocity map — and the global block. Every other curve is neutral.
  5852. std::vector<std::uint8_t> harmorTestState (bool panLfo = true)
  5853. {
  5854. std::vector<std::uint8_t> b;
  5855. auto i32 = [&] (std::int32_t v) { for (int k = 0; k < 4; ++k) b.push_back ((std::uint8_t) ((std::uint32_t) v >> (8 * k))); };
  5856. auto f64 = [&] (double v) { std::uint64_t u; std::memcpy (&u, &v, 8); for (int k = 0; k < 8; ++k) b.push_back ((std::uint8_t) (u >> (8 * k))); };
  5857. struct Pt { double dx, y, tension; int mode; };
  5858. auto curve = [&] (const std::vector<Pt>& pts, std::array<std::int32_t, 5> hdr) {
  5859. i32 (3), i32 (3), i32 ((std::int32_t) pts.size());
  5860. for (const auto& p : pts)
  5861. {
  5862. f64 (p.dx), f64 (p.y);
  5863. const auto t = (float) p.tension;
  5864. std::uint32_t u;
  5865. std::memcpy (&u, &t, 4);
  5866. i32 ((std::int32_t) u);
  5867. b.push_back ((std::uint8_t) p.mode), b.push_back (0), b.push_back (0), b.push_back (0);
  5868. }
  5869. for (auto h : hdr)
  5870. i32 (h);
  5871. };
  5872. const std::array<std::int32_t, 5> off { 0, 0, -1, -1, -1 }, on { 0, 1, -1, -1, -1 };
  5873. auto flat = [&] (double y, std::array<std::int32_t, 5> hdr = { 0, 0, -1, -1, -1 }) { curve ({ { 0, y, 0, 0 }, { 1, y, 0, 2 } }, hdr); };
  5874. i32 (18);
  5875. i32 (1 | 4);
  5876. std::vector<std::uint8_t> part;
  5877. std::swap (b, part);
  5878. std::array<std::int32_t, 386> p {};
  5879. const std::pair<int, int> values[] = { { 0, 500 }, { 3, 1000 }, { 9, 1024 }, { 11, 1000 }, { 12, 1000 }, { 17, 300 }, { 18, 4000 },
  5880. { 19, 500 }, { 20, 1000 }, { 24, 500 }, { 25, 500 }, { 28, 500 }, { 29, 256 }, { 30, -1 }, { 31, -1 }, { 33, -1 }, { 34, 3 },
  5881. { 35, 1 }, { 37, 192 }, { 38, 128 }, { 39, 500 }, { 40, 10000 }, { 41, 1 }, { 42, 10000 }, { 43, 1 }, { 45, 200 }, { 46, 500 },
  5882. { 47, 1 }, { 49, -140 }, { 50, 1200 }, { 51, 0 }, { 52, 5000 }, { 54, 500 }, { 56, 600 }, { 57, 300 }, { 59, 500 }, { 60, 600 },
  5883. { 64, 8192 }, { 66, 500 }, { 72, 600 }, { 74, 1000 }, { 75, 600 }, { 78, 5000 }, { 79, 500 }, { 80, 3000 } };
  5884. for (const auto& [i, v] : values)
  5885. p[(std::size_t) i] = v;
  5886. for (auto v : p)
  5887. i32 (v);
  5888. for (int i = 0; i < 12; ++i)
  5889. i32 (i); // module order
  5890. std::array<std::uint8_t, 0x4b> misc {};
  5891. auto put = [&] (int o, std::int32_t v) { std::memcpy (misc.data() + o, &v, 4); };
  5892. const float one = 1.0f;
  5893. put (0x08, 107), put (0x1c, 1), put (0x28, 200), std::memcpy (misc.data() + 0x30, &one, 4);
  5894. put (0x34, 0), put (0x38, 4), put (0x3c, 100), put (0x40, 108);
  5895. misc[0x44] = 1;
  5896. b.insert (b.end(), misc.begin(), misc.end());
  5897. static const int mode1[] = { 0, 2, 4, 5, 12, 13, 14, 15, 17, 18, 23, 24, 27, 28, 29, 30, 33, 36, 38, 39, 40, 41, 42 };
  5898. for (int k = 0; k < 43; ++k)
  5899. {
  5900. static const int mode2[] = { 2, 14, 23, 28, 30, 38, 39, 41, 42 }; // ×2 around 0.5: 1.0 is neutral
  5901. const bool centred = std::find (std::begin (mode1), std::end (mode1), k) != std::end (mode1);
  5902. const bool doubled = std::find (std::begin (mode2), std::end (mode2), k) != std::end (mode2);
  5903. const double neutral = centred && ! doubled ? 0.5 : 1.0;
  5904. i32 (3);
  5905. i32 (1065353216), i32 (1065353216), i32 (1065353216);
  5906. if (k == 1) // volume envelope: attack, decay to the sustain point, release
  5907. curve ({ { 0, 0, 0, 0 }, { 0.01, 1, 0.3, 0 }, { 0.3, 0.6, -0.4, 0 }, { 0.4, 0, 0.2, 0 } }, { 0, 1, 1, -1, 2 });
  5908. else if (k == 4) // filter-1 envelope
  5909. curve ({ { 0, 1, 0, 0 }, { 0.25, 0.2, -0.5, 0 } }, { 0, 1, -1, -1, -1 });
  5910. else
  5911. flat (neutral);
  5912. for (int a : { 128, 128, 0, 128 })
  5913. i32 (a);
  5914. if (k == 0 && panLfo) // pan LFO
  5915. flat (1.0, on);
  5916. else
  5917. flat (0.5);
  5918. for (int a : { k == 0 ? 40000 : 0, 0, 0, 0 })
  5919. i32 (a);
  5920. i32 (0);
  5921. for (int m = 2; m < 11; ++m)
  5922. if (k == 1 && m == 3)
  5923. curve ({ { 0, 0.2, 0, 0 }, { 1, 1, -0.3, 0 } }, off); // velocity → volume
  5924. else
  5925. flat (neutral);
  5926. }
  5927. for (int c = 0; c < 26; ++c)
  5928. if (c == 2 || c == 3)
  5929. curve ({ { 0, 0.25, 0, 0 }, { 0.006, 0.12, -0.46, 0 }, { 0.994, 0, 0, 0 } }, off); // timbres
  5930. else if (c == 14)
  5931. curve ({ { 0, 1, 0, 0 }, { 1, 0, 0, 0 } }, off); // pluck curve
  5932. else
  5933. flat (c == 0 || c == 17 ? 0.25 : (c == 5 ? 0.0 : (c == 6 || c == 10 || c == 11 || (c >= 18 && c <= 24) ? 1.0 : 0.5)));
  5934. std::swap (b, part);
  5935. i32 ((std::int32_t) part.size());
  5936. b.insert (b.end(), part.begin(), part.end());
  5937. std::array<std::int32_t, 53> g {};
  5938. g[0] = g[1] = g[2] = 256, g[10] = 500, g[11] = 1000, g[12] = 1000, g[15] = 1000;
  5939. for (auto v : g)
  5940. i32 (v);
  5941. for (int i = 0; i < 6; ++i)
  5942. i32 (i);
  5943. std::array<std::uint8_t, 0x3d> gm {};
  5944. const std::int32_t cr = 200, vr = 1;
  5945. std::memcpy (gm.data() + 12, &vr, 4);
  5946. std::memcpy (gm.data() + 24, &cr, 4);
  5947. b.insert (b.end(), gm.begin(), gm.end());
  5948. return b;
  5949. }
  5950. } // namespace
  5951. TEST (harmor_engine)
  5952. {
  5953. // REA_rodada34: state parsing, the additive engine against our reference model (hmodel.py), host levels, voice end
  5954. const auto blob = harmorTestState();
  5955. if (const char* dump = std::getenv ("LYNX_DUMP_HARMOR"))
  5956. std::ofstream (dump, std::ios::binary).write ((const char*) blob.data(), (std::streamsize) blob.size());
  5957. CHECK (lynx::harmorStateUsable (blob));
  5958. CHECK (lynx::harmorFallbacks (blob).size() == 1); // (only the harmonic-randomness note)
  5959. const auto at = lynx::harmorParamOffset (blob, 0, 52);
  5960. std::int32_t cutoff = 0;
  5961. CHECK (at > 0 && (std::memcpy (&cutoff, blob.data() + at, 4), cutoff == 5000));
  5962. CHECK (lynx::harmorParamOffset (blob, 1, 52) < 0 && lynx::harmorParamOffset (blob, -1, 12) > at);
  5963. auto broken = blob;
  5964. broken.resize (broken.size() / 2);
  5965. CHECK (! lynx::harmorStateUsable (broken));
  5966. auto old = blob;
  5967. old[0] = 15; // articulators and curves are stored from version 16
  5968. CHECK (! lynx::harmorStateUsable (old));
  5969. lynx::ChannelDef c;
  5970. c.instrument = lynx::InstrumentKind::harmor;
  5971. c.pluginState = blob;
  5972. auto render = [] (const lynx::ChannelDef& def, int total, float gl, float gr, int offAt) {
  5973. auto inst = lynx::makeInstrument (lynx::InstrumentKind::harmor);
  5974. inst->configure (def, 120.0);
  5975. inst->prepare (44100.0);
  5976. std::vector<float> l ((std::size_t) total), r ((std::size_t) total);
  5977. inst->noteOn (60, 0.78125f);
  5978. for (int s = 0; s < total; s += 512)
  5979. {
  5980. if (s == offAt)
  5981. inst->noteOff (60);
  5982. inst->render (l.data() + s, r.data() + s, std::min (512, total - s), gl, gr);
  5983. }
  5984. return std::make_tuple (l, r, std::move (inst));
  5985. };
  5986. {
  5987. // reference model (REA round 34 hmodel.py; C5 at FL velocity 100, Final.Vol 1, centre, released at 6144, the
  5988. // Mersenne Twister seeded like LYNX's)
  5989. auto [l, r, inst] = render (c, 8192, 1.0f, 1.0f, 6144);
  5990. const std::tuple<int, float, float> golden[] {
  5991. { 0, 0.0f, 0.0f }, { 100, 0.00947693f, 0.04249846f }, { 1000, 0.08140575f, -0.03251422f }, { 3000, 0.05928446f, -0.00247572f },
  5992. { 6000, 0.02997839f, 0.14549091f }, { 7000, -0.01121871f, 0.04197952f }, { 8191, 0.00314545f, 0.03857505f } };
  5993. for (const auto& [i, gl, gr] : golden)
  5994. CHECK (std::abs (l[(std::size_t) i] - gl) < 2e-6f && std::abs (r[(std::size_t) i] - gr) < 2e-6f);
  5995. // after the release the volume envelope ends, the record declicks and the instrument goes idle
  5996. std::vector<float> tail (44100), tailR (tail.size());
  5997. inst->render (tail.data(), tailR.data(), (int) tail.size(), 1.0f, 1.0f);
  5998. CHECK (inst->idle());
  5999. CHECK (std::abs (tail.back()) == 0.0f);
  6000. }
  6001. // the reference renderer gives the same samples as the instrument
  6002. {
  6003. const auto ref = lynx::harmor::renderReference (blob, { { 0, 60, 0.78125, 1.0, 0.0, 6144 } }, 44100.0, 8192);
  6004. const auto [l, r, inst] = render (c, 8192, 1.0f, 1.0f, 6144);
  6005. double worst = 0.0;
  6006. for (int i = 0; i < 8192; ++i)
  6007. worst = std::max ({ worst, (double) std::abs (ref[2 * (std::size_t) i] - l[(std::size_t) i]), (double) std::abs (ref[2 * (std::size_t) i + 1] - r[(std::size_t) i]) });
  6008. CHECK (worst == 0.0);
  6009. }
  6010. // FL's level law applied once: half the channel volume halves the output; full right pan silences the left side
  6011. const auto full = std::get<0> (render (c, 2048, 1.0f, 1.0f, -1));
  6012. const auto half = std::get<0> (render (c, 2048, 0.5f, 0.5f, -1));
  6013. CHECK (std::abs (half[1000] - 0.5f * full[1000]) < 1e-6f && std::abs (full[1000]) > 0.01f);
  6014. auto mono = c;
  6015. mono.pluginState = harmorTestState (false); // no pan LFO ...
  6016. const std::int32_t one = 1;
  6017. std::memcpy (mono.pluginState.data() + lynx::harmorParamOffset (mono.pluginState, 0, 34), &one, 4); // ... nor unison spread
  6018. const auto [pl, pr, pi] = render (mono, 2048, 0.0f, 1.41421356f, -1);
  6019. double el = 0.0, er = 0.0;
  6020. for (int i = 0; i < 2048; ++i)
  6021. el += (double) pl[(std::size_t) i] * pl[(std::size_t) i], er += (double) pr[(std::size_t) i] * pr[(std::size_t) i];
  6022. CHECK (el < 1e-10 * er && er > 1e-3);
  6023. }
  6024. // our own Maximus v7 state (layout REA_rodada8 §1.1): 7 globals, 4 × 13 band parameters, 8 envelopes (dx, y, tension, type)
  6025. static std::vector<std::uint8_t> maximusTestState (const std::array<int, 7>& g, const std::array<std::array<int, 13>, 4>& bands,
  6026. const std::array<std::vector<std::array<double, 4>>, 8>& envs, int oversampling)
  6027. {
  6028. std::vector<std::uint8_t> d;
  6029. auto put = [&] (const void* v, std::size_t n) { d.insert (d.end(), (const std::uint8_t*) v, (const std::uint8_t*) v + n); };
  6030. auto i32 = [&] (std::int32_t v) { put (&v, 4); };
  6031. i32 (7);
  6032. for (int copy = 0; copy < 2; ++copy)
  6033. {
  6034. for (auto v : g)
  6035. i32 (v);
  6036. for (const auto& b : bands)
  6037. for (auto v : b)
  6038. i32 (v);
  6039. }
  6040. d.resize (0x1fe, 0);
  6041. std::memcpy (d.data() + 0x1f4, &oversampling, 4);
  6042. for (const auto& e : envs)
  6043. {
  6044. i32 (3), i32 (2), i32 ((std::int32_t) e.size());
  6045. for (const auto& pt : e)
  6046. {
  6047. const double dx = pt[0], y = pt[1];
  6048. const float t = (float) pt[2];
  6049. put (&dx, 8), put (&y, 8), put (&t, 4);
  6050. const std::uint8_t flags[4] { (std::uint8_t) pt[3], 0, 0, 0 };
  6051. put (flags, 4);
  6052. }
  6053. i32 (0), i32 (-1), i32 (-1), i32 (-1), i32 (-1);
  6054. }
  6055. return d;
  6056. }
  6057. TEST (harmless_rack)
  6058. {
  6059. // REA_rodada36: Harmless's effects rack against our reference model (rack.py / maxmodel.py, which match the
  6060. // installation's Harmless_x64.dll and SG_x64.dll), 44.1 kHz, host blocks of 512
  6061. std::vector<float> inL (8192), inR (8192);
  6062. for (int i = 0; i < 4096; ++i)
  6063. {
  6064. inL[(std::size_t) i] = (float) (1.5 * std::sin (2.0 * 3.141592653589793 * 440.0 * i / 44100.0) * std::min (1.0, i / 400.0));
  6065. inR[(std::size_t) i] = (float) (1.2 * std::sin (2.0 * 3.141592653589793 * 660.0 * i / 44100.0));
  6066. }
  6067. auto run = [&] (const std::array<int, 100>& p, int compType, std::shared_ptr<const lynx::hlfx::MaximusPreset> comp, int total, int voicesUntil) {
  6068. lynx::hlfx::Rack rack;
  6069. std::array<int, 7> t {};
  6070. t[3] = compType;
  6071. rack.prepare (p, t, 44100.0, 120.0, std::move (comp));
  6072. std::vector<float> l (inL.begin(), inL.begin() + total), r (inR.begin(), inR.begin() + total);
  6073. for (int s = 0; s < total; s += 512)
  6074. rack.process (l.data() + s, r.data() + s, std::min (512, total - s), s < voicesUntil);
  6075. return std::make_pair (l, r);
  6076. };
  6077. {
  6078. // chorus type 3 (mix 400), ping-pong delay type 2 (vol 600, feedback 500, 1/4 beat), reverb type 4 (vol 700)
  6079. std::array<int, 100> p {};
  6080. p[90] = 3, p[91] = 400, p[92] = 2, p[93] = 600, p[94] = 500, p[95] = 48, p[96] = 4, p[97] = 700;
  6081. const auto [l, r] = run (p, 0, nullptr, 8192, 4096);
  6082. const std::tuple<int, float, float> golden[] { { 0, 0.0f, 0.0f }, { 500, -0.25248247f, 0.15141529f }, { 3000, -0.65128994f, -0.64854866f },
  6083. { 5000, -0.54308629f, -0.36827448f }, { 6000, -0.98378551f, -0.72790027f },
  6084. { 8191, 0.50599128f, -0.43637198f } };
  6085. for (const auto& [i, gl, gr] : golden)
  6086. CHECK (std::abs (l[(std::size_t) i] - gl) < 2e-6f && std::abs (r[(std::size_t) i] - gr) < 2e-6f);
  6087. }
  6088. {
  6089. // the delay alone: an impulse comes back after round(time·fs·0.3125/bpm) samples × (11^0.6 − 1)/10, then × feedback
  6090. std::array<int, 100> p {};
  6091. p[92] = 1, p[93] = 600, p[94] = 500, p[95] = 48;
  6092. lynx::hlfx::Rack rack;
  6093. rack.prepare (p, {}, 44100.0, 120.0, nullptr);
  6094. std::vector<float> l (16384), r (16384);
  6095. l[0] = 1.0f;
  6096. for (int s = 0; s < 16384; s += 512)
  6097. rack.process (l.data() + s, r.data() + s, 512, s == 0);
  6098. const auto D = 5512; // 48·44100·0.3125/120 = 5512.5 → 5512 (round half to even)
  6099. const auto vol = (float) ((std::exp ((double) (600 * 0.001f) * (double) (float) std::log (11.0)) - 1.0) * (double) 0.1f);
  6100. CHECK (std::abs (l[(std::size_t) D] - vol) < 1e-7f && std::abs (l[(std::size_t) D - 1]) < 1e-12f);
  6101. // the feedback ramps from 0.5 toward 0.5: the second echo is vol·0.5
  6102. CHECK (std::abs (l[(std::size_t) (2 * D)] - vol * 0.5f) < 1e-7f && std::abs (r[(std::size_t) D]) < 1e-12f);
  6103. }
  6104. // the compressor: Maximus states of our own (no preset data), checked against SG_x64.dll by REA round 36
  6105. using Env = std::vector<std::array<double, 4>>;
  6106. const Env def { { 0.0, 0.0, 0.0, 0 }, { 0.5, 0.5, 0.0, 0 }, { 0.5, 0.5, 0.0, 0 } };
  6107. auto band = [] (int mode, int pre = 1000, int post = 1000, int sep = 0, int sat = 0, int ceil = 1000, int att = 1115, int rel2 = 0,
  6108. int sus = 2882) { return std::array<int, 13> { mode, pre, post, sep, sat, ceil, att, rel2, 2, 5000, 3, sus, 0 }; };
  6109. {
  6110. // master brickwall at −0.22 dB only (bands off / compression off)
  6111. const auto st = maximusTestState ({ 19800, 1, 48065, 1, 1115, 1000, -1 }, { band (3), band (1), band (3), band (0) },
  6112. { def, def, def, def, def, def, def, def }, 0);
  6113. const auto preset = lynx::hlfx::makeMaximusPreset (st);
  6114. CHECK (preset != nullptr);
  6115. std::array<int, 100> p {};
  6116. p[98] = 1000;
  6117. const auto [l, r] = run (p, 1, preset, 4096, 4096);
  6118. const std::tuple<int, float, float> golden[] { { 100, 0.02499794f, 0.88166064f }, { 1000, 0.56971455f, -0.62808162f },
  6119. { 2047, -0.27541649f, 0.70913559f }, { 3000, 0.32431602f, -0.37985173f },
  6120. { 4095, -0.12743534f, -0.15237498f } };
  6121. for (const auto& [i, gl, gr] : golden)
  6122. CHECK (std::abs (l[(std::size_t) i] - gl) < 2e-6f && std::abs (r[(std::size_t) i] - gr) < 2e-6f);
  6123. float peak = 0.0f;
  6124. for (int i = 2048; i < 4096; ++i)
  6125. peak = std::max ({ peak, std::abs (l[(std::size_t) i]), std::abs (r[(std::size_t) i]) });
  6126. CHECK (peak < 0.9751f);
  6127. }
  6128. {
  6129. // 24 dB crossovers, ×2 oversampling, low cut, stereo separation, saturation A, a knee with tension (type 7) and
  6130. // exponential tensions (type 0), release 2 on the master, band mix 600
  6131. const Env knee { { 0.0, 0.0, 0.0, 0 }, { 0.35, 0.35, 0.0, 0 }, { 0.65, 0.6, 0.36, 7 } };
  6132. const Env t0 { { 0.0, 0.0, 0.0, 0 }, { 0.5, 0.5, 0.14, 0 }, { 0.5, 0.5, 0.0, 0 } };
  6133. const Env m0 { { 0.0, 0.0, 0.0, 0 }, { 0.5, 0.5, 0.0, 0 }, { 0.5, 0.6, 0.085, 0 } };
  6134. const auto st = maximusTestState ({ 19800, 1, 48065, 1, 891, 600, 32768 },
  6135. { band (1, 1264, 1296, 500, -500, 1200), band (0, 1340, 1000, -348, 0, 1000, 1115, 0, 1570),
  6136. band (0, 1364, 1152, 0, 0, 1000, 1115, 0, 1186), band (0, 1000, 1000, 0, -196, 1000, 1115, 4464, 1538) },
  6137. { def, def, knee, def, t0, def, m0, def }, 1);
  6138. const auto preset = lynx::hlfx::makeMaximusPreset (st);
  6139. CHECK (preset != nullptr);
  6140. std::array<int, 100> p {};
  6141. p[98] = 600;
  6142. const auto [l, r] = run (p, 2, preset, 4096, 4096);
  6143. const std::tuple<int, float, float> golden[] { { 100, 0.0f, 0.0f }, { 1000, -0.46856275f, -0.63261062f },
  6144. { 2047, 0.20268074f, 0.5414567f }, { 3000, -0.25614089f, -0.49984524f },
  6145. { 4095, 0.10172816f, 0.0505573f } };
  6146. for (const auto& [i, gl, gr] : golden)
  6147. CHECK (std::abs (l[(std::size_t) i] - gl) < 2e-6f && std::abs (r[(std::size_t) i] - gr) < 2e-6f);
  6148. }
  6149. {
  6150. // an .fst wrapper around a state is found; unsupported states are rejected
  6151. const auto st = maximusTestState ({ 19800, 1, 48065, 1, 1115, 1000, -1 }, { band (3), band (1), band (3), band (0) },
  6152. { def, def, def, def, def, def, def, def }, 0);
  6153. std::vector<std::uint8_t> fst { 'F', 'L', 'h', 'd', 6, 0, 0, 0, 0, 0, 1, 0, 0x60, 0, 'F', 'L', 'd', 't' };
  6154. std::vector<std::uint8_t> body { 0xC9, 8, 'M', 'a', 'x', 'i', 'm', 'u', 's', 0, 0xD5 };
  6155. for (auto n = st.size(); ; n >>= 7)
  6156. {
  6157. body.push_back ((std::uint8_t) ((n & 0x7f) | (n >= 0x80 ? 0x80 : 0)));
  6158. if (n < 0x80)
  6159. break;
  6160. }
  6161. body.insert (body.end(), st.begin(), st.end());
  6162. const auto len = (std::uint32_t) body.size();
  6163. for (int k = 0; k < 4; ++k)
  6164. fst.push_back ((std::uint8_t) (len >> (8 * k)));
  6165. fst.insert (fst.end(), body.begin(), body.end());
  6166. const auto found = lynx::hlfx::maximusStateFromFst (fst);
  6167. CHECK (found && *found == st);
  6168. auto rms = st;
  6169. rms[4 + 4 * (7 + 13 * 3 + 12)] = 1; // RMS detector on the master (decoded in REA_rodada38: Harmor's preset 2)
  6170. CHECK (lynx::hlfx::makeMaximusPreset (rms) != nullptr);
  6171. }
  6172. }
  6173. // ---- Sytrus (REA_rodada31) -------------------------------------------------------------------------------------------
  6174. // A Sytrus state built from scratch (version 25 layout, our own values — no FL preset data), zlib "stored" blocks.
  6175. namespace
  6176. {
  6177. struct SytrusTestPatch
  6178. {
  6179. std::vector<std::int32_t> main = std::vector<std::int32_t> (240, 0); // 962-byte main block as ints (+ mute bytes)
  6180. struct Op
  6181. {
  6182. int p[10] { 0, 256, 0, 0, 0, 0, 0, 0, 0, 0 };
  6183. int ratio = 20000, offset = 0, noise = 0;
  6184. std::vector<float> amps { 1.0f };
  6185. std::uint8_t flags[8] {};
  6186. int env1[3] { -1, -1, -1 }; // volume envelope: on (≠ −1 → on), decay point, sustain point
  6187. std::vector<std::pair<double, double>> env1pts;
  6188. } ops[6];
  6189. struct Filt
  6190. {
  6191. int p[10] { 0, 0, 128, 0, 128, 0, 0, 128, 128, 0 };
  6192. int type = 3;
  6193. } filts[3];
  6194. std::array<std::array<std::uint8_t, 23>, 3> delays {};
  6195. std::array<std::int32_t, 9> reverb { 19, 221, 0, 50, 80, 30, 221, 2, 0 };
  6196. bool reverbOn = false;
  6197. int eqmode = 0;
  6198. SytrusTestPatch()
  6199. {
  6200. main[0] = 128, main[1] = 128;
  6201. for (int i = 0; i < 8; ++i)
  6202. main[(std::size_t) (165 + i)] = (i % 4 == 2) ? 0 : 128;
  6203. main[173] = 1, main[175] = 128, main[188] = 128, main[189] = -1, main[190] = main[191] = 256;
  6204. }
  6205. void cell (int layer, int row, int col, int v) { main[(std::size_t) (3 + layer * 81 + row * 9 + col)] = v; }
  6206. std::vector<std::uint8_t> blob() const
  6207. {
  6208. std::vector<std::uint8_t> b;
  6209. auto i32 = [&] (std::int32_t v) { for (int k = 0; k < 4; ++k) b.push_back ((std::uint8_t) ((std::uint32_t) v >> (8 * k))); };
  6210. auto f32 = [&] (float v) { std::int32_t x; std::memcpy (&x, &v, 4); i32 (x); };
  6211. auto f64 = [&] (double v) { std::uint64_t x; std::memcpy (&x, &v, 8); for (int k = 0; k < 8; ++k) b.push_back ((std::uint8_t) (x >> (8 * k))); };
  6212. // point lists: kind 1 envelope, 2 LFO, 3 map / shaper curve; format version 3
  6213. auto env = [&] (int kind, const std::vector<std::pair<double, double>>& pts, int on, int decay, int sus) {
  6214. i32 (kind), i32 (3), i32 ((std::int32_t) pts.size());
  6215. for (const auto& [dt, y] : pts)
  6216. f64 (dt), f64 (y), f32 (0.0f), i32 (0);
  6217. i32 (0), i32 (on), i32 (decay), i32 (-1), i32 (sus);
  6218. };
  6219. for (int i = 0; i < 240; ++i)
  6220. if (4 * i + 4 <= 0x320)
  6221. i32 (main[(std::size_t) i]);
  6222. b.resize (962, 0); // mute bytes: none muted
  6223. i32 (0); // global declick amount
  6224. b.push_back (0), b.push_back (0), b.push_back (0); // OSC grouping, DC stage, GIBBS OFF
  6225. for (int k = 0; k < 9; ++k)
  6226. b.push_back (k == 7 ? 1 : 0); // flag group (release multiplier on, as Default.fst)
  6227. for (const auto& d : delays)
  6228. b.insert (b.end(), d.begin(), d.end());
  6229. for (auto v : reverb)
  6230. i32 (v);
  6231. b.push_back (reverbOn ? 1 : 0), b.push_back (0);
  6232. i32 (eqmode);
  6233. for (int k = 0; k < 3; ++k)
  6234. i32 (0), i32 (30000), i32 (20000), i32 (k);
  6235. b.push_back (0); // no info text
  6236. for (int u = 0; u < 10; ++u)
  6237. {
  6238. const int narts = u < 6 ? 6 : (u < 9 ? 8 : 2);
  6239. for (int j = 0; j < 10; ++j)
  6240. i32 (u < 6 ? ops[u].p[j] : (u < 9 ? filts[u - 6].p[j] : 0));
  6241. if (u < 6)
  6242. {
  6243. const auto& o = ops[u];
  6244. const auto at = b.size();
  6245. b.resize (at + 0x828, 0);
  6246. auto put = [&] (std::size_t off, const void* src, std::size_t n) { std::memcpy (b.data() + at + off, src, n); };
  6247. put (0, &o.ratio, 4), put (4, &o.offset, 4), put (8, &o.noise, 4);
  6248. put (0xc, o.amps.data(), 4 * o.amps.size());
  6249. const std::int32_t shape[5] { 0, 0, 0, 0, 128 };
  6250. put (0x80c, shape, sizeof shape);
  6251. put (0x820, o.flags, 8);
  6252. }
  6253. else if (u < 9)
  6254. {
  6255. const auto at = b.size();
  6256. b.resize (at + 0x30, 0);
  6257. std::memcpy (b.data() + at + 0x2c, &filts[u - 6].type, 4);
  6258. env (3, { { 0.0, 0.0 }, { 1.0, 1.0 } }, 0, -1, -1);
  6259. b.push_back (0);
  6260. }
  6261. for (int k = 0; k < narts; ++k)
  6262. {
  6263. const bool add = k == 0 || k == 3 || (u >= 6 && u <= 8 && (k == 2 || k == 3)) || (u < 6 && k == 4);
  6264. const double neutral = add ? 0.5 : 1.0;
  6265. i32 (3), i32 (0), f32 (1.0f), f32 (1.0f);
  6266. if (u < 6 && k == 1 && ops[u].env1[0] != -1)
  6267. env (1, ops[u].env1pts, -1, ops[u].env1[1], ops[u].env1[2]);
  6268. else
  6269. env (1, { { 0.0, 0.0 }, { 1.0, 1.0 } }, 0, -1, -1);
  6270. i32 (128), i32 (128), i32 (0), i32 (128);
  6271. env (2, { { 0.0, 1.0 }, { 1.0, 1.0 } }, 0, -1, -1);
  6272. i32 (40000), i32 (0), i32 (0), i32 (0), i32 (0);
  6273. for (int m = 0; m < 6; ++m)
  6274. env (3, { { 0.0, neutral }, { 1.0, neutral } }, 0, -1, -1);
  6275. }
  6276. }
  6277. b.push_back (0), b.push_back (0);
  6278. // zlib with stored blocks
  6279. std::vector<std::uint8_t> z { 0x78, 0x01 };
  6280. for (std::size_t at = 0; at < b.size(); at += 65535)
  6281. {
  6282. const auto n = std::min<std::size_t> (65535, b.size() - at);
  6283. z.push_back (at + n >= b.size() ? 1 : 0);
  6284. z.push_back ((std::uint8_t) n), z.push_back ((std::uint8_t) (n >> 8));
  6285. z.push_back ((std::uint8_t) ~n), z.push_back ((std::uint8_t) (~n >> 8));
  6286. z.insert (z.end(), b.begin() + (std::ptrdiff_t) at, b.begin() + (std::ptrdiff_t) (at + n));
  6287. }
  6288. std::uint32_t a = 1, c = 0;
  6289. for (auto x : b)
  6290. a = (a + x) % 65521, c = (c + a) % 65521;
  6291. for (int k = 3; k >= 0; --k)
  6292. z.push_back ((std::uint8_t) (((c << 16) | a) >> (8 * k)));
  6293. std::vector<std::uint8_t> out { 25, 0, 0, 0 };
  6294. out.insert (out.end(), z.begin(), z.end());
  6295. return out;
  6296. }
  6297. };
  6298. // renders like FL's Gen_Render calls: notes start/release at the block that contains them
  6299. std::pair<std::vector<float>, std::vector<float>> sytrusRender (const std::vector<std::uint8_t>& blob, bool renderMode, int n,
  6300. std::vector<std::array<int, 3>> notes, double fs = 44100.0)
  6301. {
  6302. lynx::sytrus::Engine e;
  6303. e.setTempo (120.0);
  6304. e.prepare (fs, renderMode, 512);
  6305. e.setPatch (lynx::sytrus::parsePatch (blob));
  6306. std::vector<float> l ((std::size_t) n), r ((std::size_t) n);
  6307. for (int n0 = 0; n0 < n; n0 += 512)
  6308. {
  6309. for (std::size_t k = 0; k < notes.size(); ++k)
  6310. {
  6311. if (notes[k][1] >= n0 && notes[k][1] < n0 + 512)
  6312. {
  6313. lynx::sytrus::NoteParams p;
  6314. p.key = (float) notes[k][0];
  6315. p.id = (std::int64_t) k + 1;
  6316. e.noteOn (p);
  6317. }
  6318. if (notes[k][2] >= n0 && notes[k][2] < n0 + 512)
  6319. e.release ((std::int64_t) k + 1);
  6320. }
  6321. e.render (l.data() + n0, r.data() + n0, std::min (512, n - n0), 1.0f, 0.0f);
  6322. }
  6323. return { l, r };
  6324. }
  6325. } // namespace
  6326. TEST (sytrus_engine_sine)
  6327. {
  6328. // one sine operator, ratio 1, OUT 256, no envelopes: C5 = 523.2511 Hz at 0.7071 (centre of the pan law, §6.1)
  6329. SytrusTestPatch t;
  6330. t.cell (0, 0, 8, 256);
  6331. const auto blob = t.blob();
  6332. CHECK (lynx::sytrus::stateUsable (blob));
  6333. CHECK (lynx::sytrus::parsePatch (blob) != nullptr);
  6334. auto broken = blob;
  6335. broken.resize (broken.size() / 2);
  6336. CHECK (! lynx::sytrus::stateUsable (broken));
  6337. const auto [l, r] = sytrusRender (blob, false, 8192, { { 60, 0, 4096 } });
  6338. double worst = 0.0;
  6339. for (int k = 0; k < 4000; ++k)
  6340. worst = std::max (worst, std::abs ((double) l[(std::size_t) k] - 0.70710678 * std::sin (2.0 * 3.14159265358979 * 523.251130601197 * k / 44100.0)));
  6341. CHECK (worst < 2e-5);
  6342. CHECK (l == r);
  6343. // envelope-less voice end (§4.9, §6.2): finished at a tick after the note-off, then the L/R gains (0.7071) ramp to 0
  6344. // at 0.001 per sample: the last non-zero sample is 4895 for a release at 4096 — the DLL's own figure (EXEC, §6.2)
  6345. int last = 0;
  6346. for (int k = 0; k < 8192; ++k)
  6347. if (l[(std::size_t) k] != 0.0f)
  6348. last = k;
  6349. CHECK (last == 4895);
  6350. // key 69 = 880 Hz; 48 kHz
  6351. const auto [l2, r2] = sytrusRender (blob, false, 4096, { { 69, 0, -1 } }, 48000.0);
  6352. worst = 0.0;
  6353. for (int k = 0; k < 4000; ++k)
  6354. worst = std::max (worst, std::abs ((double) l2[(std::size_t) k] - 0.70710678 * std::sin (2.0 * 3.14159265358979 * 880.0 * k / 48000.0)));
  6355. CHECK (worst < 5e-5);
  6356. (void) r2;
  6357. }
  6358. TEST (sytrus_engine_reference)
  6359. {
  6360. // FM 2→1, Vanilla LP filter, volume envelope, unison 3, delay and reverb, 2× oversampling with the 8-sample
  6361. // envelope tick (render settings): against our Python reference model of REA_rodada31 (sytmodel.render)
  6362. SytrusTestPatch t;
  6363. t.main[195] = 0, t.main[196] = 1, t.main[193] = 0, t.main[194] = 1;
  6364. t.main[173] = 3, t.main[174] = 64, t.main[176] = 100;
  6365. t.ops[1].ratio = 40000;
  6366. t.cell (0, 0, 1, 128); // op 2 → op 1 FM
  6367. t.cell (0, 0, 8, 128);
  6368. t.cell (0, 6, 0, 256); // op 1 → filter 1
  6369. t.cell (0, 6, 8, 256);
  6370. t.cell (0, 0, 7, 200); // FX send
  6371. t.filts[0].p[0] = 1, t.filts[0].p[2] = 180, t.filts[0].p[3] = 60;
  6372. t.ops[0].env1[0] = 0, t.ops[0].env1[1] = 1, t.ops[0].env1[2] = 2;
  6373. t.ops[0].env1pts = { { 0.0, 0.0 }, { 0.05, 1.0 }, { 0.1, 0.6 }, { 0.2, 0.0 } };
  6374. const std::int32_t d0[5] { 40, 100, 50, 100, 0 };
  6375. std::memcpy (t.delays[0].data(), d0, 20);
  6376. t.delays[0][22] = 1;
  6377. t.reverb = { 19, 221, 10, 50, 80, 30, 100, 2, 100 };
  6378. t.reverbOn = true;
  6379. const auto blob = t.blob();
  6380. const auto [l, r] = sytrusRender (blob, true, 12000, { { 60, 0, 6000 } });
  6381. // reference values (model render_mode=True, 44.1 kHz, block 512, key 60, velocity 0.78125, release at 6000); the same
  6382. // state rendered by FL's own Sytrus DLL in render mode differs from this by −136 dB (EXEC, REA round 31 harness)
  6383. const std::array<std::pair<int, float>, 8> golden { { { 100, -0.00235529384f }, { 777, -0.175126165f }, { 2000, 0.30976975f }, { 4321, -0.0213534199f },
  6384. { 6100, 0.202372357f }, { 7000, 0.249530748f }, { 9000, 0.0307101421f }, { 11999, 0.176390275f } } };
  6385. for (const auto& [i, v] : golden)
  6386. CHECK (std::abs (l[(std::size_t) i] - v) < 1e-6f);
  6387. const std::array<std::pair<int, float>, 3> goldenR { { { 777, -0.166890964f }, { 4321, -0.212358952f }, { 9000, -0.0251909085f } } };
  6388. for (const auto& [i, v] : goldenR)
  6389. CHECK (std::abs (r[(std::size_t) i] - v) < 1e-6f);
  6390. }
  6391. TEST (sytrus_instrument)
  6392. {
  6393. // the LYNX instrument: state in ChannelDef::pluginState, channel volume/pan recovered from the rack gains
  6394. SytrusTestPatch t;
  6395. t.cell (0, 0, 8, 256);
  6396. lynx::ChannelDef c;
  6397. c.instrument = lynx::InstrumentKind::sytrus;
  6398. c.pluginState = t.blob();
  6399. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sytrus);
  6400. inst->prepare (44100.0);
  6401. inst->configure (c, 120.0);
  6402. CHECK (inst->idle());
  6403. std::vector<float> l (4096), r (4096);
  6404. inst->noteOn (60, 100.0f / 128.0f);
  6405. // rack gains for volume V and pan p: √2·V·cos((1 + p)π/4), √2·V·sin(…); V = 0.5, p = 0 → Final.Vol 0.5
  6406. inst->render (l.data(), r.data(), 4096, 0.5f, 0.5f);
  6407. double peak = 0.0;
  6408. for (int k = 1000; k < 4096; ++k)
  6409. peak = std::max (peak, (double) std::abs (l[(std::size_t) k]));
  6410. CHECK (std::abs (peak - 0.5 * 0.70710678) < 1e-3); // Final.Vol 0.5 × the plugin's centre pan law
  6411. CHECK (! inst->idle());
  6412. inst->noteOff (60);
  6413. std::vector<float> tail (44100 * 3), tailR (tail.size());
  6414. inst->render (tail.data(), tailR.data(), (int) tail.size(), 0.5f, 0.5f);
  6415. CHECK (inst->idle());
  6416. CHECK (tail.back() == 0.0f);
  6417. }
  6418. TEST (harmor_effects_rack)
  6419. {
  6420. // REA_rodada38: the rack runs in the state's unit order and the records' FX send joins it at unit 4 — with the FX
  6421. // amount at 1000 every record output bypasses a reverb placed before unit 4 (EXEC: −600 dB vs the rack off)
  6422. auto blob = harmorTestState (false);
  6423. auto set = [&] (std::vector<std::uint8_t>& st, int part, int index, std::int32_t v) {
  6424. std::memcpy (st.data() + lynx::harmorParamOffset (st, part, index), &v, 4);
  6425. };
  6426. set (blob, 0, 10, 1000); // all to the FX send
  6427. auto render = [] (const std::vector<std::uint8_t>& st) {
  6428. return lynx::harmor::renderReference (st, { { 0, 60, 0.8, 1.0, 0.0, 6000 } }, 44100.0, 12000);
  6429. };
  6430. const auto dry = render (blob);
  6431. auto rev = blob;
  6432. set (rev, -1, 22, 1); // reverb on: room 50, diffusion 100, decay 2^3·0.1 s, high cut / damping off, wet 0.8
  6433. set (rev, -1, 24, 1050), set (rev, -1, 26, 50), set (rev, -1, 27, 100), set (rev, -1, 28, 300), set (rev, -1, 29, 1050);
  6434. set (rev, -1, 30, 2), set (rev, -1, 31, 800);
  6435. const auto bypassed = render (rev);
  6436. double eb = 0.0, db = 0.0;
  6437. for (std::size_t i = 0; i < dry.size(); ++i)
  6438. eb += (double) (bypassed[i] - dry[i]) * (bypassed[i] - dry[i]), db += (double) dry[i] * dry[i];
  6439. CHECK (eb < 1e-12 * db && db > 1e-3); // (float rounding of the rack's buffers only)
  6440. auto after = rev;
  6441. const std::int32_t order[6] { 0, 1, 2, 4, 3, 5 }; // the join before the reverb
  6442. for (int k = 0; k < 6; ++k)
  6443. set (after, -1, 53 + k, order[k]);
  6444. const auto wet = render (after);
  6445. double e = 0.0, d = 0.0;
  6446. bool finite = true;
  6447. for (std::size_t i = 0; i < wet.size(); ++i)
  6448. e += (double) (wet[i] - dry[i]) * (wet[i] - dry[i]), d += (double) dry[i] * dry[i], finite = finite && std::isfinite (wet[i]);
  6449. CHECK (finite && e > 1e-4 * d && d > 1e-3);
  6450. // a distortion (type 6) and a delay on the dry path change the sound, stay finite, and the instrument ends quiet
  6451. auto dist = harmorTestState (false);
  6452. {
  6453. const auto at = lynx::harmorParamOffset (dist, -1, 0) + 0xd4 + 0x18 + 48; // global misc +48: distortion type
  6454. const std::int32_t six = 6;
  6455. std::memcpy (dist.data() + at, &six, 4);
  6456. }
  6457. set (dist, -1, 17, 600), set (dist, -1, 19, 1000), set (dist, -1, 21, 1100);
  6458. set (dist, -1, 39, 1), set (dist, -1, 40, 2), set (dist, -1, 41, 400), set (dist, -1, 42, 96), set (dist, -1, 44, 800);
  6459. set (dist, -1, 47, 1050);
  6460. lynx::ChannelDef c;
  6461. c.instrument = lynx::InstrumentKind::harmor;
  6462. c.pluginState = dist;
  6463. auto inst = lynx::makeInstrument (lynx::InstrumentKind::harmor);
  6464. inst->configure (c, 120.0);
  6465. inst->prepare (44100.0);
  6466. std::vector<float> l (44100 * 4), r (l.size());
  6467. inst->noteOn (60, 0.8f);
  6468. double energy = 0.0;
  6469. for (int s = 0; s < (int) l.size(); s += 512)
  6470. {
  6471. if (s == 8192)
  6472. inst->noteOff (60);
  6473. inst->render (l.data() + s, r.data() + s, 512, 1.0f, 1.0f);
  6474. }
  6475. for (std::size_t i = 0; i < l.size(); ++i)
  6476. finite = finite && std::isfinite (l[i]) && std::isfinite (r[i]), energy += (double) l[i] * l[i];
  6477. CHECK (finite && energy > 1.0);
  6478. std::vector<float> tail (44100 * 6), tailR (tail.size());
  6479. for (int s = 0; s < (int) tail.size(); s += 512)
  6480. inst->render (tail.data() + s, tailR.data() + s, 512, 1.0f, 1.0f);
  6481. CHECK (inst->idle());
  6482. }
  6483. TEST (harmless_engine)
  6484. {
  6485. // REA_rodada32: state parsing, the additive engine against our reference model (hlmodel.py), host levels, voice end
  6486. std::vector<std::uint8_t> blob;
  6487. auto put = [&] (std::int32_t v) { for (int k = 0; k < 4; ++k) blob.push_back ((std::uint8_t) ((std::uint32_t) v >> (8 * k))); };
  6488. std::array<std::int32_t, 100> p {}; // the reference's clean patch: Saw, open filter, no modulation
  6489. for (int i = 11; i < 23; ++i)
  6490. p[(std::size_t) i] = 1000;
  6491. p[27] = 1000, p[28] = 250, p[31] = 1000, p[36] = 1000, p[37] = 1, p[47] = 1, p[49] = 500, p[51] = -300, p[54] = 8192;
  6492. p[56] = 500, p[65] = 1, p[66] = 128, p[67] = 128, p[68] = 64, p[89] = 3000, p[91] = 500, p[95] = 144, p[97] = 500, p[98] = 500;
  6493. // + resonance, pluck, 3-voice unison, tremolo, LFO on pitch
  6494. p[54] = 3500, p[59] = 600, p[31] = 500, p[65] = 3, p[67] = 150, p[25] = 300, p[86] = 0, p[42] = 200, p[89] = 5000;
  6495. put (12);
  6496. for (auto v : p)
  6497. put (v);
  6498. for (int i = 0; i < 7; ++i)
  6499. put (0);
  6500. put (524); // Custom colour table: 524 × (amplitude, phase)
  6501. for (int i = 0; i < 1048; ++i)
  6502. {
  6503. const auto f = i < 524 ? 1.0f / (float) (i + 1) : 0.25f;
  6504. std::uint32_t bits = 0;
  6505. std::memcpy (&bits, &f, 4);
  6506. put ((std::int32_t) bits);
  6507. }
  6508. const auto parsed = lynx::harmlessParams (blob);
  6509. CHECK (parsed && (int) parsed->size() == lynx::harmlessParamCount);
  6510. CHECK (parsed && (*parsed)[54] == 3500.0f && (*parsed)[99] == 0.0f && (*parsed)[lynx::harmlessCustomFlagIndex] == 1.0f);
  6511. CHECK (parsed && (*parsed)[lynx::harmlessCustomIndex + 1] == 0.5f && (*parsed)[lynx::harmlessCustomIndex + 524] == 0.25f);
  6512. auto old = blob;
  6513. old[0] = 3; // versions below 4 are not Harmless states we know
  6514. CHECK (! lynx::harmlessParams (old));
  6515. old = blob;
  6516. old.resize (300);
  6517. CHECK (! lynx::harmlessParams (old));
  6518. lynx::ChannelDef c;
  6519. c.instrument = lynx::InstrumentKind::harmless;
  6520. c.modelParams = *parsed;
  6521. c.modelParams[lynx::harmlessCustomFlagIndex] = 0.0f; // colour 0 (Saw): the custom table is not read
  6522. auto render = [] (const lynx::ChannelDef& def, int total, float gl, float gr, int offAt) {
  6523. auto inst = lynx::makeInstrument (lynx::InstrumentKind::harmless);
  6524. inst->configure (def, 120.0);
  6525. inst->prepare (44100.0);
  6526. std::vector<float> l ((std::size_t) total), r ((std::size_t) total);
  6527. inst->noteOn (60, 0.78125f);
  6528. for (int s = 0; s < total; s += 512)
  6529. {
  6530. if (s == offAt)
  6531. inst->noteOff (60);
  6532. inst->render (l.data() + s, r.data() + s, std::min (512, total - s), gl, gr);
  6533. }
  6534. return std::make_tuple (l, r, std::move (inst));
  6535. };
  6536. {
  6537. // reference model (REA round 32 hlmodel.py, C5 at FL velocity 100, channel volume 1, centre, released at 6144)
  6538. auto [l, r, inst] = render (c, 8192, 1.0f, 1.0f, 6144);
  6539. const std::tuple<int, float, float> golden[] {
  6540. { 0, 0.0f, 0.0f }, { 10, -0.02220994f, -0.06232700f }, { 100, 0.40623373f, 0.17308202f }, { 1000, -0.04091963f, -0.26821208f },
  6541. { 3000, 0.14519004f, 0.11027778f }, { 6000, 0.50411958f, 0.27901855f }, { 8191, 0.02117692f, -0.01466602f } };
  6542. for (const auto& [i, gl, gr] : golden)
  6543. CHECK (std::abs (l[(std::size_t) i] - gl) < 2e-6f && std::abs (r[(std::size_t) i] - gr) < 2e-6f);
  6544. // after the release the record fades out (below 1e-4, then 30 ms) and the instrument goes idle
  6545. std::vector<float> tail (44100), tailR (tail.size());
  6546. inst->render (tail.data(), tailR.data(), (int) tail.size(), 1.0f, 1.0f);
  6547. CHECK (inst->idle());
  6548. }
  6549. // FL's level law applied once: half the channel volume halves the output; full right pan silences the left side
  6550. const auto full = std::get<0> (render (c, 2048, 1.0f, 1.0f, -1));
  6551. const auto half = std::get<0> (render (c, 2048, 0.5f, 0.5f, -1));
  6552. CHECK (std::abs (half[100] - 0.5f * full[100]) < 1e-6f && std::abs (full[100]) > 0.1f);
  6553. auto mono = c;
  6554. mono.modelParams[25] = 0.0f; // no tremolo, no unison pan spread
  6555. mono.modelParams[65] = 1.0f;
  6556. const auto [pl, pr, pi] = render (mono, 2048, 0.0f, 1.41421356f, -1);
  6557. double el = 0.0, er = 0.0;
  6558. for (int i = 0; i < 2048; ++i)
  6559. el += (double) pl[(std::size_t) i] * pl[(std::size_t) i], er += (double) pr[(std::size_t) i] * pr[(std::size_t) i];
  6560. CHECK (el < 1e-10 * er && er > 1.0);
  6561. }
  6562. TEST (startup_sound)
  6563. {
  6564. // the splash's sound: the right length, finite, at its peak level, quiet before the whoosh swells,
  6565. // a landing "pop" at impactTime and a chime ringing after it
  6566. using namespace lynx::startup;
  6567. const auto sound = makeSound (48000.0);
  6568. CHECK (sound.left.size() == (std::size_t) (soundLength * 48000.0) && sound.right.size() == sound.left.size());
  6569. float peak = 0.0f;
  6570. bool finite = true;
  6571. for (std::size_t i = 0; i < sound.left.size(); ++i)
  6572. {
  6573. finite = finite && std::isfinite (sound.left[i]) && std::isfinite (sound.right[i]);
  6574. peak = std::max ({ peak, std::abs (sound.left[i]), std::abs (sound.right[i]) });
  6575. }
  6576. CHECK (finite && std::abs (peak - peakLevel) < 1.0e-4f);
  6577. auto rms = [&sound] (double from, double to) {
  6578. double e = 0.0;
  6579. const auto a = (std::size_t) (from * 48000.0), b = (std::size_t) (to * 48000.0);
  6580. for (auto i = a; i < b; ++i)
  6581. e += (double) sound.left[i] * sound.left[i];
  6582. return std::sqrt (e / (double) (b - a));
  6583. };
  6584. CHECK (rms (0.0, 0.05) < 0.2 * rms (impactTime - 0.05, impactTime)); // the whoosh swells
  6585. CHECK (rms (impactTime, impactTime + 0.05) > rms (impactTime - 0.05, impactTime)); // the landing
  6586. CHECK (rms (0.8, 1.0) > 0.005 && rms (soundLength - 0.02, soundLength) < rms (0.8, 1.0)); // chime rings, tail fades
  6587. CHECK (makeSound (48000.0).left == sound.left); // the same sound on every start
  6588. }