tests.cpp 383 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130
  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/Gms.h"
  30. #include "core/Harmless.h"
  31. #include "core/Harmor.h"
  32. #include "core/Morphine.h"
  33. #include "core/Ogun.h"
  34. #include "core/Kepler.h"
  35. #include "core/HarmlessFx.h"
  36. #include "core/MaximusFx.h"
  37. #include "core/LiveEventQueue.h"
  38. #include "core/RackRenderer.h"
  39. #include "core/Scheduler.h"
  40. #include "core/SnapshotExchange.h"
  41. #include "core/SoftClip.h"
  42. #include "core/Slicer.h"
  43. #include "core/SytrusEngine.h"
  44. #include "core/Templates.h"
  45. #include "core/Vocodex.h"
  46. #include "core/TimeStretch.h"
  47. #include "core/WorkerPool.h"
  48. #include "core/Song.h"
  49. #include "core/NoteEdit.h"
  50. #include "core/Recorder.h"
  51. #include "core/KeyMap.h"
  52. #include "core/RackOps.h"
  53. #include "core/ValueMath.h"
  54. #include "core/Workspace.h"
  55. #include "core/StartupSound.h"
  56. #include "flp/Flp.h"
  57. #include "ui/I18nData.h"
  58. namespace
  59. {
  60. int failures = 0;
  61. int checks = 0;
  62. std::vector<std::pair<const char*, std::function<void()>>>& registry()
  63. {
  64. static std::vector<std::pair<const char*, std::function<void()>>> r;
  65. return r;
  66. }
  67. struct Register
  68. {
  69. Register (const char* name, std::function<void()> fn) { registry().emplace_back (name, std::move (fn)); }
  70. };
  71. #define TEST(name) \
  72. static void name(); \
  73. static Register reg_##name (#name, name); \
  74. static void name()
  75. #define CHECK(cond) \
  76. do \
  77. { \
  78. ++checks; \
  79. if (! (cond)) \
  80. { \
  81. ++failures; \
  82. std::printf (" FAILED %s:%d: %s\n", __FILE__, __LINE__, #cond); \
  83. } \
  84. } while (false)
  85. std::string realFlpDir;
  86. // --- helpers for building synthetic .flp files -----------------------------
  87. struct FlpBuilder
  88. {
  89. std::vector<std::uint8_t> bytes;
  90. FlpBuilder (std::uint16_t ppq = 96)
  91. {
  92. put ("FLhd");
  93. u32 (6);
  94. u16 (0);
  95. u16 (1);
  96. u16 (ppq);
  97. put ("FLdt");
  98. u32 (0); // size is not used by the reader
  99. }
  100. void put (const char* s) { bytes.insert (bytes.end(), s, s + std::strlen (s)); }
  101. void u8 (std::uint8_t v) { bytes.push_back (v); }
  102. void u16 (std::uint16_t v) { u8 ((std::uint8_t) v); u8 ((std::uint8_t) (v >> 8)); }
  103. void u32 (std::uint32_t v) { u16 ((std::uint16_t) v); u16 ((std::uint16_t) (v >> 16)); }
  104. void varint (std::size_t n)
  105. {
  106. do
  107. {
  108. auto b = (std::uint8_t) (n & 0x7F);
  109. n >>= 7;
  110. u8 (n ? (std::uint8_t) (b | 0x80) : b);
  111. } while (n);
  112. }
  113. void data (std::uint8_t id, const std::vector<std::uint8_t>& payload)
  114. {
  115. u8 (id);
  116. varint (payload.size());
  117. bytes.insert (bytes.end(), payload.begin(), payload.end());
  118. }
  119. void ascii (std::uint8_t id, const std::string& s)
  120. {
  121. std::vector<std::uint8_t> p (s.begin(), s.end());
  122. p.push_back (0);
  123. data (id, p);
  124. }
  125. void utf16 (std::uint8_t id, const std::u16string& s)
  126. {
  127. std::vector<std::uint8_t> p;
  128. for (auto c : s)
  129. {
  130. p.push_back ((std::uint8_t) c);
  131. p.push_back ((std::uint8_t) (c >> 8));
  132. }
  133. p.push_back (0);
  134. p.push_back (0);
  135. data (id, p);
  136. }
  137. };
  138. std::vector<std::uint8_t> noteRecord (std::uint32_t pos, std::uint16_t channel, std::uint32_t len, std::uint16_t key,
  139. std::uint8_t velocity)
  140. {
  141. std::vector<std::uint8_t> r (24, 0);
  142. std::memcpy (&r[0], &pos, 4);
  143. std::memcpy (&r[6], &channel, 2);
  144. std::memcpy (&r[8], &len, 4);
  145. std::memcpy (&r[12], &key, 2);
  146. r[16] = 120;
  147. r[20] = 64;
  148. r[21] = velocity;
  149. return r;
  150. }
  151. } // namespace
  152. // ---------------------------------------------------------------------------
  153. // FLP
  154. TEST (flp_rejects_garbage)
  155. {
  156. std::vector<std::uint8_t> junk (64, 0x41);
  157. bool threw = false;
  158. try { flp::EventReader r (junk); } catch (const flp::Error&) { threw = true; }
  159. CHECK (threw);
  160. }
  161. TEST (flp_reads_size_classes_varint_and_extended_ids)
  162. {
  163. FlpBuilder b;
  164. b.u8 (0x15); b.u8 (2); // u8
  165. b.u8 (0x40); b.u16 (513); // u16
  166. b.u8 (0x9C); b.u32 (128500); // u32
  167. b.data (0xD5, std::vector<std::uint8_t> (300, 7)); // 2-byte varint
  168. b.u8 (0xAC); b.u32 (0xC0000100); b.varint (3); b.u8 (1); b.u8 (2); b.u8 (3); // extended ID
  169. flp::EventReader r (b.bytes);
  170. flp::Event e;
  171. CHECK (r.header().ppq == 96);
  172. CHECK (r.next (e) && e.id == 0x15 && e.value == 2);
  173. CHECK (r.next (e) && e.id == 0x40 && e.value == 513);
  174. CHECK (r.next (e) && e.id == 0x9C && e.value == 128500);
  175. CHECK (r.next (e) && e.id == 0xD5 && e.data.size() == 300 && e.data[299] == 7);
  176. CHECK (r.next (e) && e.id == 0xC0000100 && e.isData() && e.data.size() == 3 && e.data[2] == 3);
  177. CHECK (! r.next (e));
  178. }
  179. TEST (flp_truncated_file_throws)
  180. {
  181. FlpBuilder b;
  182. b.u8 (0x9C); b.u8 (1); // u32 with only 1 byte
  183. flp::EventReader r (b.bytes);
  184. flp::Event e;
  185. bool threw = false;
  186. try { r.next (e); } catch (const flp::Error&) { threw = true; }
  187. CHECK (threw);
  188. }
  189. TEST (flp_version_numbers)
  190. {
  191. CHECK (flp::parseVersionNumber ("25.2.5.5319") == 25002005u);
  192. CHECK (flp::parseVersionNumber ("20.99.3000.3031") == 20102000u);
  193. CHECK (flp::parseVersionNumber ("11.0.3") == 11000003u);
  194. }
  195. TEST (flp_playlist_record_size_by_version)
  196. {
  197. CHECK (flp::playlistRecordSize (12009003, 64) == 32);
  198. CHECK (flp::playlistRecordSize (21000000, 120) == 60);
  199. CHECK (flp::playlistRecordSize (25002005, 160) == 80);
  200. CHECK (flp::playlistRecordSize (25002005, 60) == 60); // size doesn't match the version -> tries the others
  201. CHECK (flp::playlistRecordSize (25002005, 7) == 0);
  202. }
  203. TEST (flp_parses_project_model)
  204. {
  205. FlpBuilder b (96);
  206. b.ascii (0xC7, "25.2.5.5319");
  207. b.u8 (0x9C); b.u32 (174500);
  208. b.utf16 (0xC2, u"Título");
  209. b.u8 (0x41); b.u16 (3);
  210. b.u8 (0x96); b.u32 (0x00A14547); // BGR in the file
  211. auto notes = noteRecord (96, 1, 48, 64, 100);
  212. auto n2 = noteRecord (0, 0, 0, 60, 128);
  213. notes.insert (notes.end(), n2.begin(), n2.end());
  214. b.data (0xE0, notes);
  215. b.u8 (0x40); b.u16 (0);
  216. b.u8 (0x15); b.u8 (0);
  217. b.utf16 (0xCB, u"Kick");
  218. {
  219. std::vector<std::uint8_t> levels (24, 0);
  220. const std::int32_t lv[] = { 3200, 12800, -150 };
  221. std::memcpy (levels.data(), lv, sizeof (lv));
  222. b.data (0xDB, levels);
  223. }
  224. b.u8 (0x68); b.u16 (5);
  225. b.u8 (0x40); b.u16 (1);
  226. b.u8 (0x15); b.u8 (2);
  227. b.utf16 (0xC9, u"FLEX");
  228. b.utf16 (0xCB, u"Lead");
  229. b.u8 (0x63); b.u16 (0);
  230. std::vector<std::uint8_t> item (80, 0);
  231. std::uint32_t pos = 384, len = 768;
  232. std::uint16_t base = 20480, idx = 20480 + 3, rv = 499 - 2;
  233. std::memcpy (&item[0], &pos, 4);
  234. std::memcpy (&item[4], &base, 2);
  235. std::memcpy (&item[6], &idx, 2);
  236. std::memcpy (&item[8], &len, 4);
  237. std::memcpy (&item[12], &rv, 2);
  238. b.data (0xE9, item);
  239. b.utf16 (0xCC, u"Drums");
  240. b.data (0xEC, std::vector<std::uint8_t> (12, 0));
  241. b.data (0xEC, std::vector<std::uint8_t> (12, 0));
  242. const auto p = flp::parseProject (b.bytes);
  243. CHECK (p.version == "25.2.5.5319");
  244. CHECK (std::abs (p.tempo - 174.5) < 1e-9);
  245. CHECK (p.title == "Título");
  246. CHECK (p.channels.size() == 2);
  247. CHECK (p.channels[0].name == "Kick" && p.channels[0].mixerTrack == 5);
  248. CHECK (p.channels[0].hasLevels && p.channels[0].pan == 3200 && p.channels[0].volume == 12800 && p.channels[0].pitchCents == -150);
  249. CHECK (p.channels[1].type == flp::ChannelType::instrument && p.channels[1].pluginName == "FLEX");
  250. CHECK (p.patterns.size() == 1 && p.patterns[0].index == 3);
  251. CHECK (p.patterns[0].colour && *p.patterns[0].colour == 0x4745A1);
  252. CHECK (p.patterns[0].notes.size() == 2 && p.patterns[0].notes[0].position == 0); // sorted
  253. CHECK (p.patterns[0].notes[1].key == 64 && p.patterns[0].notes[1].length == 48);
  254. CHECK (p.arrangements.size() == 1 && p.arrangements[0].items.size() == 1);
  255. const auto& it = p.arrangements[0].items[0];
  256. CHECK (it.kind == flp::PlaylistItem::Kind::pattern && it.index == 3 && it.track == 2 && it.position == 384);
  257. CHECK (p.mixer.size() == 2 && p.mixer[0].name == "Drums" && p.mixer[1].name.empty());
  258. CHECK (p.warnings.empty());
  259. }
  260. TEST (flp_fuzz_corrupted_files_do_not_crash)
  261. {
  262. if (realFlpDir.empty())
  263. return;
  264. // some real .flp files, corrupted in various ways: the parser may reject them (flp::Error), but
  265. // must never hang, read past the buffer or produce a Song with invalid indices
  266. std::vector<std::vector<std::uint8_t>> sources;
  267. for (auto& entry : std::filesystem::recursive_directory_iterator (realFlpDir))
  268. if (entry.path().extension() == ".flp" && sources.size() < 6 && std::filesystem::file_size (entry.path()) < 3'000'000)
  269. {
  270. std::ifstream in (entry.path(), std::ios::binary);
  271. sources.emplace_back ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  272. }
  273. std::uint32_t seed = 2024;
  274. auto rnd = [&] (std::uint32_t n) { seed = seed * 1664525u + 1013904223u; return n == 0 ? 0u : (seed >> 8) % n; };
  275. int parsed = 0, rejected = 0;
  276. for (int round = 0; round < 240 && ! sources.empty(); ++round)
  277. {
  278. auto bytes = sources[(std::size_t) rnd ((std::uint32_t) sources.size())];
  279. switch (round % 4)
  280. {
  281. case 0: bytes.resize (rnd ((std::uint32_t) bytes.size())); break; // truncated
  282. 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;
  283. case 2: // absurd event size
  284. for (int k = 0; k < 5; ++k)
  285. bytes[(std::size_t) rnd ((std::uint32_t) bytes.size())] = 0xFF;
  286. break;
  287. default: // shuffled block
  288. {
  289. const auto a = rnd ((std::uint32_t) bytes.size()), b = rnd ((std::uint32_t) bytes.size());
  290. std::reverse (bytes.begin() + std::min (a, b), bytes.begin() + std::max (a, b));
  291. break;
  292. }
  293. }
  294. try
  295. {
  296. const auto project = flp::parseProject (bytes);
  297. const auto song = lynx::importFlp (project);
  298. ++parsed;
  299. for (const auto& p : song.patterns)
  300. for (const auto& n : p.notes)
  301. CHECK (n.channel >= 0 && n.channel < (int) song.channels.size());
  302. for (const auto& c : song.playlist)
  303. CHECK (c.kind != lynx::ClipKind::pattern || (c.pattern >= 0 && c.pattern < (int) song.patterns.size()));
  304. }
  305. catch (const flp::Error&)
  306. {
  307. ++rejected;
  308. }
  309. }
  310. std::printf (" fuzz: %d imported, %d rejected\n", parsed, rejected);
  311. CHECK (parsed + rejected == 240);
  312. }
  313. TEST (plugin_state_decoders_survive_garbage)
  314. {
  315. // random blobs (varied sizes, including valid headers followed by garbage)
  316. std::uint32_t seed = 77;
  317. auto rnd = [&] { seed = seed * 1664525u + 1013904223u; return seed >> 8; };
  318. const char* plugins[] = { "Fruity Parametric EQ 2", "Fruity Limiter", "Fruity Reeverb 2", "Fruity Delay 2", "Fruity Delay 3",
  319. "Fruity Compressor", "Fruity Balance", "Fruity PanOMatic", "Fruity Stereo Shaper", "Fruity Phase Inverter" };
  320. int decoded = 0;
  321. for (int round = 0; round < 3000; ++round)
  322. {
  323. std::vector<std::uint8_t> blob ((std::size_t) (rnd() % 600));
  324. for (auto& b : blob)
  325. b = (std::uint8_t) rnd();
  326. if (blob.size() >= 4 && round % 3 == 0) // versions the readers accept
  327. {
  328. const std::uint32_t versions[] = { 8, 10001, 10000, 12, 14, 6, 1 };
  329. const auto v = versions[rnd() % 7];
  330. std::memcpy (blob.data(), &v, 4);
  331. }
  332. if (auto fx = lynx::effectFromFl (plugins[rnd() % 10], blob))
  333. {
  334. ++decoded;
  335. for (auto v : fx->params)
  336. CHECK (std::isfinite (v) && v >= 0.0f && v <= 1.0f);
  337. }
  338. lynx::SynthSettings synth;
  339. if (lynx::synthFrom3xOsc (blob, synth))
  340. for (const auto& o : synth.osc)
  341. CHECK (std::isfinite (o.level) && o.level >= 0.0f && o.level <= 1.0f);
  342. float harmlessGain = 1.0f;
  343. if (lynx::synthFromHarmless (blob, 120.0, synth, harmlessGain))
  344. CHECK (std::isfinite (harmlessGain) && std::isfinite (synth.cutoff) && std::isfinite (synth.attack));
  345. if (lynx::synthFromFruitKick (blob, synth))
  346. CHECK (std::isfinite (synth.decay) && std::isfinite (synth.pitchEnv.amount));
  347. if (lynx::synthFromGms (blob, 120.0, synth, harmlessGain) || lynx::synthFromHarmor (blob, synth, harmlessGain) || lynx::synthFromOgun (blob, synth, harmlessGain)
  348. || lynx::synthFromSakura (blob, synth) || lynx::synthFromKepler (blob, synth, harmlessGain))
  349. CHECK (std::isfinite (synth.cutoff) && std::isfinite (synth.attack) && std::isfinite (harmlessGain));
  350. if (auto sound = lynx::drumSynthLiveSound (blob))
  351. CHECK (sound->size() < 256);
  352. if (auto wave = lynx::waveTravellerSample (blob))
  353. CHECK (! wave->first.empty() && wave->second >= 0 && wave->second <= 127);
  354. lynx::synthFromBooBass (blob, synth);
  355. lynx::gmsStateUsable (blob); // (the exact engines' parsers reject garbage without crashing)
  356. lynx::morphineStateUsable (blob);
  357. if (lynx::synthFromPoiZone (blob, synth, harmlessGain) || lynx::synthFromBassDrum (blob, synth, harmlessGain) || lynx::synthFromToxic (blob, synth, harmlessGain)
  358. || lynx::synthFromMorphine (blob, synth, harmlessGain))
  359. CHECK (std::isfinite (synth.cutoff) && std::isfinite (harmlessGain));
  360. if (auto patch = lynx::drumpadPatchName (blob))
  361. CHECK (patch->size() <= 0x30 && std::isfinite (lynx::drumToneForName (*patch).decay));
  362. if (auto flex = lynx::flexPresetName (blob))
  363. CHECK ((! flex->first.empty() || ! flex->second.empty()) && flex->second.size() <= 1024);
  364. if (lynx::synthFromSytrus (blob, 120.0, synth, harmlessGain))
  365. CHECK (std::isfinite (synth.cutoff) && std::isfinite (synth.attack));
  366. if (lynx::synthFromDX10 (blob, synth))
  367. CHECK (std::isfinite (synth.decay) && std::isfinite (synth.release) && std::isfinite (synth.osc[1].level));
  368. if (blob.size() >= 4 && round % 5 == 0) // MiniSynth header followed by garbage
  369. {
  370. std::memcpy (blob.data(), "SSLF", 4);
  371. if (blob.size() > 220)
  372. {
  373. std::memcpy (blob.data() + 40, "DATA", 4);
  374. std::memcpy (blob.data() + 48, "0rev", 4);
  375. }
  376. }
  377. if (lynx::synthFromMiniSynth (blob, 120.0, synth))
  378. CHECK (std::isfinite (synth.cutoff) && std::isfinite (synth.decay) && std::isfinite (synth.attack));
  379. lynx::ForeignPlugin foreign;
  380. lynx::parseFlWrapper (blob, foreign);
  381. std::vector<std::uint8_t> component, controller;
  382. lynx::splitFlVst3State (blob, component, controller);
  383. }
  384. CHECK (decoded == 3000); // every known name yields an effect (default when the blob is unusable)
  385. }
  386. TEST (inflate_zlib)
  387. {
  388. // fixed Huffman with back-references
  389. const std::uint8_t fixed[] = { 0x78, 0xda, 0x4b, 0x4c, 0x4a, 0x4e, 0xc4, 0x86, 0x22, 0x00, 0x7c, 0x69, 0x09, 0x89 };
  390. const auto a = lynx::inflateZlib (fixed, sizeof (fixed));
  391. CHECK (a && std::string (a->begin(), a->end()) == "abcabcabcabcabcabcabcabcX");
  392. // stored (uncompressed) block
  393. const std::uint8_t stored[] = { 0x78, 0x01, 0x01, 0x03, 0x00, 0xfc, 0xff, 'L', 'Y', 'N', 0x00, 0x00, 0x00, 0x00 };
  394. const auto b = lynx::inflateZlib (stored, sizeof (stored));
  395. CHECK (b && std::string (b->begin(), b->end()) == "LYN");
  396. // truncated, bad header and size limit
  397. CHECK (! lynx::inflateZlib (fixed, 6));
  398. const std::uint8_t bad[] = { 0x12, 0x34, 0x00 };
  399. CHECK (! lynx::inflateZlib (bad, sizeof (bad)));
  400. CHECK (! lynx::inflateZlib (fixed, sizeof (fixed), false, 10));
  401. }
  402. TEST (fl_round15_effects_convert_known_values)
  403. {
  404. auto blob = [] (std::vector<std::int32_t> words) {
  405. std::vector<std::uint8_t> b (words.size() * 4);
  406. std::memcpy (b.data(), words.data(), b.size());
  407. return b;
  408. };
  409. // Frequency Shifter "+800 Hz": frequency 51542 in the 20 kHz range, 100% wet
  410. const auto fs = lynx::effectFromFl ("Frequency Shifter", blob ({ 4, 10000, 0, 51542, 0, 10000, 10000, 5000, 10000, 0, 5000, 0, 0 }));
  411. CHECK (fs && fs->kind == lynx::EffectKind::freqShift);
  412. if (fs)
  413. {
  414. const auto x = (fs->params[0] - 0.5) * 2.0;
  415. CHECK (std::abs (2000.0 * x * std::abs (x) - 800.0) < 10.0);
  416. CHECK (std::abs (fs->params[1] - 1.0f) < 1e-4f);
  417. }
  418. // Emphasis: input 0.0625 (= +1.5 dB) and ceiling 0.9308 (≈ −1.6 dB) -> limiter
  419. const auto em = lynx::effectFromFl ("Emphasis", blob ({ 8, 0, 0, 2, 1, 0, 0, 625, 10000, 10000, 9308, 0, 2, 7, 0 }));
  420. CHECK (em && em->kind == lynx::EffectKind::limiter && em->enabled);
  421. if (em)
  422. {
  423. CHECK (std::abs (em->params[1] * 24.0f - 1.5f) < 0.05f);
  424. CHECK (std::abs (em->params[0] * 12.0f - 12.0f + 1.6f) < 0.1f);
  425. }
  426. // Pitch Shifter +12 st, mix 100%
  427. 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 }));
  428. CHECK (ps && ps->kind == lynx::EffectKind::pitchShift && std::abs (ps->params[0] - (0.5f + 12.0f / 48.0f)) < 1e-4f);
  429. }
  430. TEST (frequency_shifter_moves_spectrum_by_hz)
  431. {
  432. auto fx = lynx::makeEffect (lynx::EffectKind::freqShift);
  433. fx->prepare (48000.0);
  434. auto slot = lynx::makeEffectSlot (lynx::EffectKind::freqShift);
  435. // +200 Hz: x·|x|·2000 = 200 -> x = sqrt(0.1)
  436. slot.params[0] = (float) (0.5 + std::sqrt (0.1) / 2.0);
  437. std::vector<float> l (48000), r (48000);
  438. for (int i = 0; i < 48000; ++i)
  439. l[(std::size_t) i] = r[(std::size_t) i] = (float) std::sin (2.0 * 3.141592653589793 * 1000.0 * i / 48000.0);
  440. for (int done = 0; done < 48000; done += 480)
  441. fx->process (l.data() + done, r.data() + done, 480, slot.params, 120.0);
  442. auto energy = [&] (double f) {
  443. const auto w = 2.0 * 3.141592653589793 * f / 48000.0, k = 2.0 * std::cos (w);
  444. double s1 = 0.0, s2 = 0.0;
  445. for (int i = 9600; i < 48000; ++i)
  446. {
  447. const auto s0 = l[(std::size_t) i] + k * s1 - s2;
  448. s2 = s1;
  449. s1 = s0;
  450. }
  451. return s1 * s1 + s2 * s2 - k * s1 * s2;
  452. };
  453. // the energy moves to 1200 Hz; little remains at 1000 and almost nothing at the image (800)
  454. CHECK (energy (1200.0) > 50.0 * energy (1000.0));
  455. CHECK (energy (1200.0) > 50.0 * energy (800.0));
  456. }
  457. TEST (pitch_shift_moves_frequency_keeps_length)
  458. {
  459. auto fx = lynx::makeEffect (lynx::EffectKind::pitchShift);
  460. fx->prepare (48000.0);
  461. auto slot = lynx::makeEffectSlot (lynx::EffectKind::pitchShift);
  462. auto crossingsAfter = [&] (float semitoneParam) {
  463. fx->reset();
  464. slot.params[0] = semitoneParam;
  465. std::vector<float> l (48000), r (48000);
  466. for (int i = 0; i < 48000; ++i)
  467. l[(std::size_t) i] = r[(std::size_t) i] = (float) std::sin (2.0 * 3.141592653589793 * 220.0 * i / 48000.0);
  468. for (int done = 0; done < 48000; done += 512)
  469. fx->process (l.data() + done, r.data() + done, std::min (512, 48000 - done), slot.params, 120.0);
  470. int crossings = 0;
  471. for (int i = 9600; i < 48000; ++i)
  472. crossings += (l[(std::size_t) i - 1] < 0.0f) != (l[(std::size_t) i] < 0.0f);
  473. for (auto v : l)
  474. CHECK (std::isfinite (v) && std::abs (v) < 1.6f);
  475. return crossings / 0.8 / 2.0; // cycles per second
  476. };
  477. CHECK (std::abs (crossingsAfter (0.5f) - 220.0) < 8.0); // 0 st
  478. CHECK (std::abs (crossingsAfter (0.5f + 12.0f / 48.0f) - 440.0) < 25.0); // +12 st
  479. CHECK (std::abs (crossingsAfter (0.5f - 12.0f / 48.0f) - 110.0) < 12.0); // −12 st
  480. }
  481. TEST (volume_gate_follows_bar_position)
  482. {
  483. auto fx = lynx::makeEffect (lynx::EffectKind::volumeGate);
  484. fx->prepare (48000.0);
  485. auto slot = lynx::makeEffectSlot (lynx::EffectKind::volumeGate);
  486. for (int i = 0; i < 32; ++i)
  487. slot.params[(std::size_t) i] = i < 16 ? 1.0f : 0.0f; // first two beats open, two closed
  488. slot.params[33] = slot.params[34] = 0.0f; // no smoothing
  489. // 120 BPM: one beat = 0.5 s = 24000 samples; the 4-beat bar starts at tick 0
  490. std::vector<float> l (96000, 1.0f), r (96000, 1.0f);
  491. fx->setSongPosition (0.0);
  492. for (int done = 0; done < 96000; done += 512)
  493. fx->process (l.data() + done, r.data() + done, std::min (512, 96000 - done), slot.params, 120.0);
  494. CHECK (l[10000] > 0.99f && l[40000] > 0.99f); // beats 1 and 2
  495. CHECK (l[60000] < 0.01f && l[90000] < 0.01f); // beats 3 and 4
  496. // starting mid-bar (beat 3): already closed
  497. std::vector<float> l2 (4800, 1.0f), r2 (4800, 1.0f);
  498. fx->reset();
  499. fx->setSongPosition (2.0 * lynx::ppq);
  500. fx->process (l2.data(), r2.data(), 4800, slot.params, 120.0);
  501. CHECK (l2[4000] < 0.01f);
  502. // mix 0: transparent
  503. slot.params[32] = 0.0f;
  504. std::vector<float> l3 (4800, 1.0f), r3 (4800, 1.0f);
  505. fx->setSongPosition (2.0 * lynx::ppq);
  506. fx->process (l3.data(), r3.data(), 4800, slot.params, 120.0);
  507. CHECK (l3[4000] > 0.99f);
  508. }
  509. TEST (patcher_branch_heads_follow_rea)
  510. {
  511. auto words = [] (std::vector<std::int32_t> v) {
  512. std::vector<std::uint8_t> b (v.size() * 4);
  513. std::memcpy (b.data(), v.data(), b.size());
  514. return b;
  515. };
  516. // Frequency Splitter, 2 bands, destinations 1/2/3, slope combo 3 (24 dB/oct), high send −6 dB
  517. std::vector<std::int32_t> fs (18, 0);
  518. fs[0] = 4;
  519. fs[1] = 32768;
  520. fs[3] = 3;
  521. fs[6] = 0;
  522. fs[11] = -600;
  523. fs[15] = 1;
  524. fs[16] = 2;
  525. fs[17] = 3;
  526. const auto split = words (fs);
  527. const auto low = lynx::patcherBranchHead ("Frequency Splitter", split, 1);
  528. CHECK (low.valid && low.slot && low.note.empty());
  529. if (low.slot)
  530. {
  531. // low band = just the Crossover low-pass, combo 3 (24 dB/oct)
  532. CHECK (low.slot->kind == lynx::EffectKind::crossover && low.slot->params[0] == 0.0f && low.slot->params[3] == 1.0f);
  533. CHECK (std::lround (low.slot->params[5] * 7.0f) == 3);
  534. }
  535. const auto mid = lynx::patcherBranchHead ("Frequency Splitter", split, 2);
  536. CHECK (mid.valid && mid.gain == 0.0f); // with 2 bands the mid is silent
  537. const auto high = lynx::patcherBranchHead ("Frequency Splitter", split, 3);
  538. CHECK (high.valid && std::abs (high.gain - std::pow (10.0f, -6.0f / 20.0f)) < 1e-4f);
  539. CHECK (! lynx::patcherBranchHead ("Frequency Splitter", split, 7).valid);
  540. // Stereo Shaper with identity matrix: the difference (destination 4) is zero
  541. const auto shaper = words ({ 3, 0, 12800, 12800, 0, 0, 0, 4, 0 });
  542. const auto diff = lynx::patcherBranchHead ("Fruity Stereo Shaper", shaper, 4);
  543. 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);
  544. CHECK (! lynx::patcherBranchHead ("Fruity Stereo Shaper", shaper, 2).valid);
  545. }
  546. TEST (parallel_container_sums_branches)
  547. {
  548. // two branches: dry with gain 0.5 and a utility that flips phase (matrix −1) with gain 0.5 -> silence
  549. auto slot = lynx::makeEffectSlot (lynx::EffectKind::parallel);
  550. lynx::EffectBranch dry;
  551. dry.gain = 0.5f;
  552. lynx::EffectBranch inverted;
  553. inverted.gain = 0.5f;
  554. auto flip = lynx::makeEffectSlot (lynx::EffectKind::utility);
  555. flip.params[2] = flip.params[5] = 0.25f; // (−1 + 2)/4
  556. inverted.chain.push_back (flip);
  557. slot.branches = { dry, inverted };
  558. auto fx = lynx::makeParallelEffect (slot);
  559. fx->prepare (48000.0);
  560. std::vector<float> l (9000, 0.8f), r (9000, -0.4f);
  561. fx->process (l.data(), r.data(), 9000, slot.params, 120.0);
  562. CHECK (std::abs (l[100]) < 1e-5f && std::abs (r[8999]) < 1e-5f);
  563. // only the dry branch with gain 2: doubles
  564. slot.branches = { lynx::EffectBranch { {}, 2.0f } };
  565. auto doubler = lynx::makeParallelEffect (slot);
  566. doubler->prepare (48000.0);
  567. std::fill (l.begin(), l.end(), 0.25f);
  568. doubler->process (l.data(), r.data(), 9000, slot.params, 120.0);
  569. CHECK (std::abs (l[5000] - 0.5f) < 1e-6f);
  570. }
  571. TEST (fl_controller_constant_outputs)
  572. {
  573. std::vector<std::int32_t> xy { 2, 32768, 0, 65536, 0, 16384, 0, 65536, 0, 1024, 256 };
  574. std::vector<std::uint8_t> blob (xy.size() * 4 + 8, 0);
  575. std::memcpy (blob.data(), xy.data(), xy.size() * 4);
  576. CHECK (std::abs (lynx::controllerConstantOutput ("Fruity X-Y Controller", blob, 0).value_or (-1.0f) - 0.5f) < 1e-4f);
  577. CHECK (std::abs (lynx::controllerConstantOutput ("Fruity X-Y Controller", blob, 1).value_or (-1.0f) - 0.25f) < 1e-4f);
  578. // Control Surface: version + group { 0x836: value 0.75, -, output 2 }
  579. std::vector<std::uint8_t> cs (4, 0);
  580. cs[0] = 1;
  581. auto chunk = [] (std::vector<std::uint8_t>& out, std::uint32_t id, const std::vector<std::uint8_t>& body) {
  582. const auto size = (std::uint64_t) body.size();
  583. out.insert (out.end(), reinterpret_cast<const std::uint8_t*> (&id), reinterpret_cast<const std::uint8_t*> (&id) + 4);
  584. out.insert (out.end(), reinterpret_cast<const std::uint8_t*> (&size), reinterpret_cast<const std::uint8_t*> (&size) + 8);
  585. out.insert (out.end(), body.begin(), body.end());
  586. };
  587. std::vector<std::uint8_t> value (12, 0);
  588. const float v = 0.75f;
  589. const std::int32_t out = 2;
  590. std::memcpy (value.data(), &v, 4);
  591. std::memcpy (value.data() + 8, &out, 4);
  592. std::vector<std::uint8_t> group;
  593. chunk (group, 0x836, value);
  594. chunk (cs, 0, group);
  595. CHECK (std::abs (lynx::controllerConstantOutput ("Control Surface", cs, 2).value_or (-1.0f) - 0.75f) < 1e-6f);
  596. CHECK (! lynx::controllerConstantOutput ("Control Surface", cs, 0).has_value());
  597. }
  598. TEST (flp_midi_out_notes_reach_wrapper_on_same_port)
  599. {
  600. auto record = [] (std::vector<std::uint8_t>& out, std::uint32_t id, std::vector<std::uint8_t> body) {
  601. const auto size = (std::uint64_t) body.size();
  602. out.insert (out.end(), reinterpret_cast<const std::uint8_t*> (&id), reinterpret_cast<const std::uint8_t*> (&id) + 4);
  603. out.insert (out.end(), reinterpret_cast<const std::uint8_t*> (&size), reinterpret_cast<const std::uint8_t*> (&size) + 8);
  604. out.insert (out.end(), body.begin(), body.end());
  605. };
  606. auto i32s = [] (std::vector<std::int32_t> v) {
  607. std::vector<std::uint8_t> b (v.size() * 4);
  608. std::memcpy (b.data(), v.data(), b.size());
  609. return b;
  610. };
  611. flp::Project p;
  612. flp::Channel midiOut;
  613. midiOut.index = 0;
  614. midiOut.type = flp::ChannelType::native;
  615. midiOut.pluginName = "MIDI Out";
  616. midiOut.pluginState = i32s ({ 7, 0, -1, -1, -1, 0, 3, 0 }); // channel 1, port 3 (@24)
  617. flp::Channel wrapper;
  618. wrapper.index = 1;
  619. wrapper.type = flp::ChannelType::native;
  620. wrapper.pluginName = "Fruity Wrapper";
  621. wrapper.pluginState = i32s ({ 9 });
  622. record (wrapper.pluginState, 0x32, i32s ({ 7 })); // VST3
  623. record (wrapper.pluginState, 0x01, i32s ({ 3, -1, 0, 0, 0 })); // input port 3
  624. p.channels = { midiOut, wrapper };
  625. flp::Pattern pattern;
  626. pattern.index = 1;
  627. flp::Note note;
  628. note.channel = 0;
  629. note.key = 64;
  630. note.length = 96;
  631. pattern.notes.push_back (note);
  632. p.patterns.push_back (pattern);
  633. const auto song = lynx::importFlp (p);
  634. CHECK (song.channels.size() == 2 && song.channels[0].muted);
  635. CHECK (song.channels[1].plugin.foreign.midiInPort == 3);
  636. int toWrapper = 0;
  637. for (const auto& pat : song.patterns)
  638. for (const auto& n : pat.notes)
  639. toWrapper += n.channel == 1 && n.key == 64;
  640. CHECK (toWrapper == 1);
  641. }
  642. TEST (flp_effect_automation_follows_slots_and_params)
  643. {
  644. // track 1: slot 0 with an effect that has no equivalent (dropped), slot 2 with Parametric EQ 2
  645. flp::Project p;
  646. flp::MixerInsert insert;
  647. insert.index = 1;
  648. insert.slots.push_back ({ 0, "Some Unknown FX", {} });
  649. insert.slots.push_back ({ 2, "Fruity Parametric EQ 2", {} });
  650. p.mixer.push_back (insert);
  651. auto clip = [&] (int index, std::uint32_t target) {
  652. flp::Channel c;
  653. c.index = index;
  654. c.type = flp::ChannelType::automationClip;
  655. c.automation = { { 0.0, 0.0 }, { 96.0, 1.0 } };
  656. p.channels.push_back (c);
  657. p.automationLinks.push_back ({ index, { target } });
  658. };
  659. 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; };
  660. clip (0, mixer (1, 2, 0x8000 + 7)); // EQ band 1 frequency
  661. clip (1, mixer (1, 2, 0x1F01)); // EQ slot mix
  662. clip (2, mixer (1, 0, 0x8000)); // parameter of the dropped effect
  663. clip (3, mixer (1, 2, 0x8000 + 21)); // band type: no equivalent
  664. const auto song = lynx::importFlp (p);
  665. CHECK (song.automations.size() == 4);
  666. CHECK (song.mixer[1].effects.size() == 1 && song.mixer[1].effects[0].kind == lynx::EffectKind::parametricEq);
  667. const auto& freq = song.automations[0];
  668. CHECK (freq.target.kind == lynx::AutomationTargetKind::effectParam && freq.target.index == 1 && freq.target.slot == 0);
  669. CHECK (freq.target.param == lynx::peq::param (0, 1));
  670. // FL's 0..1 (20 Hz..20 kHz) becomes our frequency scale
  671. CHECK (std::abs (freq.points.front().value - lynx::peq::hzValue (20.0)) < 1e-4f);
  672. CHECK (std::abs (freq.points.back().value - lynx::peq::hzValue (20000.0)) < 1e-4f);
  673. CHECK (song.automations[1].target.kind == lynx::AutomationTargetKind::effectMix && song.automations[1].target.slot == 0);
  674. CHECK (song.automations[2].target.kind == lynx::AutomationTargetKind::none);
  675. CHECK (song.automations[3].target.kind == lynx::AutomationTargetKind::none);
  676. // the automated mix is read/written through the target
  677. auto copy = song;
  678. CHECK (copy.setTargetValue (song.automations[1].target, 0.25f) && std::abs (copy.mixer[1].effects[0].mix - 0.25f) < 1e-6f);
  679. CHECK (std::abs (copy.targetValue (song.automations[1].target) - 0.25f) < 1e-6f);
  680. }
  681. TEST (flp_real_files)
  682. {
  683. if (realFlpDir.empty())
  684. {
  685. std::printf (" (skipped: pass a folder with .flp files as argument)\n");
  686. return;
  687. }
  688. int files = 0, withNotes = 0, withPlaylist = 0, automations = 0, automationsWithTarget = 0, sends = 0;
  689. int threeOsc = 0, threeOscDecoded = 0, wrapped = 0, wrappedParsed = 0, markers = 0, signatures = 0, trackEqs = 0;
  690. int harmless = 0, harmlessDecoded = 0, harmlessParsed = 0, harmlessKind = 0, sytrus = 0, sytrusDecoded = 0, sytrusEngine = 0, sytrusRendered = 0,
  691. sytrusSounding = 0;
  692. int harmor = 0, harmorUsable = 0, harmorKind = 0, harmorSounding = 0;
  693. int gms = 0, gmsUsable = 0, gmsKind = 0, gmsSounding = 0, morphine = 0, morphineUsable = 0, morphineKind = 0, morphineSounding = 0, demoGoldens = 0;
  694. int ogun = 0, ogunUsable = 0, ogunKind = 0, ogunSounding = 0;
  695. int kepler = 0, keplerUsable = 0, keplerKind = 0, keplerSounding = 0;
  696. std::map<std::string, std::pair<int, int>> generators; // GMS/Ogun/Autogun/Sakura/DrumSynth: channels, decoded
  697. int ogunTrumpet = 0; // Ogun channels whose spectrum matches the REA "Trumpet" reference
  698. int peqSlots = 0, peqShaped = 0, reverbs = 0, reverbsDryless = 0, reverbsLowCut = 0;
  699. int dwChannels = 0, dwZones = 0, fpcKits = 0, padChannels = 0, padNotes = 0;
  700. int harmlessCompWanted = 0, harmlessCompLoaded = 0; // Harmless rack compressors / presets read from the installation
  701. int maximusSlots = 0, maximusExact = 0, sgzSlots = 0, sgzExact = 0, vocodexSlots = 0, vocodexWithData = 0; // REA_rodada40
  702. // import with the installation's samples (realFlpDir is ...\Data): for DirectWave/FPC
  703. lynx::FlpImportOptions withFiles;
  704. const auto flRoot = std::filesystem::path (realFlpDir).parent_path().string();
  705. withFiles.roots = { flRoot, realFlpDir, "" };
  706. withFiles.fileExists = [] (const std::string& path) {
  707. auto local = path;
  708. std::replace (local.begin(), local.end(), '\\', '/');
  709. return std::filesystem::exists (local);
  710. };
  711. withFiles.readFile = [] (const std::string& path) {
  712. auto local = path;
  713. std::replace (local.begin(), local.end(), '\\', '/');
  714. std::ifstream in (local, std::ios::binary);
  715. return std::vector<std::uint8_t> ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  716. };
  717. int embeddedSaved = 0;
  718. withFiles.saveEmbedded = [&embeddedSaved] (const std::vector<std::uint8_t>& wav, const std::string&) {
  719. ++embeddedSaved;
  720. return wav.size() > 44 ? std::string ("embutido.wav") : std::string();
  721. };
  722. int slicedChannels = 0, flKeysChannels = 0;
  723. for (auto& entry : std::filesystem::recursive_directory_iterator (realFlpDir))
  724. {
  725. if (entry.path().extension() != ".flp")
  726. continue;
  727. std::ifstream in (entry.path(), std::ios::binary);
  728. std::vector<std::uint8_t> bytes ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  729. ++files;
  730. try
  731. {
  732. const auto p = flp::parseProject (bytes);
  733. CHECK (! p.version.empty());
  734. CHECK (p.tempo > 10.0 && p.tempo < 1000.0);
  735. const auto song = lynx::importFlp (p);
  736. CHECK (! song.patterns.empty());
  737. {
  738. const auto full = lynx::importFlp (p, withFiles);
  739. bool hasFpc = false;
  740. for (const auto& c : p.channels)
  741. hasFpc = hasFpc || c.pluginName == "FPC";
  742. // GMS and Morphine (REA_rodada39): every state plays on the exact engine (GMS with its waves from the
  743. // installation) and sounds; two demo channels match golden samples of our round-39 models
  744. for (const auto& c : p.channels)
  745. {
  746. if (c.pluginName == "GMS")
  747. ++gms, gmsUsable += lynx::gmsStateUsable (c.pluginState) ? 1 : 0;
  748. if (c.pluginName == "Morphine")
  749. ++morphine, morphineUsable += lynx::morphineStateUsable (c.pluginState) ? 1 : 0;
  750. }
  751. // Kepler: every state in the demos plays on the exact engine (REA_rodada46) when the engine DLL is installed
  752. for (const auto& c : p.channels)
  753. if (c.pluginName == "Kepler")
  754. {
  755. ++kepler;
  756. keplerUsable += lynx::keplerStateUsable (c.pluginState) ? 1 : 0;
  757. }
  758. for (const auto& c : full.channels)
  759. if (c.instrument == lynx::InstrumentKind::kepler)
  760. {
  761. ++keplerKind;
  762. const auto y = lynx::kepler::renderReference (c.pluginState, c.samplePath, { { 0, 60, 1.0, 0.0, 0.0, 6000 }, { 2000, 67, 0.6, 0.0, 0.0, 8000 } },
  763. 44100.0, 11025);
  764. double e = 0.0;
  765. bool finite = ! y.empty();
  766. for (auto v : y)
  767. finite = finite && std::isfinite (v), e += (double) v * v;
  768. CHECK (finite);
  769. keplerSounding += e > 1e-6 ? 1 : 0;
  770. }
  771. const auto file = entry.path().filename().string();
  772. for (const auto& c : full.channels)
  773. {
  774. const auto isGms = c.instrument == lynx::InstrumentKind::gms, isMorphine = c.instrument == lynx::InstrumentKind::morphine;
  775. if (! isGms && ! isMorphine)
  776. continue;
  777. (isGms ? gmsKind : morphineKind)++;
  778. auto iv = [] (double vel) { return (std::pow (11.0, vel / 100.0) - 1.0) / 10.0; };
  779. const auto golden = (isGms && c.name == "GMS" && file.find ("Song For You") != std::string::npos)
  780. || (isMorphine && c.name == "Morphine" && file.find ("SHINE") != std::string::npos);
  781. std::vector<float> y;
  782. if (isGms)
  783. y = lynx::gms::renderReference (c.pluginState,
  784. { { 0, 60, (float) iv (100), 1.0, 0.0, 0.0, 30000 }, { 11025, 64, (float) iv (80), 1.0, 0.0, 0.0, 40000 },
  785. { 22050, 67, (float) iv (110), 1.0, 0.0, 0.0, 52000 }, { 60000, 48, (float) iv (127), 1.0, 0.0, 0.0, 70000 } },
  786. 44100.0, golden ? 88200 : 22050, c.samplePath);
  787. else
  788. y = lynx::morphine::renderReference (c.pluginState, { { 0, 60, 1.0, 1.0, 0.0, 0.0, 30000 }, { 11025, 64, 0.5, 1.0, 0.0, 0.0, 50000 }, { 22050, 67, 2.0, 1.0, 0.0, 0.0, 70000 } },
  789. 44100.0, golden ? 100000 : 22050, c.samplePath);
  790. double e = 0.0;
  791. bool finite = ! y.empty();
  792. for (auto v : y)
  793. finite = finite && std::isfinite (v), e += (double) v * v;
  794. CHECK (finite);
  795. (isGms ? gmsSounding : morphineSounding) += e > 1e-6 ? 1 : 0;
  796. if (golden && ! y.empty())
  797. {
  798. // our model, same events (GMS: tempo 140; Morphine: tempo 120), state as saved, 44.1 kHz
  799. const auto rms = std::sqrt (e / (double) y.size());
  800. CHECK (std::abs (rms - (isGms ? 0.213602668574 : 0.0673606448152)) < 1e-5);
  801. static const struct { int i; float l, r; } gmsAt[] = { { 2000, 0.0890912563f, 0.00406081323f }, { 15000, 0.395968914f, 0.213082865f }, { 30000, -0.33275044f, -0.530703545f }, { 50000, 0.277897179f, 0.482887864f }, { 65000, 0.266831428f, 0.366135627f }, { 80000, 0.00021339106f, 0.000807374308f } },
  802. morAt[] = { { 2000, 0.0620051622f, 0.0791224241f }, { 15000, 0.000745030935f, 0.0800722092f }, { 30000, 0.102371402f, 0.0262862686f }, { 50000, 0.000215340013f, 0.0249186736f }, { 65000, -0.0414967388f, -0.0449344926f }, { 90000, -0.00397050008f, -0.00165477558f } };
  803. for (const auto& g : isGms ? std::vector (std::begin (gmsAt), std::end (gmsAt)) : std::vector (std::begin (morAt), std::end (morAt)))
  804. CHECK (std::abs (y[2 * (std::size_t) g.i] - g.l) < 1e-5f && std::abs (y[2 * (std::size_t) g.i + 1] - g.r) < 1e-5f);
  805. ++demoGoldens;
  806. }
  807. }
  808. for (const auto& c : full.channels)
  809. {
  810. if (c.instrument == lynx::InstrumentKind::harmless && c.modelParams.size() >= (std::size_t) lynx::harmlessParamCount
  811. && c.modelParams[(std::size_t) lynx::harmlessComboIndex + 3] > 0.5f)
  812. {
  813. ++harmlessCompWanted;
  814. harmlessCompLoaded += c.modelParams.size() > (std::size_t) lynx::harmlessCompIndex + 1000 ? 1 : 0;
  815. }
  816. flKeysChannels += c.zones.size() == 30 && c.zones.front().path.find ("CHANGPIANO") != std::string::npos ? 1 : 0;
  817. if (c.sampler.slices.size() >= 4)
  818. {
  819. ++slicedChannels;
  820. CHECK (std::is_sorted (c.sampler.slices.begin(), c.sampler.slices.end()));
  821. CHECK (c.sampler.slices.back() < 1.0f);
  822. }
  823. if (! c.zones.empty() && c.name.find (" - ") == std::string::npos)
  824. {
  825. ++dwChannels;
  826. dwZones += (int) c.zones.size();
  827. }
  828. padChannels += c.name.find (" - ") != std::string::npos && c.instrument == lynx::InstrumentKind::sampler ? 1 : 0;
  829. }
  830. fpcKits += hasFpc;
  831. // Maximus / Soundgoodizer become the exact engine (REA_rodada40); Vocodex carries SG.dat (and its
  832. // carrier's Sytrus preset) read from the installation
  833. for (const auto& insert : p.mixer)
  834. for (const auto& slot : insert.slots)
  835. {
  836. maximusSlots += slot.plugin == "Maximus";
  837. sgzSlots += slot.plugin == "Soundgoodizer";
  838. vocodexSlots += slot.plugin == "Vocodex";
  839. }
  840. for (const auto& t : full.mixer)
  841. for (const auto& fx : t.effects)
  842. {
  843. if (fx.kind == lynx::EffectKind::maximus)
  844. {
  845. const auto blob = lynx::maximusfx::unpack (fx.state);
  846. CHECK (blob && lynx::maximusfx::presetOf (*blob) != nullptr);
  847. if (blob)
  848. (blob->build == lynx::hlfx::MaximusBuild::soundgoodizer ? sgzExact : maximusExact) += 1;
  849. }
  850. if (fx.kind == lynx::EffectKind::vocodex)
  851. vocodexWithData += ! lynx::vocodex::splitInstallData (fx.state).second.sgDat.empty();
  852. }
  853. for (const auto& pat : full.patterns)
  854. for (const auto& n : pat.notes)
  855. {
  856. CHECK (n.channel >= 0 && n.channel < (int) full.channels.size());
  857. padNotes += full.channels[(std::size_t) n.channel].name.find (" - ") != std::string::npos ? 1 : 0;
  858. }
  859. }
  860. const auto peqDefaults = lynx::makeEffectSlot (lynx::EffectKind::parametricEq).params;
  861. for (const auto& t : song.mixer)
  862. for (const auto& fx : t.effects)
  863. {
  864. if (fx.kind == lynx::EffectKind::parametricEq)
  865. {
  866. ++peqSlots;
  867. peqShaped += fx.params != peqDefaults;
  868. for (double hz : { 50.0, 1000.0, 10000.0 })
  869. CHECK (std::isfinite (lynx::peq::responseDb (fx.params, 48000.0, hz)));
  870. }
  871. if (fx.kind == lynx::EffectKind::reverb)
  872. {
  873. ++reverbs;
  874. reverbsDryless += fx.params[4] < 0.01f;
  875. reverbsLowCut += fx.params[5] > 0.0f;
  876. }
  877. }
  878. for (const auto& t : song.mixer)
  879. if (t.eq.active())
  880. {
  881. ++trackEqs;
  882. for (std::size_t b = 0; b < 3; ++b)
  883. CHECK (t.eq.hz[b] >= 10.0f && t.eq.hz[b] <= 16000.0f && std::abs (t.eq.gainDb[b]) <= 18.0f);
  884. }
  885. for (const auto& a : song.arrangements)
  886. for (const auto& m : a.markers)
  887. {
  888. ++markers;
  889. signatures += m.isSignature();
  890. CHECK (m.tick >= 0);
  891. }
  892. // Fruity Wrapper (channels and mixer slots): every blob in the demos is read
  893. auto countWrapper = [&] (const std::string& plugin, const std::vector<std::uint8_t>& state) {
  894. if (plugin != "Fruity Wrapper")
  895. return;
  896. ++wrapped;
  897. lynx::ForeignPlugin f;
  898. wrappedParsed += lynx::parseFlWrapper (state, f) && f.format != lynx::ForeignPlugin::Format::none && ! f.name.empty();
  899. };
  900. for (const auto& c : p.channels)
  901. countWrapper (c.pluginName, c.pluginState);
  902. for (const auto& insert : p.mixer)
  903. for (const auto& slot : insert.slots)
  904. countWrapper (slot.plugin, slot.state);
  905. // Harmless: every state in the demos becomes a synth, with finite values
  906. for (const auto& c : p.channels)
  907. if (c.pluginName == "Harmless")
  908. {
  909. ++harmless;
  910. lynx::SynthSettings hs;
  911. float g = 1.0f;
  912. if (lynx::synthFromHarmless (c.pluginState, 128.0, hs, g))
  913. {
  914. ++harmlessDecoded;
  915. CHECK (std::isfinite (g) && hs.cutoff >= 20.0f && hs.cutoff <= 20000.0f && std::isfinite (hs.decay) && std::isfinite (hs.release));
  916. }
  917. if (const auto hp = lynx::harmlessParams (c.pluginState))
  918. harmlessParsed += (int) hp->size() == lynx::harmlessParamCount ? 1 : 0;
  919. }
  920. for (const auto& c : song.channels)
  921. harmlessKind += c.instrument == lynx::InstrumentKind::harmless ? 1 : 0;
  922. // Harmor: every state in the demos plays on the exact engine (REA_rodada34) and sounds, with finite samples
  923. for (const auto& c : p.channels)
  924. if (c.pluginName == "Harmor")
  925. {
  926. ++harmor;
  927. harmorUsable += lynx::harmorStateUsable (c.pluginState) ? 1 : 0;
  928. }
  929. for (const auto& c : song.channels)
  930. if (c.instrument == lynx::InstrumentKind::harmor)
  931. {
  932. ++harmorKind;
  933. 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);
  934. double e = 0.0;
  935. bool finite = ! y.empty();
  936. for (auto v : y)
  937. finite = finite && std::isfinite (v), e += (double) v * v;
  938. CHECK (finite);
  939. harmorSounding += e > 1e-6 ? 1 : 0;
  940. }
  941. // Ogun: every state in the demos plays on the exact engine (REA_rodada37) and sounds, with finite samples
  942. for (const auto& c : p.channels)
  943. if (c.pluginName == "Ogun")
  944. {
  945. ++ogun;
  946. ogunUsable += lynx::ogunStateUsable (c.pluginState) ? 1 : 0;
  947. }
  948. for (const auto& c : song.channels)
  949. if (c.instrument == lynx::InstrumentKind::ogun)
  950. {
  951. ++ogunKind;
  952. const auto y = lynx::ogun::renderReference (c.pluginState, { { 0, 60, 0.8, 1.0, 0.0, 0.0, 0.0, 0.0, 0.5, 6000 },
  953. { 2000, 67, 0.6, 1.0, 0.0, 0.0, 0.0, 0.0, 0.5, 8000 } }, 44100.0, 11025);
  954. double e = 0.0;
  955. bool finite = ! y.empty();
  956. for (auto v : y)
  957. finite = finite && std::isfinite (v), e += (double) v * v;
  958. CHECK (finite);
  959. ogunSounding += e > 1e-6 ? 1 : 0;
  960. }
  961. // Sytrus: every state in the demos (zlib + 10 units) decodes, with finite values
  962. for (const auto& c : p.channels)
  963. if (c.pluginName == "Sytrus")
  964. {
  965. ++sytrus;
  966. lynx::SynthSettings ss;
  967. float g = 1.0f;
  968. // the Sytrus engine (REA_rodada31) reads every demo state; the first 24 play a short note (render settings)
  969. if (lynx::sytrus::stateUsable (c.pluginState))
  970. {
  971. ++sytrusEngine;
  972. if (sytrusRendered < 24)
  973. {
  974. ++sytrusRendered;
  975. lynx::sytrus::Engine e;
  976. e.prepare (44100.0, true, 512);
  977. e.setPatch (lynx::sytrus::parsePatch (c.pluginState));
  978. lynx::sytrus::NoteParams note;
  979. e.noteOn (note);
  980. std::vector<float> l (8192), r (8192);
  981. e.render (l.data(), r.data(), 8192, 0.551f, 0.0f);
  982. bool finite = true;
  983. double energy = 0.0;
  984. for (std::size_t k = 0; k < l.size(); ++k)
  985. finite = finite && std::isfinite (l[k]) && std::isfinite (r[k]), energy += (double) l[k] * l[k];
  986. CHECK (finite);
  987. sytrusSounding += energy > 1e-6;
  988. }
  989. }
  990. if (lynx::synthFromSytrus (c.pluginState, 128.0, ss, g))
  991. {
  992. ++sytrusDecoded;
  993. CHECK (std::isfinite (g) && ss.cutoff >= 20.0f && ss.cutoff <= 20000.0f && std::isfinite (ss.attack) && std::isfinite (ss.decay)
  994. && std::isfinite (ss.release) && ss.sustain >= 0.0f && ss.sustain <= 1.0f && std::isfinite (ss.filterEnv.amount));
  995. for (const auto& o : ss.osc)
  996. CHECK (o.level >= 0.0f && o.level <= 1.0f && o.octave >= -3 && o.octave <= 3);
  997. }
  998. }
  999. // round 12 generators
  1000. for (const auto& c : p.channels)
  1001. {
  1002. lynx::SynthSettings gs;
  1003. float g = 1.0f;
  1004. int decoded = -1;
  1005. if (c.pluginName == "Harmor")
  1006. {
  1007. decoded = lynx::synthFromHarmor (c.pluginState, gs, g);
  1008. if (decoded)
  1009. {
  1010. // REA_rodada25 §4: most resonant settings stay below Q ≈ 3, a few saturate
  1011. CHECK (gs.resonance >= 0.0f && gs.resonance <= 1.0f);
  1012. static int resonant = 0, strong = 0, total = 0;
  1013. resonant += gs.resonance > 0.0f;
  1014. strong += gs.resonance > 0.9f;
  1015. if (++total % 50 == 0)
  1016. std::printf (" Harmor resonance: %d with a peak, %d with Q > ~5 (of %d)\n", resonant, strong, total);
  1017. }
  1018. static int saw = 0, square = 0, other = 0, total = 0;
  1019. if (decoded && std::any_of (gs.osc.begin(), gs.osc.end(), [] (const lynx::SynthOscillator& o) { return o.wave == lynx::Waveform::spectral; }))
  1020. {
  1021. auto isSaw = true, isSquare = true;
  1022. for (int n = 1; n <= 16; ++n)
  1023. {
  1024. isSaw = isSaw && std::abs (gs.spectrum[(std::size_t) n - 1] - 1.0f / n) < 1e-3f;
  1025. isSquare = isSquare && std::abs (gs.spectrum[(std::size_t) n - 1] - (n % 2 == 1 ? 1.1535f / n : 0.0f)) < 2e-3f;
  1026. }
  1027. ++(isSaw ? saw : isSquare ? square : other);
  1028. if (++total % 20 == 0 || total == 100)
  1029. std::printf (" Harmor spectrum: %d saw, %d square, %d other (of %d)\n", saw, square, other, total);
  1030. }
  1031. }
  1032. else if (c.pluginName == "GMS")
  1033. decoded = lynx::synthFromGms (c.pluginState, 128.0, gs, g);
  1034. else if (c.pluginName == "Ogun" || c.pluginName == "Autogun")
  1035. {
  1036. decoded = lynx::synthFromOgun (c.pluginState, gs, g);
  1037. // REA_rodada24 §1.9: the "Trumpet" preset (richness 7, no seeds) has partials 0.9087, 0.8610,
  1038. // 0.8151… at the fixed seed-3 phases 0.919, 0.380, 0.130
  1039. if (decoded && gs.osc[0].wave == lynx::Waveform::spectral)
  1040. {
  1041. CHECK (std::all_of (gs.spectrum.begin(), gs.spectrum.end(), [] (float a) { return std::isfinite (a) && a >= 0.0f; }));
  1042. static constexpr float trumpet[3] { 0.9087f, 0.8610f, 0.8151f }, phases[3] { 0.919f, 0.380f, 0.130f };
  1043. auto match = true;
  1044. for (std::size_t k = 0; k < 3; ++k)
  1045. match = match && std::abs (gs.spectrum[k] * 2.0f / 3.14159265f - trumpet[k]) < 1e-3f && std::abs (gs.spectrumPhase[k] - phases[k]) < 1e-3f;
  1046. ogunTrumpet += match ? 1 : 0;
  1047. }
  1048. }
  1049. else if (c.pluginName == "Sakura")
  1050. decoded = lynx::synthFromSakura (c.pluginState, gs);
  1051. else if (c.pluginName == "Kepler")
  1052. decoded = lynx::synthFromKepler (c.pluginState, gs, g);
  1053. else if (c.pluginName == "Wave Traveller")
  1054. decoded = lynx::waveTravellerSample (c.pluginState).has_value() ? 2 : 0;
  1055. else if (c.pluginName == "PoiZone")
  1056. decoded = lynx::synthFromPoiZone (c.pluginState, gs, g);
  1057. else if (c.pluginName == "BassDrum")
  1058. decoded = lynx::synthFromBassDrum (c.pluginState, gs, g);
  1059. else if (c.pluginName == "Toxic Biohazard")
  1060. decoded = lynx::synthFromToxic (c.pluginState, gs, g);
  1061. else if (c.pluginName == "Morphine")
  1062. decoded = lynx::synthFromMorphine (c.pluginState, gs, g);
  1063. else if (c.pluginName == "BooBass")
  1064. decoded = lynx::synthFromBooBass (c.pluginState, gs);
  1065. else if (c.pluginName == "Drumpad" || c.pluginName == "DrumPad")
  1066. decoded = lynx::drumpadPatchName (c.pluginState).has_value() ? 2 : 0;
  1067. else if (c.pluginName == "Fruity Envelope Controller" && c.pluginState.size() >= 4 && c.pluginState[2] >= 6) // v >= 6
  1068. decoded = lynx::parseEnvelopeController (c.pluginState).has_value() ? 2 : 0;
  1069. else if (c.pluginName == "FLEX")
  1070. decoded = lynx::flexPresetName (c.pluginState).has_value() ? 2 : 0;
  1071. else if (c.pluginName == "Fruity DrumSynth Live")
  1072. decoded = lynx::drumSynthLiveParams (c.pluginState).has_value() ? 2 : 0;
  1073. if (decoded < 0)
  1074. continue;
  1075. auto& counter = generators[c.pluginName];
  1076. ++counter.first;
  1077. counter.second += decoded != 0;
  1078. if (decoded == 1 && c.pluginName != "Fruity DrumSynth Live")
  1079. {
  1080. CHECK (std::isfinite (g) && g >= 0.0f && gs.cutoff >= 20.0f && gs.cutoff <= 20000.0f && gs.sustain >= 0.0f && gs.sustain <= 1.0f);
  1081. 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));
  1082. for (const auto& o : gs.osc)
  1083. CHECK (o.level >= 0.0f && o.level <= 4.0f && std::isfinite (o.detune) && std::isfinite (o.pan));
  1084. }
  1085. }
  1086. // 3x Osc: every state in the demos decodes, with levels summing to at most 1
  1087. for (const auto& c : p.channels)
  1088. if (c.pluginName == "3x Osc")
  1089. {
  1090. ++threeOsc;
  1091. lynx::SynthSettings s;
  1092. if (lynx::synthFrom3xOsc (c.pluginState, s))
  1093. {
  1094. ++threeOscDecoded;
  1095. // with AM, osc 3 is the modulation depth and is left out of the sum
  1096. const auto sum = s.osc[0].level + s.osc[1].level + (s.am ? 0.0f : s.osc[2].level);
  1097. CHECK (sum <= 1.001f && s.osc[2].level <= 1.0f);
  1098. for (const auto& o : s.osc)
  1099. CHECK (o.octave >= -2 && o.octave <= 2 && std::abs (o.semitones) <= 11 && std::abs (o.pan) <= 1.0f);
  1100. }
  1101. }
  1102. for (auto& pat : p.patterns)
  1103. if (! pat.notes.empty())
  1104. {
  1105. ++withNotes;
  1106. break;
  1107. }
  1108. for (auto& a : p.arrangements)
  1109. for (auto& item : a.items)
  1110. CHECK (item.track >= 0 && item.track < 500);
  1111. for (auto& clip : song.playlist)
  1112. {
  1113. CHECK (clip.pattern >= 0 && clip.pattern < (int) song.patterns.size());
  1114. CHECK (clip.length > 0 && clip.offset >= 0);
  1115. if (clip.kind == lynx::ClipKind::automation)
  1116. CHECK (clip.automation >= 0 && clip.automation < (int) song.automations.size());
  1117. }
  1118. for (auto& a : song.automations)
  1119. {
  1120. ++automations;
  1121. automationsWithTarget += a.target.kind != lynx::AutomationTargetKind::none;
  1122. CHECK (a.isLive() || ! a.points.empty());
  1123. for (std::size_t i = 1; i < a.points.size(); ++i)
  1124. CHECK (a.points[i].tick >= a.points[i - 1].tick);
  1125. }
  1126. // imported routing has no cycles and valid destinations
  1127. CHECK (song.mixerOrder().size() + 1 == song.mixer.size());
  1128. for (auto& t : song.mixer)
  1129. for (auto& s : t.sends)
  1130. {
  1131. ++sends;
  1132. CHECK (s.target > 0 && s.target < (int) song.mixer.size());
  1133. }
  1134. if (! song.playlist.empty())
  1135. ++withPlaylist;
  1136. }
  1137. catch (const flp::Error& e)
  1138. {
  1139. ++failures;
  1140. std::printf (" FAILED %s: %s\n", entry.path().string().c_str(), e.what());
  1141. }
  1142. }
  1143. CHECK (threeOscDecoded == threeOsc);
  1144. std::printf (" Harmless: %d channels, %d decoded\n", harmless, harmlessDecoded);
  1145. std::printf (" Sytrus: %d channels, %d decoded, %d by the engine (%d of %d rendered sound)\n", sytrus, sytrusDecoded, sytrusEngine,
  1146. sytrusSounding, sytrusRendered);
  1147. CHECK (sytrusEngine == sytrus);
  1148. CHECK (sytrusSounding >= sytrusRendered * 3 / 4);
  1149. for (const auto& [name, counter] : generators)
  1150. {
  1151. std::printf (" %s: %d channels, %d decoded\n", name.c_str(), counter.first, counter.second);
  1152. CHECK (counter.second == counter.first);
  1153. }
  1154. std::printf (" Ogun spectra matching the Trumpet reference: %d\n", ogunTrumpet);
  1155. CHECK (ogunTrumpet >= 1);
  1156. // demo Gross Beat: the volume slot becomes the gate (those using an envelope slot get steps < 1)
  1157. {
  1158. int vocodexes = 0, vocodexSides = 0;
  1159. int lovePhilterLinks[4] {}; // live links: cutoff, resonance; inside containers: cutoff, resonance
  1160. int embeddedZones = 0, lovePhilters = 0, lovePhiltersRead = 0, lovePhiltersConverted = 0, gates = 0, shaped = 0, effectors = 0, patchers = 0, serial = 0, parallel = 0, generatorPatchers = 0;
  1161. for (const auto& entry : std::filesystem::recursive_directory_iterator (std::filesystem::path (realFlpDir) / "Demo projects"))
  1162. if (entry.path().extension() == ".flp")
  1163. {
  1164. std::ifstream in (entry.path(), std::ios::binary);
  1165. const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1166. try
  1167. {
  1168. const auto project = flp::parseProject (file);
  1169. for (const auto& insert : project.mixer)
  1170. for (const auto& slot : insert.slots)
  1171. if (slot.plugin == "Gross Beat")
  1172. {
  1173. const auto fx = lynx::effectFromFl (slot.plugin, slot.state);
  1174. CHECK (fx && fx->kind == lynx::EffectKind::volumeGate);
  1175. ++gates;
  1176. if (fx && std::any_of (fx->params.begin(), fx->params.begin() + 32, [] (float v) { return v < 0.99f; }))
  1177. ++shaped;
  1178. }
  1179. else if (slot.plugin == "Fruity Love Philter")
  1180. {
  1181. ++lovePhilters;
  1182. lovePhiltersRead += lynx::parseLovePhilter (slot.state).has_value();
  1183. if (const auto conv = lynx::lovePhilterEffects (slot.state))
  1184. {
  1185. ++lovePhiltersConverted;
  1186. CHECK (! conv->slots.empty());
  1187. for (const auto& fx : conv->slots)
  1188. for (auto v : fx.params)
  1189. CHECK (std::isfinite (v) && v >= 0.0f && v <= 1.0f);
  1190. for (const auto& fx : conv->slots)
  1191. for (const auto& link : fx.links)
  1192. {
  1193. const auto& chain = fx.branches[(std::size_t) link.branch].chain;
  1194. CHECK (link.source < (int) chain.size() && chain[(std::size_t) link.target].kind == lynx::EffectKind::parametricEq);
  1195. lovePhilterLinks[2 + (link.param == lynx::peq::param (0, 3) ? 1 : 0)]++;
  1196. }
  1197. for (const auto& link : conv->links)
  1198. {
  1199. lovePhilterLinks[link.param == lynx::peq::param (0, 3) ? 1 : 0]++;
  1200. CHECK (link.curve.size() == 33);
  1201. for (auto v : link.curve)
  1202. CHECK (std::isfinite (v) && v >= 0.0f && v <= 1.0f);
  1203. }
  1204. }
  1205. }
  1206. else if (slot.plugin == "Vocodex")
  1207. {
  1208. const auto v = lynx::vocodexEffect (slot.state);
  1209. CHECK (v.has_value());
  1210. vocodexes += v.has_value();
  1211. vocodexSides += v && (v->modIn > 0 || v->carIn > 0);
  1212. }
  1213. else if (slot.plugin == "Effector")
  1214. effectors += lynx::effectFromFl (slot.plugin, slot.state).has_value();
  1215. else if (slot.plugin == "Patcher")
  1216. {
  1217. const auto graph = lynx::parsePatcher (slot.state);
  1218. CHECK (graph.has_value());
  1219. ++patchers;
  1220. if (graph && ! graph->serialChain.empty())
  1221. ++serial;
  1222. if (graph && graph->serialChain.empty() && graph->audio)
  1223. ++parallel;
  1224. }
  1225. for (const auto& c : project.channels)
  1226. if (c.pluginName == "DirectWave")
  1227. if (const auto program = lynx::directWaveProgram (c.pluginState))
  1228. for (const auto& wav : program->embeddedWav)
  1229. if (! wav.empty())
  1230. {
  1231. ++embeddedZones;
  1232. CHECK (wav.size() > 44 && std::memcmp (wav.data(), "RIFF", 4) == 0);
  1233. }
  1234. for (const auto& c : project.channels)
  1235. if (c.pluginName == "Patcher")
  1236. {
  1237. const auto graph = lynx::parsePatcher (c.pluginState);
  1238. CHECK (graph.has_value());
  1239. generatorPatchers += graph && graph->mainGenerator >= 0;
  1240. }
  1241. }
  1242. catch (const flp::Error&) {}
  1243. }
  1244. std::printf (" Gross Beat: %d slots, %d with gate; Effector: %d converted; Love Philter: %d, %d read\n", gates, shaped, effectors,
  1245. lovePhilters, lovePhiltersRead);
  1246. CHECK (lovePhiltersRead == lovePhilters && lovePhiltersConverted == lovePhilters);
  1247. std::printf (" Vocodex: %d converted, %d with side inputs\n", vocodexes, vocodexSides);
  1248. CHECK (vocodexes >= 9);
  1249. std::printf (" Love Philter live links: %d cutoff, %d resonance; in multi-unit containers: %d cutoff, %d resonance\n",
  1250. lovePhilterLinks[0], lovePhilterLinks[1], lovePhilterLinks[2], lovePhilterLinks[3]);
  1251. CHECK (lovePhilterLinks[2] + lovePhilterLinks[3] > 0);
  1252. std::printf (" DirectWave: %d zones with embedded audio\n", embeddedZones);
  1253. CHECK (embeddedZones == 12);
  1254. std::printf (" Patcher: %d in the mixer (%d serial, %d reduced to serial/parallel), %d as instrument with generator\n", patchers, serial,
  1255. parallel, generatorPatchers);
  1256. CHECK (gates == 0 || shaped > 0);
  1257. }
  1258. // Envelope Controller "Basic Sidechain" (Future House): drops on the note and returns to ~1 within ~1/3 s
  1259. {
  1260. const auto path = std::filesystem::path (realFlpDir) / "Demo projects" / "Demo songs" / "Asher Postman - Future House.flp";
  1261. if (std::filesystem::exists (path))
  1262. {
  1263. std::ifstream in (path, std::ios::binary);
  1264. const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1265. const auto song = lynx::importFlp (flp::parseProject (file));
  1266. const lynx::ChannelDef* controller = nullptr;
  1267. for (const auto& c : song.channels)
  1268. if (c.instrument == lynx::InstrumentKind::controller)
  1269. controller = &c;
  1270. CHECK (controller != nullptr);
  1271. if (controller != nullptr)
  1272. {
  1273. auto inst = lynx::makeInstrument (lynx::InstrumentKind::controller);
  1274. inst->prepare (48000.0);
  1275. inst->configure (*controller, song.bpm);
  1276. std::vector<float> l (480), r (480);
  1277. inst->render (l.data(), r.data(), 480, 1.0f, 1.0f);
  1278. inst->noteOn (60, 1.0f);
  1279. inst->render (l.data(), r.data(), 480, 1.0f, 1.0f); // 10 ms
  1280. const auto ducked = inst->controlOutput (0);
  1281. for (int i = 0; i < 100; ++i) // +1 s
  1282. inst->render (l.data(), r.data(), 480, 1.0f, 1.0f);
  1283. const auto recovered = inst->controlOutput (0);
  1284. std::printf (" Envelope Controller (Basic Sidechain): %.2f on the note, %.2f after 1 s\n", ducked, recovered);
  1285. CHECK (ducked < 0.3f && recovered > 0.9f);
  1286. }
  1287. }
  1288. }
  1289. // mutation fuzz: real states with flipped and truncated bytes must not crash the readers
  1290. {
  1291. std::map<std::string, std::vector<std::uint8_t>> samples; // one real blob per plugin
  1292. for (const auto& entry : std::filesystem::recursive_directory_iterator (std::filesystem::path (realFlpDir) / "Demo projects"))
  1293. {
  1294. if (entry.path().extension() != ".flp")
  1295. continue;
  1296. std::ifstream in (entry.path(), std::ios::binary);
  1297. const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1298. try
  1299. {
  1300. const auto project = flp::parseProject (file);
  1301. for (const auto& c : project.channels)
  1302. if (! c.pluginState.empty())
  1303. samples.emplace (c.pluginName, c.pluginState);
  1304. for (const auto& insert : project.mixer)
  1305. for (const auto& slot : insert.slots)
  1306. if (! slot.state.empty())
  1307. samples.emplace (slot.plugin, slot.state);
  1308. }
  1309. catch (const flp::Error&) {}
  1310. }
  1311. std::uint32_t seed = 12345;
  1312. auto rnd = [&seed] { seed = seed * 1664525u + 1013904223u; return seed >> 8; };
  1313. int mutations = 0;
  1314. for (const auto& [name, original] : samples)
  1315. for (int round = 0; round < 40; ++round)
  1316. {
  1317. auto blob = original;
  1318. if (round % 4 == 3 && ! blob.empty())
  1319. blob.resize (rnd() % blob.size()); // truncated
  1320. else
  1321. for (int k = 0; k < 1 + (int) (rnd() % 8) && ! blob.empty(); ++k)
  1322. blob[rnd() % blob.size()] = (std::uint8_t) rnd();
  1323. ++mutations;
  1324. lynx::SynthSettings synth;
  1325. float gain = 1.0f;
  1326. lynx::synthFromSytrus (blob, 120.0, synth, gain);
  1327. lynx::synthFromHarmor (blob, synth, gain);
  1328. lynx::synthFromGms (blob, 120.0, synth, gain);
  1329. lynx::synthFromOgun (blob, synth, gain);
  1330. lynx::synthFromMorphine (blob, synth, gain);
  1331. lynx::synthFromKepler (blob, synth, gain);
  1332. lynx::synthFromPoiZone (blob, synth, gain);
  1333. lynx::synthFromToxic (blob, synth, gain);
  1334. lynx::synthFromBassDrum (blob, synth, gain);
  1335. lynx::synthFromHarmless (blob, 120.0, synth, gain);
  1336. lynx::harmlessParams (blob);
  1337. if (lynx::harmorStateUsable (blob))
  1338. lynx::harmorFallbacks (blob);
  1339. lynx::parseEnvelopeController (blob);
  1340. lynx::parseKeyboardController (blob);
  1341. lynx::parseLovePhilter (blob);
  1342. lynx::parsePatcher (blob);
  1343. lynx::effectFromFl (name, blob);
  1344. lynx::fpcPads (blob);
  1345. lynx::directWaveProgram (blob);
  1346. CHECK (std::isfinite (gain) && std::isfinite (synth.cutoff));
  1347. }
  1348. std::printf (" mutation fuzz: %d blobs from %d plugins\n", mutations, (int) samples.size());
  1349. }
  1350. // WavPack (.wv) samples from FL packs: all decode, with finite, non-silent audio
  1351. {
  1352. int files = 0, decoded = 0, audible = 0;
  1353. double seconds = 0.0;
  1354. for (const auto& entry : std::filesystem::recursive_directory_iterator (std::filesystem::path (realFlpDir) / "Patches" / "Packs"))
  1355. if (entry.path().extension() == ".wv")
  1356. {
  1357. std::ifstream in (entry.path(), std::ios::binary);
  1358. const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1359. ++files;
  1360. lynx::DecodedAudio audio;
  1361. if (! lynx::decodeWavPack (file.data(), file.size(), audio))
  1362. continue;
  1363. ++decoded;
  1364. float peak = 0.0f;
  1365. bool finite = true;
  1366. for (const auto& ch : audio.channels)
  1367. for (auto v : ch)
  1368. {
  1369. finite = finite && std::isfinite (v);
  1370. peak = std::max (peak, std::abs (v));
  1371. }
  1372. CHECK (finite && peak <= 4.0f);
  1373. audible += peak > 1e-4f;
  1374. seconds += (double) audio.channels[0].size() / audio.sampleRate;
  1375. }
  1376. std::printf (" WavPack: %d .wv files, %d decoded, %d audible, %.0f s of audio\n", files, decoded, audible, seconds);
  1377. CHECK (decoded == files);
  1378. }
  1379. // native GMS presets (.gmsynth = the contents of 0xD5 without the "SSLF")
  1380. int gmsPresets = 0, gmsDecoded = 0;
  1381. const auto gmsFolder = std::filesystem::path (realFlpDir) / "Patches" / "Plugin presets" / "Generators" / "GMS";
  1382. if (std::filesystem::exists (gmsFolder))
  1383. for (const auto& entry : std::filesystem::recursive_directory_iterator (gmsFolder))
  1384. if (entry.path().extension() == ".gmsynth")
  1385. {
  1386. std::ifstream in (entry.path(), std::ios::binary);
  1387. std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1388. std::vector<std::uint8_t> blob { 'S', 'S', 'L', 'F' };
  1389. const auto n = (std::uint32_t) file.size();
  1390. blob.insert (blob.end(), reinterpret_cast<const std::uint8_t*> (&n), reinterpret_cast<const std::uint8_t*> (&n) + 4);
  1391. blob.insert (blob.end(), file.begin(), file.end());
  1392. lynx::SynthSettings gs;
  1393. float g = 1.0f;
  1394. ++gmsPresets;
  1395. if (lynx::synthFromGms (blob, 120.0, gs, g))
  1396. {
  1397. ++gmsDecoded;
  1398. CHECK (std::isfinite (g) && gs.cutoff >= 20.0f && std::isfinite (gs.pitchEnv.amount) && std::isfinite (gs.lfo[lynx::lfoPitch].period));
  1399. }
  1400. }
  1401. std::printf (" GMS presets: %d, %d decoded\n", gmsPresets, gmsDecoded);
  1402. // the synth's "FL presets" button: Sytrus/Harmor .fst and .gmsynth become synth settings
  1403. int presetFiles = 0, presetsRead = 0;
  1404. for (const auto* name : { "Sytrus", "Harmor", "GMS", "Harmless", "Ogun", "Sakura", "Fruit Kick", "Fruity DX10", "MiniSynth", "Kepler",
  1405. "PoiZone", "Toxic Biohazard", "BassDrum" })
  1406. {
  1407. const auto folder = std::filesystem::path (realFlpDir) / "Patches" / "Plugin presets" / "Generators" / name;
  1408. if (! std::filesystem::exists (folder))
  1409. continue;
  1410. for (const auto& entry : std::filesystem::recursive_directory_iterator (folder))
  1411. if (entry.path().extension() == ".fst" || entry.path().extension() == ".gmsynth")
  1412. {
  1413. std::ifstream in (entry.path(), std::ios::binary);
  1414. const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1415. ++presetFiles;
  1416. presetsRead += lynx::synthFromFlPreset (file).has_value();
  1417. }
  1418. }
  1419. std::printf (" FL synth presets: %d files, %d read\n", presetFiles, presetsRead);
  1420. CHECK (presetsRead >= presetFiles * 95 / 100);
  1421. CHECK (gmsDecoded == gmsPresets);
  1422. CHECK (sytrusDecoded == sytrus);
  1423. CHECK (harmlessDecoded == harmless && harmless > 100);
  1424. std::printf (" Harmless: %d states parsed for the engine, %d channels imported as Harmless\n", harmlessParsed, harmlessKind);
  1425. CHECK (harmlessParsed == harmless && harmlessKind >= harmless);
  1426. std::printf (" Harmor: %d channels, %d states usable by the engine, %d imported as Harmor (%d sounding)\n", harmor, harmorUsable, harmorKind, harmorSounding);
  1427. CHECK (harmorUsable == harmor && harmor > 90 && harmorKind >= harmor && harmorSounding >= harmorKind * 9 / 10);
  1428. std::printf (" GMS: %d channels, %d usable, %d imported as GMS (%d sounding); Morphine: %d channels, %d usable, %d imported (%d sounding); %d demo goldens\n",
  1429. gms, gmsUsable, gmsKind, gmsSounding, morphine, morphineUsable, morphineKind, morphineSounding, demoGoldens);
  1430. CHECK (gmsUsable == gms && gms >= 9 && gmsKind == gms && gmsSounding == gmsKind);
  1431. CHECK (morphineUsable == morphine && morphine >= 7 && morphineKind == morphine && morphineSounding == morphineKind && demoGoldens == 2);
  1432. std::printf (" Ogun: %d channels, %d states usable by the engine, %d imported as Ogun (%d sounding)\n", ogun, ogunUsable, ogunKind, ogunSounding);
  1433. CHECK (ogunUsable == ogun && ogun >= 20 && ogunKind >= ogun && ogunSounding >= ogunKind * 9 / 10);
  1434. std::printf (" Kepler: %d channels, %d states usable by the engine, %d imported as Kepler (%d sounding)\n", kepler, keplerUsable, keplerKind, keplerSounding);
  1435. CHECK (keplerUsable == kepler && kepler >= 4 && keplerSounding == keplerKind && (keplerKind == 0 || keplerKind == kepler));
  1436. std::printf (" Harmless rack compressor: %d of %d presets read from the installation\n", harmlessCompLoaded, harmlessCompWanted);
  1437. CHECK (harmlessCompLoaded == harmlessCompWanted && harmlessCompWanted > 100);
  1438. std::printf (" Maximus: %d of %d slots on the exact engine; Soundgoodizer: %d of %d; Vocodex with SG.dat: %d of %d\n", maximusExact,
  1439. maximusSlots, sgzExact, sgzSlots, vocodexWithData, vocodexSlots);
  1440. // REA_rodada40 §6: in Demo projects the 4 states left on the approximation use the Frequency Splitter linear-phase
  1441. // option; the other Data folders add states with options not decoded
  1442. CHECK (maximusSlots - maximusExact <= 16 && maximusExact >= 97 && sgzExact == sgzSlots && sgzSlots > 90);
  1443. CHECK (vocodexWithData == vocodexSlots && vocodexSlots >= 10);
  1444. // 3x Osc channel presets shipped with FL (.fst): all become synth settings
  1445. int presets = 0, presetsDecoded = 0;
  1446. const auto presetDir = std::filesystem::path (realFlpDir) / "Patches" / "Channel presets" / "3x Osc";
  1447. if (std::filesystem::is_directory (presetDir))
  1448. for (auto& entry : std::filesystem::directory_iterator (presetDir))
  1449. if (entry.path().extension() == ".fst")
  1450. {
  1451. ++presets;
  1452. std::ifstream in (entry.path(), std::ios::binary);
  1453. std::vector<std::uint8_t> bytes ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  1454. if (auto synth = lynx::synthFromFlPreset (bytes))
  1455. {
  1456. ++presetsDecoded;
  1457. CHECK (synth->osc[0].level + synth->osc[1].level + (synth->am ? 0.0f : synth->osc[2].level) <= 1.001f);
  1458. }
  1459. }
  1460. std::printf (" %d 3x Osc presets, %d read\n", presets, presetsDecoded);
  1461. CHECK (presetsDecoded == presets);
  1462. // FL effect presets that become built-in effects
  1463. int fxPresets = 0, fxDecoded = 0;
  1464. for (auto kind : { lynx::EffectKind::parametricEq, lynx::EffectKind::limiter, lynx::EffectKind::reverb, lynx::EffectKind::delay,
  1465. lynx::EffectKind::utility })
  1466. for (const auto& plugin : lynx::flPluginsForEffect (kind))
  1467. {
  1468. const auto dir = std::filesystem::path (realFlpDir) / "Patches" / "Plugin presets" / "Effects" / plugin;
  1469. if (! std::filesystem::is_directory (dir))
  1470. continue;
  1471. for (auto& entry : std::filesystem::recursive_directory_iterator (dir))
  1472. if (entry.path().extension() == ".fst")
  1473. {
  1474. ++fxPresets;
  1475. std::ifstream in (entry.path(), std::ios::binary);
  1476. std::vector<std::uint8_t> bytes ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  1477. fxDecoded += lynx::effectFromFlPreset (bytes).has_value();
  1478. }
  1479. }
  1480. std::printf (" %d FL effect presets, %d read\n", fxPresets, fxDecoded);
  1481. CHECK (fxDecoded == fxPresets);
  1482. CHECK (wrappedParsed == wrapped);
  1483. std::printf (" %d plugins in Fruity Wrapper, %d read\n", wrapped, wrappedParsed);
  1484. std::printf (" %d markers, %d time signature changes, %d tracks with EQ\n", markers, signatures, trackEqs);
  1485. std::printf (" %d parametric EQs (%d with FL settings), %d reverbs (%d without dry)\n", peqSlots, peqShaped, reverbs, reverbsDryless);
  1486. std::printf (" DirectWave: %d channels, %d zones; FPC: %d projects, %d pad channels, %d pad notes\n", dwChannels, dwZones, fpcKits,
  1487. padChannels, padNotes);
  1488. CHECK (dwZones > 1000 && padChannels > 250 && padNotes > 500);
  1489. std::printf (" sliced channels (Slicer/Slicex): %d; embedded WAVs saved: %d\n", slicedChannels, embeddedSaved);
  1490. CHECK (slicedChannels >= 25 && embeddedSaved >= 10); // without decoding Ogg here, some loops have no duration
  1491. std::printf (" FL Keys (Grand Piano, 30 zones): %d channels\n", flKeysChannels);
  1492. CHECK (flKeysChannels >= 8);
  1493. CHECK (peqSlots > 1000 && peqShaped > 900 && reverbsDryless > 20 && reverbsLowCut > 250);
  1494. CHECK (markers > 300 && signatures > 60);
  1495. std::printf (" %d 3x Osc channels, %d decoded\n", threeOsc, threeOscDecoded);
  1496. std::printf (" %d .flp files read, %d with notes, %d with playlist, %d automations (%d with target), %d sends\n",
  1497. files, withNotes, withPlaylist, automations, automationsWithTarget, sends);
  1498. CHECK (files > 0);
  1499. CHECK (automations > 0 && sends > 0);
  1500. }
  1501. // ---------------------------------------------------------------------------
  1502. // Sequencer
  1503. TEST (pattern_toggle_step_and_length)
  1504. {
  1505. lynx::Pattern p;
  1506. CHECK (! p.hasStep (0, 4));
  1507. p.toggleStep (0, 4);
  1508. CHECK (p.hasStep (0, 4));
  1509. CHECK (p.notes.size() == 1 && p.notes[0].start == 4 * lynx::ticksPerStep);
  1510. CHECK (p.effectiveLength (4) == 4 * lynx::ppq); // one bar
  1511. p.toggleStep (1, 20); // second bar
  1512. CHECK (p.effectiveLength (4) == 8 * lynx::ppq);
  1513. p.toggleStep (0, 4);
  1514. CHECK (! p.hasStep (0, 4) && p.notes.size() == 1);
  1515. }
  1516. TEST (scheduler_places_events_at_exact_samples)
  1517. {
  1518. lynx::Pattern p;
  1519. p.toggleStep (0, 0);
  1520. p.toggleStep (0, 4); // tick 960 = 1 beat
  1521. const double sr = 48000.0, bpm = 120.0; // 1 beat = 0.5 s = 24000 samples
  1522. const auto tps = lynx::ticksPerSample (bpm, sr);
  1523. lynx::EventBuffer ev;
  1524. lynx::schedulePatternLoop (p, p.effectiveLength (4), 23900.0 * tps, 512, tps, ev);
  1525. // the beat-2 note starts at sample 24000 -> offset 100 in this block
  1526. int ons = 0;
  1527. for (auto& e : ev)
  1528. if (e.type == lynx::NoteEvent::Type::on)
  1529. {
  1530. ++ons;
  1531. CHECK (e.sampleOffset == 100);
  1532. }
  1533. CHECK (ons == 1);
  1534. }
  1535. TEST (scheduler_wraps_the_loop)
  1536. {
  1537. lynx::Pattern p;
  1538. p.toggleStep (2, 0);
  1539. const auto len = p.effectiveLength (4); // 3840 ticks
  1540. const double sr = 48000.0;
  1541. const auto tps = lynx::ticksPerSample (120.0, sr);
  1542. lynx::EventBuffer ev;
  1543. // block that crosses the loop end: starts 10 samples before
  1544. const auto start = (double) len - 10.0 * tps;
  1545. lynx::schedulePatternLoop (p, len, start, 64, tps, ev);
  1546. bool found = false;
  1547. for (auto& e : ev)
  1548. if (e.type == lynx::NoteEvent::Type::on && e.channel == 2)
  1549. {
  1550. found = true;
  1551. CHECK (e.sampleOffset == 10);
  1552. }
  1553. CHECK (found);
  1554. }
  1555. TEST (scheduler_off_before_on_at_same_sample)
  1556. {
  1557. lynx::Pattern p;
  1558. lynx::Note a;
  1559. a.start = 0; a.length = 240; a.channel = 0;
  1560. lynx::Note b = a;
  1561. b.start = 240;
  1562. p.notes = { a, b };
  1563. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  1564. lynx::EventBuffer ev;
  1565. lynx::schedulePatternLoop (p, p.effectiveLength (4), 200.0, 4000, tps, ev);
  1566. CHECK (ev.size() >= 2);
  1567. CHECK (ev[0].type == lynx::NoteEvent::Type::off);
  1568. CHECK (ev[1].type == lynx::NoteEvent::Type::on);
  1569. CHECK (ev[0].sampleOffset == ev[1].sampleOffset);
  1570. }
  1571. TEST (snapshot_exchange_hands_over_and_recycles)
  1572. {
  1573. struct Counted
  1574. {
  1575. int value;
  1576. int* alive;
  1577. Counted (int v, int* a) : value (v), alive (a) { ++*alive; }
  1578. ~Counted() { --*alive; }
  1579. };
  1580. int alive = 0;
  1581. {
  1582. lynx::SnapshotExchange<Counted> x;
  1583. CHECK (x.acquire() == nullptr);
  1584. x.publish (std::make_unique<Counted> (1, &alive));
  1585. CHECK (x.acquire()->value == 1);
  1586. x.publish (std::make_unique<Counted> (2, &alive));
  1587. x.publish (std::make_unique<Counted> (3, &alive)); // 2 was never read: freed immediately
  1588. CHECK (alive == 2);
  1589. CHECK (x.acquire()->value == 3);
  1590. CHECK (alive == 2); // 1 was returned, but only the UI frees it
  1591. x.collectGarbage();
  1592. CHECK (alive == 1);
  1593. // without collection, the return slots fill up and the audio side holds on to the current one
  1594. for (int i = 0; i < 20; ++i)
  1595. {
  1596. x.publish (std::make_unique<Counted> (10 + i, &alive));
  1597. CHECK (x.acquire() != nullptr);
  1598. }
  1599. }
  1600. CHECK (alive == 0);
  1601. }
  1602. TEST (rack_renderer_makes_sound_and_reuses_instruments)
  1603. {
  1604. auto song = lynx::Song::makeDefault();
  1605. song.bpm = 120.0;
  1606. const double sr = 48000.0;
  1607. auto state = lynx::RackState::build (song, nullptr, sr);
  1608. lynx::RackRenderer r;
  1609. r.prepare (sr);
  1610. std::vector<float> l (512), rr (512);
  1611. double tick = 0.0;
  1612. float peak = 0.0f;
  1613. int kicks = 0;
  1614. for (int block = 0; block < 93; ++block) // 47616 samples: just before 1 s
  1615. {
  1616. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  1617. for (auto& e : r.lastEvents())
  1618. if (e.type == lynx::NoteEvent::Type::on && e.channel == 0)
  1619. ++kicks;
  1620. for (int i = 0; i < 512; ++i)
  1621. {
  1622. CHECK (std::isfinite (l[(std::size_t) i]));
  1623. peak = std::max (peak, std::abs (l[(std::size_t) i]));
  1624. }
  1625. tick += 512 * lynx::ticksPerSample (song.bpm, sr);
  1626. }
  1627. CHECK (peak > 0.1f && peak < 4.0f);
  1628. CHECK (kicks == 2); // 120 BPM: beats at 0 and 0.5 s
  1629. // editing the song keeps the instruments of channels whose type didn't change
  1630. song.channels[4].instrument = lynx::InstrumentKind::kick;
  1631. auto next = lynx::RackState::build (song, state.get(), sr);
  1632. CHECK (next->instruments[0] == state->instruments[0]);
  1633. CHECK (next->instruments[4] != state->instruments[4]);
  1634. // stopping silences the synth and triggers no new notes
  1635. r.process (next.get(), false, tick, 512, l.data(), rr.data());
  1636. CHECK (r.lastEvents().size() == 0);
  1637. }
  1638. TEST (flp_import_maps_channels_and_rescales)
  1639. {
  1640. flp::Project p;
  1641. p.header.ppq = 96;
  1642. p.tempo = 150.0;
  1643. p.channels = { { 0, flp::ChannelType::sampler, "Kick 808", "", "", 1 },
  1644. { 1, flp::ChannelType::audioClip, "Vocal", "", "", 2 },
  1645. { 2, flp::ChannelType::instrument, "Lead", "FLEX", "", 3 } };
  1646. flp::Pattern pat;
  1647. pat.index = 1;
  1648. flp::Note n;
  1649. n.position = 96;
  1650. n.length = 0;
  1651. n.channel = 2;
  1652. n.key = 72;
  1653. n.velocity = 64;
  1654. pat.notes.push_back (n);
  1655. p.patterns.push_back (pat);
  1656. const auto s = lynx::importFlp (p);
  1657. CHECK (s.bpm == 150.0);
  1658. CHECK (s.channels.size() == 3); // audio clip channels stay in the rack, as in FL
  1659. CHECK (s.channels[0].instrument == lynx::InstrumentKind::kick);
  1660. CHECK (s.channels[1].instrument == lynx::InstrumentKind::audioClip);
  1661. CHECK (s.channels[2].instrument == lynx::InstrumentKind::synth);
  1662. CHECK (s.patterns.size() == 1);
  1663. CHECK (s.patterns[0].notes[0].start == lynx::ppq); // 96 @ PPQ 96 = 1 beat
  1664. CHECK (s.patterns[0].notes[0].channel == 2);
  1665. CHECK (s.patterns[0].notes[0].length == lynx::ticksPerStep); // step note
  1666. CHECK (std::abs (s.patterns[0].notes[0].velocity - 0.5f) < 1e-6f);
  1667. }
  1668. TEST (live_queue_is_fifo_and_bounded)
  1669. {
  1670. lynx::LiveEventQueue q;
  1671. lynx::NoteEvent e;
  1672. CHECK (! q.pop (e));
  1673. for (int i = 0; i < 10; ++i)
  1674. {
  1675. lynx::NoteEvent in;
  1676. in.key = i;
  1677. CHECK (q.push (in));
  1678. }
  1679. for (int i = 0; i < 10; ++i)
  1680. CHECK (q.pop (e) && e.key == i);
  1681. int pushed = 0;
  1682. while (q.push (e))
  1683. ++pushed;
  1684. CHECK (pushed == (int) lynx::LiveEventQueue::capacity - 1); // one slot stays free to tell full from empty
  1685. }
  1686. TEST (sampler_plays_pitched_one_shot)
  1687. {
  1688. // 1000-frame ramp sample: the position can be measured from the amplitude
  1689. auto data = std::make_shared<lynx::SampleData>();
  1690. data->sampleRate = 48000.0;
  1691. for (int i = 0; i < 1000; ++i)
  1692. data->left.push_back (1.0f);
  1693. auto sampler = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  1694. sampler->prepare (48000.0);
  1695. std::vector<float> l (2048, 0.0f), r (2048, 0.0f);
  1696. sampler->noteOn (60, 1.0f);
  1697. sampler->noteOff (60); // one-shot: noteOff doesn't cut
  1698. sampler->render (l.data(), r.data(), 2048, 1.0f, 1.0f);
  1699. int sounding = 0;
  1700. for (auto s : l)
  1701. sounding += s > 0.5f;
  1702. CHECK (sounding >= 995 && sounding <= 1000); // plays the whole sample at the original pitch
  1703. std::fill (l.begin(), l.end(), 0.0f);
  1704. sampler->noteOn (72, 1.0f); // one octave up: half the duration
  1705. sampler->render (l.data(), r.data(), 2048, 1.0f, 1.0f);
  1706. sounding = 0;
  1707. for (auto s : l)
  1708. sounding += s > 0.5f;
  1709. CHECK (sounding >= 495 && sounding <= 500);
  1710. CHECK (r[10] > 0.5f); // mono goes to both sides
  1711. auto silent = lynx::makeInstrument (lynx::InstrumentKind::sampler, nullptr);
  1712. silent->prepare (48000.0);
  1713. silent->noteOn (60, 1.0f);
  1714. std::fill (l.begin(), l.end(), 0.0f);
  1715. silent->render (l.data(), r.data(), 64, 1.0f, 1.0f);
  1716. CHECK (l[0] == 0.0f);
  1717. }
  1718. TEST (rack_live_notes_and_sample_provider)
  1719. {
  1720. lynx::Song song;
  1721. lynx::ChannelDef c;
  1722. c.name = "Smp";
  1723. c.instrument = lynx::InstrumentKind::sampler;
  1724. c.samplePath = "a.wav";
  1725. song.channels.push_back (c);
  1726. song.patterns.emplace_back();
  1727. int loads = 0;
  1728. auto provider = [&] (const std::string& path) -> std::shared_ptr<const lynx::SampleData> {
  1729. ++loads;
  1730. CHECK (path == "a.wav");
  1731. auto d = std::make_shared<lynx::SampleData>();
  1732. d->left.assign (4800, 0.5f);
  1733. return d;
  1734. };
  1735. auto state = lynx::RackState::build (song, nullptr, 48000.0, provider);
  1736. CHECK (loads == 1);
  1737. lynx::RackRenderer renderer;
  1738. renderer.prepare (48000.0);
  1739. lynx::LiveEventQueue live;
  1740. lynx::NoteEvent on;
  1741. on.channel = 0;
  1742. on.velocity = 1.0f;
  1743. live.push (on);
  1744. std::vector<float> l (256), r (256);
  1745. renderer.process (state.get(), false, 0.0, 256, l.data(), r.data(), &live); // stopped, but the live note plays
  1746. CHECK (l[0] > 0.1f);
  1747. // same sample: reused; different sample: reloaded
  1748. auto same = lynx::RackState::build (song, state.get(), 48000.0, provider);
  1749. CHECK (loads == 1 && same->instruments[0] == state->instruments[0]);
  1750. song.channels[0].samplePath = "b.wav";
  1751. auto other = lynx::RackState::build (song, state.get(), 48000.0, [&] (const std::string&) { ++loads; return nullptr; });
  1752. CHECK (loads == 2 && other->instruments[0] != state->instruments[0]);
  1753. }
  1754. TEST (flp_paths_resolve_and_samplers_import)
  1755. {
  1756. lynx::FlPathRoots roots { "C:\\FL", "C:\\FL\\Data", "D:\\User" };
  1757. CHECK (lynx::resolveFlPath ("%FLStudioFactoryData%\\Data\\x.wav", roots) == "C:\\FL\\Data\\x.wav");
  1758. CHECK (lynx::resolveFlPath ("%FLStudioData%\\Patches\\y.wav", roots) == "C:\\FL\\Data\\Patches\\y.wav");
  1759. CHECK (lynx::resolveFlPath ("%FLStudioUserData%\\z.wav", roots) == "D:\\User\\z.wav");
  1760. CHECK (lynx::resolveFlPath ("E:\\abs.wav", roots) == "E:\\abs.wav");
  1761. CHECK (lynx::resolveFlPath ("%FLStudioUserData%\\z.wav", {}) == "");
  1762. flp::Project p;
  1763. p.channels = { { 0, flp::ChannelType::sampler, "Kick", "", "%FLStudioData%\\k.wav", 1 },
  1764. { 1, flp::ChannelType::sampler, "Hat", "", "%FLStudioData%\\missing.wav", 1 } };
  1765. lynx::FlpImportOptions options;
  1766. options.roots = roots;
  1767. options.fileExists = [] (const std::string& path) { return path == "C:\\FL\\Data\\k.wav"; };
  1768. const auto s = lynx::importFlp (p, options);
  1769. CHECK (s.channels[0].instrument == lynx::InstrumentKind::sampler);
  1770. CHECK (s.channels[0].samplePath == "C:\\FL\\Data\\k.wav");
  1771. CHECK (s.channels[1].instrument == lynx::InstrumentKind::hat); // no file: built-in instrument
  1772. }
  1773. TEST (soft_clip_is_transparent_below_knee_and_bounded)
  1774. {
  1775. float s[] = { 0.5f, -0.89f, 1.5f, -3.0f, 0.95f };
  1776. lynx::softClip (s, 5);
  1777. CHECK (s[0] == 0.5f && s[1] == -0.89f);
  1778. CHECK (s[2] > 0.9f && s[2] <= 1.0f);
  1779. CHECK (s[3] < -0.9f && s[3] >= -1.0f);
  1780. CHECK (s[4] > 0.9f && s[4] < 0.95f);
  1781. }
  1782. TEST (song_scheduler_plays_clips_with_offset_and_cut)
  1783. {
  1784. lynx::Song s;
  1785. s.channels.resize (1);
  1786. auto& p = s.patterns.emplace_back();
  1787. for (int step : { 0, 4, 8, 12 }) // one note per beat
  1788. p.toggleStep (0, step);
  1789. // clip at bar 2 playing only the second half of the pattern (beats 3 and 4)
  1790. lynx::Clip c;
  1791. c.pattern = 0;
  1792. c.start = 4 * lynx::ppq;
  1793. c.length = 2 * lynx::ppq;
  1794. c.offset = 2 * lynx::ppq;
  1795. s.playlist.push_back (c);
  1796. CHECK (s.songLength() == 8 * lynx::ppq);
  1797. const double sr = 48000.0;
  1798. const auto tps = lynx::ticksPerSample (120.0, sr); // 1 beat = 24000 samples
  1799. lynx::EventBuffer ev;
  1800. // whole song in a single block (8 beats = 192000 samples)
  1801. lynx::scheduleSong (s, 0.0, 192000, tps, ev);
  1802. std::vector<int> ons;
  1803. for (auto& e : ev)
  1804. if (e.type == lynx::NoteEvent::Type::on)
  1805. ons.push_back (e.sampleOffset);
  1806. CHECK (ons.size() == 2);
  1807. CHECK (ons.size() == 2 && ons[0] == 4 * 24000 && ons[1] == 5 * 24000);
  1808. // crossing the loop: bar 1 is empty, so nothing at the start of the second pass
  1809. ev.clear();
  1810. lynx::scheduleSong (s, 8.0 * lynx::ppq - 100 * tps, 200, tps, ev);
  1811. CHECK (ev.size() == 0);
  1812. // a note longer than the clip is cut at the clip end
  1813. p.notes[3].length = 4 * lynx::ppq;
  1814. ev.clear();
  1815. lynx::scheduleSong (s, 0.0, 192000, tps, ev);
  1816. int lastOff = -1;
  1817. for (auto& e : ev)
  1818. if (e.type == lynx::NoteEvent::Type::off)
  1819. lastOff = std::max (lastOff, e.sampleOffset);
  1820. CHECK (lastOff == 6 * 24000);
  1821. }
  1822. TEST (remove_pattern_fixes_clips)
  1823. {
  1824. lynx::Song s;
  1825. s.patterns.resize (3);
  1826. s.currentPattern = 2;
  1827. s.playlist = { { 0, 0, 0, 100, 0 }, { 1, 0, 100, 100, 0 }, { 2, 1, 0, 100, 0 } };
  1828. s.removePattern (1);
  1829. CHECK (s.patterns.size() == 2);
  1830. CHECK (s.playlist.size() == 2 && s.playlist[1].pattern == 1);
  1831. CHECK (s.currentPattern == 1);
  1832. }
  1833. TEST (flp_import_3x_osc_state_and_channel_filter)
  1834. {
  1835. // new 3x Osc patch (version 14): osc 2 mix 64 coarse -12, osc 3 mix 32 coarse -24
  1836. std::vector<std::uint8_t> blob (460, 0);
  1837. auto put = [&] (std::size_t off, std::int32_t v) {
  1838. for (int b = 0; b < 4; ++b)
  1839. blob[off + (std::size_t) b] = (std::uint8_t) ((std::uint32_t) v >> (8 * b));
  1840. };
  1841. put (0x00, 14);
  1842. put (0x08, 3); // osc 1 saw
  1843. put (0x10, 7); // osc 1 fine +7
  1844. put (0x04, -32); // osc 1 pan -0.5
  1845. put (0x1C, 64); // osc 2 mix
  1846. put (0x28, -12); // osc 2 coarse
  1847. put (0x38, 32); // osc 3 mix
  1848. put (0x40, 2); // osc 3 square
  1849. put (0x44, -19); // osc 3 coarse: -1 octave and -7 semitones
  1850. lynx::SynthSettings s;
  1851. CHECK (lynx::synthFrom3xOsc (blob, s));
  1852. 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);
  1853. CHECK (s.osc[0].wave == lynx::Waveform::saw && s.osc[0].detune == 7.0f && s.osc[0].pan == -0.5f);
  1854. CHECK (s.osc[1].wave == lynx::Waveform::sine && s.osc[1].octave == -1 && s.osc[1].semitones == 0);
  1855. CHECK (s.osc[2].wave == lynx::Waveform::square && s.osc[2].octave == -1 && s.osc[2].semitones == -7);
  1856. CHECK (! lynx::synthFrom3xOsc (std::vector<std::uint8_t> (40, 0), s));
  1857. // channel filter: open by default; LP with Mod X 128 ~ 2.71 kHz; Fast LP with Mod X 128 ~ 280 Hz
  1858. float hz = 0.0f, res = 1.0f;
  1859. int mode = -1;
  1860. lynx::synthFilterFromChannel (256, 0, 0, hz, res, mode);
  1861. CHECK (hz >= 19999.0f && res == 0.0f);
  1862. lynx::synthFilterFromChannel (128, 0, 1, hz, res, mode);
  1863. CHECK (std::abs (hz - 2710.0f) < 30.0f && res == 0.0f);
  1864. lynx::synthFilterFromChannel (128, 0, 0, hz, res, mode);
  1865. CHECK (hz > 240.0f && hz < 320.0f);
  1866. lynx::synthFilterFromChannel (128, 256, 1, hz, res, mode);
  1867. CHECK (res > 0.8f);
  1868. CHECK (mode == 0);
  1869. lynx::synthFilterFromChannel (64, 0, 3, hz, res, mode); // high-pass at ~840 Hz
  1870. CHECK (mode == 2 && std::abs (hz - 840.0f) < 40.0f);
  1871. lynx::synthFilterFromChannel (128, 0, 2, hz, res, mode); // band-pass
  1872. CHECK (mode == 1);
  1873. }
  1874. TEST (synth_pitch_and_filter_envelopes)
  1875. {
  1876. auto render = [] (const lynx::SynthSettings& s, int frames) {
  1877. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  1878. inst->prepare (48000.0);
  1879. lynx::ChannelDef c;
  1880. c.synth = s;
  1881. inst->configure (c, 120.0);
  1882. inst->noteOn (45, 1.0f); // A2 = 110 Hz
  1883. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  1884. inst->render (l.data(), r.data(), frames, 1.0f, 1.0f);
  1885. return l;
  1886. };
  1887. auto crossings = [] (const std::vector<float>& b, int from, int to) {
  1888. int n = 0;
  1889. for (int i = from + 1; i < to; ++i)
  1890. n += (b[(std::size_t) i - 1] < 0.0f) != (b[(std::size_t) i] < 0.0f);
  1891. return n;
  1892. };
  1893. // 3x Osc "kick": sine with a +24 st pitch envelope falling fast
  1894. lynx::SynthSettings kick;
  1895. kick.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  1896. kick.cutoff = 20000.0f;
  1897. kick.pitchEnv = { 24.0f, 0.0f, 0.0f, 0.05f, 0.0f, 0.05f };
  1898. const auto k = render (kick, 48000);
  1899. const auto early = crossings (k, 0, 2400); // first 50 ms: well above 110 Hz
  1900. const auto late = crossings (k, 24000, 48000); // then back to 110 Hz (~110 crossings in 0.5 s)
  1901. CHECK (early > 20); // +24 st ramp over 50 ms: ~2.2x the average frequency (11 crossings without envelope)
  1902. CHECK (std::abs (late - 110) < 4);
  1903. // cutoff envelope: saw closed at 200 Hz opens +5 octaves on attack and closes again
  1904. lynx::SynthSettings pluck;
  1905. pluck.cutoff = 200.0f;
  1906. pluck.filterEnv = { 5.0f, 0.0f, 0.0f, 0.1f, 0.0f, 0.1f };
  1907. const auto p = render (pluck, 48000);
  1908. auto hf = [&] (int from, int to) { // energy of the difference (highs)
  1909. double e = 0.0;
  1910. for (int i = from + 1; i < to; ++i)
  1911. e += std::pow ((double) p[(std::size_t) i] - p[(std::size_t) i - 1], 2.0);
  1912. return e;
  1913. };
  1914. CHECK (hf (0, 2400) > 4.0 * hf (40000, 42400));
  1915. // Toxic Biohazard's envelope (REA_rodada33 §2): exponential towards 5 clipped at 1, so the cutoff is still near
  1916. // its base early in the attack, fully open at A = 0.2 s and back down after the exponential decay
  1917. lynx::SynthSettings toxic = pluck;
  1918. toxic.filterEnv = { 5.0f, 0.2f, 0.0f, 0.1f, 0.0f, 0.1f, 1 };
  1919. const auto t = render (toxic, 48000);
  1920. auto thf = [&] (int from, int to) {
  1921. double e = 0.0;
  1922. for (int i = from + 1; i < to; ++i)
  1923. e += std::pow ((double) t[(std::size_t) i] - t[(std::size_t) i - 1], 2.0);
  1924. return e;
  1925. };
  1926. CHECK (thf (9000, 9600) > 4.0 * thf (300, 900));
  1927. CHECK (thf (9000, 9600) > 4.0 * thf (40000, 40600));
  1928. }
  1929. TEST (synth_mono_reuses_the_sounding_voice)
  1930. {
  1931. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  1932. inst->prepare (48000.0);
  1933. lynx::ChannelDef c;
  1934. c.synth.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  1935. c.synth.cutoff = 20000.0f;
  1936. c.synth.mono = true;
  1937. inst->configure (c, 120.0);
  1938. std::vector<float> l (48000), r (48000);
  1939. inst->noteOn (57, 1.0f);
  1940. inst->render (l.data(), r.data(), 4800, 1.0f, 1.0f);
  1941. inst->noteOn (69, 1.0f); // A4 takes over the A3 voice: only one note sounding
  1942. inst->render (l.data() + 4800, r.data() + 4800, 43200, 1.0f, 1.0f);
  1943. int crossings = 0;
  1944. float peak = 0.0f;
  1945. for (std::size_t i = 24001; i < 48000; ++i)
  1946. {
  1947. crossings += (l[i - 1] < 0.0f) != (l[i] < 0.0f);
  1948. peak = std::max (peak, std::abs (l[i]));
  1949. }
  1950. CHECK (std::abs (crossings - 440) < 4); // 0.5 s of 440 Hz, without the A3 underneath
  1951. CHECK (peak < 0.35f); // one voice (0.3 level), not two summed
  1952. // no click on the handover: the jump between neighbouring samples stays sine-sized
  1953. float jump = 0.0f;
  1954. for (std::size_t i = 4790; i < 4810; ++i)
  1955. jump = std::max (jump, std::abs (l[i] - l[i - 1]));
  1956. CHECK (jump < 0.05f);
  1957. }
  1958. TEST (synth_porta_glides_and_am_modulates)
  1959. {
  1960. auto make = [] (const lynx::SynthSettings& s) {
  1961. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  1962. inst->prepare (48000.0);
  1963. lynx::ChannelDef c;
  1964. c.synth = s;
  1965. inst->configure (c, 120.0);
  1966. return inst;
  1967. };
  1968. auto crossings = [] (const std::vector<float>& b, std::size_t from, std::size_t to) {
  1969. int n = 0;
  1970. for (auto i = from + 1; i < to; ++i)
  1971. n += (b[i - 1] < 0.0f) != (b[i] < 0.0f);
  1972. return n;
  1973. };
  1974. // mono + 1-beat porta (0.5 s at 120 BPM): from A3 to A4, halfway ~E4 (329.6 Hz)
  1975. lynx::SynthSettings s;
  1976. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  1977. s.cutoff = 20000.0f;
  1978. s.mono = true;
  1979. s.porta = true;
  1980. s.portaBeats = 1.0f;
  1981. auto inst = make (s);
  1982. std::vector<float> l (96000), r (96000);
  1983. inst->noteOn (57, 1.0f);
  1984. inst->render (l.data(), r.data(), 4800, 1.0f, 1.0f);
  1985. inst->noteOn (69, 1.0f);
  1986. inst->render (l.data() + 4800, r.data() + 4800, 91200, 1.0f, 1.0f);
  1987. const auto middle = crossings (l, 4800 + 12000 - 2400, 4800 + 12000 + 2400); // 0.1 s around 0.25 s
  1988. CHECK (std::abs (middle - 66) < 6); // ~330 Hz * 0.1 s * 2
  1989. CHECK (std::abs (crossings (l, 48000, 96000) - 880) < 4); // reached A4 (1 s = 880 crossings)
  1990. // AM: osc 3 at level 1.0, slow sine, modulates osc 1 (the average level drops, the sum doesn't gain osc 3)
  1991. lynx::SynthSettings am;
  1992. am.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  1993. am.osc[2] = { lynx::Waveform::sine, -3, 0.0f, 1.0f };
  1994. am.cutoff = 20000.0f;
  1995. am.am = true;
  1996. auto modulated = make (am);
  1997. modulated->noteOn (69, 1.0f);
  1998. std::fill (l.begin(), l.end(), 0.0f);
  1999. modulated->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  2000. float peak = 0.0f;
  2001. for (std::size_t i = 4800; i < 48000; ++i)
  2002. peak = std::max (peak, std::abs (l[i]));
  2003. CHECK (peak > 0.45f && peak < 0.65f); // 0.3 · (1 + 1) at most: (1 − o3) goes up to 2
  2004. }
  2005. TEST (channel_lfo_vibrato_and_tremolo)
  2006. {
  2007. auto render = [] (const lynx::SynthSettings& s) {
  2008. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  2009. inst->prepare (48000.0);
  2010. lynx::ChannelDef c;
  2011. c.synth = s;
  2012. inst->configure (c, 120.0);
  2013. inst->noteOn (69, 1.0f);
  2014. std::vector<float> l (48000), r (48000);
  2015. inst->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  2016. return l;
  2017. };
  2018. lynx::SynthSettings s;
  2019. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  2020. s.cutoff = 20000.0f;
  2021. // tremolo: 100% volume LFO at 4 Hz (0.25 s period) -> the amplitude envelope goes from ~0 to ~2x
  2022. auto tremolo = s;
  2023. tremolo.lfo[lynx::lfoVolume] = { 1.0f, 0.25f, false, 0, 0.0f, 0.0f };
  2024. const auto t = render (tremolo);
  2025. float lowest = 1.0f, highest = 0.0f;
  2026. for (std::size_t w = 4800; w + 480 <= 48000; w += 480) // 10 ms windows (4.4 cycles of 440 Hz)
  2027. {
  2028. float peak = 0.0f;
  2029. for (auto i = w; i < w + 480; ++i)
  2030. peak = std::max (peak, std::abs (t[i]));
  2031. lowest = std::min (lowest, peak);
  2032. highest = std::max (highest, peak);
  2033. }
  2034. CHECK (lowest < 0.08f && highest > 0.5f);
  2035. // synced vibrato: ±1 semitone, 1-beat period (0.5 s at 120 BPM); the average stays at 440 Hz
  2036. auto vibrato = s;
  2037. vibrato.lfo[lynx::lfoPitch] = { 1.0f, 1.0f, true, 0, 0.0f, 0.0f };
  2038. const auto v = render (vibrato);
  2039. int crossings = 0;
  2040. for (std::size_t i = 1; i < 48000; ++i)
  2041. crossings += (v[i - 1] < 0.0f) != (v[i] < 0.0f);
  2042. CHECK (std::abs (crossings - 880) < 12);
  2043. int firstQuarter = 0; // first quarter of the cycle: rising sine -> higher than 440
  2044. for (std::size_t i = 1; i < 6000; ++i)
  2045. firstQuarter += (v[i - 1] < 0.0f) != (v[i] < 0.0f);
  2046. CHECK (firstQuarter > 112);
  2047. }
  2048. TEST (sampler_porta_glides_from_previous_note)
  2049. {
  2050. auto data = std::make_shared<lynx::SampleData>();
  2051. data->sampleRate = 48000.0;
  2052. data->left.resize (96000);
  2053. for (std::size_t i = 0; i < data->left.size(); ++i)
  2054. data->left[i] = 0.5f * (float) std::sin (6.283185307 * 220.0 * (double) i / 48000.0);
  2055. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  2056. inst->prepare (48000.0);
  2057. lynx::ChannelDef c;
  2058. c.sampler.cut = true;
  2059. c.sampler.porta = true;
  2060. c.sampler.portaBeats = 1.0f; // 0.5 s at 120 BPM
  2061. inst->configure (c, 120.0);
  2062. std::vector<float> l (24000), r (24000);
  2063. inst->noteOn (60, 1.0f);
  2064. inst->render (l.data(), r.data(), 2400, 1.0f, 1.0f);
  2065. inst->noteOn (72, 1.0f); // one octave up: starts at 220 Hz and rises
  2066. std::fill (l.begin(), l.end(), 0.0f);
  2067. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  2068. auto crossings = [&] (std::size_t from, std::size_t to) {
  2069. int n = 0;
  2070. for (auto i = from + 1; i < to; ++i)
  2071. n += (l[i - 1] < 0.0f) != (l[i] < 0.0f);
  2072. return n;
  2073. };
  2074. const auto start = crossings (600, 2400); // 37.5 ms still near 220 Hz: ~17 crossings (440 Hz would give 33)
  2075. const auto end = crossings (21600, 24000); // 50 ms at the end of the glide: near 440 Hz (~44; 220 Hz would give 22)
  2076. CHECK (start < 22);
  2077. CHECK (end > 36);
  2078. }
  2079. TEST (zoned_sampler_picks_zone_by_key_and_velocity)
  2080. {
  2081. auto sine = [] (double hz, float amp) {
  2082. auto d = std::make_shared<lynx::SampleData>();
  2083. d->sampleRate = 48000.0;
  2084. d->left.resize (48000);
  2085. for (std::size_t i = 0; i < d->left.size(); ++i)
  2086. d->left[i] = amp * (float) std::sin (6.283185307 * hz * (double) i / 48000.0);
  2087. return d;
  2088. };
  2089. // lows: 220 Hz sine recorded as A3 (57), up to key 69; highs: 880 Hz as A5 (81)
  2090. // hard layer on the highs: same tuning, louder
  2091. std::vector<lynx::LoadedZone> zones {
  2092. { { "graves.wav", 57, 0, 69, 0, 127, 0.0f, 1.0f }, sine (220.0, 0.5f) },
  2093. { { "agudos.wav", 81, 70, 127, 0, 99, 0.0f, 1.0f }, sine (880.0, 0.25f) },
  2094. { { "agudos forte.wav", 81, 70, 127, 100, 127, 0.0f, 1.0f }, sine (880.0, 0.9f) },
  2095. };
  2096. auto inst = lynx::makeZonedSampler (zones);
  2097. inst->prepare (48000.0);
  2098. inst->configure (lynx::ChannelDef {}, 120.0);
  2099. auto play = [&] (int key, float velocity) {
  2100. inst->allNotesOff();
  2101. std::vector<float> l (24000), r (24000);
  2102. inst->render (l.data(), r.data(), 2000, 1.0f, 1.0f); // let the old voices die out
  2103. std::fill (l.begin(), l.end(), 0.0f);
  2104. inst->noteOn (key, velocity);
  2105. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  2106. int crossings = 0;
  2107. float peak = 0.0f;
  2108. for (std::size_t i = 1; i < 24000; ++i)
  2109. {
  2110. crossings += (l[i - 1] < 0.0f) != (l[i] < 0.0f);
  2111. peak = std::max (peak, std::abs (l[i]));
  2112. }
  2113. return std::pair { crossings, peak };
  2114. };
  2115. const auto low = play (69, 0.5f); // A4 from root A3: 440 Hz -> 440 crossings in 0.5 s
  2116. CHECK (std::abs (low.first - 440) < 4);
  2117. const auto soft = play (81, 0.5f); // high zone at the root: 880 Hz
  2118. CHECK (std::abs (soft.first - 880) < 6);
  2119. const auto hard = play (81, 0.95f); // high velocity: hard layer
  2120. CHECK (hard.second > soft.second * 2.0f);
  2121. // overlapping layers round-robin: two identical zones at different levels, notes alternate
  2122. auto rr = lynx::makeZonedSampler ({ { { "a.wav", 60 }, sine (440.0, 0.2f) }, { { "b.wav", 60 }, sine (440.0, 0.8f) } });
  2123. rr->prepare (48000.0);
  2124. rr->configure (lynx::ChannelDef {}, 120.0);
  2125. float peaks[2] {};
  2126. for (int k = 0; k < 2; ++k)
  2127. {
  2128. rr->allNotesOff();
  2129. std::vector<float> l (4800), r (4800);
  2130. rr->render (l.data(), r.data(), 2000, 1.0f, 1.0f);
  2131. std::fill (l.begin(), l.end(), 0.0f);
  2132. rr->noteOn (60, 1.0f);
  2133. rr->render (l.data(), r.data(), 4800, 1.0f, 1.0f);
  2134. for (auto v : l)
  2135. peaks[k] = std::max (peaks[k], std::abs (v));
  2136. }
  2137. CHECK (std::abs (peaks[0] - peaks[1]) > 0.3f);
  2138. }
  2139. TEST (zoned_sampler_loops_while_held)
  2140. {
  2141. // 0.1 s sample with a loop in the middle: holding the note it keeps sounding well past the end of the file;
  2142. // on release, it leaves the loop and ends
  2143. auto data = std::make_shared<lynx::SampleData>();
  2144. data->sampleRate = 48000.0;
  2145. data->left.resize (4800);
  2146. for (std::size_t i = 0; i < data->left.size(); ++i)
  2147. data->left[i] = 0.5f * (float) std::sin (6.283185307 * 480.0 * (double) i / 48000.0); // 100 frames per cycle
  2148. lynx::SampleZone zone { "loop.wav", 60 };
  2149. zone.loopStart = 1000;
  2150. zone.loopEnd = 3000;
  2151. zone.loopMode = 2;
  2152. auto inst = lynx::makeZonedSampler ({ { zone, data } });
  2153. inst->prepare (48000.0);
  2154. lynx::ChannelDef c;
  2155. c.sampler.release = 0.01f;
  2156. inst->configure (c, 120.0);
  2157. inst->noteOn (60, 1.0f);
  2158. std::vector<float> l (48000), r (48000);
  2159. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f); // 0.5 s held
  2160. float held = 0.0f;
  2161. for (std::size_t i = 20000; i < 24000; ++i)
  2162. held = std::max (held, std::abs (l[i]));
  2163. CHECK (held > 0.3f);
  2164. inst->noteOff (60);
  2165. inst->render (l.data() + 24000, r.data() + 24000, 24000, 1.0f, 1.0f);
  2166. float after = 0.0f;
  2167. for (std::size_t i = 40000; i < 48000; ++i)
  2168. after = std::max (after, std::abs (l[i]));
  2169. CHECK (after == 0.0f);
  2170. }
  2171. TEST (global_lfo_follows_song_position)
  2172. {
  2173. // global volume LFO (1-beat period): a note mid-cycle starts mid-wave; the
  2174. // same note with a per-note LFO starts at phase 0
  2175. auto first = [] (bool global, double songTicks) {
  2176. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  2177. inst->prepare (48000.0);
  2178. lynx::ChannelDef c;
  2179. c.synth.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  2180. c.synth.cutoff = 20000.0f;
  2181. c.synth.lfo[lynx::lfoVolume] = { 1.0f, 1.0f, true, 2, 0.0f, 0.0f, global }; // pulse: +1 in the first half
  2182. inst->configure (c, 120.0);
  2183. inst->setSongPosition (songTicks);
  2184. inst->noteOn (69, 1.0f);
  2185. std::vector<float> l (4800), r (4800);
  2186. inst->render (l.data(), r.data(), 4800, 1.0f, 1.0f);
  2187. float peak = 0.0f;
  2188. for (std::size_t i = 2400; i < 4800; ++i)
  2189. peak = std::max (peak, std::abs (l[i]));
  2190. return peak;
  2191. };
  2192. // mid-cycle (phase 0.6) the pulse is at −1: volume ~0; per note (phase 0) it is at +1: ~2x
  2193. const auto globalLate = first (true, 0.6 * lynx::ppq);
  2194. const auto perNote = first (false, 0.6 * lynx::ppq);
  2195. CHECK (globalLate < 0.05f);
  2196. CHECK (perNote > 0.4f);
  2197. }
  2198. TEST (sampler_channel_filter_darkens_and_bypasses_when_open)
  2199. {
  2200. // white noise in the sampler: with a 300 Hz cutoff the energy drops a lot; open passes unchanged
  2201. auto data = std::make_shared<lynx::SampleData>();
  2202. data->sampleRate = 48000.0;
  2203. data->left.resize (48000);
  2204. std::uint32_t seed = 7;
  2205. for (auto& v : data->left)
  2206. {
  2207. seed = seed * 1664525u + 1013904223u;
  2208. v = ((float) (seed >> 8) / 16777216.0f - 0.5f);
  2209. }
  2210. data->right = data->left;
  2211. auto energy = [&] (float cutoff) {
  2212. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  2213. inst->prepare (48000.0);
  2214. lynx::ChannelDef c;
  2215. c.sampler.cutoff = cutoff;
  2216. inst->configure (c, 120.0);
  2217. inst->noteOn (60, 1.0f);
  2218. std::vector<float> l (24000), r (24000);
  2219. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  2220. double e = 0.0;
  2221. for (auto v : l)
  2222. e += (double) v * v;
  2223. return e;
  2224. };
  2225. const auto open = energy (20000.0f), dark = energy (300.0f);
  2226. {
  2227. // high-pass at 10 kHz: also removes most of the noise energy, but from the other side
  2228. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  2229. inst->prepare (48000.0);
  2230. lynx::ChannelDef hp;
  2231. hp.sampler.cutoff = 10000.0f;
  2232. hp.sampler.filterType = 2;
  2233. inst->configure (hp, 120.0);
  2234. inst->noteOn (60, 1.0f);
  2235. std::vector<float> l (24000), r (24000);
  2236. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  2237. double e = 0.0, lowE = 0.0;
  2238. float lp = 0.0f;
  2239. for (auto v : l)
  2240. {
  2241. e += (double) v * v;
  2242. lp += 0.01f * (v - lp); // crude low-pass: almost nothing should remain below
  2243. lowE += (double) lp * lp;
  2244. }
  2245. CHECK (e > 10.0 && e < 0.7 * energy (20000.0f));
  2246. CHECK (lowE < e * 0.01);
  2247. }
  2248. CHECK (open > 100.0);
  2249. CHECK (dark < open * 0.05);
  2250. // +12 st pitch envelope with sustain 1: the sample runs at double speed
  2251. // and ends in half the time (1 s of sample -> 0.5 s)
  2252. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  2253. inst->prepare (48000.0);
  2254. lynx::ChannelDef c;
  2255. c.sampler.pitchEnv = { 12.0f, 0.0f, 0.0f, 0.1f, 1.0f, 0.1f };
  2256. inst->configure (c, 120.0);
  2257. inst->noteOn (60, 1.0f);
  2258. std::vector<float> l (48000), r (48000);
  2259. inst->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  2260. float tail = 0.0f, body = 0.0f;
  2261. for (std::size_t i = 20000; i < 23000; ++i)
  2262. body = std::max (body, std::abs (l[i]));
  2263. for (std::size_t i = 25000; i < 48000; ++i)
  2264. tail = std::max (tail, std::abs (l[i]));
  2265. CHECK (body > 0.1f);
  2266. CHECK (tail == 0.0f);
  2267. }
  2268. TEST (synth_oscillator_pan_and_semitones)
  2269. {
  2270. auto render = [] (lynx::SynthSettings s, std::vector<float>& l, std::vector<float>& r) {
  2271. auto synth = lynx::makeInstrument (lynx::InstrumentKind::synth);
  2272. synth->prepare (48000.0);
  2273. lynx::ChannelDef c;
  2274. c.synth = s;
  2275. synth->configure (c, 120.0);
  2276. synth->noteOn (69, 1.0f);
  2277. l.assign (24000, 0.0f);
  2278. r.assign (24000, 0.0f);
  2279. synth->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  2280. };
  2281. lynx::SynthSettings s;
  2282. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f, 7, 1.0f }; // a fifth up, fully right
  2283. s.cutoff = 20000.0f;
  2284. std::vector<float> l, r;
  2285. render (s, l, r);
  2286. float peakL = 0.0f, peakR = 0.0f;
  2287. int crossings = 0;
  2288. for (std::size_t i = 4800; i < 24000; ++i)
  2289. {
  2290. peakL = std::max (peakL, std::abs (l[i]));
  2291. peakR = std::max (peakR, std::abs (r[i]));
  2292. crossings += (r[i - 1] < 0.0f) != (r[i] < 0.0f);
  2293. }
  2294. CHECK (peakL < 1e-4f && peakR > 0.1f);
  2295. // 440 * 2^(7/12) = 659.3 Hz; 0.4 s = 263.7 cycles = ~527 crossings
  2296. CHECK (std::abs (crossings - 527) < 6);
  2297. }
  2298. TEST (fl_wrapper_state_parses_records_and_vst3_state)
  2299. {
  2300. // Fruity Wrapper blob (version 12): VST3 generator type, class ID, name, path and state
  2301. std::vector<std::uint8_t> blob;
  2302. 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))); };
  2303. auto record = [&] (std::vector<std::uint8_t>& b, std::uint32_t id, const std::vector<std::uint8_t>& payload) {
  2304. u32 (b, id);
  2305. u32 (b, (std::uint32_t) payload.size());
  2306. u32 (b, 0);
  2307. b.insert (b.end(), payload.begin(), payload.end());
  2308. };
  2309. auto bytes = [] (const std::string& s) { return std::vector<std::uint8_t> (s.begin(), s.end()); };
  2310. std::vector<std::uint8_t> vst3State;
  2311. u32 (vst3State, 1);
  2312. record (vst3State, 1, std::vector<std::uint8_t> (64, 0));
  2313. record (vst3State, 3, bytes ("COMPONENTE"));
  2314. record (vst3State, 2, bytes ("CONTROLADOR"));
  2315. // record 4: 3 slots → ParamIDs 700, −1 (empty), 0xFFFFFF01
  2316. std::vector<std::uint8_t> slots;
  2317. for (auto v : { 3u, 700u, 0xFFFFFFFFu, 0xFFFFFF01u })
  2318. u32 (slots, v);
  2319. record (vst3State, 4, slots);
  2320. u32 (blob, 12);
  2321. record (blob, 0x01, std::vector<std::uint8_t> (20, 0xFF));
  2322. record (blob, 0x32, { 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });
  2323. std::vector<std::uint8_t> cid;
  2324. for (int i = 0; i < 16; ++i)
  2325. cid.push_back ((std::uint8_t) (0xA0 + i));
  2326. record (blob, 0x34, cid);
  2327. record (blob, 0x36, bytes ("Surge XT"));
  2328. record (blob, 0x37, bytes ("C:/Program Files/Common Files/VST3/Surge XT.vst3"));
  2329. record (blob, 0x35, vst3State);
  2330. lynx::ForeignPlugin p;
  2331. CHECK (lynx::parseFlWrapper (blob, p));
  2332. CHECK (p.format == lynx::ForeignPlugin::Format::vst3);
  2333. CHECK (p.hasClassId && p.classId[0] == 0xA0 && p.classId[15] == 0xAF);
  2334. CHECK (p.name == "Surge XT" && p.path.find ("Surge XT.vst3") != std::string::npos);
  2335. std::vector<std::uint8_t> component, controller;
  2336. CHECK (lynx::splitFlVst3State (p.state, component, controller));
  2337. CHECK (component == bytes ("COMPONENTE") && controller == bytes ("CONTROLADOR"));
  2338. const auto saved = lynx::flVst3ParamSlots (p.state);
  2339. CHECK (saved == (std::vector<std::int32_t> { 700, -1, (std::int32_t) 0xFFFFFF01u }));
  2340. // FL's slot assignment: saved slots keep their ParamID wherever it now sits; the empty slot stays empty;
  2341. // a vanished ParamID (0xFFFFFF01) leaves its slot dead; parameters without a slot get slots 3, 4… in list order
  2342. const auto positions = lynx::flVst3SlotPositions (saved, { 5u, 700u, 9u });
  2343. CHECK (positions == (std::vector<int> { 1, -1, -1, 0, 2 }));
  2344. CHECK (lynx::flVst3SlotPositions ({}, { 5u, 6u }) == (std::vector<int> { 0, 1 })); // new instance: slot = position
  2345. // version out of range or no type: not a usable wrapper
  2346. blob[0] = 13;
  2347. CHECK (! lynx::parseFlWrapper (blob, p));
  2348. CHECK (! lynx::parseFlWrapper ({ 12, 0, 0, 0 }, p));
  2349. }
  2350. TEST (schedule_index_matches_full_scan)
  2351. {
  2352. // random song (long notes, swing, clips with offset); indexed scheduling must yield
  2353. // exactly the same events as the full scan, including in the block that wraps around
  2354. lynx::Song s = lynx::Song::makeDefault();
  2355. s.swing = 0.6f;
  2356. std::uint32_t seed = 12345;
  2357. auto rnd = [&] (int n) { seed = seed * 1664525u + 1013904223u; return (int) ((seed >> 8) % (std::uint32_t) n); };
  2358. s.patterns.resize (3);
  2359. for (auto& p : s.patterns)
  2360. {
  2361. p.notes.clear();
  2362. for (int i = 0; i < 60; ++i)
  2363. {
  2364. lynx::Note n;
  2365. n.start = rnd (16 * lynx::ppq);
  2366. n.length = rnd (5) == 0 ? rnd (12 * lynx::ppq) + 1 : rnd (lynx::ppq) + 1;
  2367. n.channel = rnd (4);
  2368. n.key = 40 + rnd (40);
  2369. n.slide = rnd (20) == 0;
  2370. p.notes.push_back (n);
  2371. }
  2372. p.sortNotes();
  2373. }
  2374. s.playlist.clear();
  2375. for (int i = 0; i < 12; ++i)
  2376. {
  2377. lynx::Clip c;
  2378. c.pattern = rnd (3);
  2379. c.track = rnd (4);
  2380. c.start = rnd (40) * lynx::ppq;
  2381. c.length = (rnd (12) + 1) * lynx::ppq;
  2382. c.offset = rnd (4) * lynx::ppq;
  2383. s.playlist.push_back (c);
  2384. }
  2385. s.mode = lynx::PlayMode::song;
  2386. const auto index = lynx::makeScheduleIndex (s);
  2387. const auto tps = lynx::ticksPerSample (140.0, 48000.0);
  2388. const auto loop = (double) s.songLength();
  2389. int mismatches = 0, events = 0;
  2390. for (int block = 0; block < 400; ++block)
  2391. {
  2392. const auto start = block == 0 ? loop - 100.0 * tps : (double) rnd ((int) loop * 2);
  2393. const auto samples = 64 + rnd (24000); // up to ~1 beat per block
  2394. lynx::EventBuffer a, b;
  2395. lynx::scheduleSong (s, start, samples, tps, a, false, nullptr);
  2396. lynx::scheduleSong (s, start, samples, tps, b, false, &index);
  2397. events += a.size();
  2398. if (a.size() != b.size())
  2399. {
  2400. ++mismatches;
  2401. continue;
  2402. }
  2403. for (int i = 0; i < a.size(); ++i)
  2404. {
  2405. const auto& x = *(a.begin() + i);
  2406. const auto& y = *(b.begin() + i);
  2407. mismatches += x.sampleOffset != y.sampleOffset || x.type != y.type || x.key != y.key || x.channel != y.channel;
  2408. }
  2409. }
  2410. CHECK (events > 500);
  2411. CHECK (mismatches == 0);
  2412. }
  2413. TEST (mixer_track_eq_defaults_and_boost)
  2414. {
  2415. // FL defaults: 90 Hz, 1.5 kHz and 8 kHz; peak Q 0.632; shelf slope 0.607
  2416. lynx::TrackEq eq;
  2417. CHECK (std::abs (lynx::TrackEq::peakQ (eq.width[1]) - 0.632) < 0.01);
  2418. CHECK (std::abs (lynx::TrackEq::shelfSlope (eq.width[0]) - 0.607) < 0.01);
  2419. CHECK (! eq.active());
  2420. // +12 dB peak at 1.5 kHz on a track: a 1.5 kHz sine rises ~4x
  2421. lynx::Song song = lynx::Song::makeDefault();
  2422. song.mixer[1].eq.gainDb[1] = 12.0f;
  2423. for (auto& c : song.channels)
  2424. c.mixerTrack = 1;
  2425. song.channels[4].instrument = lynx::InstrumentKind::synth;
  2426. song.channels[4].synth = {};
  2427. song.channels[4].synth.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  2428. song.channels[4].synth.cutoff = 20000.0f;
  2429. auto render = [] (const lynx::Song& s) {
  2430. auto state = lynx::RackState::build (s, nullptr, 48000.0);
  2431. lynx::RackRenderer renderer;
  2432. renderer.prepare (48000.0);
  2433. lynx::LiveEventQueue live;
  2434. lynx::NoteEvent on; // 1.5 kHz ~ key 90.6: use 91 (1568 Hz), still within the wide peak
  2435. on.channel = 4;
  2436. on.key = 91;
  2437. on.velocity = 1.0f;
  2438. live.push (on);
  2439. std::vector<float> l (24000), r (24000);
  2440. for (int pos = 0; pos < 24000; pos += 480)
  2441. renderer.process (state.get(), false, 0.0, 480, l.data() + pos, r.data() + pos, pos == 0 ? &live : nullptr);
  2442. float peak = 0.0f;
  2443. for (std::size_t i = 12000; i < 24000; ++i)
  2444. peak = std::max (peak, std::abs (l[i]));
  2445. return peak;
  2446. };
  2447. const auto boosted = render (song);
  2448. song.mixer[1].eq.gainDb[1] = 0.0f;
  2449. const auto flat = render (song);
  2450. CHECK (flat > 0.01f);
  2451. CHECK (boosted / flat > 3.0f && boosted / flat < 4.2f);
  2452. }
  2453. TEST (bars_follow_time_signature_markers)
  2454. {
  2455. lynx::Song song;
  2456. song.beatsPerBar = 4;
  2457. const auto bar4 = (std::int64_t) lynx::ppq * 4;
  2458. auto bars = song.barsBetween (0, bar4 * 3);
  2459. CHECK (bars.size() == 3 && bars[2].tick == bar4 * 2 && bars[2].number == 3);
  2460. // 7/4 from bar 3, and 3/4 in the middle of a 7 bar (cuts and restarts)
  2461. song.addMarker ({ bar4 * 2, "Verso", 7, 4 });
  2462. song.addMarker ({ bar4, "Nome só", 0, 4 });
  2463. const auto seven = (std::int64_t) lynx::ppq * 7;
  2464. song.addMarker ({ bar4 * 2 + seven + lynx::ppq * 2, "", 3, 4 });
  2465. bars = song.barsBetween (0, bar4 * 2 + seven * 2);
  2466. CHECK (bars.size() >= 5);
  2467. CHECK (bars[1].length == bar4 && bars[2].tick == bar4 * 2 && bars[2].length == seven);
  2468. CHECK (bars[3].length == lynx::ppq * 2); // cut short by the change
  2469. CHECK (bars[4].length == lynx::ppq * 3 && bars[4].number == 5);
  2470. CHECK (song.markers()[0].name == "Nome só"); // sorted by tick
  2471. // from far away: starts at the right bar without losing the numbering
  2472. const auto far = song.barsBetween (lynx::ppq * 3000, lynx::ppq * 3001);
  2473. CHECK (far.size() == 1 && far[0].length == lynx::ppq * 3);
  2474. CHECK (song.barAt (lynx::ppq * 3000).number == far[0].number);
  2475. CHECK ((lynx::ppq * 3000 - far[0].tick) < far[0].length);
  2476. }
  2477. TEST (split_drum_channel_moves_notes_to_pads)
  2478. {
  2479. lynx::Song song = lynx::Song::makeDefault();
  2480. const auto channels = (int) song.channels.size();
  2481. song.patterns[0].notes.clear();
  2482. song.patterns[0].notes.push_back ({ 0, 240, 1, 36, 0.9f }); // kit kick (channel 1)
  2483. song.patterns[0].notes.push_back ({ 240, 240, 1, 38, 0.8f }); // snare
  2484. song.patterns[0].notes.push_back ({ 480, 240, 1, 50, 0.8f }); // key without a pad: dropped
  2485. song.patterns[0].notes.push_back ({ 480, 240, 3, 60, 0.8f }); // other channel: shifts by 1 position
  2486. lynx::Automation a;
  2487. a.target = { lynx::AutomationTargetKind::channelVolume, 3, 0, 0 };
  2488. song.automations.push_back (a);
  2489. std::vector<lynx::DrumPad> pads (2);
  2490. pads[0].name = "Kick";
  2491. pads[0].key = 36;
  2492. pads[0].layers = { { "kick.wav" } };
  2493. pads[1].name = "Snare";
  2494. pads[1].key = 38;
  2495. pads[1].layers = { { "snare soft.wav", 60, 0, 127, 0, 90 }, { "snare hard.wav", 60, 0, 127, 91, 127 } };
  2496. pads[1].cutGroup = 2;
  2497. pads[1].cutBy = 2;
  2498. lynx::splitDrumChannel (song, 1, pads);
  2499. CHECK ((int) song.channels.size() == channels + 1);
  2500. CHECK (song.channels[1].samplePath == "kick.wav" && song.channels[1].instrument == lynx::InstrumentKind::sampler);
  2501. CHECK (song.channels[2].zones.size() == 2 && song.channels[2].cutGroup == song.channels[2].cutBy && song.channels[2].cutGroup != 0);
  2502. const auto& notes = song.patterns[0].notes;
  2503. CHECK (notes.size() == 3);
  2504. CHECK (notes[0].channel == 1 && notes[0].key == 60);
  2505. CHECK (notes[1].channel == 2 && notes[1].key == 60);
  2506. CHECK (notes[2].channel == 4); // the old channel 3
  2507. CHECK (song.automations[0].target.index == 4);
  2508. }
  2509. TEST (flp_import_brings_playlist)
  2510. {
  2511. flp::Project p;
  2512. p.header.ppq = 96;
  2513. p.channels = { { 0, flp::ChannelType::sampler, "Kick", "", "", 1 } };
  2514. flp::Pattern empty;
  2515. empty.index = 1;
  2516. flp::Pattern full;
  2517. full.index = 2;
  2518. flp::Note n;
  2519. n.channel = 0;
  2520. full.notes.push_back (n);
  2521. p.patterns = { empty, full };
  2522. flp::Arrangement a;
  2523. flp::PlaylistItem item;
  2524. item.kind = flp::PlaylistItem::Kind::pattern;
  2525. item.index = 2;
  2526. item.position = 384;
  2527. item.length = 192;
  2528. item.track = 3;
  2529. item.patternStartTick = 96;
  2530. a.items.push_back (item);
  2531. item.index = 1; // empty pattern: discarded
  2532. a.items.push_back (item);
  2533. item.kind = flp::PlaylistItem::Kind::channelClip; // audio: not supported yet
  2534. a.items.push_back (item);
  2535. p.arrangements.push_back (a);
  2536. const auto s = lynx::importFlp (p);
  2537. CHECK (s.mode == lynx::PlayMode::song);
  2538. CHECK (s.playlist.size() == 1);
  2539. CHECK (s.playlist[0].pattern == 0 && s.playlist[0].track == 3);
  2540. CHECK (s.playlist[0].start == 4 * lynx::ppq && s.playlist[0].length == 2 * lynx::ppq && s.playlist[0].offset == lynx::ppq);
  2541. }
  2542. TEST (rack_releases_notes_on_position_jump)
  2543. {
  2544. lynx::Song s;
  2545. lynx::ChannelDef c;
  2546. c.instrument = lynx::InstrumentKind::synth;
  2547. s.channels.push_back (c);
  2548. auto& p = s.patterns.emplace_back();
  2549. lynx::Note n;
  2550. n.start = 0;
  2551. n.length = 4 * lynx::ppq; // long note
  2552. p.notes.push_back (n);
  2553. s.bpm = 120.0;
  2554. auto state = lynx::RackState::build (s, nullptr, 48000.0);
  2555. lynx::RackRenderer r;
  2556. r.prepare (48000.0);
  2557. std::vector<float> l (512), rr (512);
  2558. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  2559. double tick = 0.0;
  2560. for (int i = 0; i < 20; ++i, tick += 512 * tps)
  2561. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  2562. // jump to tick 2000 (mid-note, no new "on"): the synth must go silent
  2563. for (int i = 0; i < 40; ++i)
  2564. r.process (state.get(), true, 2000.0 + i * 512 * tps, 512, l.data(), rr.data());
  2565. float tail = 0.0f;
  2566. for (auto v : l)
  2567. tail = std::max (tail, std::abs (v));
  2568. CHECK (tail < 0.001f);
  2569. }
  2570. namespace
  2571. {
  2572. // Two samplers with a constant 0.5 signal on different inserts; returns the output peak.
  2573. float juce_db (float gain)
  2574. {
  2575. return 20.0f * std::log10 (gain);
  2576. }
  2577. float renderMixerCase (const std::function<void (lynx::Song&)>& tweak, lynx::MeterBank* meters = nullptr)
  2578. {
  2579. lynx::Song s;
  2580. s.mixer = lynx::Song::defaultMixer (4);
  2581. for (int i = 0; i < 2; ++i)
  2582. {
  2583. lynx::ChannelDef c;
  2584. c.instrument = lynx::InstrumentKind::sampler;
  2585. c.samplePath = "dc";
  2586. c.volume = 1.0f;
  2587. c.mixerTrack = i + 1;
  2588. s.channels.push_back (c);
  2589. }
  2590. s.patterns.emplace_back();
  2591. tweak (s);
  2592. auto provider = [] (const std::string&) {
  2593. auto d = std::make_shared<lynx::SampleData>();
  2594. d->left.assign (48000, 0.5f);
  2595. return std::shared_ptr<const lynx::SampleData> (d);
  2596. };
  2597. auto state = lynx::RackState::build (s, nullptr, 48000.0, provider);
  2598. lynx::RackRenderer r;
  2599. r.prepare (48000.0, 256);
  2600. lynx::LiveEventQueue live;
  2601. for (int ch = 0; ch < 2; ++ch)
  2602. {
  2603. lynx::NoteEvent on;
  2604. on.channel = ch;
  2605. on.velocity = 1.0f;
  2606. live.push (on);
  2607. }
  2608. std::vector<float> l (1000), rr (1000); // larger than the mixer block: tests the chunking
  2609. r.process (state.get(), false, 0.0, 1000, l.data(), rr.data(), &live, meters);
  2610. return std::max (std::abs (l[999]), std::abs (rr[999]));
  2611. }
  2612. } // namespace
  2613. TEST (mixer_routes_mutes_solos_and_meters)
  2614. {
  2615. // two 0.5 channels summed on the Master at 0 dB
  2616. CHECK (std::abs (renderMixerCase ([] (lynx::Song&) {}) - 1.0f) < 1e-4f);
  2617. // insert 1 muted: only channel 2 remains
  2618. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.mixer[1].muted = true; }) - 0.5f) < 1e-4f);
  2619. // solo on insert 2: same
  2620. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.mixer[2].solo = true; }) - 0.5f) < 1e-4f);
  2621. // FL fader curve: 0.8 = 0 dB, max ≈ +5.6 dB, half travel ≈ -12.7 dB
  2622. CHECK (std::abs (lynx::faderGain (0.8f) - 1.0f) < 1e-5f);
  2623. CHECK (std::abs (juce_db (lynx::faderGain (1.0f)) - 5.59f) < 0.05f);
  2624. CHECK (lynx::faderGain (0.0f) == 0.0f);
  2625. // Master fader at max
  2626. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.mixer[0].volume = 1.0f; }) - lynx::faderGain (1.0f)) < 1e-4f);
  2627. // both channels on the same insert, insert fader at 0.4
  2628. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) {
  2629. s.channels[1].mixerTrack = 1;
  2630. s.mixer[1].volume = 0.4f;
  2631. }) - lynx::faderGain (0.4f)) < 1e-4f);
  2632. // a route outside the mixer falls to the last existing insert, without crashing
  2633. CHECK (renderMixerCase ([] (lynx::Song& s) { s.channels[0].mixerTrack = 100; }) > 0.9f);
  2634. // no mixer: everything straight to the output at 0 dB
  2635. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.mixer.clear(); }) - 1.0f) < 1e-4f);
  2636. lynx::MeterBank meters;
  2637. renderMixerCase ([] (lynx::Song&) {}, &meters);
  2638. CHECK (std::abs (meters.takePeak (1, 0) - 0.5f) < 1e-4f);
  2639. CHECK (std::abs (meters.takePeak (0, 1) - 1.0f) < 1e-4f);
  2640. CHECK (meters.takePeak (1, 0) == 0.0f); // reading resets
  2641. CHECK (meters.takePeak (3, 0) == 0.0f); // insert with no channel
  2642. }
  2643. TEST (next_free_insert_and_flp_mixer_import)
  2644. {
  2645. auto s = lynx::Song::makeDefault();
  2646. CHECK (s.mixer.size() == 17 && s.mixer[0].name == "Master");
  2647. CHECK (s.nextFreeInsert() == 6); // the 5 default channels take 1..5
  2648. flp::Project p;
  2649. p.channels = { { 0, flp::ChannelType::sampler, "Kick", "", "", 30 } };
  2650. p.mixer = { { 0, "" }, { 30, "Drums" } };
  2651. const auto song = lynx::importFlp (p);
  2652. CHECK (song.channels[0].mixerTrack == 30);
  2653. CHECK (song.mixer.size() == 31);
  2654. CHECK (song.mixer[30].name == "Drums" && song.mixer[0].name == "Master");
  2655. }
  2656. namespace
  2657. {
  2658. float runEffectOnSine (lynx::EffectKind kind, const std::function<void (lynx::EffectSlot&)>& tweak, double hz, float amp,
  2659. int frames = 48000)
  2660. {
  2661. auto fx = lynx::makeEffect (kind);
  2662. fx->prepare (48000.0);
  2663. auto slot = lynx::makeEffectSlot (kind);
  2664. tweak (slot);
  2665. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  2666. for (int i = 0; i < frames; ++i)
  2667. l[(std::size_t) i] = r[(std::size_t) i] = amp * (float) std::sin (6.283185307 * hz * i / 48000.0);
  2668. for (int i = 0; i < frames; i += 480)
  2669. fx->process (l.data() + i, r.data() + i, std::min (480, frames - i), slot.params, 120.0);
  2670. float peak = 0.0f;
  2671. for (int i = frames / 2; i < frames; ++i) // second half: already settled
  2672. {
  2673. CHECK (std::isfinite (l[(std::size_t) i]));
  2674. peak = std::max (peak, std::abs (l[(std::size_t) i]));
  2675. }
  2676. return peak;
  2677. }
  2678. } // namespace
  2679. TEST (parametric_eq_bands_and_response)
  2680. {
  2681. // default: transparent
  2682. auto slot = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  2683. CHECK (std::abs (lynx::peq::responseDb (slot.params, 48000.0, 1000.0)) < 0.01);
  2684. CHECK (std::abs (runEffectOnSine (lynx::EffectKind::parametricEq, [] (auto&) {}, 1000.0, 0.5f) - 0.5f) < 0.005f);
  2685. // +12 dB peak at 1 kHz on band 4: the response and the signal agree
  2686. auto boost = [] (lynx::EffectSlot& s) {
  2687. s.params[(std::size_t) lynx::peq::param (3, 1)] = lynx::peq::hzValue (1000.0);
  2688. s.params[(std::size_t) lynx::peq::param (3, 2)] = lynx::peq::gainValue (12.0);
  2689. };
  2690. boost (slot);
  2691. CHECK (std::abs (lynx::peq::responseDb (slot.params, 48000.0, 1000.0) - 12.0) < 0.2);
  2692. CHECK (std::abs (lynx::peq::responseDb (slot.params, 48000.0, 100.0)) < 1.0);
  2693. const auto peak = runEffectOnSine (lynx::EffectKind::parametricEq, boost, 1000.0, 0.1f);
  2694. CHECK (std::abs (peak - 0.1f * std::pow (10.0f, 12.0f / 20.0f)) < 0.01f);
  2695. // low cut at 48 dB/oct at 200 Hz: 50 Hz (2 octaves below) drops ~96 dB; 2 kHz passes
  2696. auto cut = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  2697. cut.params[(std::size_t) lynx::peq::param (0, 0)] = lynx::peq::typeValue (lynx::peq::BandType::lowCut);
  2698. cut.params[(std::size_t) lynx::peq::param (0, 1)] = lynx::peq::hzValue (200.0);
  2699. cut.params[(std::size_t) lynx::peq::param (0, 3)] = lynx::peq::qValue (0.70710678); // Butterworth
  2700. cut.params[(std::size_t) (lynx::peq::slopeParam + 0)] = 1.0f;
  2701. CHECK (lynx::peq::responseDb (cut.params, 48000.0, 50.0) < -80.0);
  2702. CHECK (std::abs (lynx::peq::responseDb (cut.params, 48000.0, 200.0) + 3.0) < 0.5); // -3 dB at the cutoff (Butterworth)
  2703. CHECK (std::abs (lynx::peq::responseDb (cut.params, 48000.0, 2000.0)) < 0.1);
  2704. // round-trip conversions
  2705. CHECK (std::abs (lynx::peq::hz (lynx::peq::hzValue (440.0)) - 440.0) < 0.5);
  2706. CHECK (std::abs (lynx::peq::q (lynx::peq::qValue (2.5)) - 2.5) < 0.01);
  2707. CHECK (lynx::peq::type (lynx::peq::typeValue (lynx::peq::BandType::notch)) == lynx::peq::BandType::notch);
  2708. }
  2709. TEST (fl_parametric_eq2_state_maps_to_bands)
  2710. {
  2711. // v8 blob: band 1 low cut at 100 Hz "Steep 8", band 4 peak +6 dB at 1 kHz, output −3 dB
  2712. std::vector<std::uint8_t> blob (354, 0);
  2713. auto put = [&] (std::size_t off, std::int32_t v) { std::memcpy (blob.data() + off, &v, 4); };
  2714. put (0, 8);
  2715. auto param = [&] (int i, std::int32_t v) { put (4 + 4 * (std::size_t) i, v); };
  2716. auto hzRaw = [] (double hz) { return (std::int32_t) std::lround (std::log (hz / 20.0) / std::log (1000.0) * 65536.0); };
  2717. for (int b = 0; b < 7; ++b)
  2718. param (21 + b, 0); // all off
  2719. param (21 + 0, 3); // high pass (= low cut)
  2720. param (7 + 0, hzRaw (100.0));
  2721. param (14 + 0, 40124); // default width -> Q ~0.68
  2722. param (28 + 0, -3); // Steep 8 -> 4 biquads
  2723. param (21 + 3, 6); // peaking
  2724. param (7 + 3, hzRaw (1000.0));
  2725. param (3, 600); // +6 dB
  2726. param (14 + 3, 25412);
  2727. param (35, -300); // main level −3 dB
  2728. put (0x13E, 0x7F);
  2729. const auto slot = lynx::effectFromFl ("Fruity Parametric EQ 2", blob);
  2730. CHECK (slot.has_value() && slot->kind == lynx::EffectKind::parametricEq);
  2731. const auto& p = slot->params;
  2732. CHECK (lynx::peq::type (p[(std::size_t) lynx::peq::param (0, 0)]) == lynx::peq::BandType::lowCut);
  2733. CHECK (lynx::peq::slopeStages (p[(std::size_t) lynx::peq::slopeParam]) == 4);
  2734. CHECK (lynx::peq::type (p[(std::size_t) lynx::peq::param (3, 0)]) == lynx::peq::BandType::peak);
  2735. CHECK (lynx::peq::type (p[(std::size_t) lynx::peq::param (1, 0)]) == lynx::peq::BandType::off);
  2736. CHECK (std::abs (lynx::peq::responseDb (p, 48000.0, 1000.0) - 3.0) < 0.3); // +6 from the peak −3 from the output
  2737. CHECK (lynx::peq::responseDb (p, 48000.0, 30.0) < -40.0); // 48 dB/oct below 100 Hz
  2738. CHECK (std::abs (lynx::peq::responseDb (p, 48000.0, 8000.0) + 3.0) < 0.3);
  2739. // a band muted by the mask doesn't sound
  2740. put (0x13E, 0x7F & ~(1 << 3));
  2741. const auto muted = lynx::effectFromFl ("Fruity Parametric EQ 2", blob);
  2742. CHECK (lynx::peq::type (muted->params[(std::size_t) lynx::peq::param (3, 0)]) == lynx::peq::BandType::off);
  2743. }
  2744. TEST (reverb_low_cut_and_predelay)
  2745. {
  2746. // impulse: with 100 ms predelay the wet only starts later; with a 3 kHz low cut a
  2747. // 100 Hz sine barely enters the reverb
  2748. auto run = [] (const std::function<void (lynx::EffectSlot&)>& tweak, double hz, bool impulse) {
  2749. auto fx = lynx::makeEffect (lynx::EffectKind::reverb);
  2750. fx->prepare (48000.0);
  2751. auto slot = lynx::makeEffectSlot (lynx::EffectKind::reverb);
  2752. slot.params[4] = 0.0f; // wet only
  2753. slot.params[3] = 1.0f;
  2754. tweak (slot);
  2755. std::vector<float> l (48000), r (48000);
  2756. for (int i = 0; i < 48000; ++i)
  2757. 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);
  2758. for (int i = 0; i < 48000; i += 480)
  2759. fx->process (l.data() + i, r.data() + i, 480, slot.params, 120.0);
  2760. return l;
  2761. };
  2762. const auto delayed = run ([] (auto& s) { s.params[7] = 0.1f; }, 0.0, true);
  2763. float early = 0.0f, later = 0.0f;
  2764. for (std::size_t i = 0; i < 4800; ++i)
  2765. early = std::max (early, std::abs (delayed[i]));
  2766. for (std::size_t i = 4800; i < 24000; ++i)
  2767. later = std::max (later, std::abs (delayed[i]));
  2768. CHECK (early == 0.0f && later > 0.0f);
  2769. 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; };
  2770. const auto open = energy (run ([] (auto&) {}, 100.0, false));
  2771. const auto cut = energy (run ([] (auto& s) { s.params[5] = 1.0f; }, 100.0, false));
  2772. CHECK (cut < open * 0.01);
  2773. }
  2774. TEST (utility_effect_and_fl_stereo_tools)
  2775. {
  2776. // transparent by default; balance fully right silences the left
  2777. CHECK (std::abs (runEffectOnSine (lynx::EffectKind::utility, [] (auto&) {}, 440.0, 0.5f) - 0.5f) < 0.001f);
  2778. CHECK (runEffectOnSine (lynx::EffectKind::utility, [] (auto& s) { s.params[1] = 1.0f; }, 440.0, 0.5f) < 0.001f);
  2779. // Stereo Shaper in "mono": each output = 0.5 L + 0.5 R
  2780. std::vector<std::uint8_t> blob (36, 0);
  2781. auto put = [&] (std::size_t off, std::int32_t v) { std::memcpy (blob.data() + off, &v, 4); };
  2782. put (4, 6400); put (8, 6400); put (12, 6400); put (16, 6400);
  2783. const auto slot = lynx::effectFromFl ("Fruity Stereo Shaper", blob);
  2784. CHECK (slot && slot->kind == lynx::EffectKind::utility);
  2785. auto fx = lynx::makeEffect (lynx::EffectKind::utility);
  2786. float l = 1.0f, r = 0.0f;
  2787. fx->process (&l, &r, 1, slot->params, 120.0);
  2788. CHECK (std::abs (l - 0.5f) < 1e-4f && std::abs (r - 0.5f) < 1e-4f);
  2789. // Balance: volume 256 = 0 dB, pan −128 = fully left
  2790. std::vector<std::uint8_t> bal (8, 0);
  2791. std::int32_t pan = -128, vol = 256;
  2792. std::memcpy (bal.data(), &pan, 4);
  2793. std::memcpy (bal.data() + 4, &vol, 4);
  2794. const auto b = lynx::effectFromFl ("Fruity Balance", bal);
  2795. l = 0.5f; r = 0.5f;
  2796. fx->process (&l, &r, 1, b->params, 120.0);
  2797. CHECK (std::abs (l - 0.5f) < 1e-3f && std::abs (r) < 1e-4f);
  2798. }
  2799. TEST (effects_eq_compressor_behave)
  2800. {
  2801. // EQ at default is transparent
  2802. CHECK (std::abs (runEffectOnSine (lynx::EffectKind::eq, [] (auto&) {}, 1000.0, 0.5f) - 0.5f) < 0.01f);
  2803. // +18 dB on the lows: 60 Hz rises a lot, 5 kHz barely
  2804. CHECK (runEffectOnSine (lynx::EffectKind::eq, [] (auto& s) { s.params[0] = 1.0f; }, 60.0, 0.05f) > 0.3f);
  2805. CHECK (runEffectOnSine (lynx::EffectKind::eq, [] (auto& s) { s.params[0] = 1.0f; }, 5000.0, 0.05f) < 0.06f);
  2806. // compressor: threshold -20 dB, ratio 20:1 flattens a 0 dBFS signal to near the threshold
  2807. const auto squashed = runEffectOnSine (lynx::EffectKind::compressor, [] (auto& s) {
  2808. s.params[0] = 40.0f / 60.0f;
  2809. s.params[1] = 1.0f;
  2810. }, 200.0, 1.0f);
  2811. CHECK (squashed < 0.2f && squashed > 0.05f);
  2812. // a signal below the threshold passes intact
  2813. CHECK (std::abs (runEffectOnSine (lynx::EffectKind::compressor, [] (auto& s) { s.params[0] = 1.0f; }, 200.0, 0.3f) - 0.3f) < 0.01f);
  2814. }
  2815. TEST (effects_delay_echoes_on_tempo_and_reverb_has_tail)
  2816. {
  2817. auto delay = lynx::makeEffect (lynx::EffectKind::delay);
  2818. delay->prepare (48000.0);
  2819. auto slot = lynx::makeEffectSlot (lynx::EffectKind::delay);
  2820. slot.params[0] = 3.5f / 8.0f; // index 3 = 1/4 = 0.5 s at 120 BPM
  2821. slot.params[1] = 0.0f; // no feedback: a single echo
  2822. slot.params[2] = 1.0f;
  2823. slot.params[4] = 0.0f; // no damping
  2824. std::vector<float> l (48000, 0.0f), r (48000, 0.0f);
  2825. l[0] = r[0] = 1.0f;
  2826. delay->process (l.data(), r.data(), 48000, slot.params, 120.0);
  2827. CHECK (std::abs (l[24000] - 1.0f) < 1e-4f);
  2828. CHECK (std::abs (l[12000]) < 1e-6f);
  2829. auto reverb = lynx::makeEffect (lynx::EffectKind::reverb);
  2830. reverb->prepare (48000.0);
  2831. auto rs = lynx::makeEffectSlot (lynx::EffectKind::reverb);
  2832. rs.params[3] = 1.0f;
  2833. std::fill (l.begin(), l.end(), 0.0f);
  2834. std::fill (r.begin(), r.end(), 0.0f);
  2835. l[0] = r[0] = 1.0f;
  2836. reverb->process (l.data(), r.data(), 48000, rs.params, 120.0);
  2837. float tail = 0.0f;
  2838. for (int i = 4800; i < 9600; ++i) // between 100 and 200 ms after the impulse
  2839. tail = std::max (tail, std::abs (l[(std::size_t) i]));
  2840. CHECK (tail > 1e-4f && tail < 1.0f);
  2841. CHECK (lynx::formatEffectParam (lynx::EffectKind::delay, 0, slot.params[0], 120.0) == "1/4 (500 ms)");
  2842. }
  2843. TEST (rack_runs_insert_effects_and_reuses_them)
  2844. {
  2845. // an insert with EQ at -inf doesn't exist; we use the EQ output at -18 dB to see the effect act
  2846. const auto quiet = renderMixerCase ([] (lynx::Song& s) {
  2847. auto eq = lynx::makeEffectSlot (lynx::EffectKind::eq);
  2848. eq.params[4] = 0.0f; // output -18 dB
  2849. s.mixer[1].effects.push_back (eq);
  2850. });
  2851. CHECK (quiet > 0.55f && quiet < 0.6f); // 0.5 from channel 2 + 0.5 * 0.126 from channel 1
  2852. const auto bypassed = renderMixerCase ([] (lynx::Song& s) {
  2853. auto eq = lynx::makeEffectSlot (lynx::EffectKind::eq);
  2854. eq.params[4] = 0.0f;
  2855. eq.enabled = false;
  2856. s.mixer[1].effects.push_back (eq);
  2857. });
  2858. CHECK (std::abs (bypassed - 1.0f) < 1e-4f);
  2859. auto s = lynx::Song::makeDefault();
  2860. s.mixer[2].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::reverb));
  2861. auto a = lynx::RackState::build (s, nullptr, 48000.0);
  2862. s.mixer[2].effects[0].params[0] = 0.9f; // turning a knob doesn't recreate the effect
  2863. auto b = lynx::RackState::build (s, a.get(), 48000.0);
  2864. CHECK (b->effects[2][0] == a->effects[2][0]);
  2865. s.mixer[2].effects[0] = lynx::makeEffectSlot (lynx::EffectKind::delay);
  2866. auto c = lynx::RackState::build (s, b.get(), 48000.0);
  2867. CHECK (c->effects[2][0] != b->effects[2][0]);
  2868. }
  2869. TEST (audio_clips_trigger_cut_and_resume)
  2870. {
  2871. lynx::Song s;
  2872. s.bpm = 120.0; // 1 beat = 0.5 s = 24000 samples at 48 kHz
  2873. lynx::ChannelDef c;
  2874. c.instrument = lynx::InstrumentKind::audioClip;
  2875. c.samplePath = "ramp";
  2876. c.volume = 1.0f;
  2877. s.channels.push_back (c);
  2878. s.patterns.emplace_back();
  2879. lynx::Clip clip;
  2880. clip.kind = lynx::ClipKind::audio;
  2881. clip.channel = 0;
  2882. clip.start = lynx::ppq; // starts at beat 2
  2883. clip.length = 2 * lynx::ppq; // lasts 2 beats
  2884. clip.offset = lynx::ppq; // skips the first beat of the audio
  2885. s.playlist.push_back (clip);
  2886. s.mode = lynx::PlayMode::song;
  2887. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  2888. lynx::EventBuffer ev;
  2889. lynx::scheduleSong (s, 0.0, 4 * 24000, tps, ev);
  2890. CHECK (ev.size() == 2);
  2891. CHECK (ev[0].type == lynx::NoteEvent::Type::on && ev[0].sampleOffset == 24000 && std::abs (ev[0].startSeconds - 0.5) < 1e-9);
  2892. CHECK (ev[1].type == lynx::NoteEvent::Type::off && ev[1].sampleOffset == 3 * 24000);
  2893. // seek to the middle of the clip (beat 2.5): with resume, starts at the block's first sample
  2894. ev.clear();
  2895. lynx::scheduleSong (s, 1.5 * lynx::ppq, 256, tps, ev, true);
  2896. CHECK (ev.size() == 1 && ev[0].sampleOffset == 0 && std::abs (ev[0].startSeconds - 0.75) < 1e-9);
  2897. ev.clear();
  2898. lynx::scheduleSong (s, 1.5 * lynx::ppq, 256, tps, ev, false);
  2899. CHECK (ev.size() == 0);
  2900. // sample whose value = position in seconds: lets us check where playback started
  2901. auto provider = [] (const std::string&) {
  2902. auto d = std::make_shared<lynx::SampleData>();
  2903. d->sampleRate = 48000.0;
  2904. for (int i = 0; i < 48000 * 3; ++i)
  2905. d->left.push_back ((float) i / 48000.0f);
  2906. return std::shared_ptr<const lynx::SampleData> (d);
  2907. };
  2908. auto state = lynx::RackState::build (s, nullptr, 48000.0, provider);
  2909. lynx::RackRenderer r;
  2910. r.prepare (48000.0, 512);
  2911. std::vector<float> l (256), rr (256);
  2912. // first block already playing mid-clip
  2913. r.process (state.get(), true, 1.5 * lynx::ppq, 256, l.data(), rr.data());
  2914. CHECK (std::abs (l[0] - 0.75f) < 0.001f);
  2915. // the clip ends at beat 3: after the short fade, silence (the sample would still have audio)
  2916. double tick = 3.0 * lynx::ppq - 10 * tps;
  2917. r.process (state.get(), false, tick, 256, l.data(), rr.data()); // stops (fade)
  2918. for (int i = 0; i < 4; ++i)
  2919. r.process (state.get(), false, tick, 256, l.data(), rr.data());
  2920. CHECK (std::abs (l[255]) < 1e-6f);
  2921. }
  2922. TEST (remove_channel_fixes_notes_and_audio_clips)
  2923. {
  2924. lynx::Song s;
  2925. s.channels.resize (3);
  2926. s.patterns.resize (1);
  2927. s.patterns[0].notes = { { 0, 240, 0, 60, 1.0f }, { 0, 240, 1, 60, 1.0f }, { 0, 240, 2, 60, 1.0f } };
  2928. lynx::Clip a;
  2929. a.kind = lynx::ClipKind::audio;
  2930. a.channel = 1;
  2931. a.length = 100;
  2932. lynx::Clip b = a;
  2933. b.channel = 2;
  2934. s.playlist = { a, b };
  2935. s.removeChannel (1);
  2936. CHECK (s.channels.size() == 2);
  2937. CHECK (s.patterns[0].notes.size() == 2 && s.patterns[0].notes[1].channel == 1);
  2938. CHECK (s.playlist.size() == 1 && s.playlist[0].channel == 1);
  2939. }
  2940. TEST (flp_import_audio_clips_with_offsets)
  2941. {
  2942. flp::Project p;
  2943. p.header.ppq = 96;
  2944. p.tempo = 120.0;
  2945. p.channels = { { 0, flp::ChannelType::audioClip, "Vocal", "", "%FLStudioData%\\v.wav", 2 },
  2946. { 1, flp::ChannelType::audioClip, "Loop", "", "%FLStudioData%\\l.wav", 3 } };
  2947. flp::Arrangement arr;
  2948. flp::PlaylistItem beats; // offset in beats: end - start = duration in beats
  2949. beats.kind = flp::PlaylistItem::Kind::channelClip;
  2950. beats.index = 0;
  2951. beats.position = 192;
  2952. beats.length = 384; // 4 beats
  2953. beats.startOffset = 2.0f;
  2954. beats.endOffset = 6.0f;
  2955. flp::PlaylistItem ms = beats; // offset in ms: 4 beats at 120 BPM = 2000 ms
  2956. ms.index = 1;
  2957. ms.startOffset = 500.0f;
  2958. ms.endOffset = 2500.0f;
  2959. arr.items = { beats, ms };
  2960. p.arrangements.push_back (arr);
  2961. lynx::FlpImportOptions options;
  2962. options.roots = { "C:\\FL", "C:\\FL\\Data", "" };
  2963. options.fileExists = [] (const std::string&) { return true; };
  2964. const auto s = lynx::importFlp (p, options);
  2965. CHECK (s.channels.size() == 2 && s.channels[0].instrument == lynx::InstrumentKind::audioClip);
  2966. CHECK (s.channels[0].samplePath == "C:\\FL\\Data\\v.wav");
  2967. CHECK (s.playlist.size() == 2);
  2968. CHECK (s.playlist[0].kind == lynx::ClipKind::audio && s.playlist[0].start == 2 * lynx::ppq);
  2969. CHECK (s.playlist[0].offset == 2 * lynx::ppq);
  2970. CHECK (s.playlist[1].offset == lynx::ppq); // 500 ms at 120 BPM = 1 beat
  2971. CHECK (s.mode == lynx::PlayMode::song);
  2972. }
  2973. TEST (plugin_factories_create_reuse_and_fallback)
  2974. {
  2975. lynx::Song s;
  2976. s.mixer = lynx::Song::defaultMixer (2);
  2977. lynx::ChannelDef c;
  2978. c.instrument = lynx::InstrumentKind::plugin;
  2979. c.plugin.id = "VST3-Synth-123";
  2980. c.mixerTrack = 1;
  2981. s.channels.push_back (c);
  2982. lynx::ChannelDef missing = c;
  2983. missing.plugin.id = "VST3-Ausente-0";
  2984. s.channels.push_back (missing);
  2985. lynx::EffectSlot fx;
  2986. fx.kind = lynx::EffectKind::plugin;
  2987. fx.plugin.id = "VST3-Reverb-9";
  2988. s.mixer[1].effects.push_back (fx);
  2989. s.patterns.emplace_back();
  2990. int instrumentsMade = 0, effectsMade = 0;
  2991. lynx::RackState::Factories f;
  2992. f.pluginInstruments = [&] (const lynx::PluginRef& ref, double) -> std::shared_ptr<lynx::Instrument> {
  2993. if (ref.id != "VST3-Synth-123")
  2994. return nullptr;
  2995. ++instrumentsMade;
  2996. auto synth = lynx::makeInstrument (lynx::InstrumentKind::synth);
  2997. synth->prepare (48000.0);
  2998. return synth;
  2999. };
  3000. f.pluginEffects = [&] (const lynx::PluginRef&, double) -> std::shared_ptr<lynx::Effect> {
  3001. ++effectsMade;
  3002. auto eq = lynx::makeEffect (lynx::EffectKind::eq);
  3003. eq->prepare (48000.0);
  3004. return eq;
  3005. };
  3006. auto a = lynx::RackState::build (s, nullptr, 48000.0, f);
  3007. CHECK (instrumentsMade == 1 && effectsMade == 1);
  3008. CHECK (a->instruments.size() == 2 && a->instruments[1] != nullptr); // missing: muted, but it exists
  3009. // changing the saved state doesn't recreate; swapping the plugin does
  3010. s.channels[0].plugin.state = "abc";
  3011. auto b = lynx::RackState::build (s, a.get(), 48000.0, f);
  3012. CHECK (instrumentsMade == 1 && b->instruments[0] == a->instruments[0] && b->effects[1][0] == a->effects[1][0]);
  3013. s.mixer[1].effects[0].plugin.id = "VST3-Outro-1";
  3014. auto c2 = lynx::RackState::build (s, b.get(), 48000.0, f);
  3015. CHECK (effectsMade == 2);
  3016. // rendering with a missing plugin and a plugin slot breaks nothing
  3017. lynx::RackRenderer r;
  3018. r.prepare (48000.0, 256);
  3019. lynx::LiveEventQueue live;
  3020. lynx::NoteEvent on;
  3021. on.channel = 0;
  3022. on.velocity = 1.0f;
  3023. live.push (on);
  3024. on.channel = 1;
  3025. live.push (on);
  3026. std::vector<float> l (256), rr (256);
  3027. r.process (c2.get(), false, 0.0, 256, l.data(), rr.data(), &live);
  3028. float peak = 0.0f;
  3029. for (auto v : l)
  3030. {
  3031. CHECK (std::isfinite (v));
  3032. peak = std::max (peak, std::abs (v));
  3033. }
  3034. CHECK (peak > 0.0f);
  3035. }
  3036. TEST (export_song_adds_silent_tail_and_never_restarts)
  3037. {
  3038. auto s = lynx::Song::makeDefault();
  3039. s.playlist.clear();
  3040. std::int64_t length = 0;
  3041. auto pat = lynx::makeExportSong (s, true, lynx::ppq * 8, length); // empty Playlist: uses the pattern
  3042. CHECK (length == lynx::ppq * 4);
  3043. CHECK (pat.mode == lynx::PlayMode::song && pat.playlist.size() == 2);
  3044. CHECK (pat.songLength() >= length + lynx::ppq * 8);
  3045. // no new notes after the song ends, only silence until the end of the tail
  3046. lynx::EventBuffer events;
  3047. const auto tps = lynx::ticksPerSample (pat.bpm, 48000.0);
  3048. int onsAfterEnd = 0, onsBefore = 0;
  3049. for (double tick = 0.0; tick < (double) (length + lynx::ppq * 8); tick += 512 * tps)
  3050. {
  3051. events.clear();
  3052. lynx::scheduleSong (pat, tick, 512, tps, events);
  3053. for (const auto& e : events)
  3054. if (e.type == lynx::NoteEvent::Type::on)
  3055. (tick + e.sampleOffset * tps >= (double) length ? onsAfterEnd : onsBefore)++;
  3056. }
  3057. CHECK (onsBefore == (int) s.patterns[0].notes.size());
  3058. CHECK (onsAfterEnd == 0);
  3059. // with Playlist: the end is the last clip's, without rounding
  3060. s.playlist.push_back ({ 0, 0, lynx::ppq * 2, lynx::ppq * 3, 0 });
  3061. auto song = lynx::makeExportSong (s, true, 0, length);
  3062. CHECK (length == lynx::ppq * 5 && song.playlist.size() == 1);
  3063. song = lynx::makeExportSong (s, false, 0, length);
  3064. CHECK (length == lynx::ppq * 4 && song.playlist[0].start == 0);
  3065. }
  3066. TEST (note_edit_selection_operations)
  3067. {
  3068. namespace ne = lynx::noteedit;
  3069. lynx::Pattern p;
  3070. p.notes = { { 0, 240, 0, 60 }, { 480, 240, 0, 64 }, { 960, 480, 1, 67 } };
  3071. // sorting keeps the indices in step
  3072. p.notes[0].start = 1200;
  3073. std::vector<int> tracked { 0, 2 };
  3074. ne::sortTracking (p, tracked);
  3075. CHECK (p.notes[2].start == 1200 && p.notes[(std::size_t) tracked[0]].start == 1200);
  3076. CHECK (p.notes[(std::size_t) tracked[1]].key == 67);
  3077. // group move respects the limits
  3078. std::int64_t dt = -5000;
  3079. int dk = 100;
  3080. ne::move (p, { 0, 1 }, dt, dk);
  3081. CHECK (dt == -480 && dk == 127 - 67 && p.notes[0].start == 0 && p.notes[1].key == 127);
  3082. // duplicate: right after the selection, rounded to the grid
  3083. lynx::Pattern q;
  3084. q.notes = { { 0, 240, 0, 60 }, { 240, 300, 0, 62 } }; // 540-tick selection
  3085. const auto added = ne::duplicate (q, { 0, 1 }, 960);
  3086. CHECK (added.size() == 2 && q.notes[(std::size_t) added[0]].start == 960 && q.notes[(std::size_t) added[1]].start == 1200);
  3087. // paste onto another channel with an offset
  3088. const auto pasted = ne::paste (q, ne::copy (q, { 1 }), 100, 3);
  3089. CHECK (pasted.size() == 1 && q.notes.back().channel == 3 && q.notes.back().start == 340);
  3090. // quantize rounds to the nearest
  3091. q.notes[0].start = 130;
  3092. q.notes[1].start = 100;
  3093. ne::quantize (q, { 0, 1 }, 240);
  3094. CHECK (q.notes[0].start == 240 && q.notes[1].start == 0);
  3095. // remove several (order and duplicates don't matter)
  3096. const auto before = q.notes.size();
  3097. ne::remove (q, { 1, 0, 1 });
  3098. CHECK (q.notes.size() == before - 2);
  3099. }
  3100. TEST (note_edit_quick_operations)
  3101. {
  3102. namespace ne = lynx::noteedit;
  3103. const std::int64_t step = lynx::ticksPerStep, bar = lynx::ppq * 4;
  3104. // split: only strictly inside; the tail is appended and does not slide again
  3105. lynx::Pattern p;
  3106. p.notes = { { 0, 4 * step, 0, 60 } };
  3107. p.notes[0].slide = true;
  3108. CHECK (ne::split (p, 0, 0) == -1 && ne::split (p, 0, 4 * step) == -1);
  3109. CHECK (ne::split (p, 0, step) == 1 && p.notes[0].length == step && p.notes[1].start == step && p.notes[1].length == 3 * step
  3110. && ! p.notes[1].slide);
  3111. // chop to grid: a 2.5-step note from half a step becomes 3 pieces cut on the step lines
  3112. lynx::Pattern c;
  3113. c.notes = { { step / 2, step * 5 / 2, 0, 60 }, { 0, step, 1, 50 } };
  3114. const auto pieces = ne::chop (c, { 0, 1 }, step);
  3115. CHECK (pieces.size() == 4 && c.notes.size() == 4);
  3116. CHECK (c.notes[0].length == step / 2 && c.notes[2].start == step && c.notes[2].length == step && c.notes[3].start == 2 * step
  3117. && c.notes[3].length == step);
  3118. // join: touching and overlapping notes of the same key and channel merge; others stay
  3119. lynx::Pattern j;
  3120. j.notes = { { 0, step, 0, 60 }, { step, step, 0, 60 }, { step * 3 / 2, step * 2, 0, 60 }, { 5 * step, step, 0, 60 },
  3121. { step, step, 0, 62 }, { step, step, 1, 60 } };
  3122. CHECK (ne::join (j, { 0, 1, 2, 3, 4, 5 }) == 2 && j.notes.size() == 4);
  3123. CHECK (j.notes[0].start == 0 && j.notes[0].length == step * 7 / 2);
  3124. // legato: each note reaches the next start (a chord ends together); the last keeps its length
  3125. lynx::Pattern l;
  3126. l.notes = { { 0, 10, 0, 60 }, { 0, 10, 0, 64 }, { step, 10, 0, 62 }, { 3 * step, 10, 0, 65 }, { step, 10, 1, 40 } };
  3127. ne::legato (l, { 0, 1, 2, 3, 4 });
  3128. CHECK (l.notes[0].length == step && l.notes[1].length == step && l.notes[2].length == 2 * step && l.notes[3].length == 10
  3129. && l.notes[4].length == 10);
  3130. // shrink to grid and full quantise (start and end)
  3131. ne::shrinkToGrid (l, { 3 }, step / 2);
  3132. CHECK (l.notes[3].length == step / 2);
  3133. lynx::Pattern q;
  3134. q.notes = { { 10, step - 30, 0, 60 }, { step + 100, 20, 0, 60 } };
  3135. ne::quantizeFull (q, { 0, 1 }, step);
  3136. CHECK (q.notes[0].start == 0 && q.notes[0].length == step && q.notes[1].start == step && q.notes[1].length == step);
  3137. // rotate inside the bar, wrapping
  3138. lynx::Pattern r;
  3139. r.notes = { { 0, step, 0, 60 }, { bar - step, step, 0, 62 } };
  3140. ne::rotate (r, { 0, 1 }, step, bar, 1);
  3141. CHECK (r.notes[0].start == step && r.notes[1].start == 0);
  3142. ne::rotate (r, { 0, 1 }, step, bar, -2);
  3143. CHECK (r.notes[0].start == bar - step && r.notes[1].start == bar - 2 * step);
  3144. r.notes.push_back ({ bar + step, step, 0, 64 }); // alone in the second bar: wraps inside that bar
  3145. ne::rotate (r, { 2 }, step, bar, -2);
  3146. CHECK (r.notes[2].start == 2 * bar - step);
  3147. }
  3148. TEST (note_edit_grid_and_time_text)
  3149. {
  3150. namespace ne = lynx::noteedit;
  3151. const std::int64_t step = lynx::ticksPerStep, bar = lynx::ppq * 4;
  3152. CHECK (ne::snapDown (250.0, step) == step && ne::snapDown (-1.0, step) == -step && ne::snapDown (17.9, 1) == 17);
  3153. CHECK (ne::snapNearest (1000.0, { 400, 1100, 980 }, 50.0, step) == 980);
  3154. CHECK (ne::snapNearest (1000.0, { 400 }, 50.0, step) == 960); // too far: falls back to the grid
  3155. // screen grid: 24 px per step shows steps; zoomed out it climbs to beats, bars and bar multiples
  3156. CHECK (ne::screenStep (24.0 / step, bar) == step);
  3157. CHECK (ne::screenStep (96.0 / bar, bar) == lynx::ppq);
  3158. CHECK (ne::screenStep (8.0 / bar, bar) == 2 * bar);
  3159. CHECK (ne::screenStep (200.0 / step, bar) == step / 4);
  3160. CHECK (ne::formatTime (0, 4) == "1:1:0" && ne::formatTime (bar + 5 * step + 7, 4) == "2:6:7");
  3161. CHECK (ne::formatTime (step * 2, 4, true) == "0:2:0");
  3162. std::int64_t t = 0;
  3163. CHECK (ne::parseTime ("2:6:7", 4, t) && t == bar + 5 * step + 7);
  3164. CHECK (ne::parseTime ("3", 4, t) && t == 2 * bar);
  3165. CHECK (ne::parseTime ("0:2:0", 4, t, true) && t == 2 * step);
  3166. CHECK (! ne::parseTime ("0:1:0", 4, t) && ! ne::parseTime ("1:17:0", 4, t) && ! ne::parseTime ("1:1:240", 4, t)
  3167. && ! ne::parseTime ("a", 4, t) && ! ne::parseTime ("", 4, t));
  3168. CHECK (ne::parseTime ("1:12:0", 3, t) && ! ne::parseTime ("1:13:0", 3, t)); // 3/4: 12 steps per bar
  3169. }
  3170. TEST (playlist_clip_edges_and_time_selection)
  3171. {
  3172. namespace ne = lynx::noteedit;
  3173. const std::int64_t beat = lynx::ppq;
  3174. // left-edge trim: content stays in place, cannot reveal what is before the content's start
  3175. lynx::Clip c { 0, 0, 4 * beat, 4 * beat, beat };
  3176. ne::trimStart (c, 5 * beat, beat);
  3177. CHECK (c.start == 5 * beat && c.offset == 2 * beat && c.length == 3 * beat);
  3178. ne::trimStart (c, 0, beat);
  3179. CHECK (c.start == 3 * beat && c.offset == 0 && c.length == 5 * beat);
  3180. ne::trimStart (c, 100 * beat, beat);
  3181. CHECK (c.length == beat && c.end() == 8 * beat);
  3182. // slip moves the content, not the clip
  3183. lynx::Clip s { 0, 0, 0, 2 * beat, beat };
  3184. ne::slip (s, beat / 2);
  3185. CHECK (s.offset == beat / 2 && s.start == 0 && s.length == 2 * beat);
  3186. ne::slip (s, beat);
  3187. CHECK (s.offset == 0);
  3188. ne::slip (s, -3 * beat);
  3189. CHECK (s.offset == 3 * beat);
  3190. // insert / delete time across all tracks, markers included
  3191. std::vector<lynx::Clip> clips { { 0, 0, 0, 2 * beat, 0 }, { 0, 1, 4 * beat, 2 * beat, 0 }, { 0, 2, beat, 6 * beat, 0 } };
  3192. std::vector<lynx::Marker> markers { { 5 * beat, "A" }, { beat / 2, "B" } };
  3193. ne::insertTime (clips, markers, 2 * beat, 4 * beat);
  3194. CHECK (clips[0].start == 0 && clips[1].start == 8 * beat && clips[2].start == beat && markers[0].tick == 9 * beat
  3195. && markers[1].tick == beat / 2);
  3196. std::vector<lynx::Clip> d { { 0, 0, 0, 2 * beat, 0 }, // before: kept
  3197. { 0, 1, 3 * beat, beat, 0 }, // inside: deleted
  3198. { 0, 2, beat, 6 * beat, 0 }, // spans the cut: head + tail
  3199. { 0, 3, 3 * beat, 4 * beat, 0 }, // tail outside: trimmed and moved
  3200. { 0, 4, 8 * beat, beat, 0 } }; // after: moved left
  3201. std::vector<lynx::Marker> dm { { 3 * beat, "in" }, { 9 * beat, "after" } };
  3202. ne::deleteTime (d, dm, 2 * beat, 5 * beat);
  3203. CHECK (d.size() == 5);
  3204. CHECK (d[1].track == 2 && d[1].start == beat && d[1].length == beat);
  3205. CHECK (d[2].track == 2 && d[2].start == 2 * beat && d[2].offset == 4 * beat && d[2].length == 2 * beat);
  3206. CHECK (d[3].track == 3 && d[3].start == 2 * beat && d[3].offset == 2 * beat && d[3].length == 2 * beat);
  3207. CHECK (d[4].start == 5 * beat && dm.size() == 1 && dm[0].tick == 6 * beat);
  3208. // time selection: overlapping clips; Ctrl+B repeats what starts inside it after itself
  3209. std::vector<lynx::Clip> r { { 0, 0, 0, beat, 0 }, { 0, 1, beat, 2 * beat, 0 }, { 0, 0, 4 * beat, beat, 0 } };
  3210. CHECK ((ne::clipsInTime (r, beat / 2, 2 * beat) == std::vector<int> { 0, 1 }));
  3211. const auto added = ne::repeatTime (r, 0, 4 * beat, {});
  3212. CHECK (added.size() == 2 && r[3].start == 4 * beat && r[4].start == 5 * beat && r[4].track == 1);
  3213. CHECK (ne::repeatTime (r, 0, 2 * beat, { 2 }).size() == 1 && r.back().start == 6 * beat);
  3214. }
  3215. TEST (recorder_builds_notes_in_pattern_and_song_mode)
  3216. {
  3217. auto song = lynx::Song::makeDefault();
  3218. const auto loop = song.patterns[0].effectiveLength (4); // 1 bar = 3840
  3219. lynx::NoteRecorder r;
  3220. r.add (song, { 100.0, 4, 60, 0.5f, true }); // no take: ignored
  3221. CHECK (r.takeFinished().empty());
  3222. r.begin (loop);
  3223. r.add (song, { 4000.0, 4, 60, 0.5f, true }); // second loop pass
  3224. r.add (song, { 4480.0, 4, 60, 0.0f, false });
  3225. r.add (song, { 5000.0, 4, 64, 0.9f, true }); // held until stop
  3226. r.end (song, 5240.0);
  3227. const auto notes = r.takeFinished();
  3228. CHECK (notes.size() == 2);
  3229. CHECK (notes[0].start == 4000 - 3840 && notes[0].length == 480 && notes[0].velocity == 0.5f && notes[0].channel == 4);
  3230. CHECK (notes[1].key == 64 && notes[1].start == 5000 - 3840 && notes[1].length == 240);
  3231. // song mode: position inside the current pattern's clip (with offset)
  3232. song.mode = lynx::PlayMode::song;
  3233. song.playlist = { { 0, 0, 7680, 3840, 960 } };
  3234. CHECK (lynx::patternPositionForTick (song, 7680.0 + 100.0, loop) == 1060);
  3235. CHECK (lynx::patternPositionForTick (song, 100.0, loop) == 100); // outside the clip: like loop
  3236. }
  3237. TEST (automation_curve_and_playback)
  3238. {
  3239. lynx::Automation a;
  3240. a.points = { { 0, 0.0f }, { 960, 1.0f }, { 1920, 0.5f, 0.0f } };
  3241. CHECK (a.valueAt (-10.0) == 0.0f && a.valueAt (480.0) == 0.5f && a.valueAt (5000.0) == 0.5f);
  3242. CHECK (a.length() == 1920);
  3243. a.points[0].tension = 1.0f; // curve: starts slow
  3244. CHECK (a.valueAt (480.0) < 0.2f && a.valueAt (480.0) > 0.0f);
  3245. // automated Master: silence in the first bar, sound in the second, and the last value
  3246. // keeps applying after the automation clip ends
  3247. auto song = lynx::Song::makeDefault();
  3248. song.bpm = 120.0;
  3249. song.mode = lynx::PlayMode::song;
  3250. const auto bar = (std::int64_t) lynx::ppq * 4;
  3251. for (int b = 0; b < 3; ++b)
  3252. song.playlist.push_back ({ 0, 0, bar * b, bar, 0 });
  3253. lynx::Automation master;
  3254. master.target = { lynx::AutomationTargetKind::mixerVolume, 0 };
  3255. master.points = { { 0, 0.0f }, { bar - 1, 0.0f }, { bar, 0.8f } };
  3256. song.automations.push_back (master);
  3257. lynx::Clip ac;
  3258. ac.kind = lynx::ClipKind::automation;
  3259. ac.automation = 0;
  3260. ac.track = 1;
  3261. ac.length = bar + bar / 2;
  3262. song.playlist.push_back (ac);
  3263. const double sr = 48000.0;
  3264. auto state = lynx::RackState::build (song, nullptr, sr);
  3265. CHECK (state->hasAutomation && state->mixerVolumeAuto[0] == 0 && state->automationClips[0].size() == 1);
  3266. lynx::RackRenderer r;
  3267. r.prepare (sr, 512);
  3268. std::vector<float> l (512), rr (512);
  3269. const auto tps = lynx::ticksPerSample (song.bpm, sr);
  3270. float peakBar1 = 0.0f, peakBar2 = 0.0f, peakBar3 = 0.0f;
  3271. for (double tick = 0.0; tick < (double) (bar * 3); tick += 512 * tps)
  3272. {
  3273. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  3274. auto& peak = tick < (double) bar - 512 * tps ? peakBar1 : tick < (double) bar * 2 ? peakBar2 : peakBar3;
  3275. for (auto v : l)
  3276. peak = std::max (peak, std::abs (v));
  3277. }
  3278. CHECK (peakBar1 < 1.0e-6f);
  3279. CHECK (peakBar2 > 0.05f);
  3280. CHECK (peakBar3 > 0.05f); // after the clip: keeps the last value
  3281. // target removed: automation disappears from the tables
  3282. song.removeChannel (0);
  3283. song.automations[0].target = { lynx::AutomationTargetKind::channelVolume, 0 };
  3284. song.removeChannel (0);
  3285. CHECK (song.automations[0].target.kind == lynx::AutomationTargetKind::none);
  3286. song.removeAutomation (0);
  3287. CHECK (song.automations.empty() && song.playlist.size() == 3);
  3288. }
  3289. TEST (mixer_sends_between_inserts)
  3290. {
  3291. // insert 1 goes only to 3; 3 goes to the Master: same sum (0.5 + 0.5)
  3292. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.setRoute (1, 3, true); s.setRoute (1, 0, false); }) - 1.0f) < 1e-4f);
  3293. // send at 50% and muted destination
  3294. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.setRoute (1, 3, true, 0.5f); s.setRoute (1, 0, false); }) - 0.75f) < 1e-4f);
  3295. 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);
  3296. // going to the Master and to 3: the signal doubles
  3297. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.setRoute (1, 3, true); }) - 1.5f) < 1e-4f);
  3298. // solo on 3 lets what reaches it sound (insert 1), but not 2
  3299. 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);
  3300. // solo on 1 lets the path to the Master (3) sound
  3301. 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);
  3302. // order and cycles
  3303. auto song = lynx::Song::makeDefault();
  3304. song.setRoute (4, 2, true);
  3305. song.setRoute (2, 1, true);
  3306. CHECK (! song.canRoute (1, 4) && ! song.canRoute (1, 2) && song.canRoute (1, 5));
  3307. song.setRoute (1, 4, true); // ignored: would create a cycle
  3308. CHECK (! song.routes (1, 4));
  3309. const auto order = song.mixerOrder();
  3310. const auto pos = [&] (int t) { return std::find (order.begin(), order.end(), t) - order.begin(); };
  3311. CHECK ((int) order.size() == (int) song.mixer.size() - 1);
  3312. CHECK (pos (4) < pos (2) && pos (2) < pos (1));
  3313. song.setRoute (4, 2, false);
  3314. CHECK (! song.routes (4, 2) && song.routes (4, 0));
  3315. }
  3316. namespace
  3317. {
  3318. // Test effect: delays the signal by `latency` samples and reports that latency (like a lookahead plugin).
  3319. class LatentEffect final : public lynx::Effect
  3320. {
  3321. public:
  3322. explicit LatentEffect (int samples) : latency (samples), line (samples) {}
  3323. void prepare (double) noexcept override {}
  3324. void reset() noexcept override {}
  3325. void process (float* l, float* r, int n, const lynx::EffectParams&, double) noexcept override { line.process (l, r, n); }
  3326. int latencySamples() const noexcept override { return latency; }
  3327. private:
  3328. int latency;
  3329. lynx::DelayLine line;
  3330. };
  3331. } // namespace
  3332. TEST (delay_line_mix_into_matches_process_and_drains_tail)
  3333. {
  3334. // mixInto = process over source*level, added to the destination; in stretches that cross the ring
  3335. lynx::DelayLine a (37), b (37);
  3336. std::vector<float> sl (300), sr (300), dl (300, 0.5f), dr (300, -0.5f), xl (300), xr (300);
  3337. for (int i = 0; i < 300; ++i)
  3338. {
  3339. sl[(std::size_t) i] = (float) std::sin (i * 0.1);
  3340. sr[(std::size_t) i] = (float) std::cos (i * 0.07);
  3341. }
  3342. for (int start = 0; start < 300; start += 100)
  3343. {
  3344. b.mixInto (sl.data() + start, sr.data() + start, 0.25f, dl.data() + start, dr.data() + start, 100);
  3345. for (int i = start; i < start + 100; ++i)
  3346. {
  3347. xl[(std::size_t) i] = sl[(std::size_t) i] * 0.25f;
  3348. xr[(std::size_t) i] = sr[(std::size_t) i] * 0.25f;
  3349. }
  3350. a.process (xl.data() + start, xr.data() + start, 100);
  3351. }
  3352. float worst = 0.0f;
  3353. for (int i = 0; i < 300; ++i)
  3354. worst = std::max ({ worst, std::abs (dl[(std::size_t) i] - 0.5f - xl[(std::size_t) i]),
  3355. std::abs (dr[(std::size_t) i] + 0.5f - xr[(std::size_t) i]) });
  3356. CHECK (worst < 1e-6f);
  3357. // silenced source: the tail still in the line comes out, then nothing remains
  3358. std::vector<float> tl (64, 0.0f), tr (64, 0.0f);
  3359. b.mixInto (nullptr, nullptr, 1.0f, tl.data(), tr.data(), 64);
  3360. CHECK (std::abs (tl[0] - sl[263] * 0.25f) < 1e-6f);
  3361. std::vector<float> zl (64, 0.0f), zr (64, 0.0f);
  3362. b.mixInto (nullptr, nullptr, 1.0f, zl.data(), zr.data(), 64);
  3363. CHECK (*std::max_element (zl.begin(), zl.end()) == 0.0f && *std::min_element (zl.begin(), zl.end()) == 0.0f);
  3364. }
  3365. TEST (limiter_lookahead_holds_ceiling_on_bursts)
  3366. {
  3367. // short bursts over a low floor: the sliding maximum must see each peak before it leaves
  3368. auto fx = lynx::makeEffect (lynx::EffectKind::limiter);
  3369. fx->prepare (48000.0);
  3370. auto slot = lynx::makeEffectSlot (lynx::EffectKind::limiter);
  3371. slot.params[2] = 0.0f; // 10 ms release
  3372. std::vector<float> l (48000), r (48000);
  3373. std::uint32_t seed = 1;
  3374. for (int i = 0; i < 48000; ++i)
  3375. {
  3376. seed = seed * 1664525u + 1013904223u;
  3377. const auto noise = ((float) (seed >> 8) / 16777216.0f - 0.5f) * 0.1f;
  3378. l[(std::size_t) i] = noise + ((i % 9973) < 3 ? 3.0f : 0.0f);
  3379. r[(std::size_t) i] = -noise;
  3380. }
  3381. for (int i = 0; i < 48000; i += 333)
  3382. fx->process (l.data() + i, r.data() + i, std::min (333, 48000 - i), slot.params, 120.0);
  3383. float peak = 0.0f, quiet = 0.0f;
  3384. for (int i = 0; i < 48000; ++i)
  3385. peak = std::max (peak, std::abs (l[(std::size_t) i]));
  3386. for (int i = 9973 * 2 + 2000; i < 9973 * 2 + 2400; ++i) // 40 ms after the burst the gain has already recovered
  3387. quiet = std::max (quiet, std::abs (r[(std::size_t) i]));
  3388. const auto ceiling = 1.0f; // the default ceiling is at 0 dBFS or below
  3389. CHECK (peak <= ceiling + 1e-5f);
  3390. CHECK (quiet > 0.03f);
  3391. }
  3392. TEST (pdc_aligns_paths_through_latent_effects)
  3393. {
  3394. // plan: channel 0 -> insert 1 (effect of 100) -> insert 3; channel 1 -> insert 2 -> Master
  3395. lynx::Song s;
  3396. s.mixer = lynx::Song::defaultMixer (4);
  3397. s.channels.resize (3);
  3398. s.channels[0].mixerTrack = 1;
  3399. s.channels[1].mixerTrack = 2;
  3400. s.channels[2].mixerTrack = 3;
  3401. s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::eq));
  3402. s.setRoute (1, 3, true);
  3403. s.setRoute (1, 0, false);
  3404. auto plan = lynx::computePdc (s, { 0, 0, 30 }, { {}, { 100 } });
  3405. CHECK (plan.inAlign[1] == 0 && plan.outLat[1] == 100);
  3406. CHECK (plan.inAlign[3] == 100 && plan.channelDelay[2] == 70); // instrument of 30 on insert 3
  3407. CHECK (plan.sendDelay[1][1] == 0); // the slowest path isn't delayed
  3408. CHECK (plan.sendDelay[2][0] == 100 && plan.sendDelay[3][0] == 0 && plan.total == 100);
  3409. // bypass zeroes the slot's latency
  3410. s.mixer[1].effects[0].enabled = false;
  3411. CHECK (lynx::computePdc (s, { 0, 0, 30 }, { {}, { 100 } }).total == 30);
  3412. // rendered: two impulses played together come out together
  3413. lynx::Song r;
  3414. r.mixer = lynx::Song::defaultMixer (2);
  3415. for (int i = 0; i < 2; ++i)
  3416. {
  3417. lynx::ChannelDef c;
  3418. c.instrument = lynx::InstrumentKind::sampler;
  3419. c.samplePath = "impulso";
  3420. c.volume = 1.0f;
  3421. c.mixerTrack = i + 1;
  3422. r.channels.push_back (c);
  3423. }
  3424. r.patterns.emplace_back();
  3425. lynx::EffectSlot fx;
  3426. fx.kind = lynx::EffectKind::plugin;
  3427. fx.plugin.id = "latente";
  3428. r.mixer[1].effects.push_back (fx);
  3429. lynx::RackState::Factories f;
  3430. f.samples = [] (const std::string&) {
  3431. auto d = std::make_shared<lynx::SampleData>();
  3432. d->left.assign (64, 0.0f);
  3433. d->left[0] = 1.0f;
  3434. return std::shared_ptr<const lynx::SampleData> (d);
  3435. };
  3436. f.pluginEffects = [] (const lynx::PluginRef&, double) -> std::shared_ptr<lynx::Effect> { return std::make_shared<LatentEffect> (100); };
  3437. auto state = lynx::RackState::build (r, nullptr, 48000.0, f);
  3438. CHECK (state->pdc.total == 100 && state->sendDelays[2][0] != nullptr && state->sendDelays[2][0]->length() == 100);
  3439. lynx::RackRenderer renderer;
  3440. renderer.prepare (48000.0, 256);
  3441. lynx::LiveEventQueue live;
  3442. for (int ch = 0; ch < 2; ++ch)
  3443. {
  3444. lynx::NoteEvent on;
  3445. on.channel = ch;
  3446. on.key = 60;
  3447. on.velocity = 1.0f;
  3448. live.push (on);
  3449. }
  3450. std::vector<float> l (256), rr (256);
  3451. renderer.process (state.get(), false, 0.0, 256, l.data(), rr.data(), &live);
  3452. int first = -1;
  3453. for (int i = 0; i < 256 && first < 0; ++i)
  3454. if (std::abs (l[(std::size_t) i]) > 0.01f)
  3455. first = i;
  3456. CHECK (first == 100 && std::abs (l[100] - 2.0f) < 1e-3f); // both impulses arrive together, summed
  3457. // editing without changing latencies reuses the lines
  3458. r.channels[0].volume = 0.5f;
  3459. auto next = lynx::RackState::build (r, state.get(), 48000.0, f);
  3460. CHECK (next->sendDelays[2][0] == state->sendDelays[2][0]);
  3461. }
  3462. TEST (mixer_mute_fades_instead_of_clicking)
  3463. {
  3464. lynx::Song s;
  3465. s.mixer = lynx::Song::defaultMixer (2);
  3466. lynx::ChannelDef c;
  3467. c.instrument = lynx::InstrumentKind::sampler;
  3468. c.samplePath = "dc";
  3469. c.volume = 1.0f;
  3470. c.mixerTrack = 1;
  3471. s.channels.push_back (c);
  3472. s.patterns.emplace_back();
  3473. auto provider = [] (const std::string&) {
  3474. auto d = std::make_shared<lynx::SampleData>();
  3475. d->left.assign (48000, 0.5f);
  3476. return std::shared_ptr<const lynx::SampleData> (d);
  3477. };
  3478. auto on = lynx::RackState::build (s, nullptr, 48000.0, provider);
  3479. s.mixer[1].muted = true;
  3480. auto off = lynx::RackState::build (s, on.get(), 48000.0, provider);
  3481. lynx::RackRenderer r;
  3482. r.prepare (48000.0, 256);
  3483. lynx::LiveEventQueue live;
  3484. lynx::NoteEvent note;
  3485. note.velocity = 1.0f;
  3486. live.push (note);
  3487. std::vector<float> l (256), rr (256);
  3488. r.process (on.get(), false, 0.0, 256, l.data(), rr.data(), &live);
  3489. CHECK (std::abs (l[255] - 0.5f) < 1e-3f);
  3490. r.process (off.get(), false, 0.0, 256, l.data(), rr.data());
  3491. CHECK (l[0] > 0.45f && l[128] > 0.2f && l[128] < 0.3f && std::abs (l[255]) < 1e-6f); // ramp down to zero
  3492. r.process (off.get(), false, 0.0, 256, l.data(), rr.data());
  3493. CHECK (std::abs (l[0]) < 1e-9f);
  3494. }
  3495. TEST (dither_quantizes_to_lsb_grid_with_small_error)
  3496. {
  3497. lynx::Dither d (16);
  3498. std::vector<float> x (4800);
  3499. for (std::size_t i = 0; i < x.size(); ++i)
  3500. x[i] = 0.25f * std::sin ((float) i * 0.05f);
  3501. auto y = x;
  3502. d.process (y.data(), (int) y.size(), 0);
  3503. double errorSum = 0.0;
  3504. bool onGrid = true;
  3505. for (std::size_t i = 0; i < x.size(); ++i)
  3506. {
  3507. const auto steps = y[i] * 32768.0f;
  3508. onGrid = onGrid && std::abs (steps - std::round (steps)) < 1e-3f;
  3509. errorSum += std::abs (y[i] - x[i]);
  3510. }
  3511. CHECK (onGrid);
  3512. CHECK (errorSum / (double) x.size() < 4.0 / 32768.0); // a few LSBs of noise on average
  3513. }
  3514. TEST (parallel_rendering_matches_sequential)
  3515. {
  3516. // 32 channels (worth parallelizing), inserts with chained sends
  3517. auto song = lynx::Song::makeDefault();
  3518. song.mixer = lynx::Song::defaultMixer (16);
  3519. for (int i = 5; i < 32; ++i)
  3520. {
  3521. lynx::ChannelDef c;
  3522. c.instrument = i % 2 ? lynx::InstrumentKind::synth : lynx::InstrumentKind::hat;
  3523. c.mixerTrack = 1 + i % 12;
  3524. c.volume = 0.3f;
  3525. song.channels.push_back (c);
  3526. for (int step = i % 4; step < 16; step += 3)
  3527. song.patterns[0].notes.push_back ({ (std::int64_t) step * lynx::ticksPerStep, 200, i, 48 + i, 0.7f });
  3528. }
  3529. song.patterns[0].sortNotes();
  3530. song.setRoute (3, 7, true, 0.6f);
  3531. song.setRoute (7, 9, true, 0.5f);
  3532. song.setRoute (2, 9, true);
  3533. song.mixer[9].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::reverb));
  3534. auto seqState = lynx::RackState::build (song, nullptr, 48000.0);
  3535. auto parState = lynx::RackState::build (song, nullptr, 48000.0);
  3536. CHECK (parState->parallel && parState->mixerLayers.size() == 3);
  3537. lynx::WorkerPool pool (3);
  3538. lynx::RackRenderer seq, par;
  3539. seq.prepare (48000.0, 512);
  3540. par.prepare (48000.0, 512);
  3541. par.setWorkerPool (&pool);
  3542. std::vector<float> l1 (512), r1 (512), l2 (512), r2 (512);
  3543. const auto tps = lynx::ticksPerSample (song.bpm, 48000.0);
  3544. bool same = true;
  3545. float peak = 0.0f;
  3546. for (int block = 0; block < 200; ++block)
  3547. {
  3548. seq.process (seqState.get(), true, block * 512 * tps, 512, l1.data(), r1.data());
  3549. par.process (parState.get(), true, block * 512 * tps, 512, l2.data(), r2.data());
  3550. same = same && l1 == l2 && r1 == r2;
  3551. for (auto v : l1)
  3552. peak = std::max (peak, std::abs (v));
  3553. }
  3554. CHECK (same);
  3555. CHECK (peak > 0.05f);
  3556. // the pool handles many small rounds in a row
  3557. std::atomic<int> sum { 0 };
  3558. auto add = [&sum] (int i) { sum.fetch_add (i + 1); };
  3559. for (int round = 0; round < 2000; ++round)
  3560. pool.parallelFor (5, add);
  3561. CHECK (sum.load() == 2000 * 15);
  3562. }
  3563. TEST (arrangements_switch_and_keep_clip_indices)
  3564. {
  3565. auto s = lynx::Song::makeDefault();
  3566. s.patterns.emplace_back().name = "B";
  3567. s.playlist = { { 1, 0, 0, 960, 0 } };
  3568. s.loopEnd = 960;
  3569. CHECK (s.arrangements.size() == 1 && s.currentArrangement == 0);
  3570. const auto second = s.addArrangement ("Versão curta", true);
  3571. CHECK (second == 1 && s.currentArrangement == 1 && s.playlist.size() == 1 && s.loopEnd == 960);
  3572. s.playlist.push_back ({ 0, 1, 960, 960, 0 });
  3573. s.loopEnd = 0;
  3574. s.selectArrangement (0);
  3575. CHECK (s.playlist.size() == 1 && s.loopEnd == 960 && s.arrangements[1].clips.size() == 2);
  3576. // removing pattern 0 fixes the clips stored in the other arrangement
  3577. s.removePattern (0);
  3578. CHECK (s.playlist.size() == 1 && s.playlist[0].pattern == 0);
  3579. CHECK (s.arrangements[1].clips.size() == 1 && s.arrangements[1].clips[0].pattern == 0);
  3580. s.removeArrangement (0);
  3581. CHECK (s.arrangements.size() == 1 && s.currentArrangement == 0 && s.playlist.size() == 1 && s.loopEnd == 0);
  3582. }
  3583. namespace
  3584. {
  3585. // Test effect that inverts the signal and counts how many times it processed.
  3586. class CountingInverter final : public lynx::Effect
  3587. {
  3588. public:
  3589. void prepare (double) noexcept override {}
  3590. void reset() noexcept override {}
  3591. void process (float* l, float* r, int n, const lynx::EffectParams&, double) noexcept override
  3592. {
  3593. ++calls;
  3594. for (int i = 0; i < n; ++i)
  3595. {
  3596. l[i] = -l[i];
  3597. r[i] = -r[i];
  3598. }
  3599. }
  3600. int calls = 0;
  3601. };
  3602. } // namespace
  3603. TEST (keyboard_controller_outputs_key_value)
  3604. {
  3605. std::vector<std::uint8_t> blob (554, 0);
  3606. const std::uint32_t version = 3;
  3607. std::memcpy (blob.data(), &version, 4);
  3608. const float key60 = 0.7f, off = 0.2f;
  3609. std::memcpy (blob.data() + 12 + 60 * 4, &key60, 4);
  3610. std::memcpy (blob.data() + 548, &off, 4);
  3611. blob[552] = 1; // auto release
  3612. lynx::ChannelDef c;
  3613. c.instrument = lynx::InstrumentKind::controller;
  3614. c.controllerState = blob;
  3615. auto inst = lynx::makeInstrument (lynx::InstrumentKind::controller);
  3616. inst->prepare (48000.0);
  3617. inst->configure (c, 120.0);
  3618. std::vector<float> l (64), r (64);
  3619. inst->noteOn (60, 1.0f);
  3620. inst->render (l.data(), r.data(), 64, 1.0f, 1.0f);
  3621. CHECK (std::abs (inst->controlOutput (0) - 0.7f) < 1e-6f);
  3622. inst->noteOff (60);
  3623. CHECK (std::abs (inst->controlOutput (0) - 0.2f) < 1e-6f);
  3624. }
  3625. TEST (envelope_controller_ducks_on_each_note)
  3626. {
  3627. // a unipolar articulator like "Basic Sidechain": base 0.05, drops to 0 on the note and rises to 1 in 0.3 s
  3628. lynx::ControllerArticulator a;
  3629. a.envOn = true;
  3630. a.base = 0.05f;
  3631. a.envLevel = 1.0f;
  3632. a.count = 3;
  3633. a.time = { 0.0f, 0.2f, 0.3f };
  3634. a.level = { 0.0f, 0.75f, 1.0f };
  3635. CHECK (std::abs (lynx::controllerValue (a, 0.0, -1.0) - 0.05f) < 1e-4f);
  3636. CHECK (std::abs (lynx::controllerValue (a, 0.1, -1.0) - 0.425f) < 1e-3f);
  3637. CHECK (lynx::controllerValue (a, 1.0, -1.0) > 0.99f); // no sustain: runs to the end and stays
  3638. a.sustain = 1;
  3639. CHECK (std::abs (lynx::controllerValue (a, 1.0, -1.0) - 0.8f) < 1e-3f); // held at sustain
  3640. CHECK (lynx::controllerValue (a, 1.0, 0.5) > 0.99f); // released: continues to the end
  3641. a.bipolar = true;
  3642. a.base = 0.5f;
  3643. a.sustain = -1;
  3644. CHECK (std::abs (lynx::controllerValue (a, 0.0, -1.0) - 0.0f) < 1e-4f); // bipolar: 0.5 + (0 − 0.5)
  3645. }
  3646. TEST (peak_controller_drives_live_automation)
  3647. {
  3648. // track 1: source (DC 0.5) with Peak Controller; track 2: DC 0.5 with volume linked to the controller
  3649. auto render = [] (bool linked) {
  3650. lynx::Song s;
  3651. s.mixer = lynx::Song::defaultMixer (2);
  3652. for (int t = 1; t <= 2; ++t)
  3653. {
  3654. lynx::ChannelDef c;
  3655. c.instrument = lynx::InstrumentKind::sampler;
  3656. c.samplePath = "dc";
  3657. c.volume = 1.0f;
  3658. c.mixerTrack = t;
  3659. s.channels.push_back (c);
  3660. }
  3661. s.patterns.emplace_back();
  3662. auto peak = lynx::makeEffectSlot (lynx::EffectKind::peakController);
  3663. peak.params[0] = 1.0f; // base 1
  3664. peak.params[1] = 0.0f; // amount −1: 1 − peak
  3665. peak.params[2] = 0.5f; // no tension
  3666. s.mixer[1].effects.push_back (peak);
  3667. if (linked)
  3668. {
  3669. lynx::Automation a;
  3670. a.name = "Peak";
  3671. a.target = { lynx::AutomationTargetKind::mixerVolume, 2 };
  3672. a.source = { 1, 0, 0 };
  3673. s.automations.push_back (a);
  3674. }
  3675. lynx::RackState::Factories f;
  3676. f.samples = [] (const std::string&) {
  3677. auto d = std::make_shared<lynx::SampleData>();
  3678. d->left.assign (48000, 0.5f);
  3679. return std::shared_ptr<const lynx::SampleData> (d);
  3680. };
  3681. auto state = lynx::RackState::build (s, nullptr, 48000.0, f);
  3682. lynx::RackRenderer r;
  3683. r.prepare (48000.0, 512);
  3684. lynx::LiveEventQueue live;
  3685. for (int ch = 0; ch < 2; ++ch)
  3686. {
  3687. lynx::NoteEvent on;
  3688. on.channel = ch;
  3689. on.velocity = 1.0f;
  3690. live.push (on);
  3691. }
  3692. std::vector<float> l (4800), rr (4800);
  3693. r.process (state.get(), false, 0.0, 4800, l.data(), rr.data(), &live);
  3694. return l[4000];
  3695. };
  3696. const auto free = render (false), ducked = render (true);
  3697. CHECK (std::isfinite (ducked) && ducked > 0.0f);
  3698. CHECK (ducked < free - 0.05f); // the 0.5 peak on track 1 lowers track 2's volume
  3699. }
  3700. TEST (effect_slot_dry_wet_and_smart_disable)
  3701. {
  3702. lynx::Song s;
  3703. s.mixer = lynx::Song::defaultMixer (1);
  3704. lynx::ChannelDef c;
  3705. c.instrument = lynx::InstrumentKind::sampler;
  3706. c.samplePath = "dc";
  3707. c.volume = 1.0f;
  3708. c.mixerTrack = 1;
  3709. s.channels.push_back (c);
  3710. s.patterns.emplace_back();
  3711. lynx::EffectSlot fx;
  3712. fx.kind = lynx::EffectKind::plugin;
  3713. fx.plugin.id = "inversor";
  3714. fx.mix = 0.25f; // 75% dry (+0.5) and 25% wet (-0.5) = +0.25
  3715. s.mixer[1].effects.push_back (fx);
  3716. auto inverter = std::make_shared<CountingInverter>();
  3717. lynx::RackState::Factories f;
  3718. f.samples = [] (const std::string&) {
  3719. auto d = std::make_shared<lynx::SampleData>();
  3720. d->left.assign (4800, 0.5f);
  3721. return std::shared_ptr<const lynx::SampleData> (d);
  3722. };
  3723. f.pluginEffects = [inverter] (const lynx::PluginRef&, double) -> std::shared_ptr<lynx::Effect> { return inverter; };
  3724. auto state = lynx::RackState::build (s, nullptr, 48000.0, f);
  3725. lynx::RackRenderer r;
  3726. r.prepare (48000.0, 512);
  3727. lynx::LiveEventQueue live;
  3728. lynx::NoteEvent on;
  3729. on.velocity = 1.0f;
  3730. live.push (on);
  3731. std::vector<float> l (480), rr (480);
  3732. r.process (state.get(), false, 0.0, 480, l.data(), rr.data(), &live);
  3733. CHECK (std::abs (l[100] - 0.25f) < 1e-4f);
  3734. // after the sample ends: 4 s of silence and the plugin stops being called
  3735. for (int i = 0; i < 100 * 6; ++i) // 6 s
  3736. r.process (state.get(), false, 0.0, 480, l.data(), rr.data());
  3737. const auto callsAfterSilence = inverter->calls;
  3738. for (int i = 0; i < 100; ++i)
  3739. r.process (state.get(), false, 0.0, 480, l.data(), rr.data());
  3740. CHECK (inverter->calls == callsAfterSilence);
  3741. CHECK (callsAfterSilence < 100 * 6);
  3742. // sound again: processing resumes in the same block
  3743. live.push (on);
  3744. r.process (state.get(), false, 0.0, 480, l.data(), rr.data(), &live);
  3745. CHECK (inverter->calls == callsAfterSilence + 1 && std::abs (l[100] - 0.25f) < 1e-4f);
  3746. }
  3747. TEST (swing_delays_offbeat_sixteenths)
  3748. {
  3749. CHECK (lynx::swingDelay (0, 1.0f) == 0);
  3750. CHECK (lynx::swingDelay (lynx::ticksPerStep, 1.0f) == lynx::ticksPerStep / 2);
  3751. CHECK (lynx::swingDelay (lynx::ticksPerStep * 2, 1.0f) == 0);
  3752. CHECK (lynx::swingDelay (lynx::ticksPerStep + 10, 1.0f) == (lynx::ticksPerStep - 20) / 2); // off the grid: triangular weight (FL)
  3753. CHECK (lynx::swingDelay (lynx::ticksPerStep, 1.0f, 0.5f) == lynx::ticksPerStep / 4); // channel mix
  3754. CHECK (lynx::swingDelay (lynx::ticksPerStep * 3, 0.5f) == lynx::ticksPerStep / 4);
  3755. lynx::Pattern p;
  3756. p.notes = { { 0, 100, 0, 60 }, { lynx::ticksPerStep, 100, 0, 62 } };
  3757. lynx::EventBuffer ev;
  3758. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  3759. lynx::schedulePatternLoop (p, p.effectiveLength (4), 0.0, 12000, tps, ev, 1.0f);
  3760. int onOffset = -1;
  3761. for (auto& e : ev)
  3762. if (e.type == lynx::NoteEvent::Type::on && e.key == 62)
  3763. onOffset = e.sampleOffset;
  3764. CHECK (onOffset == (int) std::floor ((lynx::ticksPerStep * 1.5) / tps));
  3765. }
  3766. TEST (sampler_settings_pitch_reverse_envelope_cut)
  3767. {
  3768. auto ramp = std::make_shared<lynx::SampleData>();
  3769. for (int i = 0; i < 48000; ++i)
  3770. ramp->left.push_back ((float) i / 48000.0f); // ramp: the value tells where the read position is
  3771. ramp->sampleRate = 48000.0;
  3772. auto play = [&] (const lynx::SamplerSettings& s, int key, int frames, bool releaseAfterHalf) {
  3773. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  3774. inst->prepare (48000.0);
  3775. lynx::ChannelDef c;
  3776. c.sampler = s;
  3777. inst->configure (c, 120.0);
  3778. inst->noteOn (key, 1.0f);
  3779. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  3780. inst->render (l.data(), r.data(), frames / 2, 1.0f, 1.0f);
  3781. if (releaseAfterHalf)
  3782. inst->noteOff (key);
  3783. inst->render (l.data() + frames / 2, r.data() + frames / 2, frames - frames / 2, 1.0f, 1.0f);
  3784. return l;
  3785. };
  3786. // +12 semitones: reads twice as fast
  3787. lynx::SamplerSettings up;
  3788. up.pitch = 12.0f;
  3789. CHECK (std::abs (play (up, 60, 1000, false)[999] - 2.0f * 999.0f / 48000.0f) < 1e-3f);
  3790. // reversed: starts from the end
  3791. lynx::SamplerSettings back;
  3792. back.reverse = true;
  3793. CHECK (play (back, 60, 100, false)[10] > 0.99f);
  3794. // 10 ms attack: starts silent and reaches full level
  3795. lynx::SamplerSettings slow;
  3796. slow.attack = 0.01f;
  3797. const auto a = play (slow, 60, 2000, false);
  3798. CHECK (a[10] < 0.2f * (10.0f / 48000.0f) + 1e-6f && std::abs (a[1500] - 1500.0f / 48000.0f) < 1e-4f);
  3799. // 5 ms release: gone right after release; without release it plays in full
  3800. lynx::SamplerSettings rel;
  3801. rel.release = 0.005f;
  3802. CHECK (play (rel, 60, 2000, true)[1999] == 0.0f);
  3803. CHECK (play (lynx::SamplerSettings {}, 60, 2000, true)[1999] > 0.0f);
  3804. // cut itself: the second note cuts the first (one voice remains)
  3805. lynx::SamplerSettings cut;
  3806. cut.cut = true;
  3807. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  3808. inst->prepare (48000.0);
  3809. lynx::ChannelDef cutChannel;
  3810. cutChannel.sampler = cut;
  3811. inst->configure (cutChannel, 120.0);
  3812. inst->noteOn (60, 1.0f);
  3813. std::vector<float> l (2000), r (2000);
  3814. inst->render (l.data(), r.data(), 1000, 1.0f, 1.0f);
  3815. inst->noteOn (60, 1.0f);
  3816. std::fill (l.begin(), l.end(), 0.0f);
  3817. inst->render (l.data(), r.data(), 2000, 1.0f, 1.0f);
  3818. CHECK (std::abs (l[1999] - 1999.0f / 48000.0f) < 1e-4f); // only the new note
  3819. }
  3820. TEST (playlist_split_and_track_mute)
  3821. {
  3822. lynx::Clip c { 0, 3, 960, 3840, 480 };
  3823. const auto rest = lynx::splitClip (c, 2000);
  3824. CHECK (c.start == 960 && c.length == 1040 && c.offset == 480);
  3825. CHECK (rest.start == 2000 && rest.length == 2800 && rest.offset == 480 + 1040 && rest.track == 3);
  3826. auto s = lynx::Song::makeDefault();
  3827. s.mode = lynx::PlayMode::song;
  3828. s.playlist = { { 0, 0, 0, 3840, 0 } };
  3829. lynx::EventBuffer ev;
  3830. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  3831. lynx::scheduleSong (s, 0.0, 48000, tps, ev);
  3832. CHECK (ev.size() > 0);
  3833. s.playlistTracks.resize (1);
  3834. s.playlistTracks[0].muted = true;
  3835. ev.clear();
  3836. lynx::scheduleSong (s, 0.0, 48000, tps, ev);
  3837. CHECK (ev.size() == 0);
  3838. }
  3839. TEST (note_pan_pitch_and_mute)
  3840. {
  3841. lynx::Pattern p;
  3842. lynx::Note a { 0, 240, 0, 60 };
  3843. a.pan = -1.0f;
  3844. a.finePitch = 50.0f;
  3845. lynx::Note b { 240, 240, 0, 62 };
  3846. b.muted = true;
  3847. p.notes = { a, b };
  3848. lynx::EventBuffer ev;
  3849. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  3850. lynx::schedulePatternLoop (p, p.effectiveLength (4), 0.0, 48000, tps, ev);
  3851. int ons = 0;
  3852. for (auto& e : ev)
  3853. if (e.type == lynx::NoteEvent::Type::on)
  3854. {
  3855. ++ons;
  3856. CHECK (e.key == 60 && e.pan == -1.0f && e.cents == 50.0f);
  3857. }
  3858. CHECK (ons == 1); // the muted one doesn't play
  3859. // note pan in the sampler: fully left
  3860. auto dc = std::make_shared<lynx::SampleData>();
  3861. dc->left.assign (4800, 0.5f);
  3862. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, dc);
  3863. inst->prepare (48000.0);
  3864. inst->setNextNoteExpression (-1.0f, 0.0f);
  3865. inst->noteOn (60, 1.0f);
  3866. std::vector<float> l (100), r (100);
  3867. inst->render (l.data(), r.data(), 100, 1.0f, 1.0f);
  3868. CHECK (l[50] > 0.6f && std::abs (r[50]) < 1e-6f);
  3869. }
  3870. TEST (tempo_automation_changes_speed_and_duration)
  3871. {
  3872. auto song = lynx::Song::makeDefault();
  3873. song.bpm = 120.0;
  3874. song.mode = lynx::PlayMode::song;
  3875. const auto bar = (std::int64_t) lynx::ppq * 4;
  3876. song.playlist = { { 0, 0, 0, bar, 0 }, { 0, 0, bar, bar, 0 } };
  3877. lynx::Automation tempo;
  3878. tempo.target = { lynx::AutomationTargetKind::tempo, 0 };
  3879. const auto v120 = lynx::valueFromTempo (120.0), v240 = lynx::valueFromTempo (240.0);
  3880. tempo.points = { { 0, v120 }, { bar - 1, v120 }, { bar, v240 } }; // step: 120 -> 240 at bar 2
  3881. song.automations.push_back (tempo);
  3882. lynx::Clip clip;
  3883. clip.kind = lynx::ClipKind::automation;
  3884. clip.automation = 0;
  3885. clip.track = 1;
  3886. clip.length = bar * 2;
  3887. song.playlist.push_back (clip);
  3888. CHECK (std::abs (song.tempoAt (100.0) - 120.0) < 0.01 && std::abs (song.tempoAt ((double) bar + 100.0) - 240.0) < 0.01);
  3889. // 1 bar at 120 (2 s) + 1 at 240 (1 s)
  3890. CHECK (std::abs (song.secondsForTicks (bar * 2) - 3.0) < 0.01);
  3891. auto state = lynx::RackState::build (song, nullptr, 48000.0);
  3892. CHECK (state->tempoAutomation == 0);
  3893. lynx::RackRenderer r;
  3894. r.prepare (48000.0, 512);
  3895. std::vector<float> l (512), rr (512);
  3896. r.process (state.get(), true, 10.0, 512, l.data(), rr.data());
  3897. CHECK (std::abs (r.currentBpm() - 120.0) < 0.01);
  3898. r.process (state.get(), true, (double) bar + 10.0, 512, l.data(), rr.data());
  3899. CHECK (std::abs (r.currentBpm() - 240.0) < 0.01);
  3900. }
  3901. TEST (bounce_insert_song_and_apply)
  3902. {
  3903. auto s = lynx::Song::makeDefault();
  3904. s.setRoute (3, 7, true, 0.5f);
  3905. s.mixer[0].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::reverb));
  3906. s.mixer[2].solo = true;
  3907. const auto b = lynx::makeBounceSong (s, 3);
  3908. CHECK (b.mixer[3].solo && ! b.mixer[2].solo && b.mixer[3].toMaster && b.mixer[3].sends.empty());
  3909. CHECK (b.mixer[0].effects.empty() && b.mode == lynx::PlayMode::song);
  3910. const auto audible = b.soloAudible();
  3911. CHECK (audible[3] && ! audible[1] && ! audible[7]);
  3912. const auto channels = s.channels.size();
  3913. const auto inserts = s.mixer.size();
  3914. const auto created = lynx::applyBounce (s, 3, "C:/x.wav", 3840);
  3915. CHECK (created == (int) inserts && s.mixer.size() == inserts + 1 && s.mixer[3].muted);
  3916. CHECK (s.mixer[(std::size_t) created].sends.size() == 1 && s.mixer[(std::size_t) created].sends[0].target == 7);
  3917. CHECK (s.channels.size() == channels + 1 && s.channels.back().mixerTrack == created);
  3918. CHECK (s.playlist.back().kind == lynx::ClipKind::audio && s.playlist.back().length == 3840);
  3919. }
  3920. TEST (mixer_stereo_separation_phase_swap)
  3921. {
  3922. lynx::MixerTrack t;
  3923. std::vector<float> l { 1.0f }, r { 0.0f };
  3924. t.stereo = 1.0f; // mono
  3925. lynx::RackRenderer::applyStereoForTest (t, l.data(), r.data(), 1);
  3926. CHECK (std::abs (l[0] - 0.5f) < 1e-6f && std::abs (r[0] - 0.5f) < 1e-6f);
  3927. l = { 1.0f };
  3928. r = { 0.0f };
  3929. t.stereo = -1.0f; // doubled side: 1.5 L - 0.5 R
  3930. lynx::RackRenderer::applyStereoForTest (t, l.data(), r.data(), 1);
  3931. CHECK (std::abs (l[0] - 1.5f) < 1e-6f && std::abs (r[0] + 0.5f) < 1e-6f);
  3932. l = { 1.0f };
  3933. r = { 0.25f };
  3934. t.stereo = 0.0f;
  3935. t.swapChannels = true;
  3936. t.invertPhase = true;
  3937. lynx::RackRenderer::applyStereoForTest (t, l.data(), r.data(), 1);
  3938. CHECK (l[0] == -0.25f && r[0] == -1.0f);
  3939. }
  3940. TEST (effects_limiter_filter_distortion_chorus)
  3941. {
  3942. const double sr = 48000.0;
  3943. auto sine = [] (float hz, float amp, int n) {
  3944. std::vector<float> v ((std::size_t) n);
  3945. for (int i = 0; i < n; ++i)
  3946. v[(std::size_t) i] = amp * std::sin (2.0f * 3.14159265f * hz * (float) i / 48000.0f);
  3947. return v;
  3948. };
  3949. auto peak = [] (const std::vector<float>& v, int from) {
  3950. float p = 0.0f;
  3951. for (std::size_t i = (std::size_t) from; i < v.size(); ++i)
  3952. p = std::max (p, std::abs (v[i]));
  3953. return p;
  3954. };
  3955. // limiter: +12 dB on a 0.9 sine never exceeds the ceiling (-1 dB) and reports the latency
  3956. auto lim = lynx::makeEffect (lynx::EffectKind::limiter);
  3957. lim->prepare (sr);
  3958. auto slot = lynx::makeEffectSlot (lynx::EffectKind::limiter);
  3959. slot.params[0] = 11.0f / 12.0f; // -1 dB
  3960. slot.params[1] = 0.5f; // +12 dB
  3961. auto l = sine (100.0f, 0.9f, 48000), r = l;
  3962. lim->process (l.data(), r.data(), 48000, slot.params, 120.0);
  3963. CHECK (peak (l, 0) <= std::pow (10.0f, -1.0f / 20.0f) + 1e-4f);
  3964. CHECK (peak (l, 4800) > 0.8f);
  3965. CHECK (lim->latencySamples() == 72);
  3966. // low-pass filter at 500 Hz knocks down an 8 kHz sine
  3967. auto lp = lynx::makeEffect (lynx::EffectKind::filter);
  3968. lp->prepare (sr);
  3969. auto fs = lynx::makeEffectSlot (lynx::EffectKind::filter);
  3970. fs.params[1] = std::log (500.0f / 20.0f) / std::log (1000.0f);
  3971. l = sine (8000.0f, 1.0f, 9600);
  3972. r = l;
  3973. lp->process (l.data(), r.data(), 9600, fs.params, 120.0);
  3974. CHECK (peak (l, 4800) < 0.05f);
  3975. // distortion and chorus: finite, audible output
  3976. for (auto kind : { lynx::EffectKind::distortion, lynx::EffectKind::chorus })
  3977. {
  3978. auto fx = lynx::makeEffect (kind);
  3979. fx->prepare (sr);
  3980. auto ps = lynx::makeEffectSlot (kind);
  3981. l = sine (220.0f, 0.5f, 9600);
  3982. r = l;
  3983. fx->process (l.data(), r.data(), 9600, ps.params, 120.0);
  3984. bool finite = true;
  3985. for (auto v : l)
  3986. finite = finite && std::isfinite (v);
  3987. CHECK (finite && peak (l, 2400) > 0.1f && peak (l, 0) < 2.0f);
  3988. }
  3989. }
  3990. TEST (slide_notes_glide_without_retrigger)
  3991. {
  3992. // sampler with a ramp: the read speed doubles after a one-octave slide
  3993. auto ramp = std::make_shared<lynx::SampleData>();
  3994. for (int i = 0; i < 96000; ++i)
  3995. ramp->left.push_back ((float) i / 96000.0f);
  3996. ramp->sampleRate = 48000.0;
  3997. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  3998. inst->prepare (48000.0);
  3999. inst->noteOn (60, 1.0f);
  4000. std::vector<float> l (2000), r (2000);
  4001. inst->render (l.data(), r.data(), 1000, 1.0f, 1.0f);
  4002. const auto stepBefore = l[999] - l[998];
  4003. inst->slideTo (72, 0.0f, 100.0f);
  4004. std::fill (l.begin(), l.end(), 0.0f);
  4005. inst->render (l.data(), r.data(), 1000, 1.0f, 1.0f);
  4006. const auto stepAfter = l[999] - l[998];
  4007. CHECK (std::abs (stepAfter / stepBefore - 2.0f) < 0.01f);
  4008. // the sequencer sends "slide" (no off) for the slide note
  4009. lynx::Pattern p;
  4010. lynx::Note base { 0, 960, 0, 48 };
  4011. lynx::Note glide { 480, 240, 0, 55 };
  4012. glide.slide = true;
  4013. p.notes = { base, glide };
  4014. lynx::EventBuffer ev;
  4015. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  4016. lynx::schedulePatternLoop (p, p.effectiveLength (4), 0.0, 30000, tps, ev);
  4017. int ons = 0, offs = 0, slides = 0;
  4018. for (auto& e : ev)
  4019. {
  4020. ons += e.type == lynx::NoteEvent::Type::on;
  4021. offs += e.type == lynx::NoteEvent::Type::off;
  4022. if (e.type == lynx::NoteEvent::Type::slide)
  4023. {
  4024. ++slides;
  4025. CHECK (e.key == 55 && std::abs (e.slideSamples - 240.0f / (float) tps) < 1.0f);
  4026. }
  4027. }
  4028. CHECK (ons == 1 && offs == 1 && slides == 1);
  4029. }
  4030. TEST (synth_fm_phase_modulation)
  4031. {
  4032. auto render = [] (const lynx::SynthSettings& s) {
  4033. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  4034. inst->prepare (48000.0);
  4035. lynx::ChannelDef c;
  4036. c.synth = s;
  4037. inst->configure (c, 120.0);
  4038. inst->noteOn (69, 1.0f); // 440 Hz
  4039. std::vector<float> l (48000), r (48000);
  4040. inst->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  4041. return l;
  4042. };
  4043. // energy (Goertzel) at frequency f over frames [from, to)
  4044. auto energy = [] (const std::vector<float>& x, double f, int from, int to) {
  4045. const auto w = 2.0 * 3.141592653589793 * f / 48000.0, k = 2.0 * std::cos (w);
  4046. double s1 = 0.0, s2 = 0.0;
  4047. for (int i = from; i < to; ++i)
  4048. {
  4049. const auto s0 = x[(std::size_t) i] + k * s1 - s2;
  4050. s2 = s1;
  4051. s1 = s0;
  4052. }
  4053. return s1 * s1 + s2 * s2 - k * s1 * s2;
  4054. };
  4055. lynx::SynthSettings plain;
  4056. plain.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  4057. plain.osc[2] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  4058. plain.cutoff = 20000.0f;
  4059. auto fm = plain;
  4060. fm.fm = 1.0f;
  4061. const auto a = render (plain), b = render (fm);
  4062. // no FM: osc 3 adds (same pitch) and there's no 2nd harmonic; with FM the sidebands appear
  4063. CHECK (energy (a, 880.0, 4800, 24000) < 1e-3 * energy (a, 440.0, 4800, 24000));
  4064. CHECK (energy (b, 880.0, 4800, 24000) > 0.1 * energy (b, 440.0, 4800, 24000));
  4065. CHECK (energy (b, 1320.0, 4800, 24000) > 0.01 * energy (b, 440.0, 4800, 24000));
  4066. for (auto v : b)
  4067. CHECK (std::isfinite (v) && std::abs (v) < 1.0f);
  4068. // index decaying to 0: the start is bright, the end is nearly a sine again
  4069. auto decaying = fm;
  4070. decaying.fmDecay = 0.1f;
  4071. decaying.fmSustain = 0.0f;
  4072. const auto c = render (decaying);
  4073. const auto early = energy (c, 880.0, 0, 2400) / energy (c, 440.0, 0, 2400);
  4074. const auto late = energy (c, 880.0, 36000, 48000) / energy (c, 440.0, 36000, 48000);
  4075. CHECK (early > 0.05 && late < 1e-3);
  4076. }
  4077. TEST (synth_three_oscillators_adsr_filter)
  4078. {
  4079. auto render = [] (const lynx::SynthSettings& s, int frames, int releaseAt) {
  4080. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  4081. inst->prepare (48000.0);
  4082. lynx::ChannelDef c;
  4083. c.synth = s;
  4084. inst->configure (c, 120.0);
  4085. inst->noteOn (69, 1.0f); // A4 = 440 Hz
  4086. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  4087. inst->render (l.data(), r.data(), releaseAt, 1.0f, 1.0f);
  4088. inst->noteOff (69);
  4089. inst->render (l.data() + releaseAt, r.data() + releaseAt, frames - releaseAt, 1.0f, 1.0f);
  4090. return l;
  4091. };
  4092. auto peakIn = [] (const std::vector<float>& v, int from, int to) {
  4093. float p = 0.0f;
  4094. for (int i = from; i < to; ++i)
  4095. p = std::max (p, std::abs (v[(std::size_t) i]));
  4096. return p;
  4097. };
  4098. // default: sounds and fades after the release
  4099. const lynx::SynthSettings standard;
  4100. const auto a = render (standard, 48000, 24000);
  4101. CHECK (peakIn (a, 1000, 20000) > 0.05f && peakIn (a, 40000, 48000) < 1e-3f);
  4102. // pure sine with an open filter: zero-crossing count gives ~440 Hz
  4103. lynx::SynthSettings sine;
  4104. sine.osc[0].wave = lynx::Waveform::sine;
  4105. sine.cutoff = 20000.0f;
  4106. const auto b = render (sine, 48000, 47000);
  4107. int crossings = 0;
  4108. for (int i = 4800; i < 4800 + 48000 / 2; ++i)
  4109. crossings += (b[(std::size_t) i - 1] < 0.0f) != (b[(std::size_t) i] < 0.0f);
  4110. CHECK (std::abs (crossings - 440) < 6); // half a second = 220 cycles = 440 crossings
  4111. float sinePeak = 0.0f;
  4112. for (int i = 4800; i < 9600; ++i)
  4113. sinePeak = std::max (sinePeak, std::abs (b[(std::size_t) i]));
  4114. CHECK (sinePeak > 0.2f && sinePeak < 0.35f); // 0.3 level, approximated sine without clipping
  4115. // second oscillator an octave up adds energy; sustain 0 makes the note decay on its own
  4116. lynx::SynthSettings two = sine;
  4117. two.osc[1] = { lynx::Waveform::sine, 1, 0.0f, 1.0f };
  4118. two.sustain = 0.0f;
  4119. two.decay = 0.1f;
  4120. const auto c = render (two, 48000, 47000);
  4121. CHECK (peakIn (c, 100, 2000) > peakIn (b, 100, 2000) && peakIn (c, 30000, 40000) < 1e-3f);
  4122. }
  4123. TEST (set_target_value_round_trips)
  4124. {
  4125. auto s = lynx::Song::makeDefault();
  4126. s.mixer[2].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay));
  4127. const lynx::AutomationTarget targets[] = {
  4128. { lynx::AutomationTargetKind::channelVolume, 1 }, { lynx::AutomationTargetKind::channelPan, 2 },
  4129. { lynx::AutomationTargetKind::mixerVolume, 3 }, { lynx::AutomationTargetKind::mixerPan, 0 },
  4130. { lynx::AutomationTargetKind::effectParam, 2, 0, 1 }, { lynx::AutomationTargetKind::tempo, 0 },
  4131. };
  4132. for (const auto& t : targets)
  4133. {
  4134. CHECK (s.setTargetValue (t, 0.25f));
  4135. CHECK (std::abs (s.targetValue (t) - 0.25f) < 1e-5f);
  4136. }
  4137. CHECK (! s.setTargetValue ({ lynx::AutomationTargetKind::channelParam, 0, 0, 3 }, 0.5f)); // lives in the plugin
  4138. }
  4139. TEST (cut_groups_stretch_and_envelope_import)
  4140. {
  4141. // open hat (cut by 1) is cut when the closed one (group 1) plays
  4142. lynx::Song s;
  4143. s.mixer = lynx::Song::defaultMixer (2);
  4144. for (int i = 0; i < 2; ++i)
  4145. {
  4146. lynx::ChannelDef c;
  4147. c.instrument = lynx::InstrumentKind::sampler;
  4148. c.samplePath = "dc";
  4149. c.volume = 1.0f;
  4150. c.mixerTrack = i + 1;
  4151. s.channels.push_back (c);
  4152. }
  4153. s.channels[0].cutBy = 1; // open
  4154. s.channels[1].cutGroup = 1; // closed
  4155. auto& p = s.patterns.emplace_back();
  4156. p.notes = { { 0, 100, 0, 60 }, { 960, 100, 1, 60 } };
  4157. auto provider = [] (const std::string&) {
  4158. auto d = std::make_shared<lynx::SampleData>();
  4159. d->left.assign (96000, 0.5f);
  4160. return std::shared_ptr<const lynx::SampleData> (d);
  4161. };
  4162. auto state = lynx::RackState::build (s, nullptr, 48000.0, provider);
  4163. CHECK (state->hasCutGroups && state->cutTargets[1].size() == 1 && state->cutTargets[1][0] == 0);
  4164. lynx::RackRenderer r;
  4165. r.prepare (48000.0, 512);
  4166. std::vector<float> l (512), rr (512);
  4167. const auto tps = lynx::ticksPerSample (s.bpm, 48000.0);
  4168. float afterCut = 0.0f;
  4169. for (double tick = 0.0; tick < 960.0 * 3; tick += 512 * tps)
  4170. {
  4171. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  4172. if (tick > 960.0 * 2) // the closed one continues; the open one has stopped
  4173. afterCut = std::max (afterCut, std::abs (l[256]));
  4174. }
  4175. CHECK (std::abs (afterCut - 0.5f * 0.78f) < 0.01f); // only the closed one (default velocity 0.78)
  4176. // resampling stretch: 1 s of sample stretched to 4 beats at 120 BPM = 2 s
  4177. auto ramp = std::make_shared<lynx::SampleData>();
  4178. for (int i = 0; i < 48000; ++i)
  4179. ramp->left.push_back ((float) i / 48000.0f);
  4180. ramp->sampleRate = 48000.0;
  4181. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  4182. inst->prepare (48000.0);
  4183. lynx::ChannelDef c;
  4184. c.sampler.stretchBeats = 4.0f;
  4185. inst->configure (c, 120.0);
  4186. inst->noteOn (72, 1.0f); // the note pitch doesn't change the speed
  4187. std::vector<float> a (48000), b (48000);
  4188. inst->render (a.data(), b.data(), 48000, 1.0f, 1.0f);
  4189. CHECK (std::abs (a[47999] - 0.5f) < 0.01f); // after 1 s it has read half
  4190. // FL envelope time: 32950 = 2 s; < 101 = 0
  4191. CHECK (std::abs (flp::Channel::envelopeTime (32950) - 2.0) < 0.01 && flp::Channel::envelopeTime (50) == 0.0);
  4192. }
  4193. TEST (time_stretch_keeps_pitch)
  4194. {
  4195. lynx::SampleData sine;
  4196. sine.sampleRate = 48000.0;
  4197. for (int i = 0; i < 48000; ++i)
  4198. sine.left.push_back (0.5f * std::sin (2.0f * 3.14159265f * 440.0f * (float) i / 48000.0f));
  4199. auto crossingsPerSecond = [] (const lynx::SampleData& d) {
  4200. int c = 0;
  4201. const auto n = (int) d.frames();
  4202. for (int i = 4800; i < n - 4800; ++i)
  4203. c += (d.left[(std::size_t) i - 1] < 0.0f) != (d.left[(std::size_t) i] < 0.0f);
  4204. return (double) c / ((double) (n - 9600) / d.sampleRate);
  4205. };
  4206. for (double ratio : { 2.0, 0.5, 1.37 })
  4207. {
  4208. const auto out = lynx::timeStretch (sine, ratio);
  4209. CHECK (std::abs ((double) out->frames() - 48000.0 * ratio) < 2.0);
  4210. CHECK (std::abs (crossingsPerSecond (*out) - 880.0) < 15.0); // 440 Hz stays 440 Hz
  4211. float peak = 0.0f;
  4212. for (std::size_t i = 4800; i + 4800 < out->frames(); ++i)
  4213. peak = std::max (peak, std::abs (out->left[i]));
  4214. CHECK (peak > 0.4f && peak < 0.6f); // no gaps or clipping in the overlap
  4215. }
  4216. }
  4217. TEST (sampler_region_start_and_end)
  4218. {
  4219. auto ramp = std::make_shared<lynx::SampleData>();
  4220. for (int i = 0; i < 10000; ++i)
  4221. ramp->left.push_back ((float) i / 10000.0f);
  4222. ramp->sampleRate = 48000.0;
  4223. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  4224. inst->prepare (48000.0);
  4225. lynx::ChannelDef c;
  4226. c.sampler.regionStart = 0.25f;
  4227. c.sampler.regionEnd = 0.5f;
  4228. inst->configure (c, 120.0);
  4229. inst->noteOn (60, 1.0f);
  4230. std::vector<float> l (6000), r (6000);
  4231. inst->render (l.data(), r.data(), 6000, 1.0f, 1.0f);
  4232. CHECK (std::abs (l[0] - 0.25f) < 0.001f); // starts at the beginning of the slice
  4233. CHECK (l[2400] > 0.48f && l[2600] == 0.0f); // and stops at its end
  4234. }
  4235. TEST (arpeggiator_plays_held_chord_in_steps)
  4236. {
  4237. auto song = lynx::Song::makeDefault();
  4238. song.bpm = 120.0;
  4239. song.patterns[0].notes.clear();
  4240. for (int key : { 60, 64, 67 })
  4241. song.patterns[0].notes.push_back ({ 0, lynx::ppq * 4, 4, key, 0.8f }); // chord held for 1 bar
  4242. song.channels[4].arp.direction = 1; // up
  4243. song.channels[4].arp.stepBeats = 0.25f;
  4244. auto state = lynx::RackState::build (song, nullptr, 48000.0);
  4245. CHECK (state->arpeggiators[4] != nullptr && state->arpeggiators[0] == nullptr);
  4246. // the arpeggiator generates the notes; we count what it hands to the instrument
  4247. auto& arp = *state->arpeggiators[4];
  4248. const auto tps = lynx::ticksPerSample (song.bpm, 48000.0);
  4249. std::vector<int> keys;
  4250. lynx::EventBuffer ev;
  4251. for (double tick = 0.0; tick < lynx::ppq * 2.0; tick += 512 * tps)
  4252. {
  4253. ev.clear();
  4254. lynx::schedulePatternLoop (song.patterns[0], song.patterns[0].effectiveLength (4), tick, 512, tps, ev);
  4255. int in = 0, out = 0;
  4256. for (auto& e : ev)
  4257. if (e.channel == 4)
  4258. arp.input[(std::size_t) in++] = e;
  4259. arp.process (4, arp.input.data(), in, tick, tps, 512, song.channels[4].arp, arp.output.data(), out);
  4260. for (int i = 0; i < out; ++i)
  4261. if (arp.output[(std::size_t) i].type == lynx::NoteEvent::Type::on)
  4262. keys.push_back (arp.output[(std::size_t) i].key);
  4263. }
  4264. // 2 beats = 8 sixteenth steps: 60 64 67 60 64 67 60 64
  4265. CHECK (keys.size() >= 8); // the last block goes slightly past 2 beats
  4266. const int expected[] = { 60, 64, 67, 60, 64, 67, 60, 64 };
  4267. for (std::size_t i = 0; i < keys.size() && i < 8; ++i)
  4268. CHECK (keys[i] == expected[i]);
  4269. // actually rendering also makes sound
  4270. lynx::RackRenderer r;
  4271. r.prepare (48000.0, 512);
  4272. std::vector<float> l (512), rr (512);
  4273. float peak = 0.0f;
  4274. for (double tick = 0.0; tick < lynx::ppq; tick += 512 * tps)
  4275. {
  4276. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  4277. for (auto v : l)
  4278. peak = std::max (peak, std::abs (v));
  4279. }
  4280. CHECK (peak > 0.01f);
  4281. }
  4282. TEST (audio_clip_fades_and_gain)
  4283. {
  4284. lynx::Song s;
  4285. s.bpm = 120.0;
  4286. s.mode = lynx::PlayMode::song;
  4287. s.mixer = lynx::Song::defaultMixer (1);
  4288. lynx::ChannelDef c;
  4289. c.instrument = lynx::InstrumentKind::audioClip;
  4290. c.samplePath = "dc";
  4291. c.volume = 1.0f;
  4292. c.mixerTrack = 1;
  4293. s.channels.push_back (c);
  4294. s.patterns.emplace_back();
  4295. lynx::Clip clip;
  4296. clip.kind = lynx::ClipKind::audio;
  4297. clip.channel = 0;
  4298. clip.length = lynx::ppq * 4; // 2 s at 120 BPM
  4299. clip.fadeIn = lynx::ppq; // 0.5 s
  4300. clip.fadeOut = lynx::ppq;
  4301. clip.gain = 0.5f;
  4302. s.playlist.push_back (clip);
  4303. auto provider = [] (const std::string&) {
  4304. auto d = std::make_shared<lynx::SampleData>();
  4305. d->left.assign (48000 * 4, 1.0f);
  4306. return std::shared_ptr<const lynx::SampleData> (d);
  4307. };
  4308. auto state = lynx::RackState::build (s, nullptr, 48000.0, provider);
  4309. lynx::RackRenderer r;
  4310. r.prepare (48000.0, 512);
  4311. std::vector<float> all;
  4312. std::vector<float> l (512), rr (512);
  4313. const auto tps = lynx::ticksPerSample (s.bpm, 48000.0);
  4314. for (double tick = 0.0; tick < lynx::ppq * 4.0; tick += 512 * tps)
  4315. {
  4316. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  4317. all.insert (all.end(), l.begin(), l.end());
  4318. }
  4319. CHECK (all[100] < 0.01f); // fade-in start
  4320. CHECK (std::abs (all[12000] - 0.25f) < 0.02f); // fade-in midpoint: half of 0.5
  4321. CHECK (std::abs (all[48000] - 0.5f) < 0.01f); // body: the clip gain
  4322. CHECK (std::abs (all[96000 - 12000] - 0.25f) < 0.02f); // fade-out midpoint
  4323. }
  4324. TEST (slicer_detects_hits_and_plays_slices_by_key)
  4325. {
  4326. // 4 hits (decaying noise) every 0.25 s
  4327. lynx::SampleData loop;
  4328. loop.sampleRate = 48000.0;
  4329. loop.left.assign (48000, 0.0f);
  4330. lynx::Noise noise;
  4331. for (int hit = 0; hit < 4; ++hit)
  4332. for (int i = 0; i < 6000; ++i)
  4333. loop.left[(std::size_t) (hit * 12000 + i)] = noise.next() * 0.8f * std::exp (-(float) i / 1500.0f);
  4334. const auto slices = lynx::detectSlices (loop, 0.5f);
  4335. CHECK (slices.size() == 4);
  4336. for (std::size_t i = 0; i < slices.size(); ++i)
  4337. CHECK (std::abs (slices[i] - 0.25f * (float) i) < 0.01f);
  4338. // key 61 plays the second slice, which starts at 0.25 and ends before 0.5
  4339. auto ramp = std::make_shared<lynx::SampleData>();
  4340. for (int i = 0; i < 48000; ++i)
  4341. ramp->left.push_back ((float) i / 48000.0f);
  4342. ramp->sampleRate = 48000.0;
  4343. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  4344. inst->prepare (48000.0);
  4345. lynx::ChannelDef c;
  4346. c.sampler.slices = slices;
  4347. inst->configure (c, 120.0);
  4348. inst->noteOn (61, 1.0f);
  4349. std::vector<float> l (20000), r (20000);
  4350. inst->render (l.data(), r.data(), 20000, 1.0f, 1.0f);
  4351. CHECK (std::abs (l[0] - 0.25f) < 0.01f && l[11000] > 0.45f && l[13000] == 0.0f);
  4352. }
  4353. TEST (project_templates_render_sound)
  4354. {
  4355. const auto names = lynx::templateNames();
  4356. CHECK (names.size() == 4);
  4357. for (int t = 1; t < (int) names.size(); ++t)
  4358. {
  4359. auto song = lynx::makeTemplate (t);
  4360. auto state = lynx::RackState::build (song, nullptr, 48000.0);
  4361. lynx::RackRenderer r;
  4362. r.prepare (48000.0, 512);
  4363. std::vector<float> l (512), rr (512);
  4364. const auto tps = lynx::ticksPerSample (song.bpm, 48000.0);
  4365. float peak = 0.0f;
  4366. for (double tick = 0.0; tick < lynx::ppq * 4.0; tick += 512 * tps)
  4367. {
  4368. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  4369. for (auto v : l)
  4370. peak = std::max (peak, std::abs (v));
  4371. }
  4372. CHECK (peak > 0.05f && peak < 4.0f);
  4373. }
  4374. CHECK (lynx::makeTemplate (0).patterns[0].notes.empty());
  4375. }
  4376. // --- interface translations (resources/i18n) -------------------------------------------------------
  4377. namespace i18ntest
  4378. {
  4379. std::string readFile (const std::filesystem::path& path)
  4380. {
  4381. std::ifstream in (path, std::ios::binary);
  4382. return { std::istreambuf_iterator<char> (in), std::istreambuf_iterator<char>() };
  4383. }
  4384. std::string unescape (const std::string& s)
  4385. {
  4386. std::string out;
  4387. for (std::size_t i = 0; i < s.size(); ++i)
  4388. {
  4389. if (s[i] == '\\' && i + 1 < s.size())
  4390. {
  4391. const auto n = s[++i];
  4392. out += n == 'n' ? '\n' : n == 't' ? '\t' : n;
  4393. }
  4394. else
  4395. out += s[i];
  4396. }
  4397. return out;
  4398. }
  4399. // reads a quoted string starting at s[pos] == '"'; returns the raw (escaped) contents and moves pos past the closing quote
  4400. bool quoted (const std::string& s, std::size_t& pos, std::string& raw)
  4401. {
  4402. if (pos >= s.size() || s[pos] != '"')
  4403. return false;
  4404. raw.clear();
  4405. for (++pos; pos < s.size() && s[pos] != '"' && s[pos] != '\n'; ++pos)
  4406. {
  4407. if (s[pos] == '\\' && pos + 1 < s.size())
  4408. raw += s[pos++];
  4409. raw += s[pos];
  4410. }
  4411. if (pos >= s.size() || s[pos] != '"')
  4412. return false;
  4413. ++pos;
  4414. return true;
  4415. }
  4416. // JUCE LocalisedStrings format: "english" = "translation"; duplicates are reported in `duplicates`
  4417. std::map<std::string, std::string> parseTable (const std::string& text, std::vector<std::string>& duplicates)
  4418. {
  4419. std::map<std::string, std::string> table;
  4420. std::istringstream lines (text);
  4421. std::string line;
  4422. while (std::getline (lines, line))
  4423. {
  4424. std::size_t pos = line.find_first_not_of (" \t");
  4425. std::string key, value;
  4426. if (pos == std::string::npos || ! quoted (line, pos, key))
  4427. continue;
  4428. pos = line.find ('"', pos);
  4429. if (pos == std::string::npos || ! quoted (line, pos, value))
  4430. value.clear();
  4431. const auto k = unescape (key);
  4432. if (table.count (k) != 0)
  4433. duplicates.push_back (k);
  4434. table[k] = unescape (value);
  4435. }
  4436. return table;
  4437. }
  4438. // string literals passed to tr() / TR_NOOP() in the sources (adjacent literals are concatenated)
  4439. std::map<std::string, std::string> sourceKeys (const std::filesystem::path& srcDir)
  4440. {
  4441. std::map<std::string, std::string> keys;
  4442. for (const auto& entry : std::filesystem::recursive_directory_iterator (srcDir))
  4443. {
  4444. const auto ext = entry.path().extension().string();
  4445. if (! entry.is_regular_file() || (ext != ".cpp" && ext != ".h"))
  4446. continue;
  4447. // drop // comment lines (they may quote tr ("...") as an example)
  4448. std::string text, line;
  4449. std::istringstream in (readFile (entry.path()));
  4450. while (std::getline (in, line))
  4451. {
  4452. const auto first = line.find_first_not_of (" \t");
  4453. text += (first != std::string::npos && line.compare (first, 2, "//") == 0) ? std::string() : line;
  4454. text += '\n';
  4455. }
  4456. auto isIdent = [] (char c) { return std::isalnum ((unsigned char) c) || c == '_'; };
  4457. for (const std::string name : { "tr", "TR_NOOP" })
  4458. for (auto at = text.find (name); at != std::string::npos; at = text.find (name, at + 1))
  4459. {
  4460. if ((at > 0 && isIdent (text[at - 1])) || isIdent (text[at + name.size()]))
  4461. continue;
  4462. auto pos = text.find_first_not_of (" \t\n", at + name.size());
  4463. if (pos == std::string::npos || text[pos] != '(')
  4464. continue;
  4465. pos = text.find_first_not_of (" \t\n", pos + 1);
  4466. std::string key, raw;
  4467. bool any = false;
  4468. while (pos != std::string::npos && quoted (text, pos, raw))
  4469. {
  4470. key += raw;
  4471. any = true;
  4472. pos = text.find_first_not_of (" \t\n", pos);
  4473. }
  4474. if (any)
  4475. keys.emplace (unescape (key), entry.path().filename().string());
  4476. }
  4477. }
  4478. return keys;
  4479. }
  4480. std::set<std::string> placeholders (const std::string& s)
  4481. {
  4482. std::set<std::string> found;
  4483. for (auto open = s.find ('{'); open != std::string::npos; open = s.find ('{', open + 1))
  4484. if (const auto close = s.find ('}', open); close != std::string::npos && close - open <= 3)
  4485. found.insert (s.substr (open, close - open + 1));
  4486. return found;
  4487. }
  4488. } // namespace i18ntest
  4489. TEST (translations_cover_every_ui_string)
  4490. {
  4491. using namespace i18ntest;
  4492. const auto text = readFile ("resources/i18n/pt-BR.txt");
  4493. CHECK (! text.empty());
  4494. std::vector<std::string> duplicates;
  4495. const auto table = parseTable (text, duplicates);
  4496. CHECK (table.size() > 300);
  4497. CHECK (duplicates.empty());
  4498. for (const auto& d : duplicates)
  4499. std::printf (" duplicate pt-BR entry: \"%s\"\n", d.c_str());
  4500. const auto keys = sourceKeys ("src");
  4501. CHECK (keys.size() > 300);
  4502. int missing = 0;
  4503. for (const auto& [key, file] : keys)
  4504. if (auto it = table.find (key); it == table.end() || it->second.empty())
  4505. {
  4506. ++missing;
  4507. std::printf (" no pt-BR translation for \"%s\" (%s)\n", key.c_str(), file.c_str());
  4508. }
  4509. CHECK (missing == 0);
  4510. // no empty values, and every {n} placeholder survives the translation
  4511. int empty = 0, badPlaceholders = 0;
  4512. for (const auto& [english, portuguese] : table)
  4513. {
  4514. empty += portuguese.empty() ? 1 : 0;
  4515. if (placeholders (english) != placeholders (portuguese))
  4516. {
  4517. ++badPlaceholders;
  4518. std::printf (" placeholders differ: \"%s\"\n", english.c_str());
  4519. }
  4520. }
  4521. CHECK (empty == 0);
  4522. CHECK (badPlaceholders == 0);
  4523. }
  4524. TEST (translations_embedded_table_is_up_to_date)
  4525. {
  4526. // src/ui/I18nData.h must be regenerated (tools/make_i18n.py) whenever the .txt changes
  4527. const auto text = i18ntest::readFile ("resources/i18n/pt-BR.txt");
  4528. CHECK (text.size() == sizeof (lynx::i18n::data::ptBR));
  4529. CHECK (std::memcmp (text.data(), lynx::i18n::data::ptBR, std::min (text.size(), sizeof (lynx::i18n::data::ptBR))) == 0);
  4530. }
  4531. // --- workflow shell: pattern/channel operations, key map, workspace layout, control math -------------
  4532. TEST (workflow_pattern_navigation_and_insert)
  4533. {
  4534. auto song = lynx::Song::makeDefault();
  4535. song.patterns.resize (3);
  4536. song.patterns[1].name = "B";
  4537. song.patterns[2].name = "C";
  4538. song.patterns[2].notes.push_back ({});
  4539. song.currentPattern = 0;
  4540. CHECK (lynx::stepPattern (song, 1) == 1 && lynx::stepPattern (song, -1) == 0 && lynx::stepPattern (song, 10) == 2);
  4541. // pattern 0 has the default notes, 1 is empty, 2 has a note
  4542. CHECK (! lynx::isPatternEmpty (song.patterns[0]) && lynx::isPatternEmpty (song.patterns[1]));
  4543. CHECK (lynx::findNextEmptyPattern (song, 0) == 1 && lynx::findNextEmptyPattern (song, 1) == -1);
  4544. CHECK (lynx::gotoNextEmptyPattern (song) == 1 && song.currentPattern == 1);
  4545. song.patterns[1].notes.push_back ({});
  4546. const auto before = song.patterns.size();
  4547. CHECK (lynx::gotoNextEmptyPattern (song) == (int) before && song.patterns.size() == before + 1);
  4548. CHECK (song.patterns.back().name == "Pattern 1" || song.patterns.back().name.rfind ("Pattern ", 0) == 0);
  4549. // insert keeps Playlist clips on their patterns
  4550. lynx::Clip clip;
  4551. clip.pattern = 2;
  4552. song.playlist = { clip };
  4553. song.arrangements.push_back ({ "Other", { clip }, 0, 0, {} });
  4554. CHECK (lynx::insertPattern (song, 1, "New") == 1 && song.currentPattern == 1);
  4555. CHECK (song.patterns[1].name == "New" && song.patterns[1].notes.empty() && song.patterns[3].name == "C");
  4556. CHECK (song.playlist[0].pattern == 3 && song.arrangements[1].clips[0].pattern == 3);
  4557. }
  4558. TEST (workflow_split_pattern_by_channel)
  4559. {
  4560. auto song = lynx::Song::makeDefault();
  4561. song.patterns.resize (1);
  4562. auto& p = song.patterns[0];
  4563. p.name = "Beat";
  4564. p.notes.clear();
  4565. for (int i = 0; i < 4; ++i)
  4566. p.notes.push_back ({ (std::int64_t) i * lynx::ticksPerStep, lynx::ticksPerStep, i % 2 == 0 ? 0 : 2, 60 });
  4567. song.channels[2].colour = 0xff112233;
  4568. lynx::Clip clip;
  4569. clip.pattern = 0;
  4570. song.playlist = { clip };
  4571. const auto created = lynx::splitPatternByChannel (song, 0);
  4572. CHECK (created == 2 && song.patterns.size() == 3);
  4573. CHECK (song.patterns[0].notes.size() == 4); // the original is unchanged
  4574. CHECK (song.patterns[1].name == "Beat - " + song.channels[0].name && song.patterns[1].notes.size() == 2);
  4575. CHECK (song.patterns[2].colour == 0xff112233u && song.patterns[2].notes.size() == 2 && song.patterns[2].notes[0].channel == 2);
  4576. CHECK (song.playlist[0].pattern == 0);
  4577. CHECK (lynx::splitPatternByChannel (song, 99) == 0);
  4578. }
  4579. TEST (workflow_channel_selection)
  4580. {
  4581. lynx::ChannelSelection s;
  4582. s.selectOnly (2);
  4583. s.toggle (5);
  4584. s.toggle (0);
  4585. CHECK ((s.rows == std::vector<int> { 0, 2, 5 }) && s.contains (5) && ! s.contains (3));
  4586. s.toggle (2);
  4587. CHECK ((s.rows == std::vector<int> { 0, 5 }));
  4588. s.selectOnly (3);
  4589. s.extendTo (6);
  4590. CHECK ((s.rows == std::vector<int> { 3, 4, 5, 6 }));
  4591. s.extendTo (1);
  4592. CHECK ((s.rows == std::vector<int> { 1, 2, 3 }));
  4593. s.selectOnly (4);
  4594. s.toggle (4); // the last one stays
  4595. CHECK ((s.rows == std::vector<int> { 4 }));
  4596. s.selectAll (3);
  4597. CHECK ((s.rows == std::vector<int> { 0, 1, 2 }));
  4598. s.rows = { 7, 9 };
  4599. s.clamp (5);
  4600. CHECK (s.rows.size() == 1 && s.rows[0] < 5);
  4601. }
  4602. TEST (workflow_move_clone_insert_channels)
  4603. {
  4604. auto song = lynx::Song::makeDefault();
  4605. const auto names = [&] {
  4606. std::vector<std::string> n;
  4607. for (const auto& c : song.channels)
  4608. n.push_back (c.name);
  4609. return n;
  4610. };
  4611. const auto original = names();
  4612. const auto count = (int) song.channels.size();
  4613. CHECK (count >= 4);
  4614. // references that must follow their channel
  4615. song.patterns[0].notes.push_back ({ 0, 240, 1, 64 });
  4616. lynx::Automation a;
  4617. a.target = { lynx::AutomationTargetKind::channelVolume, 1 };
  4618. song.automations.push_back (a);
  4619. song.midiLinks.push_back ({ 7, -1, { lynx::AutomationTargetKind::channelPan, 3 } });
  4620. lynx::Clip audio;
  4621. audio.kind = lynx::ClipKind::audio;
  4622. audio.channel = 3;
  4623. song.playlist.push_back (audio);
  4624. std::vector<int> selection { 1, 3 };
  4625. CHECK (lynx::moveChannels (song, selection, -1));
  4626. CHECK ((selection == std::vector<int> { 0, 2 }));
  4627. CHECK (song.channels[0].name == original[1] && song.channels[1].name == original[0] && song.channels[2].name == original[3]
  4628. && song.channels[3].name == original[2]);
  4629. CHECK (song.automations[0].target.index == 0 && song.midiLinks[0].target.index == 2 && song.playlist.back().channel == 2);
  4630. CHECK (std::any_of (song.patterns[0].notes.begin(), song.patterns[0].notes.end(),
  4631. [] (const lynx::Note& n) { return n.channel == 0 && n.key == 64; }));
  4632. CHECK (! lynx::moveChannels (song, selection, -1)); // the block is at the top
  4633. CHECK (lynx::moveChannels (song, selection, 1) && (selection == std::vector<int> { 1, 3 }) && names() == original);
  4634. // clone: settings, not notes, right below, with a new name
  4635. song.channels[1].volume = 0.33f;
  4636. const auto notesBefore = song.patterns[0].notes.size();
  4637. const auto clone = lynx::cloneChannel (song, 1);
  4638. CHECK (clone == 2 && (int) song.channels.size() == count + 1);
  4639. CHECK (song.channels[2].name == original[1] + " #2" && song.channels[2].volume == 0.33f);
  4640. CHECK (song.patterns[0].notes.size() == notesBefore);
  4641. CHECK (song.channels[3].name == original[2] && song.automations[0].target.index == 1);
  4642. CHECK (lynx::cloneChannel (song, 1) == 2 && song.channels[2].name == original[1] + " #3");
  4643. // remove several
  4644. CHECK (lynx::removeChannels (song, { 2, 3, 2 }) == 2 && (int) song.channels.size() == count);
  4645. CHECK (names() == original);
  4646. }
  4647. TEST (workflow_send_channels_to_free_inserts)
  4648. {
  4649. auto song = lynx::Song::makeDefault();
  4650. for (auto& c : song.channels)
  4651. c.mixerTrack = 0;
  4652. song.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay)); // not free: has effects
  4653. song.channels[0].mixerTrack = 2; // not free: used
  4654. song.setRoute (5, 3, true); // 3 is not free: receives a send
  4655. CHECK (! lynx::isInsertFree (song, 1) && ! lynx::isInsertFree (song, 2) && ! lynx::isInsertFree (song, 3) && lynx::isInsertFree (song, 4));
  4656. song.channels[1].colour = 0xff445566;
  4657. const auto tracks = lynx::sendChannelsToFreeInserts (song, { 1, 2 });
  4658. CHECK ((tracks == std::vector<int> { 4, 5 }) || (tracks == std::vector<int> { 4, 6 }));
  4659. CHECK (song.channels[1].mixerTrack == 4 && song.mixer[4].name == song.channels[1].name && song.mixer[4].colour == 0xff445566u);
  4660. CHECK (song.mixer[(std::size_t) tracks[1]].name == song.channels[2].name);
  4661. // with no free insert left, a new one is added at the end
  4662. auto full = lynx::Song::makeDefault();
  4663. full.mixer = lynx::Song::defaultMixer (1);
  4664. full.channels[0].mixerTrack = 1;
  4665. const auto added = lynx::sendChannelsToFreeInserts (full, { 1 });
  4666. CHECK (added.size() == 1 && added[0] == 2 && full.mixer.size() == 3 && full.channels[1].mixerTrack == 2);
  4667. }
  4668. TEST (workflow_palette_random_colour)
  4669. {
  4670. const auto& palette = lynx::lynxPalette();
  4671. for (std::uint32_t seed = 0; seed < 50; ++seed)
  4672. {
  4673. const auto current = palette[seed % palette.size()];
  4674. const auto c = lynx::randomPaletteColour (current, seed);
  4675. CHECK (c != current && std::find (palette.begin(), palette.end(), c) != palette.end());
  4676. }
  4677. }
  4678. TEST (workflow_key_map)
  4679. {
  4680. using namespace lynx::keys;
  4681. KeyMap map;
  4682. const auto global = Context::global, rack = Context::channelRack;
  4683. CHECK (map.find ({ space, none }, global, true) == "transport.playStop");
  4684. CHECK (map.find ({ space, ctrl }, global, true) == "transport.pause");
  4685. CHECK (map.find ({ f6, none }, global, true) == "panel.channelRack");
  4686. CHECK (map.find ({ f8, alt }, global, false) == "panel.browser");
  4687. CHECK (map.find ({ insert, ctrl | shift }, global, false) == "pattern.insert");
  4688. CHECK (map.find ({ numpadPlus, none }, rack, true) == "pattern.next");
  4689. // panel context: only while focused
  4690. CHECK (map.find ({ 'L', ctrl }, rack, true) == "rack.sendToInserts");
  4691. CHECK (map.find ({ 'L', ctrl }, global, true).empty());
  4692. CHECK (map.find ({ up, alt }, rack, false) == "rack.moveUp");
  4693. // typing piano: note keys play, other plain keys only for whilePiano actions; chords always work
  4694. CHECK (KeyMap::playsNote ({ 'Z', none }, true) && ! KeyMap::playsNote ({ 'Z', none }, false) && ! KeyMap::playsNote ({ 'Z', ctrl }, true));
  4695. CHECK (map.find ({ 'L', none }, global, true) == "transport.toggleMode");
  4696. CHECK (map.find ({ '1', none }, rack, false) == "rack.mute1" && map.find ({ '0', none }, rack, false) == "rack.mute10");
  4697. CHECK (map.find ({ '1', none }, rack, true).empty()); // a plain digit is not a shortcut while the piano is on
  4698. CHECK (map.find ({ '2', ctrl }, rack, true) == "rack.solo2");
  4699. CHECK (typingPianoNote ('Z') == 60 && typingPianoNote ('q') == 72 && typingPianoNote ('P') == 88 && typingPianoNote ('L') == -1);
  4700. CHECK (map.conflicts().empty());
  4701. // chord text
  4702. CHECK (toString ({ f4, ctrl | shift }) == "Ctrl+Shift+F4" && toString ({ numpadMinus, none }) == "Numpad -");
  4703. CHECK (parseChord ("Shift+Ctrl+Ins") == (Chord { insert, ctrl | shift }));
  4704. CHECK (parseChord ("alt+up") == (Chord { up, alt }) && parseChord ("k") == (Chord { 'K', none }));
  4705. CHECK (parseChord ("Numpad +") == (Chord { numpadPlus, none }) && ! parseChord ("F13") && ! parseChord ("Ctrl+"));
  4706. for (const auto& a : actions())
  4707. for (const auto& c : a.defaults)
  4708. CHECK (parseChord (toString (c)) == c);
  4709. // JSON overrides
  4710. std::vector<std::string> errors;
  4711. CHECK (map.loadJson (R"({ "pattern.next": "Ctrl+Right", "rack.clone": ["Alt+D", "Ctrl+D"], "help.shortcuts": "", "nope": "F1", "file.open": "Hyper+Q" })", &errors));
  4712. CHECK (errors.size() == 2);
  4713. CHECK (map.find ({ right, ctrl }, global, false) == "pattern.next" && map.find ({ numpadPlus, none }, global, false).empty());
  4714. CHECK (map.find ({ 'D', ctrl }, rack, false) == "rack.clone" && map.find ({ f1, none }, global, false).empty());
  4715. map.setChords ("pattern.previous", { { right, ctrl } });
  4716. CHECK (map.conflicts().size() == 1);
  4717. KeyMap reloaded;
  4718. CHECK (reloaded.loadJson (map.toJson()) && reloaded.chordsFor ("rack.clone") == map.chordsFor ("rack.clone"));
  4719. CHECK (! map.loadJson ("[1, 2]") && ! map.loadJson ("{\"a\": }"));
  4720. map.resetToDefaults();
  4721. CHECK (map.find ({ numpadPlus, none }, global, false) == "pattern.next");
  4722. }
  4723. TEST (workflow_workspace_layout)
  4724. {
  4725. using namespace lynx::workspace;
  4726. auto l = Layout::makeDefault (1280, 620);
  4727. // every visible panel is inside the desktop; the default shows Browser, Playlist and Channel Rack
  4728. for (const auto& p : l.panels)
  4729. CHECK (p.bounds.x >= 0 && p.bounds.y >= 0 && p.bounds.right() <= 1280 && p.bounds.bottom() <= 620 && p.bounds.w >= minWidth);
  4730. CHECK (l[Panel::browser].visible && l[Panel::playlist].visible && l[Panel::channelRack].visible);
  4731. CHECK (! l[Panel::pianoRoll].visible && ! l[Panel::mixer].visible);
  4732. CHECK (l[Panel::playlist].bounds.x == l[Panel::browser].bounds.right() && l[Panel::playlist].bounds.right() == 1280);
  4733. CHECK (l.isFrontmost (Panel::channelRack) && l.focused == Panel::channelRack);
  4734. // toggle: show+focus, focus, hide
  4735. CHECK (l.toggle (Panel::mixer) && l.focused == Panel::mixer && l.isFrontmost (Panel::mixer));
  4736. CHECK (l.toggle (Panel::channelRack) && l.focused == Panel::channelRack && l.isFrontmost (Panel::channelRack));
  4737. CHECK (! l.toggle (Panel::channelRack) && ! l[Panel::channelRack].visible && l.focused == Panel::mixer);
  4738. l.toggleMaximised (Panel::playlist);
  4739. CHECK (l[Panel::playlist].maximised && l.focused == Panel::playlist);
  4740. // save and load at another size: positions scale
  4741. l[Panel::mixer].detached = true;
  4742. l[Panel::mixer].windowBounds = { 100, 50, 900, 500 };
  4743. const auto text = l.serialise();
  4744. const auto big = Layout::parse (text, 2560, 1240);
  4745. CHECK (big.has_value());
  4746. if (big)
  4747. {
  4748. CHECK ((*big)[Panel::playlist].maximised && (*big)[Panel::mixer].detached && (*big)[Panel::mixer].windowBounds.w == 900);
  4749. CHECK (std::abs ((*big)[Panel::playlist].bounds.x - 2 * l[Panel::playlist].bounds.x) <= 1);
  4750. CHECK (big->order == l.order && big->focused == l.focused);
  4751. }
  4752. 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));
  4753. // resize keeps panels inside and edges glued to the border
  4754. l.resize (1000, 500);
  4755. CHECK (l[Panel::playlist].bounds.right() == 1000 && l[Panel::browser].bounds.bottom() == 500);
  4756. for (const auto& p : l.panels)
  4757. CHECK (p.bounds.right() <= 1000 && p.bounds.bottom() <= 500);
  4758. // off-screen panels come back
  4759. l[Panel::pianoRoll].bounds = { 5000, -300, 400, 300 };
  4760. CHECK (l.bringBackOffscreen() == 1 && l[Panel::pianoRoll].bounds.x + 400 <= 1000 && l[Panel::pianoRoll].bounds.y == 0);
  4761. // snapping: to the desktop, to another panel, and resizing one edge
  4762. CHECK ((snap ({ 5, 6, 200, 100 }, {}, 1000, 500) == Rect { 0, 0, 200, 100 }));
  4763. CHECK ((snap ({ 304, 50, 200, 100 }, { { 0, 0, 300, 400 } }, 1000, 500) == Rect { 300, 50, 200, 100 }));
  4764. CHECK ((snap ({ 304, 50, 200, 100 }, { { 0, 0, 300, 400 } }, 1000, 500, 2) == Rect { 304, 50, 200, 100 })); // out of range
  4765. CHECK ((snap ({ 100, 100, 195, 100 }, { { 300, 0, 300, 400 } }, 1000, 500, 8, right) == Rect { 100, 100, 200, 100 }));
  4766. CHECK ((snap ({ 100, 100, 195, 100 }, { { 300, 1000, 300, 400 } }, 2000, 2000, 8, right) == Rect { 100, 100, 195, 100 })); // not facing
  4767. }
  4768. TEST (workflow_control_math)
  4769. {
  4770. using namespace lynx::controls;
  4771. CHECK (std::abs (dragValue (0.5, 75, 0, 1, 150, false) - 1.0) < 1e-9);
  4772. CHECK (std::abs (dragValue (0.5, 75, 0, 1, 150, true) - 0.55) < 1e-9);
  4773. CHECK (dragValue (0.5, -1000, -1, 1, 150, false) == -1.0);
  4774. 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);
  4775. CHECK (wheelValue (3, 1, 0, 10, true, 1) == 4.0); // integer controls move at least one step
  4776. CHECK (std::abs (snapToInterval (0.234, 0, 0.1) - 0.2) < 1e-9);
  4777. CHECK (tempoDrag (130.0, 8, false, false) == 132.0 && tempoDrag (130.0, -3, false, false) == 130.0);
  4778. CHECK (std::abs (tempoDrag (130.0, 25, true, false) - 130.25) < 1e-9);
  4779. CHECK (std::abs (tempoDrag (130.0, 8, false, true) - 130.2) < 1e-9);
  4780. CHECK (tempoDrag (520.0, 400, false, false) == lynx::maxTempo && halfTempo (15.0) == lynx::minTempo && doubleTempo (130.0) == 260.0);
  4781. TapTempo tap;
  4782. CHECK (! tap.tap (1000.0));
  4783. CHECK (tap.tap (1500.0) == 120.0);
  4784. CHECK (tap.tap (2000.0) == 120.0 && tap.count() == 3);
  4785. CHECK (std::abs (*tap.tap (2400.0) - 128.57) < 0.01); // average of 500, 500, 400 ms
  4786. CHECK (! tap.tap (9000.0) && tap.count() == 1); // a long pause starts over
  4787. }
  4788. int main (int argc, char** argv)
  4789. {
  4790. if (argc > 1)
  4791. realFlpDir = argv[1];
  4792. const char* only = std::getenv ("LYNX_TEST"); // run only the tests whose name contains this
  4793. for (auto& [name, fn] : registry())
  4794. {
  4795. if (only != nullptr && std::strstr (name, only) == nullptr)
  4796. continue;
  4797. std::printf ("%s\n", name);
  4798. fn();
  4799. }
  4800. std::printf ("\n%d checks, %d failures\n", checks, failures);
  4801. return failures == 0 ? 0 : 1;
  4802. }
  4803. TEST (synth_cutoff_keytrack)
  4804. {
  4805. // the cutoff follows the note from key 48 (130.81 Hz), like Harmor's "Key to filter frequency"
  4806. auto rms = [] (float keyTrack, int key) {
  4807. lynx::SynthSettings s;
  4808. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  4809. s.cutoff = 130.81f;
  4810. s.keyTrack = keyTrack;
  4811. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  4812. inst->prepare (48000.0);
  4813. lynx::ChannelDef c;
  4814. c.synth = s;
  4815. inst->configure (c, 120.0);
  4816. inst->noteOn (key, 1.0f);
  4817. std::vector<float> l (24000), r (24000);
  4818. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  4819. double e = 0.0;
  4820. for (int i = 4800; i < 24000; ++i)
  4821. e += (double) l[(std::size_t) i] * l[(std::size_t) i];
  4822. return std::sqrt (e / 19200.0);
  4823. };
  4824. const auto fixed = rms (0.0f, 72), tracked = rms (1.0f, 72);
  4825. CHECK (tracked > 4.0 * fixed); // 2 octaves up: without keytrack the low-pass cuts
  4826. CHECK (std::abs (rms (1.0f, 48) - rms (0.0f, 48)) < 0.05 * rms (0.0f, 48)); // unchanged at the reference key
  4827. }
  4828. namespace
  4829. {
  4830. std::vector<float> renderSynthNote (const lynx::SynthSettings& s, int key, int frames)
  4831. {
  4832. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  4833. inst->prepare (48000.0);
  4834. lynx::ChannelDef c;
  4835. c.synth = s;
  4836. inst->configure (c, 120.0);
  4837. inst->noteOn (key, 1.0f);
  4838. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  4839. inst->render (l.data(), r.data(), frames, 1.0f, 1.0f);
  4840. return l;
  4841. }
  4842. double goertzel (const std::vector<float>& x, double f, int from, int to)
  4843. {
  4844. const auto w = 2.0 * 3.141592653589793 * f / 48000.0, k = 2.0 * std::cos (w);
  4845. double s1 = 0.0, s2 = 0.0;
  4846. for (int i = from; i < to; ++i)
  4847. {
  4848. const auto s0 = x[(std::size_t) i] + k * s1 - s2;
  4849. s2 = s1;
  4850. s1 = s0;
  4851. }
  4852. return s1 * s1 + s2 * s2 - k * s1 * s2;
  4853. }
  4854. } // namespace
  4855. TEST (synth_pitch_sweep_ring_and_bands)
  4856. {
  4857. lynx::SynthSettings sine;
  4858. sine.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  4859. sine.cutoff = 20000.0f;
  4860. // sweep: starts at f·(1 + sweep) and returns to f (time constant s = 10 ms; s⁴ falls 4× faster)
  4861. auto sweep = sine;
  4862. sweep.sweep = 1.0f;
  4863. sweep.sweepTime = 0.01f;
  4864. const auto a = renderSynthNote (sweep, 69, 24000);
  4865. auto crossings = [] (const std::vector<float>& x, int to) {
  4866. int n = 0;
  4867. for (int i = 1; i < to; ++i)
  4868. n += (x[(std::size_t) i - 1] < 0.0f) != (x[(std::size_t) i] < 0.0f);
  4869. return n;
  4870. };
  4871. CHECK (crossings (a, 480) > 1.3 * crossings (renderSynthNote (sine, 69, 480), 480)); // 10 ms: much higher
  4872. CHECK (goertzel (a, 440.0, 12000, 24000) > 100.0 * goertzel (a, 880.0, 12000, 24000));
  4873. // ring with |a| = 1: carrier 440 × modulator 110 -> only 330 and 550, no 440
  4874. auto ring = sine;
  4875. ring.am = ring.ring = true;
  4876. ring.osc[2] = { lynx::Waveform::sine, -2, 0.0f, 1.0f };
  4877. const auto b = renderSynthNote (ring, 69, 24000);
  4878. CHECK (goertzel (b, 330.0, 4800, 24000) > 100.0 * goertzel (b, 440.0, 4800, 24000));
  4879. CHECK (goertzel (b, 550.0, 4800, 24000) > 100.0 * goertzel (b, 440.0, 4800, 24000));
  4880. // 3 bands: muting the high knocks down a 4 kHz note and barely touches an 80 Hz one
  4881. auto bands = sine;
  4882. bands.bandGain = { 1.0f, 1.0f, 0.0f };
  4883. auto rms = [] (const std::vector<float>& x) {
  4884. double e = 0.0;
  4885. for (std::size_t i = 4800; i < x.size(); ++i)
  4886. e += (double) x[i] * x[i];
  4887. return std::sqrt (e / (double) (x.size() - 4800));
  4888. };
  4889. CHECK (rms (renderSynthNote (bands, 107, 24000)) < 0.3 * rms (renderSynthNote (sine, 107, 24000)));
  4890. CHECK (rms (renderSynthNote (bands, 28, 24000)) > 0.85 * rms (renderSynthNote (sine, 28, 24000)));
  4891. }
  4892. TEST (love_philter_map_evaluation)
  4893. {
  4894. lynx::LovePhilterMap line { { { 0.0, 0.0 }, { 1.0, 1.0 } } };
  4895. CHECK (std::abs (lynx::lovePhilterMapAt (line, 0.5) - 0.5) < 1e-9);
  4896. CHECK (std::abs (lynx::lovePhilterMapAt (line, 1.0) - 1.0) < 1e-9);
  4897. // steps (Δx = 0): 1 until 0.4375, ramp to 0 at 0.5, then 0
  4898. lynx::LovePhilterMap steps { { { 0.0, 1.0 }, { 0.4375, 1.0 }, { 0.0625, 0.0 }, { 0.5, 0.0 } } };
  4899. CHECK (lynx::lovePhilterMapAt (steps, 0.27) == 1.0);
  4900. CHECK (lynx::lovePhilterMapAt (steps, 0.75) == 0.0);
  4901. CHECK (std::abs (lynx::lovePhilterMapAt (steps, 0.46875) - 0.5) < 1e-9);
  4902. CHECK (lynx::lovePhilterMapAt ({}, 0.3) == 1.0);
  4903. }
  4904. TEST (lofi_holds_and_quantizes)
  4905. {
  4906. auto fx = lynx::makeEffect (lynx::EffectKind::lofi);
  4907. fx->prepare (48000.0);
  4908. auto slot = lynx::makeEffectSlot (lynx::EffectKind::lofi);
  4909. slot.params[0] = 0.5f; // 128·0.125 + 1 = 17 samples
  4910. slot.params[1] = 1.0f; // 65536/2049 ≈ 32 levels
  4911. std::vector<float> l (170), r (170);
  4912. for (std::size_t i = 0; i < l.size(); ++i)
  4913. l[i] = r[i] = 0.9f * (float) std::sin (0.05 * (double) i);
  4914. const auto original = l;
  4915. fx->process (l.data(), r.data(), 170, slot.params, 120.0);
  4916. for (int i = 0; i < 17; ++i)
  4917. CHECK (l[(std::size_t) i] == l[0]);
  4918. CHECK (l[17] != l[16]);
  4919. const auto step = 2.0f * 2049.0f / 65536.0f;
  4920. for (auto v : l)
  4921. CHECK (std::abs (v / step - std::round (v / step)) < 1e-3f);
  4922. CHECK (std::abs (l[0] - original[0]) <= step);
  4923. CHECK (lynx::formatEffectParam (lynx::EffectKind::lofi, 1, 0.0f, 120.0) == "16.0 bits");
  4924. }
  4925. namespace
  4926. {
  4927. lynx::EffectParams effectorParams (int type, float x, float y)
  4928. {
  4929. auto slot = lynx::makeEffectSlot (lynx::EffectKind::effector);
  4930. slot.params[0] = (float) type / 11.0f;
  4931. slot.params[3] = x;
  4932. slot.params[4] = y;
  4933. return slot.params;
  4934. }
  4935. } // namespace
  4936. TEST (effector_algorithms)
  4937. {
  4938. CHECK (lynx::effector::typeOf (8.0f / 11.0f) == 8);
  4939. CHECK (std::string (lynx::effector::typeName (11)) == "Ring");
  4940. CHECK (std::abs (lynx::effector::rateBeats (0.5f, 0.0f) - 0.75) < 1e-9); // trunc(8·0.5 + 0.5) = 4 -> 3/4
  4941. CHECK (std::abs (lynx::effector::rateBeats (1.0f, 0.5f) - 2.0) < 1e-9); // 8 × (1 − 0.5)²
  4942. auto run = [] (const lynx::EffectParams& p, std::vector<float> in, double bpm = 120.0) {
  4943. auto fx = lynx::makeEffect (lynx::EffectKind::effector);
  4944. fx->prepare (48000.0);
  4945. fx->setSongPosition (0.0);
  4946. auto r = in;
  4947. fx->process (in.data(), r.data(), (int) in.size(), p, bpm);
  4948. return in;
  4949. };
  4950. // Distort with Y = 1 (everything goes to the cascade): 0.5 comes out 0.5 (compensation G = 0.5/F(0.5))
  4951. {
  4952. auto p = effectorParams (0, 0.5f, 1.0f);
  4953. const auto out = run (p, std::vector<float> (4800, 0.5f));
  4954. CHECK (std::abs (out.back() - 0.5f) < 1e-3f);
  4955. const auto small = run (p, std::vector<float> (4800, 0.05f));
  4956. CHECK (small.back() > 0.45f && small.back() < 0.5f); // saturates near ±0.5
  4957. }
  4958. // Ring: DC 1 becomes the carrier sine, 2^(8.7·0 + 5) = 32 Hz -> 32 cycles per second
  4959. {
  4960. auto p = effectorParams (11, 0.0f, 0.0f);
  4961. const auto out = run (p, std::vector<float> (48000, 1.0f));
  4962. int crossings = 0;
  4963. for (std::size_t i = 4800; i < out.size(); ++i)
  4964. crossings += (out[i - 1] < 0.0f) != (out[i] < 0.0f);
  4965. CHECK (crossings >= 56 && crossings <= 60); // 0.9 s × 32 Hz × 2
  4966. }
  4967. // Trancer, Y = 0: at the start of the period the gain drops to zero; X = 1 returns only at the end of the period
  4968. {
  4969. auto p = effectorParams (8, 1.0f, 0.0f);
  4970. p[5] = 1.0f; // 8/1 = 8 beats = 4 s at 120 BPM
  4971. const auto out = run (p, std::vector<float> (48000, 1.0f));
  4972. CHECK (out[100] > 0.3f); // still rising on the "and" (1% of the period = 40 ms)
  4973. CHECK (out[24000] < 0.05f); // 0.5 s: trough
  4974. }
  4975. // Reverb with Wet = 0: the dry passes intact
  4976. {
  4977. auto p = effectorParams (6, 0.5f, 0.5f);
  4978. p[2] = 0.0f;
  4979. std::vector<float> in (4800);
  4980. for (std::size_t i = 0; i < in.size(); ++i)
  4981. in[i] = (float) std::sin (0.01 * (double) i);
  4982. const auto out = run (p, in);
  4983. for (std::size_t i = 0; i < in.size(); ++i)
  4984. CHECK (std::abs (out[i] - in[i]) < 1e-6f);
  4985. }
  4986. // Delay: the echo arrives after the Mod Rate period (1/4 beat at 120 BPM = 125 ms), at level X²
  4987. {
  4988. auto p = effectorParams (5, 0.7f, 0.5f);
  4989. p[5] = 1.0f / 8.0f; // index 1 = 1/4
  4990. std::vector<float> in (12000, 0.0f);
  4991. in[0] = 1.0f;
  4992. const auto out = run (p, in);
  4993. CHECK (std::abs (out[6000] - 0.49f) < 0.02f);
  4994. CHECK (std::abs (out[3000]) < 1e-6f);
  4995. }
  4996. // Stutter: repeats the recorded start every period
  4997. {
  4998. auto p = effectorParams (9, 0.0f, 0.0f);
  4999. p[5] = 0.0f; // 1/8 beat = 62.5 ms = 3000 samples
  5000. std::vector<float> in (9000);
  5001. for (std::size_t i = 0; i < in.size(); ++i)
  5002. in[i] = (float) i / 9000.0f;
  5003. const auto out = run (p, in);
  5004. CHECK (std::abs (out[3000 + 500] - in[500]) < 0.01f); // after the crossfade, it's the start again
  5005. CHECK (std::abs (out[1000] - in[1000]) < 1e-6f);
  5006. }
  5007. }
  5008. TEST (crossover_linkwitz_riley_sums_flat)
  5009. {
  5010. // low band + high band of the same crossover: sum with magnitude 1 (Linkwitz-Riley; for 12 and 36 dB the HP is inverted)
  5011. for (const auto combo : { 1, 3, 4, 5, 6, 7 })
  5012. for (const auto testHz : { 200.0, 1000.0, 5000.0 })
  5013. {
  5014. auto run = [&] (bool high) {
  5015. auto fx = lynx::makeEffect (lynx::EffectKind::crossover);
  5016. fx->prepare (48000.0);
  5017. auto slot = lynx::makeEffectSlot (lynx::EffectKind::crossover);
  5018. const auto value = (float) (std::log2 (1000.0 / 30.0) / 9.0589);
  5019. slot.params[high ? 0 : 3] = 1.0f;
  5020. slot.params[high ? 1 : 4] = value;
  5021. slot.params[high ? 2 : 5] = (float) combo / 7.0f;
  5022. std::vector<float> l (24000), r (24000);
  5023. for (std::size_t i = 0; i < l.size(); ++i)
  5024. l[i] = r[i] = (float) std::sin (2.0 * 3.141592653589793 * testHz * (double) i / 48000.0);
  5025. fx->process (l.data(), r.data(), 24000, slot.params, 120.0);
  5026. return l;
  5027. };
  5028. const auto low = run (false), high = run (true);
  5029. double peak = 0.0;
  5030. for (std::size_t i = 12000; i < low.size(); ++i)
  5031. peak = std::max (peak, (double) std::abs (low[i] + high[i]));
  5032. CHECK (std::abs (peak - 1.0) < 0.02);
  5033. }
  5034. // 96 dB/oct: two octaves above the cutoff the low-pass is already below −150 dB... in practice, very low
  5035. auto fx = lynx::makeEffect (lynx::EffectKind::crossover);
  5036. fx->prepare (48000.0);
  5037. auto slot = lynx::makeEffectSlot (lynx::EffectKind::crossover);
  5038. slot.params[3] = 1.0f;
  5039. slot.params[4] = (float) (std::log2 (500.0 / 30.0) / 9.0589);
  5040. slot.params[5] = 1.0f;
  5041. std::vector<float> l (24000), r (24000);
  5042. for (std::size_t i = 0; i < l.size(); ++i)
  5043. l[i] = r[i] = (float) std::sin (2.0 * 3.141592653589793 * 2000.0 * (double) i / 48000.0);
  5044. fx->process (l.data(), r.data(), 24000, slot.params, 120.0);
  5045. float peak = 0.0f;
  5046. for (std::size_t i = 12000; i < l.size(); ++i)
  5047. peak = std::max (peak, std::abs (l[i]));
  5048. CHECK (peak < 1e-4f);
  5049. }
  5050. TEST (rhythm_gain_and_autopan)
  5051. {
  5052. // 1-beat gate: 1 → 0 at 0.5 beat (linear) → 1 at the end; at 120 BPM 1 beat = 24000 samples at 48 kHz
  5053. auto slot = lynx::makeEffectSlot (lynx::EffectKind::rhythmGain);
  5054. slot.params[0] = 1.0f / 64.0f;
  5055. slot.params[1] = 3.0f / 12.0f;
  5056. const float pts[3][3] = { { 0.0f, 1.0f, 0.5f }, { 0.5f, 0.0f, 0.5f }, { 1.0f, 1.0f, 0.5f } };
  5057. for (int k = 0; k < 3; ++k)
  5058. for (int j = 0; j < 3; ++j)
  5059. slot.params[(std::size_t) (2 + 3 * k + j)] = pts[k][j];
  5060. auto fx = lynx::makeEffect (lynx::EffectKind::rhythmGain);
  5061. fx->prepare (48000.0);
  5062. fx->setSongPosition (960.0 * 2.0); // beat 2: phase 0
  5063. std::vector<float> l (24000, 1.0f), r (24000, 1.0f);
  5064. fx->process (l.data(), r.data(), 24000, slot.params, 120.0);
  5065. CHECK (std::abs (l[0] - 1.0f) < 1e-3f);
  5066. CHECK (std::abs (l[6000] - 0.5f) < 1e-3f);
  5067. CHECK (l[12000] < 1e-3f);
  5068. CHECK (std::abs (l[18000] - 0.5f) < 1e-3f);
  5069. // positive tension: changes quickly at the start of the segment
  5070. CHECK (lynx::effectInfo (lynx::EffectKind::rhythmGain).params.size() == 39);
  5071. // auto-pan: 1-beat period, full depth; start phase 0.75 -> W = 0 rising (pan centered)
  5072. auto pan = lynx::makeEffectSlot (lynx::EffectKind::autoPan);
  5073. pan.params[0] = 1.0f / 64.0f;
  5074. pan.params[1] = 1.0f;
  5075. auto ap = lynx::makeEffect (lynx::EffectKind::autoPan);
  5076. ap->prepare (48000.0);
  5077. ap->setSongPosition (0.0);
  5078. std::vector<float> a (24000, 1.0f), b (24000, 1.0f);
  5079. ap->process (a.data(), b.data(), 24000, pan.params, 120.0);
  5080. CHECK (std::abs (a[0] - 1.0f) < 1e-3f && std::abs (b[0] - 1.0f) < 1e-3f);
  5081. CHECK (a[6000] < 0.01f && std::abs (b[6000] - 1.0f) < 1e-3f); // ¼ cycle later: fully right
  5082. }
  5083. TEST (vocoder_side_inputs_split_modulator_and_carrier)
  5084. {
  5085. // "Side inputs" mode (Vocodex): modulator from side input 1 (noise in the first half), carrier from side input 2
  5086. // (saw), own input silent → the output follows the side modulator; with input 1 silent, the output is silent
  5087. auto slot = lynx::makeEffectSlot (lynx::EffectKind::vocoder);
  5088. slot.params[16] = 1.0f;
  5089. auto fx = lynx::makeEffect (lynx::EffectKind::vocoder);
  5090. fx->prepare (48000.0);
  5091. std::vector<float> modL (48000), car (48000), l (48000, 0.0f), r (48000, 0.0f);
  5092. std::uint32_t seed = 1;
  5093. for (std::size_t i = 0; i < modL.size(); ++i)
  5094. {
  5095. seed = seed * 1664525u + 1013904223u;
  5096. modL[i] = i < 24000 ? ((float) (seed >> 8) / 16777216.0f - 0.5f) : 0.0f;
  5097. car[i] = (float) (2.0 * std::fmod ((double) i * 220.0 / 48000.0, 1.0) - 1.0) * 0.5f;
  5098. }
  5099. for (int done = 0; done < 48000; done += 480)
  5100. {
  5101. fx->setSidechain (modL.data() + done, modL.data() + done);
  5102. fx->setSidechain2 (car.data() + done, car.data() + done);
  5103. fx->process (l.data() + done, r.data() + done, 480, slot.params, 120.0);
  5104. }
  5105. auto rms = [&] (int from, int to) {
  5106. double e = 0.0;
  5107. for (int i = from; i < to; ++i)
  5108. e += (double) l[(std::size_t) i] * l[(std::size_t) i];
  5109. return std::sqrt (e / (to - from));
  5110. };
  5111. CHECK (rms (6000, 20000) > 0.01);
  5112. CHECK (rms (40000, 48000) < 0.1 * rms (6000, 20000));
  5113. // the side modulator configured but silent: nothing comes out (the own input is not used instead)
  5114. std::vector<float> a (4800, 0.3f), b (4800, 0.3f);
  5115. for (int done = 0; done < 4800; done += 480)
  5116. {
  5117. fx->setSidechain (nullptr, nullptr);
  5118. fx->setSidechain2 (car.data() + done, car.data() + done);
  5119. fx->process (a.data() + done, b.data() + done, 480, slot.params, 120.0);
  5120. }
  5121. CHECK (std::abs (a[4700]) < 0.05f);
  5122. }
  5123. TEST (vocoder_follows_modulator)
  5124. {
  5125. // modulator (L) plays only in the first half; carrier (R) is a continuous saw: the wet follows the modulator
  5126. auto slot = lynx::makeEffectSlot (lynx::EffectKind::vocoder);
  5127. auto fx = lynx::makeEffect (lynx::EffectKind::vocoder);
  5128. fx->prepare (48000.0);
  5129. std::vector<float> l (48000), r (48000);
  5130. std::uint32_t seed = 1;
  5131. for (std::size_t i = 0; i < l.size(); ++i)
  5132. {
  5133. seed = seed * 1664525u + 1013904223u;
  5134. l[i] = i < 24000 ? ((float) (seed >> 8) / 16777216.0f - 0.5f) : 0.0f;
  5135. r[i] = (float) (2.0 * std::fmod ((double) i * 220.0 / 48000.0, 1.0) - 1.0) * 0.5f;
  5136. }
  5137. fx->process (l.data(), r.data(), 48000, slot.params, 120.0);
  5138. auto rms = [&] (int from, int to) {
  5139. double e = 0.0;
  5140. for (int i = from; i < to; ++i)
  5141. e += (double) l[(std::size_t) i] * l[(std::size_t) i];
  5142. return std::sqrt (e / (to - from));
  5143. };
  5144. CHECK (rms (6000, 20000) > 0.01);
  5145. CHECK (rms (40000, 48000) < 0.1 * rms (6000, 20000)); // modulator silent: the vocoder fades out (100 ms release)
  5146. for (std::size_t i = 0; i < l.size(); ++i)
  5147. CHECK (l[i] == r[i] && std::isfinite (l[i])); // mono output
  5148. }
  5149. // Vocodex (REA_rodada35): a synthetic state in FL's layout (version 8, 13 maps, 20 parameters, the 0x24 block,
  5150. // 13 map-axis bytes, tone, notes)
  5151. struct VocodexSpec
  5152. {
  5153. // Wet, SG, ModVol, ModHP, CarVol, CarLP, CarNoise, CarNoiseHP, Hold, Att, AttCurve, Rel, RelCurve, Freeze, BW,
  5154. // Flatness, ModBW, ModPitch, FatPitch, FatPan
  5155. 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 };
  5156. std::array<std::int32_t, 7> block { 0, 2, 0, 24, 1, 1, 2 }; // hold mode, order, unison, bands, draft field, ModIn, CarIn
  5157. 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
  5158. std::vector<std::uint8_t> bytes() const
  5159. {
  5160. std::vector<std::uint8_t> d;
  5161. 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); };
  5162. auto i32 = [&] (std::int32_t v) { put (&v, 4); };
  5163. i32 (8 << 16);
  5164. for (int m = 0; m < 13; ++m)
  5165. {
  5166. const double y0 = m == 8 ? 0.1429 : (m == 3 || m == 4 || m == 11) ? 0.0 : 0.5;
  5167. const double y1 = m == 8 ? 0.9918 : y0;
  5168. i32 (1), i32 (0), i32 (2);
  5169. for (const auto& [dx, y] : { std::pair { 0.0, y0 }, std::pair { 1.0, y1 } })
  5170. {
  5171. put (&dx, 8), put (&y, 8);
  5172. i32 (0), i32 (0); // tension (f32 0), flags
  5173. }
  5174. const std::array<std::uint8_t, 20> tail {};
  5175. put (tail.data(), tail.size());
  5176. }
  5177. for (auto v : params)
  5178. i32 (v);
  5179. for (auto v : block)
  5180. i32 (v);
  5181. put (flags.data(), flags.size());
  5182. const std::array<std::uint8_t, 13> axis {};
  5183. put (axis.data(), axis.size());
  5184. d.push_back (3), put ("PWM", 3);
  5185. i32 (1), i32 (60);
  5186. return d;
  5187. }
  5188. };
  5189. std::vector<float> vocodexSaw (int n, double hz, double fs)
  5190. {
  5191. std::vector<float> out ((std::size_t) n);
  5192. for (int i = 0; i < n; ++i)
  5193. out[(std::size_t) i] = (float) (2.0 * std::fmod (i * hz / fs, 1.0) - 1.0) * 0.4f;
  5194. return out;
  5195. }
  5196. TEST (vocodex_state_parse_and_conversion)
  5197. {
  5198. VocodexSpec spec;
  5199. spec.block = { 1, 3, 2, 40, 0, 2, 1 };
  5200. spec.params[17] = -1200;
  5201. const auto raw = spec.bytes();
  5202. const auto s = lynx::vocodex::parseState (raw);
  5203. CHECK (s.has_value());
  5204. if (! s)
  5205. return;
  5206. CHECK (s->version == 8 && s->holdMode == 1 && s->order == 3 && s->unison == 2 && s->bands == 40);
  5207. CHECK (s->draft() && s->modIn == 2 && s->carIn == 1 && s->minTimes && s->subtractiveGate && ! s->lrEncoding);
  5208. CHECK (s->params[lynx::vocodex::modPitch] == -1200 && s->params[lynx::vocodex::carLp] == 65536);
  5209. 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);
  5210. CHECK (s->tone == "PWM" && s->notes.size() == 1 && s->notes[0] == 60);
  5211. const auto v = lynx::vocodexEffect (raw);
  5212. CHECK (v && v->slot.kind == lynx::EffectKind::vocodex && v->slot.state == raw && v->modIn == 2 && v->carIn == 1 && v->notes.empty());
  5213. spec.block[6] = -1; // internal synth carrier: not available yet → reported
  5214. spec.params[1] = 150; // Soundgoodizer stage
  5215. const auto w = lynx::vocodexEffect (spec.bytes());
  5216. CHECK (w && w->carIn == -1 && w->notes.size() == 2);
  5217. CHECK (! lynx::vocodex::parseState ({ 1, 2, 3 }).has_value());
  5218. }
  5219. TEST (vocodex_vocodes_side_inputs)
  5220. {
  5221. // modulator on side input 1 (noise in the first half), carrier on side input 2 (saw), own input silent: the
  5222. // output follows the modulator's envelope and fades after it stops
  5223. VocodexSpec spec;
  5224. lynx::EffectSlot slot = lynx::makeEffectSlot (lynx::EffectKind::vocodex);
  5225. slot.state = spec.bytes();
  5226. auto fx = lynx::makeEffect (slot);
  5227. fx->prepare (48000.0);
  5228. CHECK (fx->latencySamples() == 0);
  5229. const auto car = vocodexSaw (48000, 110.0, 48000.0);
  5230. std::vector<float> mod (48000), l (48000, 0.0f), r (48000, 0.0f);
  5231. std::uint32_t seed = 7;
  5232. for (std::size_t i = 0; i < mod.size(); ++i)
  5233. {
  5234. seed = seed * 1664525u + 1013904223u;
  5235. mod[i] = i < 24000 ? ((float) (seed >> 8) / 16777216.0f - 0.5f) : 0.0f;
  5236. }
  5237. for (int done = 0; done < 48000; done += 512)
  5238. {
  5239. const int n = std::min (512, 48000 - done);
  5240. fx->setSidechain (mod.data() + done, mod.data() + done);
  5241. fx->setSidechain2 (car.data() + done, car.data() + done);
  5242. fx->process (l.data() + done, r.data() + done, n, slot.params, 120.0);
  5243. }
  5244. auto rms = [&] (int from, int to) {
  5245. double e = 0.0;
  5246. for (int i = from; i < to; ++i)
  5247. e += (double) l[(std::size_t) i] * l[(std::size_t) i] + (double) r[(std::size_t) i] * r[(std::size_t) i];
  5248. return std::sqrt (e / (2.0 * (to - from)));
  5249. };
  5250. CHECK (rms (6000, 20000) > 0.02);
  5251. CHECK (rms (40000, 48000) < 0.01 * rms (6000, 20000));
  5252. CHECK (std::abs (l[0]) < 1e-6f); // the gains ramp up from 0 when the plugin is created
  5253. }
  5254. TEST (vocodex_draft_latency_and_pass_through)
  5255. {
  5256. // carrier pass-through at unit gain only (Wet 0): after a Flush the gains snap, so the output is the carrier,
  5257. // 16 samples late in Draft
  5258. VocodexSpec spec;
  5259. spec.params[0] = 0; // Wet
  5260. spec.params[4] = 12800; // CarVol = 1
  5261. for (const int draftField : { 1, 0 })
  5262. {
  5263. spec.block[4] = draftField;
  5264. const auto s = lynx::vocodex::parseState (spec.bytes());
  5265. CHECK (s.has_value());
  5266. lynx::vocodex::Engine engine;
  5267. engine.prepare (*s, 44100.0, 300, s->draft());
  5268. CHECK (engine.latencySamples() == (draftField == 0 ? 16 : 0));
  5269. engine.flush();
  5270. const auto saw = vocodexSaw (3000, 220.0, 44100.0);
  5271. std::vector<float> car (6000), mod (6000, 0.0f), out (6000);
  5272. for (int i = 0; i < 3000; ++i)
  5273. car[(std::size_t) (2 * i)] = car[(std::size_t) (2 * i + 1)] = saw[(std::size_t) i];
  5274. static constexpr int sizes[] { 300, 37, 128, 1, 255, 16, 299 }; // uneven blocks exercise the FIFOs
  5275. for (int done = 0, k = 0, n = 0; done < 3000; done += n, ++k)
  5276. {
  5277. n = std::min (sizes[k % 7], 3000 - done);
  5278. engine.process (mod.data() + 2 * done, mod.data() + 2 * done, car.data() + 2 * done, out.data() + 2 * done, n);
  5279. }
  5280. const int lag = engine.latencySamples();
  5281. auto maxError = 0.0f;
  5282. for (int i = lag; i < 3000; ++i)
  5283. maxError = std::max (maxError, std::abs (out[(std::size_t) (2 * i)] - saw[(std::size_t) (i - lag)]));
  5284. CHECK (maxError == 0.0f);
  5285. }
  5286. }
  5287. TEST (vocodex_soundgoodizer_stage_limits_the_output)
  5288. {
  5289. // SG > 0: the vocoder's output (loud here: Wet 2000) goes through the Soundgoodizer approximation, whose
  5290. // master limiter keeps the peaks under −0.2 dBFS; its look-ahead is reported as latency
  5291. VocodexSpec spec;
  5292. spec.params[0] = 2000;
  5293. spec.params[1] = 250;
  5294. lynx::EffectSlot slot = lynx::makeEffectSlot (lynx::EffectKind::vocodex);
  5295. slot.state = spec.bytes();
  5296. auto fx = lynx::makeEffect (slot);
  5297. fx->prepare (48000.0);
  5298. CHECK (fx->latencySamples() == 72); // 1.5 ms at 48 kHz
  5299. const auto car = vocodexSaw (48000, 110.0, 48000.0);
  5300. std::vector<float> mod (48000), l (48000, 0.0f), r (48000, 0.0f);
  5301. for (std::size_t i = 0; i < mod.size(); ++i)
  5302. mod[i] = 0.9f * (float) std::sin (0.07 * (double) i) * (float) std::sin (0.0003 * (double) i);
  5303. auto peak = 0.0f;
  5304. for (int done = 0; done < 48000; done += 512)
  5305. {
  5306. const int n = std::min (512, 48000 - done);
  5307. fx->setSidechain (mod.data() + done, mod.data() + done);
  5308. fx->setSidechain2 (car.data() + done, car.data() + done);
  5309. fx->process (l.data() + done, r.data() + done, n, slot.params, 120.0);
  5310. }
  5311. for (std::size_t i = 0; i < l.size(); ++i)
  5312. peak = std::max ({ peak, std::abs (l[i]), std::abs (r[i]) });
  5313. CHECK (peak > 0.5f && peak <= 0.9775f);
  5314. }
  5315. TEST (vocodex_tail_bypass_and_noise)
  5316. {
  5317. // both inputs silent for longer than 0.5 s + hold + release: the own input passes unchanged
  5318. VocodexSpec spec;
  5319. const auto s = lynx::vocodex::parseState (spec.bytes());
  5320. CHECK (s.has_value());
  5321. lynx::vocodex::Engine engine;
  5322. engine.prepare (*s, 44100.0, 512, false);
  5323. std::vector<float> zero (1024, 0.0f), own (1024), out (1024);
  5324. for (std::size_t i = 0; i < own.size(); ++i)
  5325. own[i] = 0.25f * (float) std::sin (0.01 * (double) i);
  5326. for (int b = 0; b < 80; ++b)
  5327. engine.process (own.data(), zero.data(), zero.data(), out.data(), 512);
  5328. CHECK (out == own);
  5329. // carrier noise: the IPP-compatible generator restarts from the same seed after a Flush
  5330. spec.params[6] = 9000;
  5331. const auto noisy = lynx::vocodex::parseState (spec.bytes());
  5332. lynx::vocodex::Engine a;
  5333. a.prepare (*noisy, 44100.0, 512, false);
  5334. std::vector<float> mod (1024), first (1024), second (1024);
  5335. for (std::size_t i = 0; i < mod.size(); ++i)
  5336. mod[i] = 0.3f * (float) std::sin (0.05 * (double) i);
  5337. a.flush();
  5338. a.process (own.data(), mod.data(), zero.data(), first.data(), 512);
  5339. a.flush();
  5340. a.process (own.data(), mod.data(), zero.data(), second.data(), 512);
  5341. CHECK (first == second);
  5342. auto energy = 0.0;
  5343. for (auto v : first)
  5344. energy += (double) v * v;
  5345. CHECK (energy > 1e-6 && std::isfinite (energy));
  5346. }
  5347. TEST (synth_spectral_oscillator)
  5348. {
  5349. // 1/n spectrum = saw: same harmonic proportions and same level as LYNX's saw
  5350. lynx::SynthSettings saw;
  5351. saw.osc[0] = { lynx::Waveform::saw, 0, 0.0f, 1.0f };
  5352. saw.cutoff = 20000.0f;
  5353. auto spectral = saw;
  5354. spectral.osc[0].wave = lynx::Waveform::spectral;
  5355. for (int n = 1; n <= lynx::SynthSettings::spectrumSize; ++n)
  5356. spectral.spectrum[(std::size_t) n - 1] = 1.0f / (float) n;
  5357. const auto a = renderSynthNote (saw, 57, 24000), b = renderSynthNote (spectral, 57, 24000); // 220 Hz
  5358. for (const auto h : { 1, 2, 3, 5 })
  5359. {
  5360. const auto ea = goertzel (a, 220.0 * h, 4800, 24000), eb = goertzel (b, 220.0 * h, 4800, 24000);
  5361. CHECK (std::abs (10.0 * std::log10 (eb / ea)) < 0.5); // within 0.5 dB
  5362. }
  5363. // odd only: no 2nd harmonic
  5364. auto odd = spectral;
  5365. for (int n = 2; n <= lynx::SynthSettings::spectrumSize; n += 2)
  5366. odd.spectrum[(std::size_t) n - 1] = 0.0f;
  5367. const auto c = renderSynthNote (odd, 57, 24000);
  5368. CHECK (goertzel (c, 440.0, 4800, 24000) < 1e-4 * goertzel (c, 220.0, 4800, 24000));
  5369. // high note: the band-limited tables don't pass Nyquist (no aliasing below the fundamental)
  5370. const auto d = renderSynthNote (spectral, 105, 24000); // 3520 Hz
  5371. CHECK (goertzel (d, 1000.0, 4800, 24000) < 1e-3 * goertzel (d, 3520.0, 4800, 24000));
  5372. }
  5373. TEST (compressor_sidechain_ducks_and_orders_mixer)
  5374. {
  5375. // the detector listens to the side input: quiet signal on the track, loud kick on the sidechain -> reduction
  5376. auto slot = lynx::makeEffectSlot (lynx::EffectKind::compressor);
  5377. slot.params[0] = 0.5f; // threshold
  5378. slot.params[1] = 1.0f; // high ratio
  5379. slot.params[4] = 0.0f;
  5380. auto run = [&] (bool withSidechain) {
  5381. auto fx = lynx::makeEffect (lynx::EffectKind::compressor);
  5382. fx->prepare (48000.0);
  5383. std::vector<float> l (4800, 0.1f), r (4800, 0.1f), kick (4800, 1.0f);
  5384. if (withSidechain)
  5385. fx->setSidechain (kick.data(), kick.data());
  5386. fx->process (l.data(), r.data(), 4800, slot.params, 120.0);
  5387. return l.back();
  5388. };
  5389. const auto alone = run (false), ducked = run (true);
  5390. CHECK (ducked < 0.5f * alone);
  5391. // order: track 5 listens to 7 via sidechain -> 7 comes before 5
  5392. auto song = lynx::Song::makeDefault();
  5393. while (song.mixer.size() < 8)
  5394. song.mixer.push_back ({});
  5395. auto comp = lynx::makeEffectSlot (lynx::EffectKind::compressor);
  5396. comp.sidechain = 7;
  5397. song.mixer[5].effects.push_back (comp);
  5398. const auto order = song.mixerOrder();
  5399. const auto at = [&] (int t) { return std::find (order.begin(), order.end(), t) - order.begin(); };
  5400. CHECK (at (7) < at (5));
  5401. }
  5402. TEST (pitch_correction_pulls_to_allowed_note)
  5403. {
  5404. auto run = [] (const lynx::EffectParams& p, double hz) {
  5405. auto fx = lynx::makeEffect (lynx::EffectKind::pitchCorrect);
  5406. fx->prepare (48000.0);
  5407. std::vector<float> l (48000 * 2), r;
  5408. for (std::size_t i = 0; i < l.size(); ++i)
  5409. l[i] = 0.5f * (float) std::sin (2.0 * 3.141592653589793 * hz * (double) i / 48000.0);
  5410. r = l;
  5411. fx->process (l.data(), r.data(), (int) l.size(), p, 120.0);
  5412. // frequency from zero crossings in the last second
  5413. int crossings = 0;
  5414. for (std::size_t i = 48000 + 1; i < l.size(); ++i)
  5415. crossings += (l[i - 1] < 0.0f) != (l[i] < 0.0f);
  5416. return crossings / 2.0;
  5417. };
  5418. auto slot = lynx::makeEffectSlot (lynx::EffectKind::pitchCorrect); // chromatic, instant, A 440
  5419. CHECK (std::abs (run (slot.params, 452.0) - 440.0) < 4.0);
  5420. for (int k = 0; k < 12; ++k)
  5421. slot.params[(std::size_t) (5 + k)] = k == 0 ? 1.0f : 0.0f; // only C
  5422. CHECK (std::abs (run (slot.params, 452.0) - 523.25) < 5.0); // C5 (523 Hz) is closer than C4 (262)
  5423. slot.params[2] = 1.0f; // turn everything off: passes unchanged
  5424. CHECK (std::abs (run (slot.params, 452.0) - 452.0) < 4.0);
  5425. }
  5426. TEST (pitch_correction_bypass_is_a_pure_delay)
  5427. {
  5428. // FL's Pitcher with Bypass All still runs its shifter: the plain path is an exact 9-sample delay, the formant
  5429. // path (256-Hann overlap-add) an exact 257-sample delay, and Gender changes nothing without a shift
  5430. // (REA_rodada30 §2.4/2.5); both are reported as latency
  5431. std::vector<float> in (48000);
  5432. for (std::size_t i = 0; i < in.size(); ++i)
  5433. in[i] = 0.5f * (float) std::sin (2.0 * 3.141592653589793 * 440.0 * (double) i / 48000.0)
  5434. + 0.2f * (float) std::sin (2.0 * 3.141592653589793 * 1234.5 * (double) i / 48000.0);
  5435. auto run = [&] (bool formant, float gender, int& latency) {
  5436. auto fx = lynx::makeEffect (lynx::EffectKind::pitchCorrect);
  5437. fx->prepare (48000.0);
  5438. auto slot = lynx::makeEffectSlot (lynx::EffectKind::pitchCorrect);
  5439. slot.params[2] = 1.0f;
  5440. slot.params[29] = formant ? 1.0f : 0.0f;
  5441. slot.params[30] = gender;
  5442. auto l = in, r = in;
  5443. for (std::size_t i = 0; i < l.size(); i += 480)
  5444. fx->process (l.data() + i, r.data() + i, 480, slot.params, 120.0);
  5445. latency = fx->latencySamples();
  5446. return l;
  5447. };
  5448. int latency = 0;
  5449. auto plain = run (false, 0.5f, latency);
  5450. CHECK (latency == 9);
  5451. auto worst = 0.0f;
  5452. for (std::size_t i = 4000; i < in.size(); ++i)
  5453. worst = std::max (worst, std::abs (plain[i] - in[i - 9]));
  5454. CHECK (worst < 1e-5f);
  5455. auto formant = run (true, 0.8f, latency);
  5456. CHECK (latency == 257);
  5457. worst = 0.0f;
  5458. for (std::size_t i = 4000; i < in.size(); ++i)
  5459. worst = std::max (worst, std::abs (formant[i] - in[i - 257]));
  5460. CHECK (worst < 1e-5f);
  5461. }
  5462. TEST (pitch_correction_formant_path)
  5463. {
  5464. // Formant on: PSOLA keeps the correction (output pitch = grain spacing) while Gender resamples the grains:
  5465. // the spectrum of a saw moves up with Gender > 0.5 and down with Gender < 0.5
  5466. auto run = [] (float gender) {
  5467. auto fx = lynx::makeEffect (lynx::EffectKind::pitchCorrect);
  5468. fx->prepare (48000.0);
  5469. auto slot = lynx::makeEffectSlot (lynx::EffectKind::pitchCorrect); // chromatic, instant, A 440
  5470. slot.params[29] = 1.0f;
  5471. slot.params[30] = gender;
  5472. std::vector<float> l (48000 * 2), r;
  5473. for (std::size_t i = 0; i < l.size(); ++i)
  5474. l[i] = 0.5f * (float) (2.0 * std::fmod (452.0 * (double) i / 48000.0, 1.0) - 1.0); // saw
  5475. r = l;
  5476. fx->process (l.data(), r.data(), (int) l.size(), slot.params, 120.0);
  5477. l.erase (l.begin(), l.begin() + 48000);
  5478. return l;
  5479. };
  5480. // period by autocorrelation (lags 60…160 = 300…800 Hz)
  5481. auto pitch = [] (const std::vector<float>& x) {
  5482. auto best = 0.0, bestLag = 0.0;
  5483. for (int lag = 60; lag <= 160; ++lag)
  5484. {
  5485. auto sum = 0.0;
  5486. for (std::size_t i = 0; i + (std::size_t) lag < x.size(); ++i)
  5487. sum += (double) x[i] * x[i + (std::size_t) lag];
  5488. if (sum > best)
  5489. {
  5490. best = sum;
  5491. bestLag = lag;
  5492. }
  5493. }
  5494. return 48000.0 / bestLag;
  5495. };
  5496. // brightness: energy of the first difference relative to the energy
  5497. auto brightness = [] (const std::vector<float>& x) {
  5498. auto e = 0.0, d = 0.0;
  5499. for (std::size_t i = 1; i < x.size(); ++i)
  5500. {
  5501. e += (double) x[i] * x[i];
  5502. d += (double) (x[i] - x[i - 1]) * (x[i] - x[i - 1]);
  5503. }
  5504. return d / e;
  5505. };
  5506. const auto neutral = run (0.5f), up = run (0.8f), down = run (0.3f);
  5507. CHECK (std::abs (pitch (neutral) - 440.0) < 5.0); // 452 Hz pulled to A
  5508. CHECK (std::abs (pitch (up) - 440.0) < 5.0); // Gender does not move the pitch
  5509. CHECK (brightness (up) > 1.5 * brightness (neutral));
  5510. CHECK (brightness (down) < 0.7 * brightness (neutral));
  5511. }
  5512. TEST (parallel_container_inner_links_modulate)
  5513. {
  5514. // one branch: utility (gain) + a control-only auto-pan LFO (1 beat); the link maps the LFO 0..1 onto the
  5515. // utility gain −24 dB..0 dB, so the level must swing; without the link it stays put
  5516. auto container = lynx::makeEffectSlot (lynx::EffectKind::parallel);
  5517. auto gain = lynx::makeEffectSlot (lynx::EffectKind::utility);
  5518. auto lfo = lynx::makeEffectSlot (lynx::EffectKind::autoPan);
  5519. lfo.params[0] = 1.0f / 64.0f;
  5520. lfo.params[4] = 1.0f; // control only: audio passes unchanged
  5521. container.branches.push_back ({ { gain, lfo }, 1.0f });
  5522. lynx::EffectLink link;
  5523. link.source = 1;
  5524. link.param = 0;
  5525. for (int i = 0; i <= 32; ++i)
  5526. link.curve.push_back (0.5f * (float) i / 32.0f);
  5527. auto levels = [&] (bool linked) {
  5528. auto slot = container;
  5529. if (linked)
  5530. slot.links.push_back (link);
  5531. auto fx = lynx::makeParallelEffect (slot);
  5532. fx->prepare (48000.0);
  5533. float lo = 1e9f, hi = 0.0f;
  5534. for (int block = 0; block < 94; ++block) // ~1 beat at 120 BPM in 256-sample blocks
  5535. {
  5536. std::vector<float> l (256, 1.0f), r (256, 1.0f);
  5537. fx->setSongPosition (block * 256.0 / 48000.0 * 2.0 * 960.0); // the engine positions every block
  5538. fx->process (l.data(), r.data(), 256, slot.params, 120.0);
  5539. lo = std::min (lo, std::abs (l[128]));
  5540. hi = std::max (hi, std::abs (l[128]));
  5541. }
  5542. return std::pair { lo, hi };
  5543. };
  5544. const auto [lo, hi] = levels (true);
  5545. CHECK (hi > 0.8f && lo < 0.12f);
  5546. const auto [lo0, hi0] = levels (false);
  5547. CHECK (std::abs (hi0 - lo0) < 1e-4f);
  5548. }
  5549. TEST (synth_spectrum_decays_per_harmonic)
  5550. {
  5551. // 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
  5552. lynx::SynthSettings s;
  5553. s.osc[0] = { lynx::Waveform::spectral, 0, 0.0f, 1.0f };
  5554. s.cutoff = 20000.0f;
  5555. s.decay = 0.0f;
  5556. s.sustain = 1.0f;
  5557. s.spectrum[0] = 1.0f;
  5558. s.spectrum[2] = 1.0f;
  5559. s.spectrumDecay[2] = 0.2f;
  5560. const auto x = renderSynthNote (s, 57, 48000); // 220 Hz, 48 kHz, 1 s
  5561. // equal 2400-sample windows (Goertzel power grows with the window): 10…60 ms and 500…550 ms
  5562. const auto early1 = goertzel (x, 220.0, 480, 2880), early3 = goertzel (x, 660.0, 480, 2880);
  5563. const auto late1 = goertzel (x, 220.0, 24000, 26400), late3 = goertzel (x, 660.0, 24000, 26400);
  5564. CHECK (early3 > 0.05 * early1); // ≈ −9 dB on average over 10…60 ms
  5565. CHECK (late3 < 1e-4 * late1);
  5566. CHECK (std::abs (10.0 * std::log10 (late1 / early1)) < 1.0); // the 1st holds
  5567. // without per-harmonic decay the spectrum stays as it is
  5568. s.spectrumDecay[2] = 0.0f;
  5569. const auto y = renderSynthNote (s, 57, 48000);
  5570. CHECK (std::abs (10.0 * std::log10 (goertzel (y, 660.0, 24000, 26400) / goertzel (y, 660.0, 480, 2880))) < 1.0);
  5571. }
  5572. TEST (worker_pool_runs_each_index_once_per_round)
  5573. {
  5574. // rounds of alternating sizes (a stalled worker must never run an index of a later round), each index
  5575. // exactly once, and nothing running after parallelFor returns
  5576. lynx::WorkerPool pool (3);
  5577. std::vector<std::atomic<int>> hits (64);
  5578. std::atomic<int> round { 0 }, outside { 0 }, wrongRound { 0 };
  5579. std::atomic<bool> open { false };
  5580. int failures = 0;
  5581. for (int r = 1; r <= 20000; ++r)
  5582. {
  5583. const auto n = (r % 3 == 0) ? 64 : (r % 3 == 1 ? 2 : 9);
  5584. for (int i = 0; i < n; ++i)
  5585. hits[(std::size_t) i].store (0);
  5586. round.store (r);
  5587. open.store (true);
  5588. auto fn = [&, r] (int i) {
  5589. if (! open.load())
  5590. outside.fetch_add (1);
  5591. if (round.load() != r)
  5592. wrongRound.fetch_add (1);
  5593. hits[(std::size_t) i].fetch_add (1);
  5594. };
  5595. pool.parallelFor (n, fn);
  5596. open.store (false);
  5597. for (int i = 0; i < n; ++i)
  5598. failures += hits[(std::size_t) i].load() != 1;
  5599. }
  5600. CHECK (failures == 0);
  5601. CHECK (outside.load() == 0);
  5602. CHECK (wrongRound.load() == 0);
  5603. }
  5604. TEST (ladder_filter_follows_toxic_law)
  5605. {
  5606. // the 4-pole ladder: −24 dB/oct far above the cutoff (vs −12 for the SVF), resonance raises the corner, and
  5607. // the input saturation keeps it bounded even at full resonance
  5608. auto level = [] (bool ladder, float res, double hz) {
  5609. lynx::SynthSettings s;
  5610. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  5611. s.cutoff = 500.0f;
  5612. s.resonance = res;
  5613. s.ladder = ladder;
  5614. const auto key = (int) std::lround (69.0 + 12.0 * std::log2 (hz / 440.0));
  5615. const auto x = renderSynthNote (s, key, 48000);
  5616. double e = 0.0, peak = 0.0;
  5617. for (std::size_t i = 24000; i < 48000; ++i)
  5618. e += (double) x[i] * x[i], peak = std::max (peak, (double) std::abs (x[i]));
  5619. return std::pair { std::sqrt (e / 24000.0), peak };
  5620. };
  5621. 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
  5622. const auto svfHigh = level (false, 0.0f, 3520.0).first / level (false, 0.0f, 110.0).first;
  5623. CHECK (20.0 * std::log10 (high / low) < -55.0); // ≈ 24 dB/oct over ~2.8 octaves
  5624. CHECK (20.0 * std::log10 (svfHigh) > -45.0); // the 2-pole SVF falls much less
  5625. const auto corner0 = level (true, 0.0f, 523.25).first, corner1 = level (true, 0.6f, 523.25).first;
  5626. CHECK (corner1 > 1.5 * corner0); // resonance boosts near the cutoff
  5627. const auto loud = level (true, 1.0f, 523.25);
  5628. CHECK (std::isfinite (loud.first) && loud.second < 20.0); // self-oscillation stays bounded
  5629. }
  5630. TEST (synth_spectrum_settles_on_target)
  5631. {
  5632. // ALT DECAY-like morph: harmonic 3 starts at 1 and settles on 0.25 (−12 dB) instead of fading out
  5633. lynx::SynthSettings s;
  5634. s.osc[0] = { lynx::Waveform::spectral, 0, 0.0f, 1.0f };
  5635. s.cutoff = 20000.0f;
  5636. s.decay = 0.0f;
  5637. s.sustain = 1.0f;
  5638. s.spectrum[0] = 1.0f;
  5639. s.spectrum[2] = 1.0f;
  5640. s.spectrumDecay[2] = 0.1f;
  5641. s.spectrumTarget[2] = 0.25f;
  5642. const auto x = renderSynthNote (s, 57, 48000);
  5643. const auto ratio = goertzel (x, 660.0, 24000, 26400) / goertzel (x, 220.0, 24000, 26400);
  5644. CHECK (std::abs (10.0 * std::log10 (ratio) - 20.0 * std::log10 (0.25)) < 1.0);
  5645. }
  5646. TEST (kepler_chorus_is_stereo_and_keeps_level)
  5647. {
  5648. // chorus I on a sine: L and R differ (opposite LFO phases), the level stays close to the dry one
  5649. lynx::SynthSettings s;
  5650. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  5651. s.cutoff = 20000.0f;
  5652. auto dry = s;
  5653. s.chorus = 1;
  5654. auto render = [] (const lynx::SynthSettings& set) {
  5655. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  5656. inst->prepare (48000.0);
  5657. lynx::ChannelDef c;
  5658. c.synth = set;
  5659. inst->configure (c, 120.0);
  5660. inst->noteOn (69, 1.0f);
  5661. std::vector<float> l (96000), r (96000);
  5662. inst->render (l.data(), r.data(), 96000, 1.0f, 1.0f);
  5663. return std::pair { l, r };
  5664. };
  5665. const auto [l, r] = render (s);
  5666. const auto [dl, dr] = render (dry);
  5667. double diff = 0.0, e = 0.0, ed = 0.0;
  5668. for (std::size_t i = 48000; i < 96000; ++i)
  5669. diff += std::abs (l[i] - r[i]), e += (double) l[i] * l[i], ed += (double) dl[i] * dl[i];
  5670. CHECK (diff / 48000.0 > 1e-3);
  5671. CHECK (std::abs (10.0 * std::log10 (e / ed)) < 3.0);
  5672. }
  5673. TEST (fl_pan_law_matches_love_philter_dll)
  5674. {
  5675. // values printed by the installation's Love Philter pan routine for vol 0.8 (REA_rodada27 §3.1, lppan.txt)
  5676. struct Row { double pan, ll, rr, rl, lr; };
  5677. const Row rows[] = { { -1.5, 0.239782482, -0.432956904, 0.805467963, 0.0 }, { -0.5, 0.805467963, 0.432956904, 0.239782482, 0.0 },
  5678. { 0.0, 0.8, 0.8, 0.0, 0.0 }, { 0.75, 0.220719516, 0.707889318, 0.0, 0.401742548 },
  5679. { 1.0, 0.0, 0.565685451, 0.0, 0.565685451 } };
  5680. for (const auto& row : rows)
  5681. {
  5682. float ll, rl, lr, rr;
  5683. lynx::flPanMatrix (row.pan, ll, rl, lr, rr);
  5684. CHECK (std::abs (0.8 * ll - row.ll) < 1e-6 && std::abs (0.8 * rr - row.rr) < 1e-6);
  5685. CHECK (std::abs (0.8 * rl - row.rl) < 1e-6 && std::abs (0.8 * lr - row.lr) < 1e-6);
  5686. }
  5687. }
  5688. TEST (effector_units_match_fl_dll_impulse_responses)
  5689. {
  5690. // impulse responses of the installation's Effector engine (REA_rodada27 §2, eu_<kind>_<X>_<Y>.txt; LFO off,
  5691. // wet 1, blocks of 256): samples 1, 10, 100 and 1000
  5692. struct Case { int kind; float x, y; double v[4]; };
  5693. const Case cases[] = { { 3, 0.5f, 0.5f, { -0.603055418, 0.159798339, -0.0055043716, -1.06241259e-06 } },
  5694. { 4, 0.2f, 0.5f, { 4.68885949e-26, 4.20032622e-19, 0.000487731799, 2.27715846e-09 } },
  5695. { 4, 0.8f, 0.3f, { -0.293783396, -0.0306414738, -0.00068128563, 1.358577e-15 } } };
  5696. for (const auto& c : cases)
  5697. {
  5698. auto fx = lynx::effector::make();
  5699. fx->prepare (44100.0);
  5700. lynx::EffectParams p {};
  5701. p[lynx::effector::type] = c.kind / 11.0f;
  5702. p[lynx::effector::wetMix] = 1.0f;
  5703. p[lynx::effector::paramX] = c.x;
  5704. p[lynx::effector::paramY] = c.y;
  5705. p[lynx::effector::modX] = p[lynx::effector::modY] = 0.5f;
  5706. p[lynx::effector::modRate] = 0.5f;
  5707. p[lynx::effector::inputLevel] = 1.0f;
  5708. p[lynx::effector::outputGain] = 0.5f;
  5709. std::vector<float> l (1024, 0.0f), r (1024, 0.0f);
  5710. l[0] = r[0] = 1.0f;
  5711. for (int d = 0; d < 1024; d += 256)
  5712. fx->process (l.data() + d, r.data() + d, 256, p, 120.0);
  5713. const int at[4] { 1, 10, 100, 1000 };
  5714. for (int k = 0; k < 4; ++k)
  5715. CHECK (std::abs (l[(std::size_t) at[k]] - c.v[k]) < 2e-7 + 1e-5 * std::abs (c.v[k]));
  5716. }
  5717. }
  5718. TEST (harmless_stereo_tremolo_and_vibrato)
  5719. {
  5720. // tremolo d = 1: each side swings between 0 and 1.25 at 5 Hz, L and R in anti-phase; vibrato modulates the pitch
  5721. lynx::SynthSettings s;
  5722. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  5723. s.cutoff = 20000.0f;
  5724. s.stereoTremolo = 1.0f;
  5725. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  5726. inst->prepare (48000.0);
  5727. lynx::ChannelDef c;
  5728. c.synth = s;
  5729. inst->configure (c, 120.0);
  5730. inst->noteOn (69, 1.0f);
  5731. std::vector<float> l (48000), r (48000);
  5732. inst->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  5733. 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; };
  5734. // θ = 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
  5735. CHECK (envelope (l, 19200) > 4.0f * envelope (r, 19200));
  5736. CHECK (envelope (r, 24000) > 4.0f * envelope (l, 24000));
  5737. // vibrato 100 cents: zero crossings vary in spacing; without it they are regular
  5738. auto crossingsSpread = [] (float cents) {
  5739. lynx::SynthSettings v;
  5740. v.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  5741. v.cutoff = 20000.0f;
  5742. v.vibratoCents = cents;
  5743. const auto x = renderSynthNote (v, 69, 48000);
  5744. std::vector<int> zc;
  5745. for (int i = 24000; i < 48000; ++i)
  5746. if (x[(std::size_t) i - 1] < 0.0f && x[(std::size_t) i] >= 0.0f)
  5747. zc.push_back (i);
  5748. int lo = 1 << 30, hi = 0;
  5749. for (std::size_t k = 1; k < zc.size(); ++k)
  5750. lo = std::min (lo, zc[k] - zc[k - 1]), hi = std::max (hi, zc[k] - zc[k - 1]);
  5751. return hi - lo;
  5752. };
  5753. CHECK (crossingsSpread (0.0f) <= 1);
  5754. CHECK (crossingsSpread (100.0f) >= 4);
  5755. }
  5756. TEST (physical_models_sound_and_end)
  5757. {
  5758. // Sakura: a plucked string with default-ish parameters rings and fades after the release; Drumpad: a hit decays
  5759. for (const auto kind : { lynx::InstrumentKind::sakura, lynx::InstrumentKind::drumpad })
  5760. {
  5761. lynx::ChannelDef c;
  5762. c.instrument = kind;
  5763. if (kind == lynx::InstrumentKind::sakura)
  5764. {
  5765. c.modelParams.assign (146, 0.5f);
  5766. c.modelParams[111] = 3.0f; // both strings at the note
  5767. c.modelParams[113] = 0.5f; // octave ×1
  5768. c.modelParams[6] = c.modelParams[11] = 0.99f; // long decay
  5769. c.modelParams[31] = 0.0f; // noise exciter
  5770. }
  5771. else
  5772. {
  5773. c.modelParams.assign (38, 0.5f);
  5774. c.modelParams[0] = 1.0f; // retrigger noise
  5775. c.modelParams[30] = c.modelParams[31] = c.modelParams[32] = c.modelParams[33] = 0.0f; // no velocity morph
  5776. }
  5777. auto inst = lynx::makeInstrument (kind);
  5778. inst->prepare (48000.0);
  5779. inst->configure (c, 120.0);
  5780. inst->noteOn (60, 0.8f);
  5781. std::vector<float> l (48000), r (48000);
  5782. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  5783. inst->noteOff (60);
  5784. inst->render (l.data() + 24000, r.data() + 24000, 24000, 1.0f, 1.0f);
  5785. double early = 0.0;
  5786. for (int i = 0; i < 12000; ++i)
  5787. early += (double) l[(std::size_t) i] * l[(std::size_t) i];
  5788. CHECK (early > 1e-6);
  5789. CHECK (std::all_of (l.begin(), l.end(), [] (float v) { return std::isfinite (v); }));
  5790. std::vector<float> tail (480000), tailR (480000);
  5791. inst->render (tail.data(), tailR.data(), 480000, 1.0f, 1.0f); // 10 s later the voice has ended
  5792. CHECK (inst->idle());
  5793. }
  5794. }
  5795. TEST (squeeze_matches_fl_model)
  5796. {
  5797. // Fruity Squeeze: Steps quantises, Mix 0 passes the input dry ×Volume/127; a silent block is left untouched
  5798. auto slot = lynx::makeEffectSlot (lynx::EffectKind::squeeze);
  5799. slot.params[1] = 0.0f; // mix 0: dry only
  5800. auto fx = lynx::makeEffect (lynx::EffectKind::squeeze);
  5801. fx->prepare (44100.0);
  5802. std::vector<float> l (512, 0.3f), r (512, -0.2f);
  5803. fx->process (l.data(), r.data(), 512, slot.params, 120.0);
  5804. CHECK (std::abs (l[100] - 0.3f) < 1e-6f && std::abs (r[100] + 0.2f) < 1e-6f); // Volume 127/127
  5805. slot.params[1] = 1.0f; // wet only
  5806. slot.params[2] = 32000.0f / 32768.0f; // 32768^(1 − 32000/32768) ≈ 1.27 levels per unit → heavy quantisation
  5807. std::vector<float> a (512), b (512);
  5808. for (int i = 0; i < 512; ++i)
  5809. a[(std::size_t) i] = b[(std::size_t) i] = 0.4f * (float) std::sin (i * 0.05);
  5810. fx->process (a.data(), b.data(), 512, slot.params, 120.0);
  5811. const auto levels = std::pow (32768.0f, 1.0f - 32000.0f / 32768.0f);
  5812. for (int i = 0; i < 512; i += 37)
  5813. CHECK (std::abs (a[(std::size_t) i] * levels - std::nearbyint (a[(std::size_t) i] * levels)) < 1e-3f);
  5814. std::vector<float> z (512, 0.0f), z2 (512, 0.0f);
  5815. fx->process (z.data(), z2.data(), 512, slot.params, 120.0);
  5816. CHECK (z[10] == 0.0f);
  5817. }
  5818. TEST (sakura_matrix_and_effects)
  5819. {
  5820. // REA_rodada29 §1: velocity → level follows 10^(2m)·0.05 (vel 1 vs 0.5 → ×10 in amplitude); the delay leaves
  5821. // an echo after the note has ended and keeps the instrument from going idle until its tail is silent
  5822. auto base = [] {
  5823. lynx::ChannelDef c;
  5824. c.instrument = lynx::InstrumentKind::sakura;
  5825. c.modelParams.assign (146, 0.0f);
  5826. const std::pair<int, float> values[] { { 0, 0.375f }, { 1, 0.5f }, { 3, 0.5f }, { 4, 1.0f }, { 6, 0.95f }, { 9, 0.3f },
  5827. { 11, 0.95f }, { 14, 0.3f }, { 18, 0.5f }, { 19, 0.5f }, { 27, 0.5f }, { 28, 1.0f },
  5828. { 29, 0.7f }, { 31, 1.0f }, { 32, 0.5f }, { 111, 3.0f }, { 113, 0.5f } };
  5829. for (const auto& [i, v] : values)
  5830. c.modelParams[(std::size_t) i] = v;
  5831. return c;
  5832. };
  5833. auto render = [] (const lynx::ChannelDef& c, float velocity, int held, int total) {
  5834. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sakura);
  5835. inst->prepare (48000.0);
  5836. inst->configure (c, 120.0);
  5837. inst->noteOn (60, velocity);
  5838. std::vector<float> l ((std::size_t) total), r ((std::size_t) total);
  5839. for (int s = 0; s < total; s += 256)
  5840. {
  5841. if (s == held)
  5842. inst->noteOff (60);
  5843. inst->render (l.data() + s, r.data() + s, std::min (256, total - s), 1.0f, 1.0f);
  5844. }
  5845. return std::make_pair (l, std::move (inst));
  5846. };
  5847. auto energy = [] (const std::vector<float>& x, int from, int to) {
  5848. double e = 0.0;
  5849. for (int i = from; i < to; ++i)
  5850. e += (double) x[(std::size_t) i] * x[(std::size_t) i];
  5851. return e;
  5852. };
  5853. auto c = base();
  5854. c.modelParams[79] = 6.0f; // slot 1: velocity → level, amount 1
  5855. c.modelParams[80] = 1.0f;
  5856. c.modelParams[82] = 1.0f;
  5857. const auto loud = energy (render (c, 1.0f, 24064, 24064).first, 0, 24064);
  5858. const auto soft = energy (render (c, 0.5f, 24064, 24064).first, 0, 24064);
  5859. CHECK (loud > 1e-6 && std::abs (loud / soft - 100.0) < 1.0);
  5860. auto d = base();
  5861. auto [dry, dryInst] = render (d, 0.8f, 4864, 72000);
  5862. d.modelParams[63] = 1.0f; // delay on: time 0.5 → ≈ 0.52 s, wet 1, no feedback: one echo
  5863. d.modelParams[64] = 0.5f;
  5864. d.modelParams[69] = 1.0f;
  5865. auto [wet, wetInst] = render (d, 0.8f, 4864, 72000);
  5866. CHECK (energy (wet, 26000, 40000) > 100.0 * energy (dry, 26000, 40000) + 1e-9); // the note ends near 0.2 s
  5867. CHECK (dryInst->idle() || energy (dry, 70000, 72000) < 1e-12);
  5868. CHECK (! wetInst->idle()); // the echo tail has not been silent for 3 s yet
  5869. }
  5870. TEST (drumsynth_live_engine)
  5871. {
  5872. // REA_rodada30 §1: key → patch slot, state parsing, the engine against our reference model (no DLL: synthesised
  5873. // sources only, noise from the fallback seed), voice modes, patch level/pan
  5874. CHECK (lynx::drumSynthKeyToSlot (48) == 0 && lynx::drumSynthKeyToSlot (71) == 23 && lynx::drumSynthKeyToSlot (0) == 24);
  5875. CHECK (lynx::drumSynthKeyToSlot (47) == 71 && lynx::drumSynthKeyToSlot (72) == 72 && lynx::drumSynthKeyToSlot (119) == 119);
  5876. CHECK (lynx::drumSynthKeyToSlot (120) == -1);
  5877. // a version 3 state: 120 names, 120 × 38 ints (send track −1 becomes 0 below version 4), flags
  5878. std::vector<std::uint8_t> blob;
  5879. auto put = [&] (std::uint32_t v) { for (int k = 0; k < 4; ++k) blob.push_back ((std::uint8_t) (v >> (8 * k))); };
  5880. put (3);
  5881. put (66);
  5882. for (int i = 0; i < 120; ++i)
  5883. blob.push_back (2), blob.push_back ('a'), blob.push_back ((std::uint8_t) ('0' + i % 10));
  5884. for (int i = 0; i < 120 * 38; ++i)
  5885. put ((std::uint32_t) (i % 38 == 36 ? -1 : i % 38 == 4 ? 300 : 0));
  5886. put (0);
  5887. const auto parsed = lynx::drumSynthLiveParams (blob);
  5888. CHECK (parsed && (int) parsed->size() == lynx::drumSynthParamCount);
  5889. CHECK (parsed && (*parsed)[36] == 0.0f && (*parsed)[38 * 7 + 4] == 300.0f && (*parsed)[(std::size_t) lynx::drumSynthEditorKeyIndex] == 66.0f);
  5890. blob.resize (500);
  5891. CHECK (! lynx::drumSynthLiveParams (blob));
  5892. // patch on key 60 (slot 12): tone-mode Osc1 with sweep and click, noise-band Osc2, ring, 2 retriggers
  5893. 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,
  5894. 0, 0, 0, 0, 0, 0, 30, -1, 0, 0, 64 };
  5895. lynx::ChannelDef c;
  5896. c.instrument = lynx::InstrumentKind::drumsynth;
  5897. c.modelParams.assign ((std::size_t) lynx::drumSynthParamCount, 0.0f);
  5898. for (int s = 0; s < 120; ++s)
  5899. c.modelParams[(std::size_t) (38 * s + 15)] = c.modelParams[(std::size_t) (38 * s + 34)] = -1.0f;
  5900. for (int i = 0; i < 38; ++i)
  5901. c.modelParams[(std::size_t) (38 * 12 + i)] = (float) patch[i];
  5902. auto render = [] (const lynx::ChannelDef& def, std::vector<int> keys, int total, float gl = 1.0f, float gr = 1.0f) {
  5903. auto inst = lynx::makeInstrument (lynx::InstrumentKind::drumsynth);
  5904. inst->configure (def, 120.0);
  5905. inst->prepare (48000.0);
  5906. std::vector<float> l ((std::size_t) total), r ((std::size_t) total);
  5907. for (int s = 0; s < total; s += 512)
  5908. {
  5909. for (std::size_t k = 0; k + 1 < keys.size(); k += 2)
  5910. if (keys[k + 1] == s)
  5911. inst->noteOn (keys[k], 100.0f / 128.0f);
  5912. inst->render (l.data() + s, r.data() + s, std::min (512, total - s), gl, gr);
  5913. }
  5914. return std::make_tuple (l, r, std::move (inst));
  5915. };
  5916. {
  5917. auto [l, r, inst] = render (c, { 60, 0 }, 9600);
  5918. // reference model (REA round 30 dsl_model.py, seed 0x56CE, FL velocity 100, V = 1, centre: × g(100)·cos(π/4))
  5919. const std::pair<int, float> golden[] { { 0, -0.0074092713f }, { 10, -0.13961405f }, { 100, -0.47290668f }, { 1000, -0.29188696f },
  5920. { 3000, -0.22130175f }, { 6000, -0.049537566f }, { 9599, 0.010392102f } };
  5921. for (const auto& [i, v] : golden)
  5922. CHECK (std::abs (l[(std::size_t) i] - v) < 2e-6f && std::abs (r[(std::size_t) i] - v) < 2e-6f);
  5923. std::vector<float> tail (48000 * 4), tailR (tail.size());
  5924. inst->render (tail.data(), tailR.data(), (int) tail.size(), 1.0f, 1.0f);
  5925. CHECK (inst->idle()); // the engine reported the voice finished
  5926. }
  5927. auto energy = [] (const std::vector<float>& x, int from, int to) {
  5928. double e = 0.0;
  5929. for (int i = from; i < to; ++i)
  5930. e += (double) x[(std::size_t) i] * x[(std::size_t) i];
  5931. return e;
  5932. };
  5933. // a key without a patch level (slot 0, level 0) and a key outside the 120 patches are silent
  5934. CHECK (energy (std::get<0> (render (c, { 48, 0, 125, 0 }, 4096)), 0, 4096) == 0.0);
  5935. // mono: a second hit on the same key cuts the first; poly: both ring together (Osc2 off: no noise, deterministic)
  5936. auto tone = c;
  5937. tone.modelParams[38 * 12 + 14] = 0.0f;
  5938. const auto single = std::get<0> (render (tone, { 60, 0 }, 8192));
  5939. const auto mono = std::get<0> (render (tone, { 60, 0, 60, 2048 }, 8192));
  5940. auto poly = tone;
  5941. poly.modelParams[38 * 12 + 24] = 1.0f;
  5942. const auto both = std::get<0> (render (poly, { 60, 0, 60, 2048 }, 8192));
  5943. double monoDiff = 0.0, polyDiff = 0.0;
  5944. for (int i = 2048 + 300; i < 8192; ++i) // after the cut fade: mono = only the second hit, a copy of the first
  5945. 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]);
  5946. CHECK (monoDiff < 1e-3 && polyDiff > 1.0);
  5947. // patch pan +64 → right only; channel volume counts twice (FL applies Final.Vol in the engine and at the host)
  5948. auto right = c;
  5949. right.modelParams[38 * 12 + 1] = 64.0f;
  5950. const auto [pl, pr, pi] = render (right, { 60, 0 }, 4096);
  5951. CHECK (energy (pl, 0, 4096) < 1e-12 * energy (pr, 0, 4096) && energy (pr, 0, 4096) > 1.0);
  5952. const auto full = std::get<0> (render (tone, { 60, 0 }, 4096));
  5953. const auto half = std::get<0> (render (tone, { 60, 0 }, 4096, 0.5f, 0.5f));
  5954. CHECK (std::abs (half[100] - 0.25f * full[100]) < 1e-6f && std::abs (full[100]) > 0.01f);
  5955. }
  5956. TEST (kepler_lfo_bpm_sync)
  5957. {
  5958. // 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)
  5959. std::vector<std::uint8_t> state (0x21 + 34 * 4, 0);
  5960. auto putU32 = [&] (std::size_t o, std::uint32_t v) { std::memcpy (state.data() + o, &v, 4); };
  5961. putU32 (12, 9);
  5962. std::memcpy (state.data() + 16, "Kepler-1", 9);
  5963. putU32 (0x19, 4);
  5964. putU32 (0x1D, 34);
  5965. float k[34] {};
  5966. k[5] = 0.602085769f; // "Pads - Kepler" demo: n = 286
  5967. k[6] = 1.0f;
  5968. k[10] = 1.0f; // vibrato on
  5969. k[33] = 1.0f;
  5970. std::memcpy (state.data() + 0x21, k, sizeof k);
  5971. lynx::SynthSettings s;
  5972. float gain = 0.0f;
  5973. CHECK (lynx::synthFromKepler (state, s, gain));
  5974. CHECK (s.lfo[lynx::lfoPitch].sync && s.lfo[lynx::lfoPitch].secondsTiming);
  5975. CHECK (std::abs (s.lfo[lynx::lfoPitch].period - 286.0f / 192.0f) < 1e-6f);
  5976. k[5] = 0.0f; // slowest: 32 beats
  5977. std::memcpy (state.data() + 0x21, k, sizeof k);
  5978. CHECK (lynx::synthFromKepler (state, s, gain) && std::abs (s.lfo[lynx::lfoPitch].period - 32.0f) < 1e-6f);
  5979. k[6] = 0.0f; // free rate in seconds
  5980. std::memcpy (state.data() + 0x21, k, sizeof k);
  5981. CHECK (lynx::synthFromKepler (state, s, gain) && ! s.lfo[lynx::lfoPitch].sync);
  5982. }
  5983. namespace
  5984. {
  5985. // A Harmor state written from scratch (REA_rodada11 §4.1 layout, version 18): part A only — a decaying-harmonics
  5986. // timbre, low-pass + resonance, filter envelope, 3-voice unison, vibrato, pluck, tremolo, volume envelope with a
  5987. // velocity map — and the global block. Every other curve is neutral.
  5988. std::vector<std::uint8_t> harmorTestState (bool panLfo = true)
  5989. {
  5990. std::vector<std::uint8_t> b;
  5991. 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))); };
  5992. 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))); };
  5993. struct Pt { double dx, y, tension; int mode; };
  5994. auto curve = [&] (const std::vector<Pt>& pts, std::array<std::int32_t, 5> hdr) {
  5995. i32 (3), i32 (3), i32 ((std::int32_t) pts.size());
  5996. for (const auto& p : pts)
  5997. {
  5998. f64 (p.dx), f64 (p.y);
  5999. const auto t = (float) p.tension;
  6000. std::uint32_t u;
  6001. std::memcpy (&u, &t, 4);
  6002. i32 ((std::int32_t) u);
  6003. b.push_back ((std::uint8_t) p.mode), b.push_back (0), b.push_back (0), b.push_back (0);
  6004. }
  6005. for (auto h : hdr)
  6006. i32 (h);
  6007. };
  6008. const std::array<std::int32_t, 5> off { 0, 0, -1, -1, -1 }, on { 0, 1, -1, -1, -1 };
  6009. 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); };
  6010. i32 (18);
  6011. i32 (1 | 4);
  6012. std::vector<std::uint8_t> part;
  6013. std::swap (b, part);
  6014. std::array<std::int32_t, 386> p {};
  6015. const std::pair<int, int> values[] = { { 0, 500 }, { 3, 1000 }, { 9, 1024 }, { 11, 1000 }, { 12, 1000 }, { 17, 300 }, { 18, 4000 },
  6016. { 19, 500 }, { 20, 1000 }, { 24, 500 }, { 25, 500 }, { 28, 500 }, { 29, 256 }, { 30, -1 }, { 31, -1 }, { 33, -1 }, { 34, 3 },
  6017. { 35, 1 }, { 37, 192 }, { 38, 128 }, { 39, 500 }, { 40, 10000 }, { 41, 1 }, { 42, 10000 }, { 43, 1 }, { 45, 200 }, { 46, 500 },
  6018. { 47, 1 }, { 49, -140 }, { 50, 1200 }, { 51, 0 }, { 52, 5000 }, { 54, 500 }, { 56, 600 }, { 57, 300 }, { 59, 500 }, { 60, 600 },
  6019. { 64, 8192 }, { 66, 500 }, { 72, 600 }, { 74, 1000 }, { 75, 600 }, { 78, 5000 }, { 79, 500 }, { 80, 3000 } };
  6020. for (const auto& [i, v] : values)
  6021. p[(std::size_t) i] = v;
  6022. for (auto v : p)
  6023. i32 (v);
  6024. for (int i = 0; i < 12; ++i)
  6025. i32 (i); // module order
  6026. std::array<std::uint8_t, 0x4b> misc {};
  6027. auto put = [&] (int o, std::int32_t v) { std::memcpy (misc.data() + o, &v, 4); };
  6028. const float one = 1.0f;
  6029. put (0x08, 107), put (0x1c, 1), put (0x28, 200), std::memcpy (misc.data() + 0x30, &one, 4);
  6030. put (0x34, 0), put (0x38, 4), put (0x3c, 100), put (0x40, 108);
  6031. misc[0x44] = 1;
  6032. b.insert (b.end(), misc.begin(), misc.end());
  6033. 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 };
  6034. for (int k = 0; k < 43; ++k)
  6035. {
  6036. static const int mode2[] = { 2, 14, 23, 28, 30, 38, 39, 41, 42 }; // ×2 around 0.5: 1.0 is neutral
  6037. const bool centred = std::find (std::begin (mode1), std::end (mode1), k) != std::end (mode1);
  6038. const bool doubled = std::find (std::begin (mode2), std::end (mode2), k) != std::end (mode2);
  6039. const double neutral = centred && ! doubled ? 0.5 : 1.0;
  6040. i32 (3);
  6041. i32 (1065353216), i32 (1065353216), i32 (1065353216);
  6042. if (k == 1) // volume envelope: attack, decay to the sustain point, release
  6043. 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 });
  6044. else if (k == 4) // filter-1 envelope
  6045. curve ({ { 0, 1, 0, 0 }, { 0.25, 0.2, -0.5, 0 } }, { 0, 1, -1, -1, -1 });
  6046. else
  6047. flat (neutral);
  6048. for (int a : { 128, 128, 0, 128 })
  6049. i32 (a);
  6050. if (k == 0 && panLfo) // pan LFO
  6051. flat (1.0, on);
  6052. else
  6053. flat (0.5);
  6054. for (int a : { k == 0 ? 40000 : 0, 0, 0, 0 })
  6055. i32 (a);
  6056. i32 (0);
  6057. for (int m = 2; m < 11; ++m)
  6058. if (k == 1 && m == 3)
  6059. curve ({ { 0, 0.2, 0, 0 }, { 1, 1, -0.3, 0 } }, off); // velocity → volume
  6060. else
  6061. flat (neutral);
  6062. }
  6063. for (int c = 0; c < 26; ++c)
  6064. if (c == 2 || c == 3)
  6065. curve ({ { 0, 0.25, 0, 0 }, { 0.006, 0.12, -0.46, 0 }, { 0.994, 0, 0, 0 } }, off); // timbres
  6066. else if (c == 14)
  6067. curve ({ { 0, 1, 0, 0 }, { 1, 0, 0, 0 } }, off); // pluck curve
  6068. else
  6069. 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)));
  6070. std::swap (b, part);
  6071. i32 ((std::int32_t) part.size());
  6072. b.insert (b.end(), part.begin(), part.end());
  6073. std::array<std::int32_t, 53> g {};
  6074. g[0] = g[1] = g[2] = 256, g[10] = 500, g[11] = 1000, g[12] = 1000, g[15] = 1000;
  6075. for (auto v : g)
  6076. i32 (v);
  6077. for (int i = 0; i < 6; ++i)
  6078. i32 (i);
  6079. std::array<std::uint8_t, 0x3d> gm {};
  6080. const std::int32_t cr = 200, vr = 1;
  6081. std::memcpy (gm.data() + 12, &vr, 4);
  6082. std::memcpy (gm.data() + 24, &cr, 4);
  6083. b.insert (b.end(), gm.begin(), gm.end());
  6084. return b;
  6085. }
  6086. } // namespace
  6087. TEST (harmor_engine)
  6088. {
  6089. // REA_rodada34: state parsing, the additive engine against our reference model (hmodel.py), host levels, voice end
  6090. const auto blob = harmorTestState();
  6091. if (const char* dump = std::getenv ("LYNX_DUMP_HARMOR"))
  6092. std::ofstream (dump, std::ios::binary).write ((const char*) blob.data(), (std::streamsize) blob.size());
  6093. CHECK (lynx::harmorStateUsable (blob));
  6094. CHECK (lynx::harmorFallbacks (blob).size() == 1); // (only the harmonic-randomness note)
  6095. const auto at = lynx::harmorParamOffset (blob, 0, 52);
  6096. std::int32_t cutoff = 0;
  6097. CHECK (at > 0 && (std::memcpy (&cutoff, blob.data() + at, 4), cutoff == 5000));
  6098. CHECK (lynx::harmorParamOffset (blob, 1, 52) < 0 && lynx::harmorParamOffset (blob, -1, 12) > at);
  6099. auto broken = blob;
  6100. broken.resize (broken.size() / 2);
  6101. CHECK (! lynx::harmorStateUsable (broken));
  6102. auto old = blob;
  6103. old[0] = 15; // articulators and curves are stored from version 16
  6104. CHECK (! lynx::harmorStateUsable (old));
  6105. lynx::ChannelDef c;
  6106. c.instrument = lynx::InstrumentKind::harmor;
  6107. c.pluginState = blob;
  6108. auto render = [] (const lynx::ChannelDef& def, int total, float gl, float gr, int offAt) {
  6109. auto inst = lynx::makeInstrument (lynx::InstrumentKind::harmor);
  6110. inst->configure (def, 120.0);
  6111. inst->prepare (44100.0);
  6112. std::vector<float> l ((std::size_t) total), r ((std::size_t) total);
  6113. inst->noteOn (60, 0.78125f);
  6114. for (int s = 0; s < total; s += 512)
  6115. {
  6116. if (s == offAt)
  6117. inst->noteOff (60);
  6118. inst->render (l.data() + s, r.data() + s, std::min (512, total - s), gl, gr);
  6119. }
  6120. return std::make_tuple (l, r, std::move (inst));
  6121. };
  6122. {
  6123. // reference model (REA round 34 hmodel.py; C5 at FL velocity 100, Final.Vol 1, centre, released at 6144, the
  6124. // Mersenne Twister seeded like LYNX's)
  6125. auto [l, r, inst] = render (c, 8192, 1.0f, 1.0f, 6144);
  6126. const std::tuple<int, float, float> golden[] {
  6127. { 0, 0.0f, 0.0f }, { 100, 0.00947693f, 0.04249846f }, { 1000, 0.08140575f, -0.03251422f }, { 3000, 0.05928446f, -0.00247572f },
  6128. { 6000, 0.02997839f, 0.14549091f }, { 7000, -0.01121871f, 0.04197952f }, { 8191, 0.00314545f, 0.03857505f } };
  6129. for (const auto& [i, gl, gr] : golden)
  6130. CHECK (std::abs (l[(std::size_t) i] - gl) < 2e-6f && std::abs (r[(std::size_t) i] - gr) < 2e-6f);
  6131. // after the release the volume envelope ends, the record declicks and the instrument goes idle
  6132. std::vector<float> tail (44100), tailR (tail.size());
  6133. inst->render (tail.data(), tailR.data(), (int) tail.size(), 1.0f, 1.0f);
  6134. CHECK (inst->idle());
  6135. CHECK (std::abs (tail.back()) == 0.0f);
  6136. }
  6137. // the reference renderer gives the same samples as the instrument
  6138. {
  6139. const auto ref = lynx::harmor::renderReference (blob, { { 0, 60, 0.78125, 1.0, 0.0, 6144 } }, 44100.0, 8192);
  6140. const auto [l, r, inst] = render (c, 8192, 1.0f, 1.0f, 6144);
  6141. double worst = 0.0;
  6142. for (int i = 0; i < 8192; ++i)
  6143. 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]) });
  6144. CHECK (worst == 0.0);
  6145. }
  6146. // FL's level law applied once: half the channel volume halves the output; full right pan silences the left side
  6147. const auto full = std::get<0> (render (c, 2048, 1.0f, 1.0f, -1));
  6148. const auto half = std::get<0> (render (c, 2048, 0.5f, 0.5f, -1));
  6149. CHECK (std::abs (half[1000] - 0.5f * full[1000]) < 1e-6f && std::abs (full[1000]) > 0.01f);
  6150. auto mono = c;
  6151. mono.pluginState = harmorTestState (false); // no pan LFO ...
  6152. const std::int32_t one = 1;
  6153. std::memcpy (mono.pluginState.data() + lynx::harmorParamOffset (mono.pluginState, 0, 34), &one, 4); // ... nor unison spread
  6154. const auto [pl, pr, pi] = render (mono, 2048, 0.0f, 1.41421356f, -1);
  6155. double el = 0.0, er = 0.0;
  6156. for (int i = 0; i < 2048; ++i)
  6157. el += (double) pl[(std::size_t) i] * pl[(std::size_t) i], er += (double) pr[(std::size_t) i] * pr[(std::size_t) i];
  6158. CHECK (el < 1e-10 * er && er > 1e-3);
  6159. }
  6160. namespace
  6161. {
  6162. // An Ogun state written from scratch (REA_rodada37 §1.3 layout, version 18; zlib with stored blocks): richness 4
  6163. // (255 partials), pre-decay, decay/release, fullness, Seed 1 + fixed Seed 2 with morph, 3-voice unison, a 2-stage
  6164. // low-pass with an LFO on its cutoff, a volume envelope with a sustain point and a velocity map, declick, normalisation,
  6165. // Impulse/Decay maps, and every plugin effect (EQ band, chorus, ping-pong delay, reverb). Everything else is neutral.
  6166. std::vector<std::uint8_t> ogunTestState()
  6167. {
  6168. std::vector<std::uint8_t> b;
  6169. 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))); };
  6170. auto f32v = [&] (float v) { std::uint32_t u; std::memcpy (&u, &v, 4); i32 ((std::int32_t) u); };
  6171. 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))); };
  6172. struct Pt { double dx, y, tension; int mode; };
  6173. auto curve = [&] (int type, const std::vector<Pt>& pts, std::array<std::int32_t, 5> hdr) {
  6174. i32 (type), i32 (3), i32 ((std::int32_t) pts.size());
  6175. for (const auto& p : pts)
  6176. {
  6177. f64 (p.dx), f64 (p.y), f32v ((float) p.tension);
  6178. b.push_back ((std::uint8_t) p.mode), b.push_back (0), b.push_back (0), b.push_back (0);
  6179. }
  6180. for (auto h : hdr)
  6181. i32 (h);
  6182. };
  6183. const std::array<std::int32_t, 5> off { 0, 0, -1, -1, -1 }, on { 0, 1, -1, -1, -1 };
  6184. auto flat = [&] (int type, double y) { curve (type, { { 0, y, 0, 0 }, { 1, y, 0, 0 } }, off); };
  6185. std::array<std::int32_t, 64> P {};
  6186. const std::pair<int, int> values[] = { { 0, 128 }, { 5, 300 }, { 6, 3000 }, { 7, 2000 }, { 8, 200 }, { 9, 500 }, { 10, 12 },
  6187. { 11, 34 }, { 12, 3 }, { 13, 64 }, { 14, 64 }, { 15, 40 }, { 16, 64 }, { 17, 180 }, { 18, 60 }, { 19, 2 }, { 20, 300 },
  6188. { 21, 400 }, { 22, 40 }, { 23, 30 }, { 24, 20 }, { 25, 64 }, { 26, 40 }, { 27, 96 }, { 28, 100 }, { 29, 64 }, { 30, 2 },
  6189. { 31, 19 }, { 32, 221 }, { 33, 0 }, { 34, 50 }, { 35, 100 }, { 36, 20 }, { 37, 60 }, { 38, 2 }, { 39, 64 }, { 40, 300 },
  6190. { 43, 30000 }, { 46, 20000 }, { 49, 0 }, { 50, 2 }, { 51, 0 }, { 52, 9 }, { 53, 1 }, { 54, 0 },
  6191. { 55, 0x01000000 }, // +0x20b: pitch follows the key
  6192. { 56, 0x00010000 }, // +0x20e: declick
  6193. { 62, 0x00000100 } }; // +0x225: normalise
  6194. for (const auto& [i, v] : values)
  6195. P[(std::size_t) i] = v;
  6196. for (auto v : P)
  6197. i32 (v);
  6198. b.push_back (0), b.push_back (1), b.push_back (0); // delay: not tempo-based, on
  6199. i32 (1), i32 (1), i32 (1); // EQ band types: peaking
  6200. b.push_back (0); // comment: 0 characters
  6201. for (int k = 0; k < 13; ++k)
  6202. {
  6203. static constexpr int sum[] = { 1, 2, 3, 9, 11, 12 };
  6204. const double neutral = std::find (std::begin (sum), std::end (sum), k) != std::end (sum) ? 0.5 : 1.0;
  6205. i32 (1);
  6206. f32v (0.0f), f32v (1.0f), f32v (k == 1 ? 0.3f : 0.0f);
  6207. if (k == 0) // volume envelope: attack, decay to the sustain point, release
  6208. curve (1, { { 0, 0, 0, 0 }, { 0.02, 1, 0.3, 0 }, { 0.3, 0.5, -0.4, 0 }, { 0.5, 0, 0.2, 0 } }, { 0, 1, 2, -1, 2 });
  6209. else
  6210. flat (1, neutral);
  6211. for (int a : { 128, 128, 128, 128 })
  6212. i32 (a);
  6213. if (k == 1) // cutoff LFO
  6214. curve (2, { { 0, 0.8, 0, 0 } }, on);
  6215. else
  6216. flat (2, 0.5);
  6217. for (int a : { k == 1 ? 40000 : 0, 0, 0, 0 })
  6218. i32 (a);
  6219. i32 (0);
  6220. for (int m = 0; m < 4; ++m)
  6221. if (k == 0 && m == 1)
  6222. curve (3, { { 0, 0.3, 0, 0 }, { 1, 1, -0.2, 0 } }, off); // velocity → volume
  6223. else
  6224. flat (3, neutral);
  6225. }
  6226. flat (3, 0.0); // Forced: none
  6227. curve (3, { { 0, 0.6, 0, 0 }, { 1, 0.4, 0.3, 0 } }, off); // Impulse EQ
  6228. curve (3, { { 0, 0.5, 0, 0 }, { 1, 0.3, 0, 0 } }, off); // Decay EQ
  6229. flat (3, 0.5); // Release EQ
  6230. // u32 version + zlib (stored blocks)
  6231. std::vector<std::uint8_t> s { 18, 0, 0, 0, 0x78, 0x01 };
  6232. for (std::size_t i = 0; i < b.size();)
  6233. {
  6234. const auto len = std::min<std::size_t> (65535, b.size() - i);
  6235. s.push_back (i + len >= b.size() ? 1 : 0);
  6236. s.push_back ((std::uint8_t) len), s.push_back ((std::uint8_t) (len >> 8));
  6237. s.push_back ((std::uint8_t) ~len), s.push_back ((std::uint8_t) (~len >> 8));
  6238. s.insert (s.end(), b.begin() + (std::ptrdiff_t) i, b.begin() + (std::ptrdiff_t) (i + len));
  6239. i += len;
  6240. }
  6241. std::uint32_t a1 = 1, a2 = 0;
  6242. for (auto c : b)
  6243. a1 = (a1 + c) % 65521u, a2 = (a2 + a1) % 65521u;
  6244. for (int sh = 24; sh >= 0; sh -= 8)
  6245. s.push_back ((std::uint8_t) (((a2 << 16) | a1) >> sh));
  6246. return s;
  6247. }
  6248. } // namespace
  6249. TEST (ogun_engine)
  6250. {
  6251. // REA_rodada37: state parsing, the engine against our reference model (ogmodel.py), host levels, export quality
  6252. const auto blob = ogunTestState();
  6253. if (const char* dump = std::getenv ("LYNX_DUMP_OGUN"))
  6254. std::ofstream (dump, std::ios::binary).write ((const char*) blob.data(), (std::streamsize) blob.size());
  6255. CHECK (lynx::ogunStateUsable (blob));
  6256. CHECK (lynx::ogunFallbacks (blob).empty());
  6257. CHECK (lynx::ogunParam (blob, 17) == 180 && lynx::ogunParam (blob, 52) == 9 && ! lynx::ogunParam (blob, 64));
  6258. auto broken = blob;
  6259. broken.resize (broken.size() - 300);
  6260. CHECK (! lynx::ogunStateUsable (broken));
  6261. auto old = blob;
  6262. old[0] = 13; // the articulator layout is from version 14
  6263. CHECK (! lynx::ogunStateUsable (old));
  6264. // reference model (REA round 37 ogmodel.Plugin(state).run: C5 velocity 0.75 released at 6144, G5 velocity 0.625 at 2048
  6265. // released at 8192; host block 512)
  6266. const std::vector<lynx::ogun::RefNote> notes { { 0, 60, 0.75, 1.0, 0.0, 0.0, 0.0, 0.0, 0.5, 6144 }, { 2048, 67, 0.625, 1.0, 0.0, 0.0, 0.0, 0.0, 0.5, 8192 } };
  6267. const auto ref = lynx::ogun::renderReference (blob, notes, 44100.0, 16384);
  6268. CHECK (ref.size() == 2 * 16384);
  6269. if (const char* dump = std::getenv ("LYNX_DUMP_OGUN_OUT"))
  6270. std::ofstream (dump, std::ios::binary).write ((const char*) ref.data(), (std::streamsize) (ref.size() * 4));
  6271. const std::tuple<int, float, float> golden[] {
  6272. { 100, -7.763202e-05f, -8.919523e-05f }, { 1000, 0.06195267f, 0.03858230f }, { 3000, 0.01363476f, -0.00378433f },
  6273. { 6000, -0.06601223f, -0.03084030f }, { 9000, 0.04204506f, 0.02452896f }, { 12000, 0.03420147f, -0.01837870f },
  6274. { 16383, -0.00465311f, -0.00119627f } };
  6275. for (const auto& [i, gl, gr] : golden)
  6276. CHECK (std::abs (ref[2 * (std::size_t) i] - gl) < 2e-6f && std::abs (ref[2 * (std::size_t) i + 1] - gr) < 2e-6f);
  6277. // the instrument plays like the reference renderer (Final.Vol 1, centre)
  6278. lynx::ChannelDef c;
  6279. c.instrument = lynx::InstrumentKind::ogun;
  6280. c.pluginState = blob;
  6281. auto render = [&] (const lynx::ChannelDef& def, int total, float gl, float gr, bool held = false) {
  6282. auto inst = lynx::makeInstrument (lynx::InstrumentKind::ogun);
  6283. inst->configure (def, 120.0);
  6284. inst->prepare (44100.0);
  6285. std::vector<float> l ((std::size_t) total), r ((std::size_t) total);
  6286. for (int s = 0; s < total; s += 512)
  6287. {
  6288. if (s == 0)
  6289. inst->noteOn (60, 0.75f);
  6290. if (s == 2048)
  6291. inst->noteOn (67, 0.625f);
  6292. if (s == 6144 && ! held)
  6293. inst->noteOff (60);
  6294. if (s == 8192 && ! held)
  6295. inst->noteOff (67);
  6296. inst->render (l.data() + s, r.data() + s, std::min (512, total - s), gl, gr);
  6297. }
  6298. return std::make_tuple (l, r, std::move (inst));
  6299. };
  6300. {
  6301. auto [l, r, inst] = render (c, 16384, 1.0f, 1.0f);
  6302. double worst = 0.0;
  6303. for (int i = 0; i < 16384; ++i)
  6304. 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]) });
  6305. CHECK (worst == 0.0);
  6306. // the voices end and the effect tails die out: the instrument goes idle
  6307. std::vector<float> tail (44100), tailR (tail.size());
  6308. for (int k = 0; k < 20 && ! inst->idle(); ++k)
  6309. inst->render (tail.data(), tailR.data(), (int) tail.size(), 1.0f, 1.0f);
  6310. CHECK (inst->idle());
  6311. }
  6312. // FL's level law applied once (effects off): half the channel volume halves the output once the gain ramps
  6313. // (limited to 0.001 per sample) have settled on the sustain level; full right pan silences the left side
  6314. {
  6315. auto dry = c;
  6316. for (int i : { 19, 29, 40, 53 })
  6317. CHECK (lynx::ogunSetParam (dry.pluginState, i, 0)); // chorus, delay wet, EQ band and reverb off
  6318. CHECK (lynx::ogunStateUsable (dry.pluginState) && lynx::ogunParam (dry.pluginState, 19) == 0);
  6319. const auto full = std::get<0> (render (dry, 32768, 1.0f, 1.0f, true));
  6320. const auto half = std::get<0> (render (dry, 32768, 0.5f, 0.5f, true));
  6321. double worst = 0.0, peak = 0.0;
  6322. for (int i = 30000; i < 32768; ++i)
  6323. worst = std::max (worst, (double) std::abs (half[(std::size_t) i] - 0.5f * full[(std::size_t) i])),
  6324. peak = std::max (peak, (double) std::abs (full[(std::size_t) i]));
  6325. CHECK (worst <= 1e-7 * peak && peak > 1e-3);
  6326. // FL's default channel volume (100/128): FL hands Ogun Final.Vol = (11^v − 1)/10 (REA_rodada28 §4.1); LYNX's
  6327. // centred channel gains (√2·V·cos(π/4) each) give the reference model's level at that Final.Vol
  6328. const auto V = lynx::channelGain (0.78125f);
  6329. const auto g = V * std::cos (0.25f * 3.14159265f) * 1.41421356f;
  6330. const auto atDefault = std::get<0> (render (dry, 32768, g, g, true));
  6331. const auto refDefault = lynx::ogun::renderReference (dry.pluginState, { { 0, 60, 0.75, V, 0.0, 0.0, 0.0, 0.0, 0.5, -1 },
  6332. { 2048, 67, 0.625, V, 0.0, 0.0, 0.0, 0.0, 0.5, -1 } }, 44100.0, 32768);
  6333. double ei = 0.0, er0 = 0.0;
  6334. for (int i = 30000; i < 32768; ++i)
  6335. ei += (double) atDefault[(std::size_t) i] * atDefault[(std::size_t) i], er0 += (double) refDefault[2 * (std::size_t) i] * refDefault[2 * (std::size_t) i];
  6336. CHECK (er0 > 0.0 && std::abs (10.0 * std::log10 (ei / er0)) < 0.001);
  6337. const auto [pl, pr, pi] = render (dry, 4096, 0.0f, 1.41421356f);
  6338. double el = 0.0, er = 0.0;
  6339. for (int i = 0; i < 4096; ++i)
  6340. el += (double) pl[(std::size_t) i] * pl[(std::size_t) i], er += (double) pr[(std::size_t) i] * pr[(std::size_t) i];
  6341. CHECK (el < 1e-10 * er && er > 1e-3);
  6342. }
  6343. // export: FL renders Ogun at quality 4 (×2 rate, 32-point reader), LYNX too while it renders offline
  6344. {
  6345. lynx::setOfflineRendering (true);
  6346. auto [l, r, inst] = render (c, 8192, 1.0f, 1.0f);
  6347. lynx::setOfflineRendering (false);
  6348. lynx::ogun::RefOptions q4;
  6349. q4.quality = 4;
  6350. const auto ref4 = lynx::ogun::renderReference (blob, notes, 44100.0, 8192, q4);
  6351. double worst = 0.0, diff = 0.0;
  6352. for (int i = 0; i < 8192; ++i)
  6353. worst = std::max (worst, (double) std::abs (ref4[2 * (std::size_t) i] - l[(std::size_t) i])),
  6354. diff = std::max (diff, (double) std::abs (ref[2 * (std::size_t) i] - l[(std::size_t) i]));
  6355. CHECK (worst == 0.0 && diff > 1e-3);
  6356. const std::tuple<int, float, float> golden4[] {
  6357. { 100, 0.00605961f, 0.00628969f }, { 1000, 0.03729841f, 0.01727954f }, { 3000, -0.09010383f, -0.02551294f },
  6358. { 6000, 0.02167798f, -0.01115632f }, { 8191, 0.00320288f, -0.00615792f } };
  6359. for (const auto& [i, gl, gr] : golden4)
  6360. CHECK (std::abs (ref4[2 * (std::size_t) i] - gl) < 2e-6f && std::abs (ref4[2 * (std::size_t) i + 1] - gr) < 2e-6f);
  6361. }
  6362. // feature variants of the same state against the reference model (energy per side over 8192 samples, three
  6363. // samples; C1 released at 6144): qualities, richness, unison, the filter types, ALT DECAY, 1/√h, Seed 2 Random,
  6364. // infinite decay, logarithmic axis, velocity → position, other rates. Goldens from ogmodel.py (REA round 37).
  6365. {
  6366. struct Sample { int at; float l, r; };
  6367. struct Variant { const char* name; std::vector<std::pair<int, int>> params; int rate; double el, er; Sample s[3]; };
  6368. const Variant variants[] {
  6369. { "q1", { { 54, 1 } }, 44100, 11.0970402, 6.87820714, { { 1500, 0.0240363069f, -0.0148524037f }, { 4000, 0.0873190612f, -0.000715861097f }, { 7000, -0.0378603041f, -0.00338819111f } } },
  6370. { "q2", { { 54, 2 } }, 44100, 11.2405446, 6.68045082, { { 1500, 0.0448660068f, -0.00560745923f }, { 4000, -0.0122657465f, 0.0104285963f }, { 7000, -0.0216034129f, -0.0134632047f } } },
  6371. { "q3", { { 54, 3 } }, 44100, 11.3200608, 6.86196449, { { 1500, -0.0031537537f, -0.0242648814f }, { 4000, 0.0426301025f, 0.0364697985f }, { 7000, 0.00843803957f, 0.0302239582f } } },
  6372. { "rich16_q0", { { 52, 16 }, { 54, 0 } }, 44100, 26.7616786, 19.2591256, { { 1500, 0.0728010684f, -0.0116148153f }, { 4000, 0.0797849894f, 0.0765359923f }, { 7000, -0.00811834447f, -0.0104534971f } } },
  6373. { "uni9", { { 12, 9 }, { 15, 20 }, { 16, 0 }, { 14, 16 } }, 44100, 61.7485898, 36.6693432, { { 1500, 0.0531249829f, -0.0374071151f }, { 4000, 0.165054232f, -0.0192129575f }, { 7000, -0.0373774841f, -0.00196591392f } } },
  6374. { "lp1", { { 50, 1 }, { 49, 0 } }, 44100, 7.81941168, 4.72659869, { { 1500, 0.0377117358f, -0.0157920271f }, { 4000, 0.0747607499f, 0.00154248625f }, { 7000, -0.0510631353f, 0.00884498842f } } },
  6375. { "bp3flat", { { 50, 3 }, { 49, 1 }, { 51, 1 } }, 44100, 2.19181431, 1.29483907, { { 1500, 0.0291239917f, -0.00288665155f }, { 4000, -0.0084345676f, -0.00400509313f }, { 7000, -0.00592403999f, 0.00150578981f } } },
  6376. { "bs2", { { 50, 2 }, { 49, 2 } }, 44100, 32.8440514, 25.7202184, { { 1500, 0.0730303749f, -0.0496222489f }, { 4000, 0.0696200803f, 0.0595823973f }, { 7000, -0.0482789353f, 0.0764200836f } } },
  6377. { "hp3", { { 50, 3 }, { 49, 3 } }, 44100, 8.623214, 7.95253188, { { 1500, -0.0325722694f, 0.00703159999f }, { 4000, 0.0183976218f, -0.0372007042f }, { 7000, -0.0126833525f, -0.00160143059f } } },
  6378. { "alt", { { 62, 257 } }, 44100, 17.2485711, 9.99223979, { { 1500, -0.0319156498f, -0.0186850764f }, { 4000, -0.0769012421f, -0.0375530645f }, { 7000, 0.0310976505f, 0.0445244014f } } },
  6379. { "isqrt", { { 62, 65792 } }, 44100, 45.7309307, 27.1224593, { { 1500, -0.04376591f, -0.00845711026f }, { 4000, 0.0351300463f, -0.129557073f }, { 7000, 0.0096148327f, 0.00123740174f } } },
  6380. { "seed2rnd", { { 11, 0 } }, 44100, 16.8228819, 11.5433061, { { 1500, -0.0117614279f, -0.026497297f }, { 4000, 0.00265733898f, -0.07069581f }, { 7000, 0.00576663949f, 0.0565217957f } } },
  6381. { "decinf", { { 6, 10000 } }, 44100, 19.1879226, 11.0487311, { { 1500, -0.0324105881f, -0.0190765262f }, { 4000, -0.0809780285f, -0.0395730771f }, { 7000, 0.034197174f, 0.048585102f } } },
  6382. { "logx", { { 57, 16777216 } }, 44100, 12.3064326, 7.31519289, { { 1500, -0.0438990779f, 0.0096983267f }, { 4000, -0.0175748877f, 0.0313935578f }, { 7000, 0.0639200211f, 0.024419222f } } },
  6383. { "velpos", { { 56, 66304 } }, 44100, 4.9966925, 3.16540662, { { 1500, 0.0083851777f, -0.0165472236f }, { 4000, 0.0630451962f, 0.0156494901f }, { 7000, -0.0293043777f, -0.00182877108f } } },
  6384. { "fs48", { }, 48000, 10.8813888, 6.53592373, { { 1500, -0.0485184453f, -0.0319588967f }, { 4000, 0.0230421089f, -0.0286604818f }, { 7000, -0.0117630213f, -0.017459048f } } },
  6385. { "fs96", { }, 96000, 11.0189683, 6.39821883, { { 1500, -0.0267860368f, -0.0227564126f }, { 4000, 0.0238709711f, -0.0100849615f }, { 7000, -0.0034619756f, 0.0451687202f } } },
  6386. };
  6387. for (const auto& v : variants)
  6388. {
  6389. auto st = blob;
  6390. for (const auto& [i, x] : v.params)
  6391. CHECK (lynx::ogunSetParam (st, i, x));
  6392. const auto y = lynx::ogun::renderReference (st, { { 0, 60, 0.75, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 6144 },
  6393. { 2048, 67, 0.625, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1 } }, (double) v.rate, 8192);
  6394. double el = 0.0, er = 0.0, peak = 0.0;
  6395. for (std::size_t i = 0; i + 1 < y.size(); i += 2)
  6396. el += (double) y[i] * y[i], er += (double) y[i + 1] * y[i + 1], peak = std::max ({ peak, (double) std::abs (y[i]), (double) std::abs (y[i + 1]) });
  6397. bool ok = y.size() == 2 * 8192 && std::abs (el - v.el) <= 1e-5 * v.el && std::abs (er - v.er) <= 1e-5 * v.er;
  6398. for (const auto& smp : v.s)
  6399. ok = ok && std::abs (y[2 * (std::size_t) smp.at] - smp.l) <= 1e-5 * peak && std::abs (y[2 * (std::size_t) smp.at + 1] - smp.r) <= 1e-5 * peak;
  6400. if (! ok)
  6401. std::printf (" Ogun variant %s differs from the model: energy %.9g %.9g (model %.9g %.9g)\n", v.name, el, er, v.el, v.er);
  6402. CHECK (ok);
  6403. }
  6404. }
  6405. }
  6406. // our own Maximus v7 state (layout REA_rodada8 §1.1): 7 globals, 4 × 13 band parameters, 8 envelopes (dx, y, tension, type)
  6407. static std::vector<std::uint8_t> maximusTestState (const std::array<int, 7>& g, const std::array<std::array<int, 13>, 4>& bands,
  6408. const std::array<std::vector<std::array<double, 4>>, 8>& envs, int oversampling)
  6409. {
  6410. std::vector<std::uint8_t> d;
  6411. auto put = [&] (const void* v, std::size_t n) { d.insert (d.end(), (const std::uint8_t*) v, (const std::uint8_t*) v + n); };
  6412. auto i32 = [&] (std::int32_t v) { put (&v, 4); };
  6413. i32 (7);
  6414. for (int copy = 0; copy < 2; ++copy)
  6415. {
  6416. for (auto v : g)
  6417. i32 (v);
  6418. for (const auto& b : bands)
  6419. for (auto v : b)
  6420. i32 (v);
  6421. }
  6422. d.resize (0x1fe, 0);
  6423. std::memcpy (d.data() + 0x1f4, &oversampling, 4);
  6424. for (const auto& e : envs)
  6425. {
  6426. i32 (3), i32 (2), i32 ((std::int32_t) e.size());
  6427. for (const auto& pt : e)
  6428. {
  6429. const double dx = pt[0], y = pt[1];
  6430. const float t = (float) pt[2];
  6431. put (&dx, 8), put (&y, 8), put (&t, 4);
  6432. const std::uint8_t flags[4] { (std::uint8_t) pt[3], 0, 0, 0 };
  6433. put (flags, 4);
  6434. }
  6435. i32 (0), i32 (-1), i32 (-1), i32 (-1), i32 (-1);
  6436. }
  6437. return d;
  6438. }
  6439. // A "Kepler-1" state written from scratch (REA_rodada46 §1.1 layout, version 2): the default panel values
  6440. std::vector<std::uint8_t> keplerTestState()
  6441. {
  6442. const float panel[34] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0.5f, 0.5f, 0, 0, 0, 0.5f, 0.5f };
  6443. std::vector<std::uint8_t> st;
  6444. auto u32 = [&] (std::uint32_t v) { for (int i = 0; i < 4; ++i) st.push_back ((std::uint8_t) (v >> (8 * i))); };
  6445. auto f32 = [&] (float f) { std::uint32_t v; std::memcpy (&v, &f, 4); u32 (v); };
  6446. u32 (0), u32 (0), u32 (0), u32 (9);
  6447. for (char c : std::string ("Kepler-1"))
  6448. st.push_back ((std::uint8_t) c);
  6449. st.push_back (0);
  6450. u32 (2), u32 (34);
  6451. for (auto f : panel)
  6452. f32 (f);
  6453. st.push_back (0);
  6454. f32 (1.0f), f32 (0.5f);
  6455. const auto size = (std::uint32_t) st.size() - 12;
  6456. std::memcpy (st.data() + 4, &size, 4);
  6457. return st;
  6458. }
  6459. std::string keplerDll()
  6460. {
  6461. if (realFlpDir.empty())
  6462. return {};
  6463. return (std::filesystem::path (realFlpDir).parent_path() / "Plugins" / "Fruity" / "Generators" / "Kepler" / "engine_x64.dll").string();
  6464. }
  6465. TEST (kepler_engine)
  6466. {
  6467. const auto st = keplerTestState();
  6468. CHECK (st.size() == 178 && lynx::keplerStateUsable (st));
  6469. CHECK (lynx::keplerPanelOffset (st, 19) == 0x21 + 4 * 19 && lynx::keplerPanelOffset (st, 34) == -1);
  6470. auto broken = st;
  6471. broken[17] = 'X'; // not "Kepler-1"
  6472. CHECK (! lynx::keplerStateUsable (broken) && lynx::keplerPanelOffset (broken, 0) == -1);
  6473. auto v3 = st;
  6474. v3[0x19] = 3; // version 3 needs the gate / noise / oversampling bytes
  6475. CHECK (! lynx::keplerStateUsable (v3));
  6476. const auto dll = keplerDll();
  6477. if (dll.empty() || ! lynx::keplerDllUsable (dll))
  6478. return; // no FL installation (the engine needs the user's own DLL tables)
  6479. // against FL's engine DLL (EXEC, REA_rodada46 §6): three notes, 44.1 kHz, host blocks of 512 — bit-exact
  6480. const std::vector<lynx::kepler::RefNote> notes { { 0, 60, 1.0, 0.0, 0.0, 20000 }, { 8000, 67, 0.6, 0.0, 0.0, 26000 }, { 16000, 55, 0.95, 0.0, 0.0, 30000 } };
  6481. const auto y = lynx::kepler::renderReference (st, dll, notes, 44100.0, 39690);
  6482. CHECK (y.size() == 2 * 39690);
  6483. if (y.size() != 2 * 39690)
  6484. return;
  6485. double el = 0.0, er = 0.0;
  6486. for (std::size_t i = 0; i < y.size(); i += 2)
  6487. el += (double) y[i] * y[i], er += (double) y[i + 1] * y[i + 1];
  6488. std::printf (" Kepler default patch: energy %.9g %.9g (FL's DLL 250.641268)\n", el, er);
  6489. CHECK (std::abs (el - 250.641268) < 1e-6 && std::abs (er - 250.641268) < 1e-6);
  6490. const std::tuple<int, float, float> golden[] { { 5000, 0.0467273332f, 0.0467273332f }, { 12000, -0.119412214f, -0.119412214f },
  6491. { 25000, 0.0855825394f, 0.0855825394f }, { 35000, -3.34166579e-08f, -3.34166579e-08f } };
  6492. for (const auto& [i, l, r] : golden)
  6493. CHECK (y[2 * (std::size_t) i] == l && y[2 * (std::size_t) i + 1] == r);
  6494. // the instrument: FL's wrapper velocity, channel volume as an output gain, idle after the release
  6495. lynx::ChannelDef c;
  6496. c.instrument = lynx::InstrumentKind::kepler;
  6497. c.pluginState = st;
  6498. c.samplePath = dll;
  6499. auto inst = lynx::makeInstrument (lynx::InstrumentKind::kepler);
  6500. inst->configure (c, 120.0);
  6501. inst->prepare (44100.0);
  6502. std::vector<float> l (4096), r (4096);
  6503. inst->noteOn (60, 0.8f);
  6504. double e = 0.0;
  6505. bool finite = true;
  6506. for (int b = 0; b < 8; ++b)
  6507. {
  6508. std::fill (l.begin(), l.end(), 0.0f);
  6509. std::fill (r.begin(), r.end(), 0.0f);
  6510. inst->render (l.data(), r.data(), 4096, 0.5f, 0.5f);
  6511. for (int i = 0; i < 4096; ++i)
  6512. finite = finite && std::isfinite (l[(std::size_t) i]) && std::isfinite (r[(std::size_t) i]), e += (double) l[(std::size_t) i] * l[(std::size_t) i];
  6513. if (b == 3)
  6514. inst->noteOff (60);
  6515. }
  6516. CHECK (finite && e > 1.0);
  6517. for (int b = 0; b < 40; ++b)
  6518. inst->render (l.data(), r.data(), 4096, 0.5f, 0.5f);
  6519. CHECK (inst->idle());
  6520. }
  6521. TEST (kepler_demo_channels)
  6522. {
  6523. // every Kepler channel of FL's demo projects on LYNX's engine against FL's engine DLL (EXEC fingerprints, REA_rodada46 §6;
  6524. // the engine differs from the DLL by −127 dB or less on these, from the DLL library's pow rounding)
  6525. const auto dll = keplerDll();
  6526. if (dll.empty() || ! lynx::keplerDllUsable (dll))
  6527. return;
  6528. struct Sample { int at; float l, r; };
  6529. struct Golden { const char* file; const char* channel; std::size_t stateSize; double el, er; Sample s[4]; };
  6530. const Golden goldens[] {
  6531. { "Demo songs/Edlan & Ella Noël - Song For You.flp", "Pads - Kepler", 181, 2595.34411, 1181.70052, { { 5000, 0.258449465f, 0.284368932f }, { 12000, -0.0648983642f, 0.312173635f }, { 25000, -0.271028787f, 0.103852645f }, { 35000, -0.00873807631f, -0.00636588456f } } },
  6532. { "Demo songs/Purps On The Beat Feat Luclover - Stroll Up.flp", "Kepler", 189, 2.77173241, 1.36643586, { { 5000, 0.00653714081f, 0.00885556825f }, { 12000, 0.0316556357f, 0.0255686305f }, { 25000, -0.00359999924f, -0.0027268643f }, { 35000, 3.38630743e-05f, 3.35237855e-05f } } },
  6533. { "Demo songs/Sid De La Cruz - Secret Agent Rendezvous.flp", "AceBass", 181, 491.893665, 813.858274, { { 5000, 0.00933594909f, 0.0551614426f }, { 12000, 0.11930909f, -0.387893438f }, { 25000, -0.0520403236f, -0.131727993f }, { 35000, 2.78028492e-05f, 2.75182774e-05f } } },
  6534. { "Demo songs/Sid De La Cruz - Secret Agent Rendezvous.flp", "Badious", 181, 19.0406926, 20.1997196, { { 5000, 0.00332317385f, 0.00785329007f }, { 12000, 0.0234184917f, -0.0034834384f }, { 25000, -0.0167671479f, -0.0142839653f }, { 35000, -0.0352748372f, -0.00481338287f } } },
  6535. };
  6536. int checked = 0;
  6537. for (const auto& g : goldens)
  6538. {
  6539. std::ifstream in (std::filesystem::path (realFlpDir) / "Demo projects" / g.file, std::ios::binary);
  6540. const std::vector<std::uint8_t> bytes ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  6541. if (bytes.empty())
  6542. continue;
  6543. const flp::Channel* ch = nullptr;
  6544. const auto project = flp::parseProject (bytes);
  6545. for (const auto& c : project.channels)
  6546. if (c.pluginName == "Kepler" && c.name == g.channel)
  6547. ch = &c;
  6548. CHECK (ch != nullptr);
  6549. if (ch == nullptr)
  6550. continue;
  6551. CHECK (ch->pluginState.size() == g.stateSize && lynx::keplerStateUsable (ch->pluginState));
  6552. const auto y = lynx::kepler::renderReference (ch->pluginState, dll, { { 0, 60, 1.0, 0.0, 0.0, 20000 }, { 8000, 67, 0.6, 0.0, 0.0, 26000 },
  6553. { 16000, 55, 0.95, 0.0, 0.0, 30000 } }, 44100.0, 39690);
  6554. double el = 0.0, er = 0.0, peak = 0.0;
  6555. for (std::size_t i = 0; i + 1 < y.size(); i += 2)
  6556. el += (double) y[i] * y[i], er += (double) y[i + 1] * y[i + 1], peak = std::max ({ peak, (double) std::abs (y[i]), (double) std::abs (y[i + 1]) });
  6557. bool ok = y.size() == 2 * 39690 && std::abs (el - g.el) <= 1e-5 * g.el && std::abs (er - g.er) <= 1e-5 * g.er;
  6558. for (const auto& smp : g.s)
  6559. ok = ok && std::abs (y[2 * (std::size_t) smp.at] - smp.l) <= 1e-5 * peak && std::abs (y[2 * (std::size_t) smp.at + 1] - smp.r) <= 1e-5 * peak;
  6560. if (! ok)
  6561. std::printf (" Kepler %s / %s differs from FL's DLL: energy %.9g %.9g (DLL %.9g %.9g)\n", g.file, g.channel, el, er, g.el, g.er);
  6562. CHECK (ok);
  6563. ++checked;
  6564. }
  6565. std::printf (" Kepler: %d demo channels checked against FL's engine DLL\n", checked);
  6566. CHECK (checked == (int) std::size (goldens));
  6567. }
  6568. TEST (ogun_demo_channels)
  6569. {
  6570. // every Ogun channel of FL's demo projects (with its plugin effects) against the round-37 reference model, which is
  6571. // within −60 dB of FL's DLL on all of them: three notes (C5 1.0 0–20000, G5 0.6 8000–26000, G4 0.95 16000–30000),
  6572. // 39 690 samples at 44.1 kHz, at the state's quality and at the export quality 4. Fingerprint: energy per side and
  6573. // four samples (the engine matches the model within float rounding, −125 dB or better on the whole signal).
  6574. if (realFlpDir.empty())
  6575. return;
  6576. struct Sample { int at; float l, r; };
  6577. struct Golden { const char* file; int ordinal; std::size_t stateSize; bool export4; double el, er; Sample s[4]; };
  6578. const Golden goldens[] {
  6579. { "Demo songs/Astes - Bien Duro.flp", 0, 64728, false, 710.708198, 710.708198, { { 5000, 0.133627325f, 0.133627325f }, { 12000, -0.143534407f, -0.143534407f }, { 25000, 0.079226315f, 0.079226315f }, { 35000, -0.0128487358f, -0.0128487358f } } }, // 3.3.1 Metal Drums: Drum
  6580. { "Demo songs/Astes - Bien Duro.flp", 0, 64728, true, 794.506558, 794.506558, { { 5000, -0.0112881307f, -0.0112881307f }, { 12000, -0.068779245f, -0.068779245f }, { 25000, -0.0289028231f, -0.0289028231f }, { 35000, -0.0161623377f, -0.0161623377f } } }, // 3.3.1 Metal Drums: Drum
  6581. { "Demo songs/Astes - Bien Duro.flp", 1, 4261, false, 297.957631, 297.957631, { { 5000, -0.000330464332f, -0.000330464332f }, { 12000, -0.00156057056f, -0.00156057056f }, { 25000, -9.24126434e-05f, -9.24126434e-05f }, { 35000, 0.0f, 0.0f } } }, // 3.3.1 Metal Drums: Click
  6582. { "Demo songs/Astes - Bien Duro.flp", 1, 4261, true, 189.545711, 189.545711, { { 5000, 0.00102557975f, 0.00102557975f }, { 12000, -0.00522088073f, -0.00522088073f }, { 25000, 5.81103013e-05f, 5.81103013e-05f }, { 35000, 0.0f, 0.0f } } }, // 3.3.1 Metal Drums: Click
  6583. { "Demo songs/Astes - Bien Duro.flp", 2, 133836, false, 125.683557, 125.683557, { { 5000, 0.0176561493f, 0.0176561493f }, { 12000, 0.019205872f, 0.019205872f }, { 25000, 0.0046372693f, 0.0046372693f }, { 35000, -0.00165430119f, -0.00165430119f } } }, // 3.3.2 Tibetan
  6584. { "Demo songs/Astes - Bien Duro.flp", 2, 133836, true, 105.621798, 105.621798, { { 5000, 0.00897848886f, 0.00897848886f }, { 12000, -0.0171215143f, -0.0171215143f }, { 25000, -0.00821319036f, -0.00821319036f }, { 35000, -0.00245537539f, -0.00245537539f } } }, // 3.3.2 Tibetan
  6585. { "Demo songs/Astes - Bien Duro.flp", 3, 97085, false, 2066.75611, 2066.75611, { { 5000, -0.101155393f, -0.101155393f }, { 12000, 0.355391592f, 0.355391592f }, { 25000, 0.00365939317f, 0.00365939317f }, { 35000, -0.0191957876f, -0.0191957876f } } }, // 3.3.3 Chase
  6586. { "Demo songs/Astes - Bien Duro.flp", 3, 97085, true, 1667.28674, 1667.28674, { { 5000, -0.236701503f, -0.236701503f }, { 12000, -0.126374632f, -0.126374632f }, { 25000, 0.0533663221f, 0.0533663221f }, { 35000, -0.0100225089f, -0.0100225089f } } }, // 3.3.3 Chase
  6587. { "Demo songs/Edlan & Ella Noël - Song For You.flp", 0, 819, false, 551.263856, 371.038684, { { 5000, 0.0253486633f, 0.160556272f }, { 12000, 0.194370747f, -0.0359776132f }, { 25000, -0.00528950989f, 0.01478827f }, { 35000, 0.110768802f, -0.0237054806f } } }, // Bellish 11
  6588. { "Demo songs/Edlan & Ella Noël - Song For You.flp", 0, 819, true, 547.662092, 381.048456, { { 5000, 0.0401367024f, 0.0261611789f }, { 12000, -0.157383129f, -0.0282031279f }, { 25000, -0.000249146833f, 0.0388034321f }, { 35000, -0.105665907f, 0.0320193283f } } }, // Bellish 11
  6589. { "Demo songs/LollieVox & Lezina J - I'll Be Your Madonna.flp", 0, 105571, false, 833.288142, 909.880193, { { 5000, 0.0276863724f, 0.214677185f }, { 12000, 0.00827352796f, 0.141611829f }, { 25000, -0.160458148f, 0.0101522766f }, { 35000, -0.0157076102f, 0.00129696913f } } }, // High Chords
  6590. { "Demo songs/LollieVox & Lezina J - I'll Be Your Madonna.flp", 0, 105571, true, 928.749154, 967.940976, { { 5000, -0.0623336285f, -0.0959333256f }, { 12000, 0.0601816922f, -0.0748261437f }, { 25000, -0.0872222036f, -0.101655915f }, { 35000, -0.002591094f, 0.0107459351f } } }, // High Chords
  6591. { "Product demos/Electric Loop - The Ogun Dream.flp", 0, 813, false, 21576.8988, 21576.8988, { { 5000, 0.00724618789f, 0.00724618789f }, { 12000, 0.0337664448f, 0.0337664448f }, { 25000, -1.44279329e-05f, -1.44279329e-05f }, { 35000, 0.0f, 0.0f } } }, // Kick
  6592. { "Product demos/Electric Loop - The Ogun Dream.flp", 0, 813, true, 17857.5027, 17857.5027, { { 5000, -0.0114536202f, -0.0114536202f }, { 12000, -0.00848954543f, -0.00848954543f }, { 25000, 1.20320046e-05f, 1.20320046e-05f }, { 35000, 0.0f, 0.0f } } }, // Kick
  6593. { "Product demos/Electric Loop - The Ogun Dream.flp", 1, 789, false, 172.127165, 170.39981, { { 5000, -0.00470701791f, -0.000373305753f }, { 12000, 0.0417476855f, 0.0339940563f }, { 25000, 0.0204325765f, 0.0191226583f }, { 35000, -0.000425090868f, -0.000144533216f } } }, // Clap
  6594. { "Product demos/Electric Loop - The Ogun Dream.flp", 1, 789, true, 163.557022, 149.810459, { { 5000, 0.00246403809f, 0.0228729937f }, { 12000, 0.0378073864f, 0.0445459485f }, { 25000, -0.0242712852f, -0.0313444398f }, { 35000, -0.00112735468f, -0.00138637482f } } }, // Clap
  6595. { "Product demos/Electric Loop - The Ogun Dream.flp", 2, 635, false, 125.48103, 127.519836, { { 5000, -0.00389297446f, 0.00181007839f }, { 12000, -0.0543250106f, -0.0736973509f }, { 25000, -0.00448145531f, 0.000426211918f }, { 35000, 5.35470353e-05f, 4.34564136e-05f } } }, // High Hat
  6596. { "Product demos/Electric Loop - The Ogun Dream.flp", 2, 635, true, 245.916518, 254.34816, { { 5000, 0.00147765165f, 0.00267027458f }, { 12000, 0.0883170143f, 0.173417449f }, { 25000, -0.00118842872f, 0.000863731664f }, { 35000, -0.000298409053f, -9.04561821e-05f } } }, // High Hat
  6597. { "Product demos/Electric Loop - The Ogun Dream.flp", 3, 45647, false, 271.486026, 271.486026, { { 5000, -4.96093298e-06f, -4.96093298e-06f }, { 12000, 0.000292191253f, 0.000292191253f }, { 25000, -8.18665136e-10f, -8.18665136e-10f }, { 35000, 0.0f, 0.0f } } }, // HiHat
  6598. { "Product demos/Electric Loop - The Ogun Dream.flp", 3, 45647, true, 167.753037, 167.753037, { { 5000, 2.2048649e-05f, 2.2048649e-05f }, { 12000, -1.77328075e-05f, -1.77328075e-05f }, { 25000, -3.00809999e-09f, -3.00809999e-09f }, { 35000, 0.0f, 0.0f } } }, // HiHat
  6599. { "Product demos/Electric Loop - The Ogun Dream.flp", 4, 887, false, 6005.75168, 6293.90961, { { 5000, -0.19636783f, -0.0313744769f }, { 12000, 0.178472087f, 0.601032794f }, { 25000, -0.351912051f, -0.0497151017f }, { 35000, -0.182245821f, -0.181938142f } } }, // Snare
  6600. { "Product demos/Electric Loop - The Ogun Dream.flp", 4, 887, true, 6151.47444, 6049.47136, { { 5000, -0.102814399f, 0.0690701902f }, { 12000, 0.0902677849f, 0.114889771f }, { 25000, -0.173990116f, 0.140671447f }, { 35000, 0.0744562522f, 0.0291433111f } } }, // Snare
  6601. { "Product demos/Electric Loop - The Ogun Dream.flp", 5, 705, false, 6511.3723, 5580.42134, { { 5000, 0.478397369f, 0.536334693f }, { 12000, -0.312448859f, -0.301919997f }, { 25000, 0.260874003f, -0.0129742175f }, { 35000, 0.0223956257f, 0.033103168f } } }, // Swebass 1
  6602. { "Product demos/Electric Loop - The Ogun Dream.flp", 5, 705, true, 6415.0768, 5859.44881, { { 5000, 0.0342692807f, 0.00727743423f }, { 12000, -0.0324966274f, 0.125386745f }, { 25000, -0.0785191655f, -0.25017795f }, { 35000, -0.0524680056f, -0.0384391509f } } }, // Swebass 1
  6603. { "Product demos/Electric Loop - The Ogun Dream.flp", 6, 708, false, 2487.6041, 2190.17262, { { 5000, -0.0770967156f, -0.00940297544f }, { 12000, 0.329836905f, 0.183736563f }, { 25000, 0.0137981772f, -0.0334252715f }, { 35000, 0.0132095823f, 0.0277119074f } } }, // Swebass 2
  6604. { "Product demos/Electric Loop - The Ogun Dream.flp", 6, 708, true, 2519.26975, 2230.77243, { { 5000, -0.204216316f, -0.16732122f }, { 12000, 0.0762225091f, 0.0964485779f }, { 25000, -0.0833523944f, -0.132980049f }, { 35000, -0.015998248f, 0.0112942485f } } }, // Swebass 2
  6605. { "Product demos/Electric Loop - The Ogun Dream.flp", 7, 109827, false, 1326.11782, 1397.71125, { { 5000, 0.0306534693f, 0.026510708f }, { 12000, -0.139238164f, -0.104713492f }, { 25000, 0.106734768f, 0.0295313746f }, { 35000, 0.258899271f, 0.260215104f } } }, // Midnight Lady
  6606. { "Product demos/Electric Loop - The Ogun Dream.flp", 7, 109827, true, 1252.058, 1287.83169, { { 5000, -0.0980920121f, -0.108575724f }, { 12000, 0.131130368f, 0.176118359f }, { 25000, 0.0581845529f, 0.174699515f }, { 35000, -0.17453593f, 0.0978319347f } } }, // Midnight Lady
  6607. { "Product demos/Electric Loop - The Ogun Dream.flp", 8, 34816, false, 10793.0192, 11904.6549, { { 5000, 0.36459741f, -0.0714551434f }, { 12000, 0.565215111f, -0.205066338f }, { 25000, -0.652977228f, -0.432422459f }, { 35000, -0.284279644f, -0.122116163f } } }, // Supersaw
  6608. { "Product demos/Electric Loop - The Ogun Dream.flp", 8, 34816, true, 10132.5107, 11590.7617, { { 5000, 0.192168862f, 0.0883051828f }, { 12000, -0.590734482f, 0.512839496f }, { 25000, 0.682625771f, 0.287306368f }, { 35000, -0.00662239315f, 0.700808227f } } }, // Supersaw
  6609. { "Product demos/Electric Loop - The Ogun Dream.flp", 9, 94266, false, 826.69243, 1157.08939, { { 5000, 0.0348474756f, -0.168766886f }, { 12000, -0.0719366521f, 0.288826376f }, { 25000, 0.181558818f, 0.0424098521f }, { 35000, -0.321783781f, -0.0548994206f } } }, // Airguitar 3
  6610. { "Product demos/Electric Loop - The Ogun Dream.flp", 9, 94266, true, 830.517691, 772.62552, { { 5000, -0.208309069f, 0.152180359f }, { 12000, -0.264171928f, 0.163982511f }, { 25000, 0.0313629843f, -0.187507361f }, { 35000, 0.133838147f, 0.0704783946f } } }, // Airguitar 3
  6611. { "Product demos/Electric Loop - The Ogun Dream.flp", 10, 1004, false, 12678.7464, 11831.2032, { { 5000, 0.192205578f, 0.613839507f }, { 12000, 0.269521117f, -0.585603476f }, { 25000, 0.0944993123f, 0.0806781948f }, { 35000, -0.16715017f, 0.412193805f } } }, // Trumpet
  6612. { "Product demos/Electric Loop - The Ogun Dream.flp", 10, 1004, true, 12261.8266, 9962.482, { { 5000, 0.422391087f, -0.251674503f }, { 12000, -0.46900028f, -0.57652849f }, { 25000, -0.535878778f, 0.115671799f }, { 35000, -0.545713186f, 0.0383624472f } } }, // Trumpet
  6613. { "Product demos/Electric Loop - The Ogun Dream.flp", 11, 30605, false, 1358.26232, 1520.29691, { { 5000, -0.0350573957f, 0.0372484438f }, { 12000, 0.0963054374f, -0.130206674f }, { 25000, 0.0404771306f, -0.270439237f }, { 35000, -0.0870027244f, 0.0245792065f } } }, // Silverswirll
  6614. { "Product demos/Electric Loop - The Ogun Dream.flp", 11, 30605, true, 964.637209, 1040.25756, { { 5000, 0.111636952f, -0.00114471605f }, { 12000, 0.0483313873f, 0.0637735277f }, { 25000, -0.152803347f, 0.101604536f }, { 35000, 0.0288163591f, 0.0194431469f } } }, // Silverswirll
  6615. { "Product demos/Electric Loop - The Ogun Dream.flp", 12, 34708, false, 21463.1948, 22013.1021, { { 5000, -0.00810255855f, -0.0122786947f }, { 12000, -0.163549975f, -0.203571558f }, { 25000, 0.419101298f, -1.1141516f }, { 35000, 0.498232335f, -0.394363374f } } }, // Padsaw
  6616. { "Product demos/Electric Loop - The Ogun Dream.flp", 12, 34708, true, 22903.9209, 21556.3509, { { 5000, -0.00977799948f, -0.0114432834f }, { 12000, -0.0759382695f, 0.077038914f }, { 25000, -0.556497335f, -1.22787583f }, { 35000, -1.31076968f, -1.73392022f } } }, // Padsaw
  6617. { "Product demos/Electric Loop - The Ogun Dream.flp", 13, 6395, false, 3516.18148, 3565.45486, { { 5000, -0.0564712696f, -0.262329876f }, { 12000, 0.113444217f, 0.168150783f }, { 25000, -0.45024398f, -0.694699228f }, { 35000, 0.151807249f, -0.00405737339f } } }, // Turbular Bells 2
  6618. { "Product demos/Electric Loop - The Ogun Dream.flp", 13, 6395, true, 3571.34372, 3626.15163, { { 5000, -0.0878480822f, -0.275067806f }, { 12000, 0.230907321f, 0.28320539f }, { 25000, -0.470044613f, -0.701287091f }, { 35000, 0.195627496f, 0.0175700653f } } }, // Turbular Bells 2
  6619. };
  6620. std::map<std::string, std::vector<std::vector<std::uint8_t>>> states;
  6621. int checked = 0;
  6622. for (const auto& g : goldens)
  6623. {
  6624. if (! states.contains (g.file))
  6625. {
  6626. std::ifstream in (std::filesystem::path (realFlpDir) / "Demo projects" / g.file, std::ios::binary);
  6627. const std::vector<std::uint8_t> bytes ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  6628. auto& list = states[g.file];
  6629. if (! bytes.empty())
  6630. for (const auto& c : flp::parseProject (bytes).channels)
  6631. if (c.pluginName == "Ogun")
  6632. list.push_back (c.pluginState);
  6633. }
  6634. const auto& list = states[g.file];
  6635. if (list.empty())
  6636. continue; // not this installation
  6637. CHECK ((int) list.size() > g.ordinal);
  6638. if ((int) list.size() <= g.ordinal)
  6639. continue;
  6640. const auto& st = list[(std::size_t) g.ordinal];
  6641. CHECK (st.size() == g.stateSize);
  6642. lynx::ogun::RefOptions opt;
  6643. opt.quality = g.export4 ? 4 : -1;
  6644. const auto y = lynx::ogun::renderReference (st, { { 0, 60, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 20000 },
  6645. { 8000, 67, 0.6, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 26000 },
  6646. { 16000, 55, 0.95, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 30000 } }, 44100.0, 39690, opt);
  6647. double el = 0.0, er = 0.0, peak = 0.0;
  6648. for (std::size_t i = 0; i + 1 < y.size(); i += 2)
  6649. el += (double) y[i] * y[i], er += (double) y[i + 1] * y[i + 1], peak = std::max ({ peak, (double) std::abs (y[i]), (double) std::abs (y[i + 1]) });
  6650. bool ok = y.size() == 2 * 39690 && std::abs (el - g.el) <= 1e-5 * g.el && std::abs (er - g.er) <= 1e-5 * g.er;
  6651. for (const auto& smp : g.s)
  6652. ok = ok && std::abs (y[2 * (std::size_t) smp.at] - smp.l) <= 2e-5 * peak && std::abs (y[2 * (std::size_t) smp.at + 1] - smp.r) <= 2e-5 * peak;
  6653. if (! ok)
  6654. std::printf (" Ogun %s #%d (q%s) differs from the model: energy %.9g %.9g (model %.9g %.9g)\n", g.file, g.ordinal,
  6655. g.export4 ? "4" : "-state", el, er, g.el, g.er);
  6656. CHECK (ok);
  6657. ++checked;
  6658. }
  6659. std::printf (" Ogun: %d demo renders checked against the reference model\n", checked);
  6660. CHECK (checked == (int) std::size (goldens));
  6661. }
  6662. TEST (harmless_rack)
  6663. {
  6664. // REA_rodada36: Harmless's effects rack against our reference model (rack.py / maxmodel.py, which match the
  6665. // installation's Harmless_x64.dll and SG_x64.dll), 44.1 kHz, host blocks of 512
  6666. std::vector<float> inL (8192), inR (8192);
  6667. for (int i = 0; i < 4096; ++i)
  6668. {
  6669. 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));
  6670. inR[(std::size_t) i] = (float) (1.2 * std::sin (2.0 * 3.141592653589793 * 660.0 * i / 44100.0));
  6671. }
  6672. auto run = [&] (const std::array<int, 100>& p, int compType, std::shared_ptr<const lynx::hlfx::MaximusPreset> comp, int total, int voicesUntil) {
  6673. lynx::hlfx::Rack rack;
  6674. std::array<int, 7> t {};
  6675. t[3] = compType;
  6676. rack.prepare (p, t, 44100.0, 120.0, std::move (comp));
  6677. std::vector<float> l (inL.begin(), inL.begin() + total), r (inR.begin(), inR.begin() + total);
  6678. for (int s = 0; s < total; s += 512)
  6679. rack.process (l.data() + s, r.data() + s, std::min (512, total - s), s < voicesUntil);
  6680. return std::make_pair (l, r);
  6681. };
  6682. {
  6683. // chorus type 3 (mix 400), ping-pong delay type 2 (vol 600, feedback 500, 1/4 beat), reverb type 4 (vol 700)
  6684. std::array<int, 100> p {};
  6685. p[90] = 3, p[91] = 400, p[92] = 2, p[93] = 600, p[94] = 500, p[95] = 48, p[96] = 4, p[97] = 700;
  6686. const auto [l, r] = run (p, 0, nullptr, 8192, 4096);
  6687. const std::tuple<int, float, float> golden[] { { 0, 0.0f, 0.0f }, { 500, -0.25248247f, 0.15141529f }, { 3000, -0.65128994f, -0.64854866f },
  6688. { 5000, -0.54308629f, -0.36827448f }, { 6000, -0.98378551f, -0.72790027f },
  6689. { 8191, 0.50599128f, -0.43637198f } };
  6690. for (const auto& [i, gl, gr] : golden)
  6691. CHECK (std::abs (l[(std::size_t) i] - gl) < 2e-6f && std::abs (r[(std::size_t) i] - gr) < 2e-6f);
  6692. }
  6693. {
  6694. // the delay alone: an impulse comes back after round(time·fs·0.3125/bpm) samples × (11^0.6 − 1)/10, then × feedback
  6695. std::array<int, 100> p {};
  6696. p[92] = 1, p[93] = 600, p[94] = 500, p[95] = 48;
  6697. lynx::hlfx::Rack rack;
  6698. rack.prepare (p, {}, 44100.0, 120.0, nullptr);
  6699. std::vector<float> l (16384), r (16384);
  6700. l[0] = 1.0f;
  6701. for (int s = 0; s < 16384; s += 512)
  6702. rack.process (l.data() + s, r.data() + s, 512, s == 0);
  6703. const auto D = 5512; // 48·44100·0.3125/120 = 5512.5 → 5512 (round half to even)
  6704. const auto vol = (float) ((std::exp ((double) (600 * 0.001f) * (double) (float) std::log (11.0)) - 1.0) * (double) 0.1f);
  6705. CHECK (std::abs (l[(std::size_t) D] - vol) < 1e-7f && std::abs (l[(std::size_t) D - 1]) < 1e-12f);
  6706. // the feedback ramps from 0.5 toward 0.5: the second echo is vol·0.5
  6707. CHECK (std::abs (l[(std::size_t) (2 * D)] - vol * 0.5f) < 1e-7f && std::abs (r[(std::size_t) D]) < 1e-12f);
  6708. }
  6709. // the compressor: Maximus states of our own (no preset data), checked against SG_x64.dll by REA round 36
  6710. using Env = std::vector<std::array<double, 4>>;
  6711. const Env def { { 0.0, 0.0, 0.0, 0 }, { 0.5, 0.5, 0.0, 0 }, { 0.5, 0.5, 0.0, 0 } };
  6712. 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,
  6713. int sus = 2882) { return std::array<int, 13> { mode, pre, post, sep, sat, ceil, att, rel2, 2, 5000, 3, sus, 0 }; };
  6714. {
  6715. // master brickwall at −0.22 dB only (bands off / compression off)
  6716. const auto st = maximusTestState ({ 19800, 1, 48065, 1, 1115, 1000, -1 }, { band (3), band (1), band (3), band (0) },
  6717. { def, def, def, def, def, def, def, def }, 0);
  6718. const auto preset = lynx::hlfx::makeMaximusPreset (st);
  6719. CHECK (preset != nullptr);
  6720. std::array<int, 100> p {};
  6721. p[98] = 1000;
  6722. const auto [l, r] = run (p, 1, preset, 4096, 4096);
  6723. // SG_x64.dll's own output (EXEC, REA_rodada40: bit-identical to the port)
  6724. const std::tuple<int, float, float> golden[] { { 100, 0.024997942f, 0.88166064f }, { 1000, 0.56971401f, -0.62808102f },
  6725. { 2047, -0.27541628f, 0.709135f }, { 3000, 0.32431623f, -0.37985197f },
  6726. { 4095, -0.12743522f, -0.15237485f } };
  6727. for (const auto& [i, gl, gr] : golden)
  6728. CHECK (std::abs (l[(std::size_t) i] - gl) < 2e-6f && std::abs (r[(std::size_t) i] - gr) < 2e-6f);
  6729. float peak = 0.0f;
  6730. for (int i = 2048; i < 4096; ++i)
  6731. peak = std::max ({ peak, std::abs (l[(std::size_t) i]), std::abs (r[(std::size_t) i]) });
  6732. CHECK (peak < 0.9751f);
  6733. }
  6734. {
  6735. // 24 dB crossovers, ×2 oversampling, low cut, stereo separation, saturation A, a knee with tension (type 7) and
  6736. // exponential tensions (type 0), release 2 on the master, band mix 600
  6737. const Env knee { { 0.0, 0.0, 0.0, 0 }, { 0.35, 0.35, 0.0, 0 }, { 0.65, 0.6, 0.36, 7 } };
  6738. const Env t0 { { 0.0, 0.0, 0.0, 0 }, { 0.5, 0.5, 0.14, 0 }, { 0.5, 0.5, 0.0, 0 } };
  6739. const Env m0 { { 0.0, 0.0, 0.0, 0 }, { 0.5, 0.5, 0.0, 0 }, { 0.5, 0.6, 0.085, 0 } };
  6740. const auto st = maximusTestState ({ 19800, 1, 48065, 1, 891, 600, 32768 },
  6741. { band (1, 1264, 1296, 500, -500, 1200), band (0, 1340, 1000, -348, 0, 1000, 1115, 0, 1570),
  6742. band (0, 1364, 1152, 0, 0, 1000, 1115, 0, 1186), band (0, 1000, 1000, 0, -196, 1000, 1115, 4464, 1538) },
  6743. { def, def, knee, def, t0, def, m0, def }, 1);
  6744. const auto preset = lynx::hlfx::makeMaximusPreset (st);
  6745. CHECK (preset != nullptr);
  6746. std::array<int, 100> p {};
  6747. p[98] = 600;
  6748. const auto [l, r] = run (p, 2, preset, 4096, 4096);
  6749. // SG_x64.dll's own output (EXEC, REA_rodada40; the port is within −142 dB of it)
  6750. const std::tuple<int, float, float> golden[] { { 100, 0.0f, 0.0f }, { 1000, -0.46856543f, -0.63262129f },
  6751. { 2047, 0.20268451f, 0.54145539f }, { 3000, -0.25613472f, -0.49985155f },
  6752. { 4095, 0.10172445f, 0.050564945f } };
  6753. for (const auto& [i, gl, gr] : golden)
  6754. CHECK (std::abs (l[(std::size_t) i] - gl) < 2e-6f && std::abs (r[(std::size_t) i] - gr) < 2e-6f);
  6755. }
  6756. {
  6757. // an .fst wrapper around a state is found; unsupported states are rejected
  6758. const auto st = maximusTestState ({ 19800, 1, 48065, 1, 1115, 1000, -1 }, { band (3), band (1), band (3), band (0) },
  6759. { def, def, def, def, def, def, def, def }, 0);
  6760. std::vector<std::uint8_t> fst { 'F', 'L', 'h', 'd', 6, 0, 0, 0, 0, 0, 1, 0, 0x60, 0, 'F', 'L', 'd', 't' };
  6761. std::vector<std::uint8_t> body { 0xC9, 8, 'M', 'a', 'x', 'i', 'm', 'u', 's', 0, 0xD5 };
  6762. for (auto n = st.size(); ; n >>= 7)
  6763. {
  6764. body.push_back ((std::uint8_t) ((n & 0x7f) | (n >= 0x80 ? 0x80 : 0)));
  6765. if (n < 0x80)
  6766. break;
  6767. }
  6768. body.insert (body.end(), st.begin(), st.end());
  6769. const auto len = (std::uint32_t) body.size();
  6770. for (int k = 0; k < 4; ++k)
  6771. fst.push_back ((std::uint8_t) (len >> (8 * k)));
  6772. fst.insert (fst.end(), body.begin(), body.end());
  6773. const auto found = lynx::hlfx::maximusStateFromFst (fst);
  6774. CHECK (found && *found == st);
  6775. auto rms = st;
  6776. rms[4 + 4 * (7 + 13 * 3 + 12)] = 1; // RMS detector on the master (decoded in REA_rodada40)
  6777. CHECK (lynx::hlfx::makeMaximusPreset (rms) != nullptr);
  6778. auto masterMid = st;
  6779. masterMid[0x1fc] = 1; // "Master Mid mode": not decoded
  6780. CHECK (lynx::hlfx::makeMaximusPreset (masterMid) == nullptr);
  6781. }
  6782. }
  6783. TEST (maximus_engine)
  6784. {
  6785. // REA_rodada40: the engine on its own (MaximusProcessor), states of our own against the installation's DLLs
  6786. // (goldens = the DLL's output for the same input, EXEC), and the containers of the mixer effect and Vocodex
  6787. std::vector<float> inL (4096), inR (4096);
  6788. for (int i = 0; i < 4096; ++i)
  6789. {
  6790. 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));
  6791. inR[(std::size_t) i] = (float) (1.2 * std::sin (2.0 * 3.141592653589793 * 660.0 * i / 44100.0));
  6792. }
  6793. auto run = [&] (std::shared_ptr<const lynx::hlfx::MaximusPreset> preset, int mix) {
  6794. lynx::hlfx::MaximusProcessor m;
  6795. m.prepare (std::move (preset), 44100.0, mix);
  6796. std::vector<float> l (inL), r (inR);
  6797. for (int s = 0; s < 4096; s += 512)
  6798. m.process (l.data() + s, r.data() + s, 512);
  6799. return std::make_pair (l, r);
  6800. };
  6801. using Env = std::vector<std::array<double, 4>>;
  6802. const Env def { { 0.0, 0.0, 0.0, 0 }, { 0.5, 0.5, 0.0, 0 }, { 0.5, 0.5, 0.0, 0 } };
  6803. const Env knee { { 0.0, 0.0, 0.0, 0 }, { 0.35, 0.35, 0.0, 0 }, { 0.65, 0.6, 0.36, 7 } };
  6804. const Env t0 { { 0.0, 0.0, 0.0, 0 }, { 0.5, 0.5, 0.14, 0 }, { 0.5, 0.5, 0.0, 0 } };
  6805. const Env m0 { { 0.0, 0.0, 0.0, 0 }, { 0.5, 0.5, 0.0, 0 }, { 0.5, 0.6, 0.085, 0 } };
  6806. 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,
  6807. int sus = 2882, int rms = 0) { return std::array<int, 13> { mode, pre, post, sep, sat, ceil, att, rel2, 2, 5000, 3, sus, rms }; };
  6808. auto check = [] (const std::pair<std::vector<float>, std::vector<float>>& out, const std::vector<std::tuple<int, float, float>>& golden) {
  6809. for (const auto& [i, gl, gr] : golden)
  6810. CHECK (std::abs (out.first[(std::size_t) i] - gl) < 2e-6f && std::abs (out.second[(std::size_t) i] - gr) < 2e-6f);
  6811. };
  6812. // RMS detectors, saturation mode B, a 5 Hz low cut, 12 dB high split (SG_x64.dll: port within −152 dB)
  6813. auto st3 = maximusTestState ({ 19800, 1, 48065, 0, 1115, 1000, 0 },
  6814. { band (0, 1500, 1000, 0, 400, 900, 1115, 0, 2882, 1), band (0, 1340, 1000, 0, 0, 1000, 1115, 0, 1570, 1),
  6815. band (1, 1000, 1200, 0, 1000, 1000), band (0, 1000, 1000, 0, 250, 1000, 1115, 4464, 2882, 1) },
  6816. { def, def, knee, def, t0, def, m0, def }, 0);
  6817. const auto p3 = lynx::hlfx::makeMaximusPreset (st3);
  6818. CHECK (p3 != nullptr);
  6819. check (run (p3, 1000), { { 100, 0.0f, 0.0f }, { 1000, 0.87061065f, 0.64004499f }, { 2047, -0.97266865f, 0.60940075f },
  6820. { 3000, 0.96658099f, 0.9250561f }, { 4095, 0.99094611f, -0.964059f } });
  6821. // the same with solo on (UI byte 0x1EF) and the low band selected (0x1E0): bit-identical to SG_x64.dll
  6822. auto solo = st3;
  6823. solo[0x1ef] = 1;
  6824. std::memset (solo.data() + 0x1e0, 0, 4);
  6825. check (run (lynx::hlfx::makeMaximusPreset (solo), 1000),
  6826. { { 100, 3.2922967e-06f, 0.00036916698f }, { 1000, 0.15653539f, -0.047913823f }, { 2047, -0.17336531f, 0.019099623f },
  6827. { 3000, 0.17185682f, -0.017173048f }, { 4095, 0.16714551f, 0.019473195f } });
  6828. // the legacy linear-phase FIR band split (UI byte 0x1FD; SG_x64.dll: port within −148 dB)
  6829. auto fir = st3;
  6830. fir[0x1fd] = 1;
  6831. check (run (lynx::hlfx::makeMaximusPreset (fir), 1000),
  6832. { { 100, 0.0f, 0.0f }, { 1000, 0.97986746f, 0.18555209f }, { 2047, -0.98930448f, -0.95970845f },
  6833. { 3000, 0.98856646f, -0.44592777f }, { 4095, 0.99069679f, 0.94382554f } });
  6834. // Soundgoodizer_x64.dll's own build with a v4 file (its presets' layout): a copy of the round-36 state without
  6835. // oversampling, through a byte-identical copy of the installation's DLL with this file as its preset (EXEC)
  6836. const auto st2 = maximusTestState ({ 19800, 1, 48065, 1, 891, 600, 32768 },
  6837. { band (1, 1264, 1296, 500, -500, 1200), band (0, 1340, 1000, -348, 0, 1000, 1115, 0, 1570),
  6838. band (0, 1364, 1152, 0, 0, 1000, 1115, 0, 1186), band (0, 1000, 1000, 0, -196, 1000, 1115, 4464, 1538) },
  6839. { def, def, knee, def, t0, def, m0, def }, 0);
  6840. std::vector<std::uint8_t> v4 { 4, 0, 0, 0 };
  6841. v4.insert (v4.end(), st2.begin() + 4, st2.begin() + 0x1f5);
  6842. v4.insert (v4.end(), st2.begin() + 0x1fe, st2.end());
  6843. const auto p4 = lynx::hlfx::makeMaximusPreset (v4, lynx::hlfx::MaximusBuild::soundgoodizer);
  6844. CHECK (p4 != nullptr);
  6845. check (run (p4, 600), { { 100, 0.0f, 0.0f }, { 1000, -0.60926896f, -0.6652832f }, { 2047, 0.40872875f, 0.36375371f },
  6846. { 3000, -0.41941205f, -0.61312866f }, { 4095, -0.12878418f, 0.27944946f } });
  6847. CHECK (lynx::hlfx::makeMaximusPreset (st2, lynx::hlfx::MaximusBuild::soundgoodizer) != nullptr); // v7: also read by that build
  6848. // the mixer effect's container and the effect itself
  6849. lynx::maximusfx::Blob blob;
  6850. blob.build = lynx::hlfx::MaximusBuild::soundgoodizer;
  6851. blob.mix = 600;
  6852. blob.state = v4;
  6853. const auto packed = lynx::maximusfx::pack (blob);
  6854. const auto back = lynx::maximusfx::unpack (packed);
  6855. CHECK (back && back->build == blob.build && back->mix == 600 && back->state == v4);
  6856. auto slot = lynx::makeEffectSlot (lynx::EffectKind::maximus);
  6857. slot.state = packed;
  6858. auto fx = lynx::makeEffect (slot);
  6859. fx->prepare (44100.0);
  6860. {
  6861. std::vector<float> l (inL), r (inR);
  6862. for (int s = 0; s < 4096; s += 1024) // longer host blocks are split into the engine's 512-frame calls
  6863. fx->process (l.data() + s, r.data() + s, 1024, slot.params, 120.0);
  6864. const auto ref = run (p4, 600);
  6865. CHECK (l == ref.first && r == ref.second);
  6866. }
  6867. const std::vector<std::uint8_t> sgState { 3, 0, 0, 0, 2, 0, 0, 0, 0x78, 2, 0, 0 };
  6868. const auto sg = lynx::maximusfx::parseSoundgoodizer (sgState);
  6869. CHECK (sg && sg->preset == 2 && sg->amount == 632 && std::string (lynx::maximusfx::soundgoodizerPresetFile (2)) == "c.dat");
  6870. CHECK (lynx::soundgoodizerPresetPath (sgState) == "Plugins\\Fruity\\Effects\\Soundgoodizer\\Data\\Presets\\c.dat");
  6871. CHECK (lynx::soundgoodizerExact (sgState, v4).has_value() && ! lynx::soundgoodizerExact (sgState, {}).has_value());
  6872. // Vocodex's appended installation data survives a round trip and leaves FL's state untouched
  6873. const std::vector<std::uint8_t> flState { 8, 0, 0, 0, 1, 2, 3 };
  6874. lynx::vocodex::InstallData data;
  6875. data.sgDat = st2;
  6876. data.carrierState = { 9, 9, 9 };
  6877. const auto joined = lynx::vocodex::appendInstallData (flState, data);
  6878. const auto [raw, files] = lynx::vocodex::splitInstallData (joined);
  6879. CHECK (raw == flState && files.sgDat == st2 && files.carrierState == data.carrierState);
  6880. CHECK (lynx::vocodex::splitInstallData (flState).first == flState);
  6881. }
  6882. // ---- Sytrus (REA_rodada31) -------------------------------------------------------------------------------------------
  6883. // A Sytrus state built from scratch (version 25 layout, our own values — no FL preset data), zlib "stored" blocks.
  6884. namespace
  6885. {
  6886. struct SytrusTestPatch
  6887. {
  6888. std::vector<std::int32_t> main = std::vector<std::int32_t> (240, 0); // 962-byte main block as ints (+ mute bytes)
  6889. struct Op
  6890. {
  6891. int p[10] { 0, 256, 0, 0, 0, 0, 0, 0, 0, 0 };
  6892. int ratio = 20000, offset = 0, noise = 0;
  6893. std::vector<float> amps { 1.0f };
  6894. std::uint8_t flags[8] {};
  6895. int env1[3] { -1, -1, -1 }; // volume envelope: on (≠ −1 → on), decay point, sustain point
  6896. std::vector<std::pair<double, double>> env1pts;
  6897. } ops[6];
  6898. struct Filt
  6899. {
  6900. int p[10] { 0, 0, 128, 0, 128, 0, 0, 128, 128, 0 };
  6901. int type = 3;
  6902. } filts[3];
  6903. std::array<std::array<std::uint8_t, 23>, 3> delays {};
  6904. std::array<std::int32_t, 9> reverb { 19, 221, 0, 50, 80, 30, 221, 2, 0 };
  6905. bool reverbOn = false;
  6906. int eqmode = 0;
  6907. SytrusTestPatch()
  6908. {
  6909. main[0] = 128, main[1] = 128;
  6910. for (int i = 0; i < 8; ++i)
  6911. main[(std::size_t) (165 + i)] = (i % 4 == 2) ? 0 : 128;
  6912. main[173] = 1, main[175] = 128, main[188] = 128, main[189] = -1, main[190] = main[191] = 256;
  6913. }
  6914. void cell (int layer, int row, int col, int v) { main[(std::size_t) (3 + layer * 81 + row * 9 + col)] = v; }
  6915. std::vector<std::uint8_t> blob() const
  6916. {
  6917. std::vector<std::uint8_t> b;
  6918. 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))); };
  6919. auto f32 = [&] (float v) { std::int32_t x; std::memcpy (&x, &v, 4); i32 (x); };
  6920. 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))); };
  6921. // point lists: kind 1 envelope, 2 LFO, 3 map / shaper curve; format version 3
  6922. auto env = [&] (int kind, const std::vector<std::pair<double, double>>& pts, int on, int decay, int sus) {
  6923. i32 (kind), i32 (3), i32 ((std::int32_t) pts.size());
  6924. for (const auto& [dt, y] : pts)
  6925. f64 (dt), f64 (y), f32 (0.0f), i32 (0);
  6926. i32 (0), i32 (on), i32 (decay), i32 (-1), i32 (sus);
  6927. };
  6928. for (int i = 0; i < 240; ++i)
  6929. if (4 * i + 4 <= 0x320)
  6930. i32 (main[(std::size_t) i]);
  6931. b.resize (962, 0); // mute bytes: none muted
  6932. i32 (0); // global declick amount
  6933. b.push_back (0), b.push_back (0), b.push_back (0); // OSC grouping, DC stage, GIBBS OFF
  6934. for (int k = 0; k < 9; ++k)
  6935. b.push_back (k == 7 ? 1 : 0); // flag group (release multiplier on, as Default.fst)
  6936. for (const auto& d : delays)
  6937. b.insert (b.end(), d.begin(), d.end());
  6938. for (auto v : reverb)
  6939. i32 (v);
  6940. b.push_back (reverbOn ? 1 : 0), b.push_back (0);
  6941. i32 (eqmode);
  6942. for (int k = 0; k < 3; ++k)
  6943. i32 (0), i32 (30000), i32 (20000), i32 (k);
  6944. b.push_back (0); // no info text
  6945. for (int u = 0; u < 10; ++u)
  6946. {
  6947. const int narts = u < 6 ? 6 : (u < 9 ? 8 : 2);
  6948. for (int j = 0; j < 10; ++j)
  6949. i32 (u < 6 ? ops[u].p[j] : (u < 9 ? filts[u - 6].p[j] : 0));
  6950. if (u < 6)
  6951. {
  6952. const auto& o = ops[u];
  6953. const auto at = b.size();
  6954. b.resize (at + 0x828, 0);
  6955. auto put = [&] (std::size_t off, const void* src, std::size_t n) { std::memcpy (b.data() + at + off, src, n); };
  6956. put (0, &o.ratio, 4), put (4, &o.offset, 4), put (8, &o.noise, 4);
  6957. put (0xc, o.amps.data(), 4 * o.amps.size());
  6958. const std::int32_t shape[5] { 0, 0, 0, 0, 128 };
  6959. put (0x80c, shape, sizeof shape);
  6960. put (0x820, o.flags, 8);
  6961. }
  6962. else if (u < 9)
  6963. {
  6964. const auto at = b.size();
  6965. b.resize (at + 0x30, 0);
  6966. std::memcpy (b.data() + at + 0x2c, &filts[u - 6].type, 4);
  6967. env (3, { { 0.0, 0.0 }, { 1.0, 1.0 } }, 0, -1, -1);
  6968. b.push_back (0);
  6969. }
  6970. for (int k = 0; k < narts; ++k)
  6971. {
  6972. const bool add = k == 0 || k == 3 || (u >= 6 && u <= 8 && (k == 2 || k == 3)) || (u < 6 && k == 4);
  6973. const double neutral = add ? 0.5 : 1.0;
  6974. i32 (3), i32 (0), f32 (1.0f), f32 (1.0f);
  6975. if (u < 6 && k == 1 && ops[u].env1[0] != -1)
  6976. env (1, ops[u].env1pts, -1, ops[u].env1[1], ops[u].env1[2]);
  6977. else
  6978. env (1, { { 0.0, 0.0 }, { 1.0, 1.0 } }, 0, -1, -1);
  6979. i32 (128), i32 (128), i32 (0), i32 (128);
  6980. env (2, { { 0.0, 1.0 }, { 1.0, 1.0 } }, 0, -1, -1);
  6981. i32 (40000), i32 (0), i32 (0), i32 (0), i32 (0);
  6982. for (int m = 0; m < 6; ++m)
  6983. env (3, { { 0.0, neutral }, { 1.0, neutral } }, 0, -1, -1);
  6984. }
  6985. }
  6986. b.push_back (0), b.push_back (0);
  6987. // zlib with stored blocks
  6988. std::vector<std::uint8_t> z { 0x78, 0x01 };
  6989. for (std::size_t at = 0; at < b.size(); at += 65535)
  6990. {
  6991. const auto n = std::min<std::size_t> (65535, b.size() - at);
  6992. z.push_back (at + n >= b.size() ? 1 : 0);
  6993. z.push_back ((std::uint8_t) n), z.push_back ((std::uint8_t) (n >> 8));
  6994. z.push_back ((std::uint8_t) ~n), z.push_back ((std::uint8_t) (~n >> 8));
  6995. z.insert (z.end(), b.begin() + (std::ptrdiff_t) at, b.begin() + (std::ptrdiff_t) (at + n));
  6996. }
  6997. std::uint32_t a = 1, c = 0;
  6998. for (auto x : b)
  6999. a = (a + x) % 65521, c = (c + a) % 65521;
  7000. for (int k = 3; k >= 0; --k)
  7001. z.push_back ((std::uint8_t) (((c << 16) | a) >> (8 * k)));
  7002. std::vector<std::uint8_t> out { 25, 0, 0, 0 };
  7003. out.insert (out.end(), z.begin(), z.end());
  7004. return out;
  7005. }
  7006. };
  7007. // renders like FL's Gen_Render calls: notes start/release at the block that contains them
  7008. std::pair<std::vector<float>, std::vector<float>> sytrusRender (const std::vector<std::uint8_t>& blob, bool renderMode, int n,
  7009. std::vector<std::array<int, 3>> notes, double fs = 44100.0)
  7010. {
  7011. lynx::sytrus::Engine e;
  7012. e.setTempo (120.0);
  7013. e.prepare (fs, renderMode, 512);
  7014. e.setPatch (lynx::sytrus::parsePatch (blob));
  7015. std::vector<float> l ((std::size_t) n), r ((std::size_t) n);
  7016. for (int n0 = 0; n0 < n; n0 += 512)
  7017. {
  7018. for (std::size_t k = 0; k < notes.size(); ++k)
  7019. {
  7020. if (notes[k][1] >= n0 && notes[k][1] < n0 + 512)
  7021. {
  7022. lynx::sytrus::NoteParams p;
  7023. p.key = (float) notes[k][0];
  7024. p.id = (std::int64_t) k + 1;
  7025. e.noteOn (p);
  7026. }
  7027. if (notes[k][2] >= n0 && notes[k][2] < n0 + 512)
  7028. e.release ((std::int64_t) k + 1);
  7029. }
  7030. e.render (l.data() + n0, r.data() + n0, std::min (512, n - n0), 1.0f, 0.0f);
  7031. }
  7032. return { l, r };
  7033. }
  7034. } // namespace
  7035. TEST (sytrus_engine_sine)
  7036. {
  7037. // one sine operator, ratio 1, OUT 256, no envelopes: C5 = 523.2511 Hz at 0.7071 (centre of the pan law, §6.1)
  7038. SytrusTestPatch t;
  7039. t.cell (0, 0, 8, 256);
  7040. const auto blob = t.blob();
  7041. CHECK (lynx::sytrus::stateUsable (blob));
  7042. CHECK (lynx::sytrus::parsePatch (blob) != nullptr);
  7043. auto broken = blob;
  7044. broken.resize (broken.size() / 2);
  7045. CHECK (! lynx::sytrus::stateUsable (broken));
  7046. const auto [l, r] = sytrusRender (blob, false, 8192, { { 60, 0, 4096 } });
  7047. double worst = 0.0;
  7048. for (int k = 0; k < 4000; ++k)
  7049. 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)));
  7050. CHECK (worst < 2e-5);
  7051. CHECK (l == r);
  7052. // 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
  7053. // 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)
  7054. int last = 0;
  7055. for (int k = 0; k < 8192; ++k)
  7056. if (l[(std::size_t) k] != 0.0f)
  7057. last = k;
  7058. CHECK (last == 4895);
  7059. // key 69 = 880 Hz; 48 kHz
  7060. const auto [l2, r2] = sytrusRender (blob, false, 4096, { { 69, 0, -1 } }, 48000.0);
  7061. worst = 0.0;
  7062. for (int k = 0; k < 4000; ++k)
  7063. 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)));
  7064. CHECK (worst < 5e-5);
  7065. (void) r2;
  7066. }
  7067. TEST (sytrus_engine_reference)
  7068. {
  7069. // FM 2→1, Vanilla LP filter, volume envelope, unison 3, delay and reverb, 2× oversampling with the 8-sample
  7070. // envelope tick (render settings): against our Python reference model of REA_rodada31 (sytmodel.render)
  7071. SytrusTestPatch t;
  7072. t.main[195] = 0, t.main[196] = 1, t.main[193] = 0, t.main[194] = 1;
  7073. t.main[173] = 3, t.main[174] = 64, t.main[176] = 100;
  7074. t.ops[1].ratio = 40000;
  7075. t.cell (0, 0, 1, 128); // op 2 → op 1 FM
  7076. t.cell (0, 0, 8, 128);
  7077. t.cell (0, 6, 0, 256); // op 1 → filter 1
  7078. t.cell (0, 6, 8, 256);
  7079. t.cell (0, 0, 7, 200); // FX send
  7080. t.filts[0].p[0] = 1, t.filts[0].p[2] = 180, t.filts[0].p[3] = 60;
  7081. t.ops[0].env1[0] = 0, t.ops[0].env1[1] = 1, t.ops[0].env1[2] = 2;
  7082. t.ops[0].env1pts = { { 0.0, 0.0 }, { 0.05, 1.0 }, { 0.1, 0.6 }, { 0.2, 0.0 } };
  7083. const std::int32_t d0[5] { 40, 100, 50, 100, 0 };
  7084. std::memcpy (t.delays[0].data(), d0, 20);
  7085. t.delays[0][22] = 1;
  7086. t.reverb = { 19, 221, 10, 50, 80, 30, 100, 2, 100 };
  7087. t.reverbOn = true;
  7088. const auto blob = t.blob();
  7089. const auto [l, r] = sytrusRender (blob, true, 12000, { { 60, 0, 6000 } });
  7090. // reference values (model render_mode=True, 44.1 kHz, block 512, key 60, velocity 0.78125, release at 6000); the same
  7091. // state rendered by FL's own Sytrus DLL in render mode differs from this by −136 dB (EXEC, REA round 31 harness)
  7092. const std::array<std::pair<int, float>, 8> golden { { { 100, -0.00235529384f }, { 777, -0.175126165f }, { 2000, 0.30976975f }, { 4321, -0.0213534199f },
  7093. { 6100, 0.202372357f }, { 7000, 0.249530748f }, { 9000, 0.0307101421f }, { 11999, 0.176390275f } } };
  7094. for (const auto& [i, v] : golden)
  7095. CHECK (std::abs (l[(std::size_t) i] - v) < 1e-6f);
  7096. const std::array<std::pair<int, float>, 3> goldenR { { { 777, -0.166890964f }, { 4321, -0.212358952f }, { 9000, -0.0251909085f } } };
  7097. for (const auto& [i, v] : goldenR)
  7098. CHECK (std::abs (r[(std::size_t) i] - v) < 1e-6f);
  7099. }
  7100. TEST (sytrus_instrument)
  7101. {
  7102. // the LYNX instrument: state in ChannelDef::pluginState, channel volume/pan recovered from the rack gains
  7103. SytrusTestPatch t;
  7104. t.cell (0, 0, 8, 256);
  7105. lynx::ChannelDef c;
  7106. c.instrument = lynx::InstrumentKind::sytrus;
  7107. c.pluginState = t.blob();
  7108. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sytrus);
  7109. inst->prepare (44100.0);
  7110. inst->configure (c, 120.0);
  7111. CHECK (inst->idle());
  7112. std::vector<float> l (4096), r (4096);
  7113. inst->noteOn (60, 100.0f / 128.0f);
  7114. // 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
  7115. inst->render (l.data(), r.data(), 4096, 0.5f, 0.5f);
  7116. double peak = 0.0;
  7117. for (int k = 1000; k < 4096; ++k)
  7118. peak = std::max (peak, (double) std::abs (l[(std::size_t) k]));
  7119. CHECK (std::abs (peak - 0.5 * 0.70710678) < 1e-3); // Final.Vol 0.5 × the plugin's centre pan law
  7120. CHECK (! inst->idle());
  7121. inst->noteOff (60);
  7122. std::vector<float> tail (44100 * 3), tailR (tail.size());
  7123. inst->render (tail.data(), tailR.data(), (int) tail.size(), 0.5f, 0.5f);
  7124. CHECK (inst->idle());
  7125. CHECK (tail.back() == 0.0f);
  7126. }
  7127. TEST (harmor_effects_rack)
  7128. {
  7129. // REA_rodada38: the rack runs in the state's unit order and the records' FX send joins it at unit 4 — with the FX
  7130. // amount at 1000 every record output bypasses a reverb placed before unit 4 (EXEC: −600 dB vs the rack off)
  7131. auto blob = harmorTestState (false);
  7132. auto set = [&] (std::vector<std::uint8_t>& st, int part, int index, std::int32_t v) {
  7133. std::memcpy (st.data() + lynx::harmorParamOffset (st, part, index), &v, 4);
  7134. };
  7135. set (blob, 0, 10, 1000); // all to the FX send
  7136. auto render = [] (const std::vector<std::uint8_t>& st) {
  7137. return lynx::harmor::renderReference (st, { { 0, 60, 0.8, 1.0, 0.0, 6000 } }, 44100.0, 12000);
  7138. };
  7139. const auto dry = render (blob);
  7140. auto rev = blob;
  7141. set (rev, -1, 22, 1); // reverb on: room 50, diffusion 100, decay 2^3·0.1 s, high cut / damping off, wet 0.8
  7142. 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);
  7143. set (rev, -1, 30, 2), set (rev, -1, 31, 800);
  7144. const auto bypassed = render (rev);
  7145. double eb = 0.0, db = 0.0;
  7146. for (std::size_t i = 0; i < dry.size(); ++i)
  7147. eb += (double) (bypassed[i] - dry[i]) * (bypassed[i] - dry[i]), db += (double) dry[i] * dry[i];
  7148. CHECK (eb < 1e-12 * db && db > 1e-3); // (float rounding of the rack's buffers only)
  7149. auto after = rev;
  7150. const std::int32_t order[6] { 0, 1, 2, 4, 3, 5 }; // the join before the reverb
  7151. for (int k = 0; k < 6; ++k)
  7152. set (after, -1, 53 + k, order[k]);
  7153. const auto wet = render (after);
  7154. double e = 0.0, d = 0.0;
  7155. bool finite = true;
  7156. for (std::size_t i = 0; i < wet.size(); ++i)
  7157. e += (double) (wet[i] - dry[i]) * (wet[i] - dry[i]), d += (double) dry[i] * dry[i], finite = finite && std::isfinite (wet[i]);
  7158. CHECK (finite && e > 1e-4 * d && d > 1e-3);
  7159. // a distortion (type 6) and a delay on the dry path change the sound, stay finite, and the instrument ends quiet
  7160. auto dist = harmorTestState (false);
  7161. {
  7162. const auto at = lynx::harmorParamOffset (dist, -1, 0) + 0xd4 + 0x18 + 48; // global misc +48: distortion type
  7163. const std::int32_t six = 6;
  7164. std::memcpy (dist.data() + at, &six, 4);
  7165. }
  7166. set (dist, -1, 17, 600), set (dist, -1, 19, 1000), set (dist, -1, 21, 1100);
  7167. 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);
  7168. set (dist, -1, 47, 1050);
  7169. lynx::ChannelDef c;
  7170. c.instrument = lynx::InstrumentKind::harmor;
  7171. c.pluginState = dist;
  7172. auto inst = lynx::makeInstrument (lynx::InstrumentKind::harmor);
  7173. inst->configure (c, 120.0);
  7174. inst->prepare (44100.0);
  7175. std::vector<float> l (44100 * 4), r (l.size());
  7176. inst->noteOn (60, 0.8f);
  7177. double energy = 0.0;
  7178. for (int s = 0; s < (int) l.size(); s += 512)
  7179. {
  7180. if (s == 8192)
  7181. inst->noteOff (60);
  7182. inst->render (l.data() + s, r.data() + s, 512, 1.0f, 1.0f);
  7183. }
  7184. for (std::size_t i = 0; i < l.size(); ++i)
  7185. finite = finite && std::isfinite (l[i]) && std::isfinite (r[i]), energy += (double) l[i] * l[i];
  7186. CHECK (finite && energy > 1.0);
  7187. std::vector<float> tail (44100 * 6), tailR (tail.size());
  7188. for (int s = 0; s < (int) tail.size(); s += 512)
  7189. inst->render (tail.data() + s, tailR.data() + s, 512, 1.0f, 1.0f);
  7190. CHECK (inst->idle());
  7191. }
  7192. TEST (harmless_engine)
  7193. {
  7194. // REA_rodada32: state parsing, the additive engine against our reference model (hlmodel.py), host levels, voice end
  7195. std::vector<std::uint8_t> blob;
  7196. 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))); };
  7197. std::array<std::int32_t, 100> p {}; // the reference's clean patch: Saw, open filter, no modulation
  7198. for (int i = 11; i < 23; ++i)
  7199. p[(std::size_t) i] = 1000;
  7200. 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;
  7201. 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;
  7202. // + resonance, pluck, 3-voice unison, tremolo, LFO on pitch
  7203. 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;
  7204. put (12);
  7205. for (auto v : p)
  7206. put (v);
  7207. for (int i = 0; i < 7; ++i)
  7208. put (0);
  7209. put (524); // Custom colour table: 524 × (amplitude, phase)
  7210. for (int i = 0; i < 1048; ++i)
  7211. {
  7212. const auto f = i < 524 ? 1.0f / (float) (i + 1) : 0.25f;
  7213. std::uint32_t bits = 0;
  7214. std::memcpy (&bits, &f, 4);
  7215. put ((std::int32_t) bits);
  7216. }
  7217. const auto parsed = lynx::harmlessParams (blob);
  7218. CHECK (parsed && (int) parsed->size() == lynx::harmlessParamCount);
  7219. CHECK (parsed && (*parsed)[54] == 3500.0f && (*parsed)[99] == 0.0f && (*parsed)[lynx::harmlessCustomFlagIndex] == 1.0f);
  7220. CHECK (parsed && (*parsed)[lynx::harmlessCustomIndex + 1] == 0.5f && (*parsed)[lynx::harmlessCustomIndex + 524] == 0.25f);
  7221. auto old = blob;
  7222. old[0] = 3; // versions below 4 are not Harmless states we know
  7223. CHECK (! lynx::harmlessParams (old));
  7224. old = blob;
  7225. old.resize (300);
  7226. CHECK (! lynx::harmlessParams (old));
  7227. lynx::ChannelDef c;
  7228. c.instrument = lynx::InstrumentKind::harmless;
  7229. c.modelParams = *parsed;
  7230. c.modelParams[lynx::harmlessCustomFlagIndex] = 0.0f; // colour 0 (Saw): the custom table is not read
  7231. auto render = [] (const lynx::ChannelDef& def, int total, float gl, float gr, int offAt) {
  7232. auto inst = lynx::makeInstrument (lynx::InstrumentKind::harmless);
  7233. inst->configure (def, 120.0);
  7234. inst->prepare (44100.0);
  7235. std::vector<float> l ((std::size_t) total), r ((std::size_t) total);
  7236. inst->noteOn (60, 0.78125f);
  7237. for (int s = 0; s < total; s += 512)
  7238. {
  7239. if (s == offAt)
  7240. inst->noteOff (60);
  7241. inst->render (l.data() + s, r.data() + s, std::min (512, total - s), gl, gr);
  7242. }
  7243. return std::make_tuple (l, r, std::move (inst));
  7244. };
  7245. {
  7246. // reference model (REA round 32 hlmodel.py, C5 at FL velocity 100, channel volume 1, centre, released at 6144)
  7247. auto [l, r, inst] = render (c, 8192, 1.0f, 1.0f, 6144);
  7248. const std::tuple<int, float, float> golden[] {
  7249. { 0, 0.0f, 0.0f }, { 10, -0.02220994f, -0.06232700f }, { 100, 0.40623373f, 0.17308202f }, { 1000, -0.04091963f, -0.26821208f },
  7250. { 3000, 0.14519004f, 0.11027778f }, { 6000, 0.50411958f, 0.27901855f }, { 8191, 0.02117692f, -0.01466602f } };
  7251. for (const auto& [i, gl, gr] : golden)
  7252. CHECK (std::abs (l[(std::size_t) i] - gl) < 2e-6f && std::abs (r[(std::size_t) i] - gr) < 2e-6f);
  7253. // after the release the record fades out (below 1e-4, then 30 ms) and the instrument goes idle
  7254. std::vector<float> tail (44100), tailR (tail.size());
  7255. inst->render (tail.data(), tailR.data(), (int) tail.size(), 1.0f, 1.0f);
  7256. CHECK (inst->idle());
  7257. }
  7258. // FL's level law applied once: half the channel volume halves the output; full right pan silences the left side
  7259. const auto full = std::get<0> (render (c, 2048, 1.0f, 1.0f, -1));
  7260. const auto half = std::get<0> (render (c, 2048, 0.5f, 0.5f, -1));
  7261. CHECK (std::abs (half[100] - 0.5f * full[100]) < 1e-6f && std::abs (full[100]) > 0.1f);
  7262. auto mono = c;
  7263. mono.modelParams[25] = 0.0f; // no tremolo, no unison pan spread
  7264. mono.modelParams[65] = 1.0f;
  7265. const auto [pl, pr, pi] = render (mono, 2048, 0.0f, 1.41421356f, -1);
  7266. double el = 0.0, er = 0.0;
  7267. for (int i = 0; i < 2048; ++i)
  7268. el += (double) pl[(std::size_t) i] * pl[(std::size_t) i], er += (double) pr[(std::size_t) i] * pr[(std::size_t) i];
  7269. CHECK (el < 1e-10 * er && er > 1.0);
  7270. }
  7271. TEST (startup_sound)
  7272. {
  7273. // the splash's sound: the right length, finite, at its peak level, quiet before the whoosh swells,
  7274. // a landing "pop" at impactTime and a chime ringing after it
  7275. using namespace lynx::startup;
  7276. const auto sound = makeSound (48000.0);
  7277. CHECK (sound.left.size() == (std::size_t) (soundLength * 48000.0) && sound.right.size() == sound.left.size());
  7278. float peak = 0.0f;
  7279. bool finite = true;
  7280. for (std::size_t i = 0; i < sound.left.size(); ++i)
  7281. {
  7282. finite = finite && std::isfinite (sound.left[i]) && std::isfinite (sound.right[i]);
  7283. peak = std::max ({ peak, std::abs (sound.left[i]), std::abs (sound.right[i]) });
  7284. }
  7285. CHECK (finite && std::abs (peak - peakLevel) < 1.0e-4f);
  7286. auto rms = [&sound] (double from, double to) {
  7287. double e = 0.0;
  7288. const auto a = (std::size_t) (from * 48000.0), b = (std::size_t) (to * 48000.0);
  7289. for (auto i = a; i < b; ++i)
  7290. e += (double) sound.left[i] * sound.left[i];
  7291. return std::sqrt (e / (double) (b - a));
  7292. };
  7293. CHECK (rms (0.0, 0.05) < 0.2 * rms (impactTime - 0.05, impactTime)); // the whoosh swells
  7294. CHECK (rms (impactTime, impactTime + 0.05) > rms (impactTime - 0.05, impactTime)); // the landing
  7295. CHECK (rms (0.8, 1.0) > 0.005 && rms (soundLength - 0.02, soundLength) < rms (0.8, 1.0)); // chime rings, tail fades
  7296. CHECK (makeSound (48000.0).left == sound.left); // the same sound on every start
  7297. }
  7298. namespace
  7299. {
  7300. // little-endian byte writer for the state builders below
  7301. struct Bytes
  7302. {
  7303. std::vector<std::uint8_t> b;
  7304. void raw (const char* s, std::size_t n) { b.insert (b.end(), s, s + n); }
  7305. void i32 (std::int32_t v) { b.insert (b.end(), reinterpret_cast<const std::uint8_t*> (&v), reinterpret_cast<const std::uint8_t*> (&v) + 4); }
  7306. void f32 (float v) { b.insert (b.end(), reinterpret_cast<const std::uint8_t*> (&v), reinterpret_cast<const std::uint8_t*> (&v) + 4); }
  7307. void zeros (std::size_t n) { b.insert (b.end(), n, 0); }
  7308. void bytes (const std::vector<std::uint8_t>& o) { b.insert (b.end(), o.begin(), o.end()); }
  7309. };
  7310. // A GMS state written from scratch (REA_rodada12 §1.1 layout, "Syn4"): oscillator waves that don't exist (silent
  7311. // tables, so the result does not depend on an FL installation), noise through the ladder with envelope and LFO,
  7312. // unison, slide, distortion, delay, reverb and the output EQ.
  7313. std::vector<std::uint8_t> gmsTestState()
  7314. {
  7315. std::array<float, 212> P {};
  7316. for (int i : { 1, 2, 44, 55, 56, 57, 58, 59, 60, 207, 208, 209, 210, 211 })
  7317. P[(std::size_t) i] = 0.5f;
  7318. P[0] = 0.75f, P[4] = 0.1f, P[5] = 0.4f, P[6] = 0.6f, P[7] = 0.3f, P[8] = 0.8f;
  7319. P[10] = 0.2f, P[11] = 1.0f, P[12] = 0.45f, P[13] = 0.55f, P[16] = 0.6f, P[20] = 0.2f, P[22] = 0.5f;
  7320. P[28] = 0.5f, P[34] = 0.4f, P[41] = 0.2f, P[42] = 0.6f, P[43] = 0.5f, P[45] = 0.8f, P[199] = 1.0f, P[198] = 0.8f, P[200] = 1.0f;
  7321. P[147] = 1.0f, P[117] = 0.3f, P[127] = 0.6f; // distortion
  7322. P[153] = 1.0f, P[123] = 0.5f, P[133] = 0.4f, P[143] = 0.4f; // delay (1/2 beat)
  7323. P[154] = 1.0f, P[124] = 0.6f, P[134] = 0.5f; // reverb
  7324. P[206] = 1.0f, P[207] = 0.7f, P[211] = 0.3f; // output EQ
  7325. Bytes preset;
  7326. preset.raw ("4nyS", 4);
  7327. for (const char* path : { "NoSuchDir\\NoWave A.wav", "NoSuchDir\\NoWave B.wav", "NoSuchDir\\NoWave C.wav", "", "", "", "" })
  7328. {
  7329. const auto n = std::strlen (path);
  7330. preset.raw (path, n);
  7331. preset.zeros (512 - n);
  7332. }
  7333. preset.i32 (0), preset.i32 (0), preset.i32 (0);
  7334. for (auto v : P)
  7335. preset.f32 (v);
  7336. preset.raw ("LYNX test", 9);
  7337. preset.zeros (512 - 9);
  7338. Bytes s;
  7339. s.raw ("SSLF", 4);
  7340. s.i32 ((std::int32_t) preset.b.size());
  7341. s.bytes (preset.b);
  7342. return s.b;
  7343. }
  7344. // A Morphine state written from scratch (REA_rodada16 §3 / REA_rodada39 §2.2 layout): generators A and B with a few
  7345. // frames each (A loops, PWM on A), C and D silent, a morph line A→B, four envelopes (Eg1 → pitch and velocity →
  7346. // amplitude through the matrix), the master ADSR and every plugin effect on.
  7347. std::vector<std::uint8_t> morphineTestState()
  7348. {
  7349. auto mbp = [] (int seed) {
  7350. Bytes b;
  7351. b.raw ("0PBM", 4);
  7352. for (int a = 0; a < 3; ++a)
  7353. for (int byte = 0; byte < 16; ++byte)
  7354. {
  7355. b.b.push_back (0xff);
  7356. for (int bit = 0; bit < 8; ++bit)
  7357. {
  7358. const auto k = byte * 8 + bit;
  7359. const float v = a == 0 ? std::cbrt (1.0f / (float) (k + 1 + seed * (k % 3))) * (k < 40 ? 1.0f : 0.2f)
  7360. : a == 1 ? 0.1f * (float) ((k * 7 + seed) % 11 - 5) / 5.0f
  7361. : 0.02f * (float) ((k * 5 + seed) % 7 - 3);
  7362. b.f32 (v);
  7363. }
  7364. }
  7365. return b.b;
  7366. };
  7367. auto msp = [&] (int frames, int seed, int loopMode) {
  7368. Bytes b;
  7369. b.raw ("0PSM", 4);
  7370. b.i32 (frames);
  7371. for (int f = 0; f < frames; ++f)
  7372. {
  7373. const auto m = mbp (seed + f);
  7374. b.i32 (20 + 7 * f), b.f32 (1.0f - 0.2f * (float) f), b.i32 ((std::int32_t) m.size());
  7375. b.bytes (m);
  7376. }
  7377. b.i32 (0x424);
  7378. b.i32 (10), b.i32 (40), b.i32 (0), b.i32 (loopMode);
  7379. b.f32 (0.45f), b.f32 (0.6f), b.f32 (0.5f), b.i32 (0);
  7380. for (int k = 0; k < 128; ++k)
  7381. b.f32 (0.3f);
  7382. for (int k = 0; k < 128; ++k)
  7383. b.f32 (1.0f);
  7384. return b.b;
  7385. };
  7386. auto mvc = [&] (int frames, int seed, int pwmMode) {
  7387. Bytes z;
  7388. z.raw ("0HZM", 4);
  7389. z.i32 (1);
  7390. const auto s = msp (frames, seed, 1);
  7391. z.i32 (128), z.f32 (frames > 1 ? 0.9f : 0.0f), z.i32 ((std::int32_t) s.size());
  7392. z.bytes (s);
  7393. Bytes b;
  7394. b.raw ("0CVM", 4);
  7395. b.i32 ((std::int32_t) z.b.size());
  7396. b.bytes (z.b);
  7397. b.i32 (28), b.f32 (0.4f), b.i32 (pwmMode), b.f32 (0.3f), b.i32 (0), b.f32 (0.5f), b.f32 (0.6f);
  7398. return b.b;
  7399. };
  7400. Bytes p;
  7401. p.raw ("0roM", 4);
  7402. p.raw ("0RPM", 4);
  7403. for (const auto& g : { mvc (3, 1, 2), mvc (2, 7, 0), mvc (1, 3, 0), mvc (1, 5, 0) })
  7404. {
  7405. p.i32 ((std::int32_t) g.size());
  7406. p.bytes (g);
  7407. }
  7408. {
  7409. Bytes m;
  7410. m.raw ("0LMM", 4);
  7411. m.i32 (2), m.i32 (12);
  7412. m.f32 (0.0f), m.f32 (1.0f), m.i32 (60);
  7413. m.f32 (1.0f), m.f32 (1.0f), m.i32 (60);
  7414. m.i32 (0x54), m.i32 (0), m.i32 (0), m.i32 (0), m.i32 (0);
  7415. for (float v : { 1.0f, 0.8f, 0.0f, 0.0f, 0.5f, 0.4f, 0.5f, 0.5f })
  7416. m.f32 (v);
  7417. for (int k = 0; k < 4; ++k)
  7418. m.i32 (0);
  7419. m.f32 (0.5f), m.f32 (0.5f), m.f32 (0.5f), m.i32 (0);
  7420. p.i32 ((std::int32_t) m.b.size());
  7421. p.bytes (m.b);
  7422. }
  7423. {
  7424. Bytes d;
  7425. d.raw ("0DMM", 4);
  7426. d.i32 (4);
  7427. for (int e = 0; e < 4; ++e)
  7428. {
  7429. Bytes g;
  7430. g.raw ("0GEM", 4);
  7431. g.i32 (3), g.i32 (8);
  7432. g.f32 (0.0f), g.i32 (10), g.f32 (1.0f), g.i32 (40 + 10 * e), g.f32 (0.3f), g.i32 (50);
  7433. g.i32 (0x2c), g.i32 (0), g.i32 (0), g.i32 (0), g.f32 (0.5f), g.i32 (0), g.f32 (0.45f), g.i32 (0), g.f32 (0.5f), g.f32 (0.6f),
  7434. g.i32 (e == 0 ? 1 : 0);
  7435. d.i32 ((std::int32_t) g.b.size());
  7436. d.bytes (g.b);
  7437. }
  7438. d.i32 (0x94);
  7439. const int src[12] = { 5, 2 }, dst[12] = { 3, 1 };
  7440. const float amt[12] = { 0.56f, 0.7f };
  7441. for (int k = 0; k < 12; ++k)
  7442. d.i32 (src[k]);
  7443. for (int k = 0; k < 12; ++k)
  7444. d.i32 (dst[k]);
  7445. for (int k = 0; k < 12; ++k)
  7446. d.f32 (amt[k]);
  7447. p.i32 ((std::int32_t) d.b.size());
  7448. p.bytes (d.b);
  7449. }
  7450. {
  7451. const float A[40] = { 0.5f, 0.0f, 0.0f, -1.0f, 0.2f, 0.5f, 0.55f, 0.1f, 0.17f, 0.2f, // master … velocity curve, ADSR A
  7452. 0.5f, 0.7f, 0.4f, 0.5f, 0.5f, 0.3f, 1.0f, 0.4f, 0.6f, 0.3f, // D S R, chorus, delay …
  7453. 0.4f, 0.3f, 1.0f, 0.5f, 0.5f, 0.4f, 1.0f, 0.6f, 0.4f, 0.5f, // … delay, reverb, EQ …
  7454. 0.5f, 0.5f, 0.55f, 0.5f, 0.45f, 1.0f, 0.0f, 0.5f, 1.0f, 0.0f }; // EQ on, noise (muted)
  7455. Bytes g;
  7456. g.i32 (0x5c4);
  7457. for (auto v : A)
  7458. g.f32 (v);
  7459. g.zeros (0x5c4 - g.b.size());
  7460. p.bytes (g.b);
  7461. }
  7462. Bytes s;
  7463. s.raw ("SSLF", 4);
  7464. s.i32 ((std::int32_t) p.b.size());
  7465. s.bytes (p.b);
  7466. return s.b;
  7467. }
  7468. void dumpIfAsked (const char* var, const std::vector<std::uint8_t>& blob)
  7469. {
  7470. if (const char* path = std::getenv (var))
  7471. {
  7472. std::ofstream out (path, std::ios::binary);
  7473. out.write (reinterpret_cast<const char*> (blob.data()), (std::streamsize) blob.size());
  7474. }
  7475. }
  7476. } // namespace
  7477. TEST (gms_engine)
  7478. {
  7479. const auto blob = gmsTestState();
  7480. dumpIfAsked ("LYNX_DUMP_GMS", blob);
  7481. CHECK (lynx::gmsStateUsable (blob));
  7482. CHECK (lynx::gmsWaveNames (blob) == std::vector<std::string> ({ "NoWave A", "NoWave B", "NoWave C" }));
  7483. CHECK (lynx::gmsParamOffset (blob, 12) == 8 + 4 + 7 * 512 + 12 + 4 * 12 && lynx::gmsParamOffset (blob, 212) < 0);
  7484. auto broken = blob;
  7485. broken[8] = 'X';
  7486. CHECK (! lynx::gmsStateUsable (broken));
  7487. CHECK (! lynx::gmsStateUsable (std::vector<std::uint8_t> (blob.begin(), blob.begin() + 2000)));
  7488. // golden samples of our round-39 model (gmsmodel.GmsPlugin, waves missing → silent tables, tempo 140, 44.1 kHz,
  7489. // host blocks of 512): C5 vel 100 0–30000, E5 vel 80 11025–40000, G5 vel 110 22050–52000 (Init.Vol law A)
  7490. auto iv = [] (double vel) { return (std::pow (11.0, vel / 100.0) - 1.0) / 10.0; };
  7491. const std::vector<lynx::gms::RefNote> notes = { { 0, 60, (float) iv (100), 1.0, 0.0, 0.0, 30000 },
  7492. { 11025, 64, (float) iv (80), 1.0, 0.0, 0.0, 40000 },
  7493. { 22050, 67, (float) iv (110), 1.0, 0.0, 0.0, 52000 } };
  7494. const auto y = lynx::gms::renderReference (blob, notes, 44100.0, 66150, "");
  7495. CHECK (y.size() == 2 * 66150u);
  7496. static const struct { int i; float l, r; } golden[] = { { 100, 0.0298744496f, 0.0198248848f }, { 5000, 0.0669416264f, 0.0666475743f }, { 15000, -0.005992427f, 0.013085857f }, { 25000, 0.0102018276f, 0.0130400788f }, { 35000, -0.0679694712f, -0.0050432696f }, { 45000, -0.0161557719f, 0.154340729f }, { 55000, -0.00719845621f, 0.0182181317f }, { 66000, 0.0389953516f, 0.0104107196f } };
  7497. for (const auto& g : golden)
  7498. CHECK (std::abs (y[2 * (std::size_t) g.i] - g.l) < 1e-6f && std::abs (y[2 * (std::size_t) g.i + 1] - g.r) < 1e-6f);
  7499. double e = 0.0;
  7500. for (auto v : y)
  7501. e += (double) v * v;
  7502. CHECK (std::abs (std::sqrt (e / (double) y.size()) - 0.0790270452795) < 1e-6);
  7503. // the instrument: same engine behind LYNX's channel gains (V = 1, centre → law A), velocity → Init.Vol
  7504. lynx::ChannelDef c;
  7505. c.instrument = lynx::InstrumentKind::gms;
  7506. c.pluginState = blob;
  7507. auto inst = lynx::makeInstrument (lynx::InstrumentKind::gms);
  7508. inst->configure (c, 140.0);
  7509. inst->prepare (44100.0);
  7510. std::vector<float> l (8192, 0.0f), r (8192, 0.0f);
  7511. for (int b = 0; b < 16; ++b)
  7512. {
  7513. if (b == 0)
  7514. inst->noteOn (60, 0.78125f);
  7515. if (b == 10)
  7516. inst->noteOff (60);
  7517. inst->render (l.data() + 512 * b, r.data() + 512 * b, 512, 1.0f, 1.0f);
  7518. }
  7519. const auto ref = lynx::gms::renderReference (blob, { { 0, 60, (std::pow (11.0, 1.28 * 0.78125) - 1.0) / 10.0, 1.0, 0.0, 0.0, 5120 } }, 44100.0, 8192, "");
  7520. double diff = 0.0, energy = 0.0;
  7521. for (int i = 0; i < 8192; ++i)
  7522. {
  7523. diff = std::max ({ diff, (double) std::abs (l[(std::size_t) i] - ref[2 * (std::size_t) i]), (double) std::abs (r[(std::size_t) i] - ref[2 * (std::size_t) i + 1]) });
  7524. energy += (double) l[(std::size_t) i] * l[(std::size_t) i];
  7525. }
  7526. CHECK (diff == 0.0 && energy > 1e-3);
  7527. }
  7528. TEST (morphine_engine)
  7529. {
  7530. const auto blob = morphineTestState();
  7531. dumpIfAsked ("LYNX_DUMP_MORPHINE", blob);
  7532. CHECK (lynx::morphineStateUsable (blob));
  7533. CHECK (lynx::morphineNoiseName (blob).empty());
  7534. const auto at = lynx::morphineParamOffset (blob, 9);
  7535. CHECK (at > 0);
  7536. float a9 = 0.0f;
  7537. std::memcpy (&a9, blob.data() + at, 4);
  7538. CHECK (a9 == 0.2f && lynx::morphineParamOffset (blob, 40) < 0);
  7539. auto broken = blob;
  7540. broken[12] = 'X'; // the MPR0 tag
  7541. CHECK (! lynx::morphineStateUsable (broken));
  7542. CHECK (! lynx::morphineStateUsable (std::vector<std::uint8_t> (blob.begin(), blob.end() - 10)));
  7543. // golden samples of our round-39 model (mormodel.Synth, tempo 120, 44.1 kHz, host blocks of 512): keys 60/64/67,
  7544. // Init.Vol 1.0/0.5/2.0, note-offs at 30000/50000/70000
  7545. const std::vector<lynx::morphine::RefNote> notes = { { 0, 60, 1.0, 1.0, 0.0, 0.0, 30000 },
  7546. { 11025, 64, 0.5, 1.0, 0.0, 0.0, 50000 },
  7547. { 22050, 67, 2.0, 1.0, 0.0, 0.0, 70000 } };
  7548. const auto y = lynx::morphine::renderReference (blob, notes, 44100.0, 80000, "");
  7549. CHECK (y.size() == 2 * 80000u);
  7550. static const struct { int i; float l, r; } golden[] = { { 100, 0.00094500737f, 0.00085531926f }, { 5000, 0.0311509669f, -0.11552836f }, { 15000, 0.0843918771f, 0.0369227529f }, { 25000, 0.60864079f, 1.03062224f }, { 35000, -0.346013308f, 0.135865599f }, { 45000, -0.0373920798f, -0.13064307f }, { 60000, -0.138871655f, -0.163586512f }, { 75000, 0.0251323506f, -0.00735046482f } };
  7551. for (const auto& g : golden)
  7552. CHECK (std::abs (y[2 * (std::size_t) g.i] - g.l) < 1e-6f && std::abs (y[2 * (std::size_t) g.i + 1] - g.r) < 1e-6f);
  7553. double e = 0.0;
  7554. for (auto v : y)
  7555. e += (double) v * v;
  7556. CHECK (std::abs (std::sqrt (e / (double) y.size()) - 0.18467099041) < 1e-6);
  7557. // the instrument: same engine behind LYNX's channel gains
  7558. lynx::ChannelDef c;
  7559. c.instrument = lynx::InstrumentKind::morphine;
  7560. c.pluginState = blob;
  7561. auto inst = lynx::makeInstrument (lynx::InstrumentKind::morphine);
  7562. inst->configure (c, 120.0);
  7563. inst->prepare (44100.0);
  7564. std::vector<float> l (8192, 0.0f), r (8192, 0.0f);
  7565. for (int b = 0; b < 16; ++b)
  7566. {
  7567. if (b == 0)
  7568. inst->noteOn (60, 0.78125f);
  7569. if (b == 10)
  7570. inst->noteOff (60);
  7571. inst->render (l.data() + 512 * b, r.data() + 512 * b, 512, 1.0f, 1.0f);
  7572. }
  7573. const auto ref = lynx::morphine::renderReference (blob, { { 0, 60, (std::pow (11.0, 1.28 * 0.78125) - 1.0) / 10.0, 1.0, 0.0, 0.0, 5120 } }, 44100.0, 8192, "");
  7574. double diff = 0.0, energy = 0.0;
  7575. for (int i = 0; i < 8192; ++i)
  7576. {
  7577. diff = std::max ({ diff, (double) std::abs (l[(std::size_t) i] - ref[2 * (std::size_t) i]), (double) std::abs (r[(std::size_t) i] - ref[2 * (std::size_t) i + 1]) });
  7578. energy += (double) l[(std::size_t) i] * l[(std::size_t) i];
  7579. }
  7580. CHECK (diff == 0.0 && energy > 1e-3);
  7581. }
  7582. // Workflow P2 (docs/WORKFLOW_FL.md)
  7583. #include "WorkflowP2Tests.inc"