tests.cpp 247 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781
  1. // Core tests (no JUCE). Usage: lynx_tests [folder-with-flp-files]
  2. #include <atomic>
  3. #include <cmath>
  4. #include <cstdio>
  5. #include <cstring>
  6. #include <filesystem>
  7. #include <fstream>
  8. #include <functional>
  9. #include <iterator>
  10. #include <string>
  11. #include <tuple>
  12. #include <vector>
  13. #include "core/Dither.h"
  14. #include "core/DrumSynthLive.h"
  15. #include "core/Effects.h"
  16. #include "core/Effector.h"
  17. #include "core/FlpImport.h"
  18. #include "core/FlEffects.h"
  19. #include "core/FlPatcher.h"
  20. #include "core/FlSamplers.h"
  21. #include "core/FlSynths.h"
  22. #include "core/Inflate.h"
  23. #include "core/WavPack.h"
  24. #include "core/FlWrapper.h"
  25. #include "core/Harmless.h"
  26. #include "core/LiveEventQueue.h"
  27. #include "core/RackRenderer.h"
  28. #include "core/Scheduler.h"
  29. #include "core/SnapshotExchange.h"
  30. #include "core/SoftClip.h"
  31. #include "core/Slicer.h"
  32. #include "core/Templates.h"
  33. #include "core/Vocodex.h"
  34. #include "core/TimeStretch.h"
  35. #include "core/WorkerPool.h"
  36. #include "core/Song.h"
  37. #include "core/NoteEdit.h"
  38. #include "core/Recorder.h"
  39. #include "flp/Flp.h"
  40. namespace
  41. {
  42. int failures = 0;
  43. int checks = 0;
  44. std::vector<std::pair<const char*, std::function<void()>>>& registry()
  45. {
  46. static std::vector<std::pair<const char*, std::function<void()>>> r;
  47. return r;
  48. }
  49. struct Register
  50. {
  51. Register (const char* name, std::function<void()> fn) { registry().emplace_back (name, std::move (fn)); }
  52. };
  53. #define TEST(name) \
  54. static void name(); \
  55. static Register reg_##name (#name, name); \
  56. static void name()
  57. #define CHECK(cond) \
  58. do \
  59. { \
  60. ++checks; \
  61. if (! (cond)) \
  62. { \
  63. ++failures; \
  64. std::printf (" FAILED %s:%d: %s\n", __FILE__, __LINE__, #cond); \
  65. } \
  66. } while (false)
  67. std::string realFlpDir;
  68. // --- helpers for building synthetic .flp files -----------------------------
  69. struct FlpBuilder
  70. {
  71. std::vector<std::uint8_t> bytes;
  72. FlpBuilder (std::uint16_t ppq = 96)
  73. {
  74. put ("FLhd");
  75. u32 (6);
  76. u16 (0);
  77. u16 (1);
  78. u16 (ppq);
  79. put ("FLdt");
  80. u32 (0); // size is not used by the reader
  81. }
  82. void put (const char* s) { bytes.insert (bytes.end(), s, s + std::strlen (s)); }
  83. void u8 (std::uint8_t v) { bytes.push_back (v); }
  84. void u16 (std::uint16_t v) { u8 ((std::uint8_t) v); u8 ((std::uint8_t) (v >> 8)); }
  85. void u32 (std::uint32_t v) { u16 ((std::uint16_t) v); u16 ((std::uint16_t) (v >> 16)); }
  86. void varint (std::size_t n)
  87. {
  88. do
  89. {
  90. auto b = (std::uint8_t) (n & 0x7F);
  91. n >>= 7;
  92. u8 (n ? (std::uint8_t) (b | 0x80) : b);
  93. } while (n);
  94. }
  95. void data (std::uint8_t id, const std::vector<std::uint8_t>& payload)
  96. {
  97. u8 (id);
  98. varint (payload.size());
  99. bytes.insert (bytes.end(), payload.begin(), payload.end());
  100. }
  101. void ascii (std::uint8_t id, const std::string& s)
  102. {
  103. std::vector<std::uint8_t> p (s.begin(), s.end());
  104. p.push_back (0);
  105. data (id, p);
  106. }
  107. void utf16 (std::uint8_t id, const std::u16string& s)
  108. {
  109. std::vector<std::uint8_t> p;
  110. for (auto c : s)
  111. {
  112. p.push_back ((std::uint8_t) c);
  113. p.push_back ((std::uint8_t) (c >> 8));
  114. }
  115. p.push_back (0);
  116. p.push_back (0);
  117. data (id, p);
  118. }
  119. };
  120. std::vector<std::uint8_t> noteRecord (std::uint32_t pos, std::uint16_t channel, std::uint32_t len, std::uint16_t key,
  121. std::uint8_t velocity)
  122. {
  123. std::vector<std::uint8_t> r (24, 0);
  124. std::memcpy (&r[0], &pos, 4);
  125. std::memcpy (&r[6], &channel, 2);
  126. std::memcpy (&r[8], &len, 4);
  127. std::memcpy (&r[12], &key, 2);
  128. r[16] = 120;
  129. r[20] = 64;
  130. r[21] = velocity;
  131. return r;
  132. }
  133. } // namespace
  134. // ---------------------------------------------------------------------------
  135. // FLP
  136. TEST (flp_rejects_garbage)
  137. {
  138. std::vector<std::uint8_t> junk (64, 0x41);
  139. bool threw = false;
  140. try { flp::EventReader r (junk); } catch (const flp::Error&) { threw = true; }
  141. CHECK (threw);
  142. }
  143. TEST (flp_reads_size_classes_varint_and_extended_ids)
  144. {
  145. FlpBuilder b;
  146. b.u8 (0x15); b.u8 (2); // u8
  147. b.u8 (0x40); b.u16 (513); // u16
  148. b.u8 (0x9C); b.u32 (128500); // u32
  149. b.data (0xD5, std::vector<std::uint8_t> (300, 7)); // 2-byte varint
  150. b.u8 (0xAC); b.u32 (0xC0000100); b.varint (3); b.u8 (1); b.u8 (2); b.u8 (3); // extended ID
  151. flp::EventReader r (b.bytes);
  152. flp::Event e;
  153. CHECK (r.header().ppq == 96);
  154. CHECK (r.next (e) && e.id == 0x15 && e.value == 2);
  155. CHECK (r.next (e) && e.id == 0x40 && e.value == 513);
  156. CHECK (r.next (e) && e.id == 0x9C && e.value == 128500);
  157. CHECK (r.next (e) && e.id == 0xD5 && e.data.size() == 300 && e.data[299] == 7);
  158. CHECK (r.next (e) && e.id == 0xC0000100 && e.isData() && e.data.size() == 3 && e.data[2] == 3);
  159. CHECK (! r.next (e));
  160. }
  161. TEST (flp_truncated_file_throws)
  162. {
  163. FlpBuilder b;
  164. b.u8 (0x9C); b.u8 (1); // u32 with only 1 byte
  165. flp::EventReader r (b.bytes);
  166. flp::Event e;
  167. bool threw = false;
  168. try { r.next (e); } catch (const flp::Error&) { threw = true; }
  169. CHECK (threw);
  170. }
  171. TEST (flp_version_numbers)
  172. {
  173. CHECK (flp::parseVersionNumber ("25.2.5.5319") == 25002005u);
  174. CHECK (flp::parseVersionNumber ("20.99.3000.3031") == 20102000u);
  175. CHECK (flp::parseVersionNumber ("11.0.3") == 11000003u);
  176. }
  177. TEST (flp_playlist_record_size_by_version)
  178. {
  179. CHECK (flp::playlistRecordSize (12009003, 64) == 32);
  180. CHECK (flp::playlistRecordSize (21000000, 120) == 60);
  181. CHECK (flp::playlistRecordSize (25002005, 160) == 80);
  182. CHECK (flp::playlistRecordSize (25002005, 60) == 60); // size doesn't match the version -> tries the others
  183. CHECK (flp::playlistRecordSize (25002005, 7) == 0);
  184. }
  185. TEST (flp_parses_project_model)
  186. {
  187. FlpBuilder b (96);
  188. b.ascii (0xC7, "25.2.5.5319");
  189. b.u8 (0x9C); b.u32 (174500);
  190. b.utf16 (0xC2, u"Título");
  191. b.u8 (0x41); b.u16 (3);
  192. b.u8 (0x96); b.u32 (0x00A14547); // BGR in the file
  193. auto notes = noteRecord (96, 1, 48, 64, 100);
  194. auto n2 = noteRecord (0, 0, 0, 60, 128);
  195. notes.insert (notes.end(), n2.begin(), n2.end());
  196. b.data (0xE0, notes);
  197. b.u8 (0x40); b.u16 (0);
  198. b.u8 (0x15); b.u8 (0);
  199. b.utf16 (0xCB, u"Kick");
  200. {
  201. std::vector<std::uint8_t> levels (24, 0);
  202. const std::int32_t lv[] = { 3200, 12800, -150 };
  203. std::memcpy (levels.data(), lv, sizeof (lv));
  204. b.data (0xDB, levels);
  205. }
  206. b.u8 (0x68); b.u16 (5);
  207. b.u8 (0x40); b.u16 (1);
  208. b.u8 (0x15); b.u8 (2);
  209. b.utf16 (0xC9, u"FLEX");
  210. b.utf16 (0xCB, u"Lead");
  211. b.u8 (0x63); b.u16 (0);
  212. std::vector<std::uint8_t> item (80, 0);
  213. std::uint32_t pos = 384, len = 768;
  214. std::uint16_t base = 20480, idx = 20480 + 3, rv = 499 - 2;
  215. std::memcpy (&item[0], &pos, 4);
  216. std::memcpy (&item[4], &base, 2);
  217. std::memcpy (&item[6], &idx, 2);
  218. std::memcpy (&item[8], &len, 4);
  219. std::memcpy (&item[12], &rv, 2);
  220. b.data (0xE9, item);
  221. b.utf16 (0xCC, u"Drums");
  222. b.data (0xEC, std::vector<std::uint8_t> (12, 0));
  223. b.data (0xEC, std::vector<std::uint8_t> (12, 0));
  224. const auto p = flp::parseProject (b.bytes);
  225. CHECK (p.version == "25.2.5.5319");
  226. CHECK (std::abs (p.tempo - 174.5) < 1e-9);
  227. CHECK (p.title == "Título");
  228. CHECK (p.channels.size() == 2);
  229. CHECK (p.channels[0].name == "Kick" && p.channels[0].mixerTrack == 5);
  230. CHECK (p.channels[0].hasLevels && p.channels[0].pan == 3200 && p.channels[0].volume == 12800 && p.channels[0].pitchCents == -150);
  231. CHECK (p.channels[1].type == flp::ChannelType::instrument && p.channels[1].pluginName == "FLEX");
  232. CHECK (p.patterns.size() == 1 && p.patterns[0].index == 3);
  233. CHECK (p.patterns[0].colour && *p.patterns[0].colour == 0x4745A1);
  234. CHECK (p.patterns[0].notes.size() == 2 && p.patterns[0].notes[0].position == 0); // sorted
  235. CHECK (p.patterns[0].notes[1].key == 64 && p.patterns[0].notes[1].length == 48);
  236. CHECK (p.arrangements.size() == 1 && p.arrangements[0].items.size() == 1);
  237. const auto& it = p.arrangements[0].items[0];
  238. CHECK (it.kind == flp::PlaylistItem::Kind::pattern && it.index == 3 && it.track == 2 && it.position == 384);
  239. CHECK (p.mixer.size() == 2 && p.mixer[0].name == "Drums" && p.mixer[1].name.empty());
  240. CHECK (p.warnings.empty());
  241. }
  242. TEST (flp_fuzz_corrupted_files_do_not_crash)
  243. {
  244. if (realFlpDir.empty())
  245. return;
  246. // some real .flp files, corrupted in various ways: the parser may reject them (flp::Error), but
  247. // must never hang, read past the buffer or produce a Song with invalid indices
  248. std::vector<std::vector<std::uint8_t>> sources;
  249. for (auto& entry : std::filesystem::recursive_directory_iterator (realFlpDir))
  250. if (entry.path().extension() == ".flp" && sources.size() < 6 && std::filesystem::file_size (entry.path()) < 3'000'000)
  251. {
  252. std::ifstream in (entry.path(), std::ios::binary);
  253. sources.emplace_back ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  254. }
  255. std::uint32_t seed = 2024;
  256. auto rnd = [&] (std::uint32_t n) { seed = seed * 1664525u + 1013904223u; return n == 0 ? 0u : (seed >> 8) % n; };
  257. int parsed = 0, rejected = 0;
  258. for (int round = 0; round < 240 && ! sources.empty(); ++round)
  259. {
  260. auto bytes = sources[(std::size_t) rnd ((std::uint32_t) sources.size())];
  261. switch (round % 4)
  262. {
  263. case 0: bytes.resize (rnd ((std::uint32_t) bytes.size())); break; // truncated
  264. 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;
  265. case 2: // absurd event size
  266. for (int k = 0; k < 5; ++k)
  267. bytes[(std::size_t) rnd ((std::uint32_t) bytes.size())] = 0xFF;
  268. break;
  269. default: // shuffled block
  270. {
  271. const auto a = rnd ((std::uint32_t) bytes.size()), b = rnd ((std::uint32_t) bytes.size());
  272. std::reverse (bytes.begin() + std::min (a, b), bytes.begin() + std::max (a, b));
  273. break;
  274. }
  275. }
  276. try
  277. {
  278. const auto project = flp::parseProject (bytes);
  279. const auto song = lynx::importFlp (project);
  280. ++parsed;
  281. for (const auto& p : song.patterns)
  282. for (const auto& n : p.notes)
  283. CHECK (n.channel >= 0 && n.channel < (int) song.channels.size());
  284. for (const auto& c : song.playlist)
  285. CHECK (c.kind != lynx::ClipKind::pattern || (c.pattern >= 0 && c.pattern < (int) song.patterns.size()));
  286. }
  287. catch (const flp::Error&)
  288. {
  289. ++rejected;
  290. }
  291. }
  292. std::printf (" fuzz: %d imported, %d rejected\n", parsed, rejected);
  293. CHECK (parsed + rejected == 240);
  294. }
  295. TEST (plugin_state_decoders_survive_garbage)
  296. {
  297. // random blobs (varied sizes, including valid headers followed by garbage)
  298. std::uint32_t seed = 77;
  299. auto rnd = [&] { seed = seed * 1664525u + 1013904223u; return seed >> 8; };
  300. const char* plugins[] = { "Fruity Parametric EQ 2", "Fruity Limiter", "Fruity Reeverb 2", "Fruity Delay 2", "Fruity Delay 3",
  301. "Fruity Compressor", "Fruity Balance", "Fruity PanOMatic", "Fruity Stereo Shaper", "Fruity Phase Inverter" };
  302. int decoded = 0;
  303. for (int round = 0; round < 3000; ++round)
  304. {
  305. std::vector<std::uint8_t> blob ((std::size_t) (rnd() % 600));
  306. for (auto& b : blob)
  307. b = (std::uint8_t) rnd();
  308. if (blob.size() >= 4 && round % 3 == 0) // versions the readers accept
  309. {
  310. const std::uint32_t versions[] = { 8, 10001, 10000, 12, 14, 6, 1 };
  311. const auto v = versions[rnd() % 7];
  312. std::memcpy (blob.data(), &v, 4);
  313. }
  314. if (auto fx = lynx::effectFromFl (plugins[rnd() % 10], blob))
  315. {
  316. ++decoded;
  317. for (auto v : fx->params)
  318. CHECK (std::isfinite (v) && v >= 0.0f && v <= 1.0f);
  319. }
  320. lynx::SynthSettings synth;
  321. if (lynx::synthFrom3xOsc (blob, synth))
  322. for (const auto& o : synth.osc)
  323. CHECK (std::isfinite (o.level) && o.level >= 0.0f && o.level <= 1.0f);
  324. float harmlessGain = 1.0f;
  325. if (lynx::synthFromHarmless (blob, 120.0, synth, harmlessGain))
  326. CHECK (std::isfinite (harmlessGain) && std::isfinite (synth.cutoff) && std::isfinite (synth.attack));
  327. if (lynx::synthFromFruitKick (blob, synth))
  328. CHECK (std::isfinite (synth.decay) && std::isfinite (synth.pitchEnv.amount));
  329. if (lynx::synthFromGms (blob, 120.0, synth, harmlessGain) || lynx::synthFromHarmor (blob, synth, harmlessGain) || lynx::synthFromOgun (blob, synth, harmlessGain)
  330. || lynx::synthFromSakura (blob, synth) || lynx::synthFromKepler (blob, synth, harmlessGain))
  331. CHECK (std::isfinite (synth.cutoff) && std::isfinite (synth.attack) && std::isfinite (harmlessGain));
  332. if (auto sound = lynx::drumSynthLiveSound (blob))
  333. CHECK (sound->size() < 256);
  334. if (auto wave = lynx::waveTravellerSample (blob))
  335. CHECK (! wave->first.empty() && wave->second >= 0 && wave->second <= 127);
  336. lynx::synthFromBooBass (blob, synth);
  337. if (lynx::synthFromPoiZone (blob, synth, harmlessGain) || lynx::synthFromBassDrum (blob, synth, harmlessGain) || lynx::synthFromToxic (blob, synth, harmlessGain)
  338. || lynx::synthFromMorphine (blob, synth, harmlessGain))
  339. CHECK (std::isfinite (synth.cutoff) && std::isfinite (harmlessGain));
  340. if (auto patch = lynx::drumpadPatchName (blob))
  341. CHECK (patch->size() <= 0x30 && std::isfinite (lynx::drumToneForName (*patch).decay));
  342. if (auto flex = lynx::flexPresetName (blob))
  343. CHECK ((! flex->first.empty() || ! flex->second.empty()) && flex->second.size() <= 1024);
  344. if (lynx::synthFromSytrus (blob, 120.0, synth, harmlessGain))
  345. CHECK (std::isfinite (synth.cutoff) && std::isfinite (synth.attack));
  346. if (lynx::synthFromDX10 (blob, synth))
  347. CHECK (std::isfinite (synth.decay) && std::isfinite (synth.release) && std::isfinite (synth.osc[1].level));
  348. if (blob.size() >= 4 && round % 5 == 0) // MiniSynth header followed by garbage
  349. {
  350. std::memcpy (blob.data(), "SSLF", 4);
  351. if (blob.size() > 220)
  352. {
  353. std::memcpy (blob.data() + 40, "DATA", 4);
  354. std::memcpy (blob.data() + 48, "0rev", 4);
  355. }
  356. }
  357. if (lynx::synthFromMiniSynth (blob, 120.0, synth))
  358. CHECK (std::isfinite (synth.cutoff) && std::isfinite (synth.decay) && std::isfinite (synth.attack));
  359. lynx::ForeignPlugin foreign;
  360. lynx::parseFlWrapper (blob, foreign);
  361. std::vector<std::uint8_t> component, controller;
  362. lynx::splitFlVst3State (blob, component, controller);
  363. }
  364. CHECK (decoded == 3000); // every known name yields an effect (default when the blob is unusable)
  365. }
  366. TEST (inflate_zlib)
  367. {
  368. // fixed Huffman with back-references
  369. const std::uint8_t fixed[] = { 0x78, 0xda, 0x4b, 0x4c, 0x4a, 0x4e, 0xc4, 0x86, 0x22, 0x00, 0x7c, 0x69, 0x09, 0x89 };
  370. const auto a = lynx::inflateZlib (fixed, sizeof (fixed));
  371. CHECK (a && std::string (a->begin(), a->end()) == "abcabcabcabcabcabcabcabcX");
  372. // stored (uncompressed) block
  373. const std::uint8_t stored[] = { 0x78, 0x01, 0x01, 0x03, 0x00, 0xfc, 0xff, 'L', 'Y', 'N', 0x00, 0x00, 0x00, 0x00 };
  374. const auto b = lynx::inflateZlib (stored, sizeof (stored));
  375. CHECK (b && std::string (b->begin(), b->end()) == "LYN");
  376. // truncated, bad header and size limit
  377. CHECK (! lynx::inflateZlib (fixed, 6));
  378. const std::uint8_t bad[] = { 0x12, 0x34, 0x00 };
  379. CHECK (! lynx::inflateZlib (bad, sizeof (bad)));
  380. CHECK (! lynx::inflateZlib (fixed, sizeof (fixed), false, 10));
  381. }
  382. TEST (fl_round15_effects_convert_known_values)
  383. {
  384. auto blob = [] (std::vector<std::int32_t> words) {
  385. std::vector<std::uint8_t> b (words.size() * 4);
  386. std::memcpy (b.data(), words.data(), b.size());
  387. return b;
  388. };
  389. // Frequency Shifter "+800 Hz": frequency 51542 in the 20 kHz range, 100% wet
  390. const auto fs = lynx::effectFromFl ("Frequency Shifter", blob ({ 4, 10000, 0, 51542, 0, 10000, 10000, 5000, 10000, 0, 5000, 0, 0 }));
  391. CHECK (fs && fs->kind == lynx::EffectKind::freqShift);
  392. if (fs)
  393. {
  394. const auto x = (fs->params[0] - 0.5) * 2.0;
  395. CHECK (std::abs (2000.0 * x * std::abs (x) - 800.0) < 10.0);
  396. CHECK (std::abs (fs->params[1] - 1.0f) < 1e-4f);
  397. }
  398. // Emphasis: input 0.0625 (= +1.5 dB) and ceiling 0.9308 (≈ −1.6 dB) -> limiter
  399. const auto em = lynx::effectFromFl ("Emphasis", blob ({ 8, 0, 0, 2, 1, 0, 0, 625, 10000, 10000, 9308, 0, 2, 7, 0 }));
  400. CHECK (em && em->kind == lynx::EffectKind::limiter && em->enabled);
  401. if (em)
  402. {
  403. CHECK (std::abs (em->params[1] * 24.0f - 1.5f) < 0.05f);
  404. CHECK (std::abs (em->params[0] * 12.0f - 12.0f + 1.6f) < 0.1f);
  405. }
  406. // Pitch Shifter +12 st, mix 100%
  407. 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 }));
  408. CHECK (ps && ps->kind == lynx::EffectKind::pitchShift && std::abs (ps->params[0] - (0.5f + 12.0f / 48.0f)) < 1e-4f);
  409. }
  410. TEST (frequency_shifter_moves_spectrum_by_hz)
  411. {
  412. auto fx = lynx::makeEffect (lynx::EffectKind::freqShift);
  413. fx->prepare (48000.0);
  414. auto slot = lynx::makeEffectSlot (lynx::EffectKind::freqShift);
  415. // +200 Hz: x·|x|·2000 = 200 -> x = sqrt(0.1)
  416. slot.params[0] = (float) (0.5 + std::sqrt (0.1) / 2.0);
  417. std::vector<float> l (48000), r (48000);
  418. for (int i = 0; i < 48000; ++i)
  419. l[(std::size_t) i] = r[(std::size_t) i] = (float) std::sin (2.0 * 3.141592653589793 * 1000.0 * i / 48000.0);
  420. for (int done = 0; done < 48000; done += 480)
  421. fx->process (l.data() + done, r.data() + done, 480, slot.params, 120.0);
  422. auto energy = [&] (double f) {
  423. const auto w = 2.0 * 3.141592653589793 * f / 48000.0, k = 2.0 * std::cos (w);
  424. double s1 = 0.0, s2 = 0.0;
  425. for (int i = 9600; i < 48000; ++i)
  426. {
  427. const auto s0 = l[(std::size_t) i] + k * s1 - s2;
  428. s2 = s1;
  429. s1 = s0;
  430. }
  431. return s1 * s1 + s2 * s2 - k * s1 * s2;
  432. };
  433. // the energy moves to 1200 Hz; little remains at 1000 and almost nothing at the image (800)
  434. CHECK (energy (1200.0) > 50.0 * energy (1000.0));
  435. CHECK (energy (1200.0) > 50.0 * energy (800.0));
  436. }
  437. TEST (pitch_shift_moves_frequency_keeps_length)
  438. {
  439. auto fx = lynx::makeEffect (lynx::EffectKind::pitchShift);
  440. fx->prepare (48000.0);
  441. auto slot = lynx::makeEffectSlot (lynx::EffectKind::pitchShift);
  442. auto crossingsAfter = [&] (float semitoneParam) {
  443. fx->reset();
  444. slot.params[0] = semitoneParam;
  445. std::vector<float> l (48000), r (48000);
  446. for (int i = 0; i < 48000; ++i)
  447. l[(std::size_t) i] = r[(std::size_t) i] = (float) std::sin (2.0 * 3.141592653589793 * 220.0 * i / 48000.0);
  448. for (int done = 0; done < 48000; done += 512)
  449. fx->process (l.data() + done, r.data() + done, std::min (512, 48000 - done), slot.params, 120.0);
  450. int crossings = 0;
  451. for (int i = 9600; i < 48000; ++i)
  452. crossings += (l[(std::size_t) i - 1] < 0.0f) != (l[(std::size_t) i] < 0.0f);
  453. for (auto v : l)
  454. CHECK (std::isfinite (v) && std::abs (v) < 1.6f);
  455. return crossings / 0.8 / 2.0; // cycles per second
  456. };
  457. CHECK (std::abs (crossingsAfter (0.5f) - 220.0) < 8.0); // 0 st
  458. CHECK (std::abs (crossingsAfter (0.5f + 12.0f / 48.0f) - 440.0) < 25.0); // +12 st
  459. CHECK (std::abs (crossingsAfter (0.5f - 12.0f / 48.0f) - 110.0) < 12.0); // −12 st
  460. }
  461. TEST (volume_gate_follows_bar_position)
  462. {
  463. auto fx = lynx::makeEffect (lynx::EffectKind::volumeGate);
  464. fx->prepare (48000.0);
  465. auto slot = lynx::makeEffectSlot (lynx::EffectKind::volumeGate);
  466. for (int i = 0; i < 32; ++i)
  467. slot.params[(std::size_t) i] = i < 16 ? 1.0f : 0.0f; // first two beats open, two closed
  468. slot.params[33] = slot.params[34] = 0.0f; // no smoothing
  469. // 120 BPM: one beat = 0.5 s = 24000 samples; the 4-beat bar starts at tick 0
  470. std::vector<float> l (96000, 1.0f), r (96000, 1.0f);
  471. fx->setSongPosition (0.0);
  472. for (int done = 0; done < 96000; done += 512)
  473. fx->process (l.data() + done, r.data() + done, std::min (512, 96000 - done), slot.params, 120.0);
  474. CHECK (l[10000] > 0.99f && l[40000] > 0.99f); // beats 1 and 2
  475. CHECK (l[60000] < 0.01f && l[90000] < 0.01f); // beats 3 and 4
  476. // starting mid-bar (beat 3): already closed
  477. std::vector<float> l2 (4800, 1.0f), r2 (4800, 1.0f);
  478. fx->reset();
  479. fx->setSongPosition (2.0 * lynx::ppq);
  480. fx->process (l2.data(), r2.data(), 4800, slot.params, 120.0);
  481. CHECK (l2[4000] < 0.01f);
  482. // mix 0: transparent
  483. slot.params[32] = 0.0f;
  484. std::vector<float> l3 (4800, 1.0f), r3 (4800, 1.0f);
  485. fx->setSongPosition (2.0 * lynx::ppq);
  486. fx->process (l3.data(), r3.data(), 4800, slot.params, 120.0);
  487. CHECK (l3[4000] > 0.99f);
  488. }
  489. TEST (patcher_branch_heads_follow_rea)
  490. {
  491. auto words = [] (std::vector<std::int32_t> v) {
  492. std::vector<std::uint8_t> b (v.size() * 4);
  493. std::memcpy (b.data(), v.data(), b.size());
  494. return b;
  495. };
  496. // Frequency Splitter, 2 bands, destinations 1/2/3, slope combo 3 (24 dB/oct), high send −6 dB
  497. std::vector<std::int32_t> fs (18, 0);
  498. fs[0] = 4;
  499. fs[1] = 32768;
  500. fs[3] = 3;
  501. fs[6] = 0;
  502. fs[11] = -600;
  503. fs[15] = 1;
  504. fs[16] = 2;
  505. fs[17] = 3;
  506. const auto split = words (fs);
  507. const auto low = lynx::patcherBranchHead ("Frequency Splitter", split, 1);
  508. CHECK (low.valid && low.slot && low.note.empty());
  509. if (low.slot)
  510. {
  511. // low band = just the Crossover low-pass, combo 3 (24 dB/oct)
  512. CHECK (low.slot->kind == lynx::EffectKind::crossover && low.slot->params[0] == 0.0f && low.slot->params[3] == 1.0f);
  513. CHECK (std::lround (low.slot->params[5] * 7.0f) == 3);
  514. }
  515. const auto mid = lynx::patcherBranchHead ("Frequency Splitter", split, 2);
  516. CHECK (mid.valid && mid.gain == 0.0f); // with 2 bands the mid is silent
  517. const auto high = lynx::patcherBranchHead ("Frequency Splitter", split, 3);
  518. CHECK (high.valid && std::abs (high.gain - std::pow (10.0f, -6.0f / 20.0f)) < 1e-4f);
  519. CHECK (! lynx::patcherBranchHead ("Frequency Splitter", split, 7).valid);
  520. // Stereo Shaper with identity matrix: the difference (destination 4) is zero
  521. const auto shaper = words ({ 3, 0, 12800, 12800, 0, 0, 0, 4, 0 });
  522. const auto diff = lynx::patcherBranchHead ("Fruity Stereo Shaper", shaper, 4);
  523. 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);
  524. CHECK (! lynx::patcherBranchHead ("Fruity Stereo Shaper", shaper, 2).valid);
  525. }
  526. TEST (parallel_container_sums_branches)
  527. {
  528. // two branches: dry with gain 0.5 and a utility that flips phase (matrix −1) with gain 0.5 -> silence
  529. auto slot = lynx::makeEffectSlot (lynx::EffectKind::parallel);
  530. lynx::EffectBranch dry;
  531. dry.gain = 0.5f;
  532. lynx::EffectBranch inverted;
  533. inverted.gain = 0.5f;
  534. auto flip = lynx::makeEffectSlot (lynx::EffectKind::utility);
  535. flip.params[2] = flip.params[5] = 0.25f; // (−1 + 2)/4
  536. inverted.chain.push_back (flip);
  537. slot.branches = { dry, inverted };
  538. auto fx = lynx::makeParallelEffect (slot);
  539. fx->prepare (48000.0);
  540. std::vector<float> l (9000, 0.8f), r (9000, -0.4f);
  541. fx->process (l.data(), r.data(), 9000, slot.params, 120.0);
  542. CHECK (std::abs (l[100]) < 1e-5f && std::abs (r[8999]) < 1e-5f);
  543. // only the dry branch with gain 2: doubles
  544. slot.branches = { lynx::EffectBranch { {}, 2.0f } };
  545. auto doubler = lynx::makeParallelEffect (slot);
  546. doubler->prepare (48000.0);
  547. std::fill (l.begin(), l.end(), 0.25f);
  548. doubler->process (l.data(), r.data(), 9000, slot.params, 120.0);
  549. CHECK (std::abs (l[5000] - 0.5f) < 1e-6f);
  550. }
  551. TEST (fl_controller_constant_outputs)
  552. {
  553. std::vector<std::int32_t> xy { 2, 32768, 0, 65536, 0, 16384, 0, 65536, 0, 1024, 256 };
  554. std::vector<std::uint8_t> blob (xy.size() * 4 + 8, 0);
  555. std::memcpy (blob.data(), xy.data(), xy.size() * 4);
  556. CHECK (std::abs (lynx::controllerConstantOutput ("Fruity X-Y Controller", blob, 0).value_or (-1.0f) - 0.5f) < 1e-4f);
  557. CHECK (std::abs (lynx::controllerConstantOutput ("Fruity X-Y Controller", blob, 1).value_or (-1.0f) - 0.25f) < 1e-4f);
  558. // Control Surface: version + group { 0x836: value 0.75, -, output 2 }
  559. std::vector<std::uint8_t> cs (4, 0);
  560. cs[0] = 1;
  561. auto chunk = [] (std::vector<std::uint8_t>& out, std::uint32_t id, const std::vector<std::uint8_t>& body) {
  562. const auto size = (std::uint64_t) body.size();
  563. out.insert (out.end(), reinterpret_cast<const std::uint8_t*> (&id), reinterpret_cast<const std::uint8_t*> (&id) + 4);
  564. out.insert (out.end(), reinterpret_cast<const std::uint8_t*> (&size), reinterpret_cast<const std::uint8_t*> (&size) + 8);
  565. out.insert (out.end(), body.begin(), body.end());
  566. };
  567. std::vector<std::uint8_t> value (12, 0);
  568. const float v = 0.75f;
  569. const std::int32_t out = 2;
  570. std::memcpy (value.data(), &v, 4);
  571. std::memcpy (value.data() + 8, &out, 4);
  572. std::vector<std::uint8_t> group;
  573. chunk (group, 0x836, value);
  574. chunk (cs, 0, group);
  575. CHECK (std::abs (lynx::controllerConstantOutput ("Control Surface", cs, 2).value_or (-1.0f) - 0.75f) < 1e-6f);
  576. CHECK (! lynx::controllerConstantOutput ("Control Surface", cs, 0).has_value());
  577. }
  578. TEST (flp_midi_out_notes_reach_wrapper_on_same_port)
  579. {
  580. auto record = [] (std::vector<std::uint8_t>& out, std::uint32_t id, std::vector<std::uint8_t> body) {
  581. const auto size = (std::uint64_t) body.size();
  582. out.insert (out.end(), reinterpret_cast<const std::uint8_t*> (&id), reinterpret_cast<const std::uint8_t*> (&id) + 4);
  583. out.insert (out.end(), reinterpret_cast<const std::uint8_t*> (&size), reinterpret_cast<const std::uint8_t*> (&size) + 8);
  584. out.insert (out.end(), body.begin(), body.end());
  585. };
  586. auto i32s = [] (std::vector<std::int32_t> v) {
  587. std::vector<std::uint8_t> b (v.size() * 4);
  588. std::memcpy (b.data(), v.data(), b.size());
  589. return b;
  590. };
  591. flp::Project p;
  592. flp::Channel midiOut;
  593. midiOut.index = 0;
  594. midiOut.type = flp::ChannelType::native;
  595. midiOut.pluginName = "MIDI Out";
  596. midiOut.pluginState = i32s ({ 7, 0, -1, -1, -1, 0, 3, 0 }); // channel 1, port 3 (@24)
  597. flp::Channel wrapper;
  598. wrapper.index = 1;
  599. wrapper.type = flp::ChannelType::native;
  600. wrapper.pluginName = "Fruity Wrapper";
  601. wrapper.pluginState = i32s ({ 9 });
  602. record (wrapper.pluginState, 0x32, i32s ({ 7 })); // VST3
  603. record (wrapper.pluginState, 0x01, i32s ({ 3, -1, 0, 0, 0 })); // input port 3
  604. p.channels = { midiOut, wrapper };
  605. flp::Pattern pattern;
  606. pattern.index = 1;
  607. flp::Note note;
  608. note.channel = 0;
  609. note.key = 64;
  610. note.length = 96;
  611. pattern.notes.push_back (note);
  612. p.patterns.push_back (pattern);
  613. const auto song = lynx::importFlp (p);
  614. CHECK (song.channels.size() == 2 && song.channels[0].muted);
  615. CHECK (song.channels[1].plugin.foreign.midiInPort == 3);
  616. int toWrapper = 0;
  617. for (const auto& pat : song.patterns)
  618. for (const auto& n : pat.notes)
  619. toWrapper += n.channel == 1 && n.key == 64;
  620. CHECK (toWrapper == 1);
  621. }
  622. TEST (flp_effect_automation_follows_slots_and_params)
  623. {
  624. // track 1: slot 0 with an effect that has no equivalent (dropped), slot 2 with Parametric EQ 2
  625. flp::Project p;
  626. flp::MixerInsert insert;
  627. insert.index = 1;
  628. insert.slots.push_back ({ 0, "Some Unknown FX", {} });
  629. insert.slots.push_back ({ 2, "Fruity Parametric EQ 2", {} });
  630. p.mixer.push_back (insert);
  631. auto clip = [&] (int index, std::uint32_t target) {
  632. flp::Channel c;
  633. c.index = index;
  634. c.type = flp::ChannelType::automationClip;
  635. c.automation = { { 0.0, 0.0 }, { 96.0, 1.0 } };
  636. p.channels.push_back (c);
  637. p.automationLinks.push_back ({ index, { target } });
  638. };
  639. 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; };
  640. clip (0, mixer (1, 2, 0x8000 + 7)); // EQ band 1 frequency
  641. clip (1, mixer (1, 2, 0x1F01)); // EQ slot mix
  642. clip (2, mixer (1, 0, 0x8000)); // parameter of the dropped effect
  643. clip (3, mixer (1, 2, 0x8000 + 21)); // band type: no equivalent
  644. const auto song = lynx::importFlp (p);
  645. CHECK (song.automations.size() == 4);
  646. CHECK (song.mixer[1].effects.size() == 1 && song.mixer[1].effects[0].kind == lynx::EffectKind::parametricEq);
  647. const auto& freq = song.automations[0];
  648. CHECK (freq.target.kind == lynx::AutomationTargetKind::effectParam && freq.target.index == 1 && freq.target.slot == 0);
  649. CHECK (freq.target.param == lynx::peq::param (0, 1));
  650. // FL's 0..1 (20 Hz..20 kHz) becomes our frequency scale
  651. CHECK (std::abs (freq.points.front().value - lynx::peq::hzValue (20.0)) < 1e-4f);
  652. CHECK (std::abs (freq.points.back().value - lynx::peq::hzValue (20000.0)) < 1e-4f);
  653. CHECK (song.automations[1].target.kind == lynx::AutomationTargetKind::effectMix && song.automations[1].target.slot == 0);
  654. CHECK (song.automations[2].target.kind == lynx::AutomationTargetKind::none);
  655. CHECK (song.automations[3].target.kind == lynx::AutomationTargetKind::none);
  656. // the automated mix is read/written through the target
  657. auto copy = song;
  658. CHECK (copy.setTargetValue (song.automations[1].target, 0.25f) && std::abs (copy.mixer[1].effects[0].mix - 0.25f) < 1e-6f);
  659. CHECK (std::abs (copy.targetValue (song.automations[1].target) - 0.25f) < 1e-6f);
  660. }
  661. TEST (flp_real_files)
  662. {
  663. if (realFlpDir.empty())
  664. {
  665. std::printf (" (skipped: pass a folder with .flp files as argument)\n");
  666. return;
  667. }
  668. int files = 0, withNotes = 0, withPlaylist = 0, automations = 0, automationsWithTarget = 0, sends = 0;
  669. int threeOsc = 0, threeOscDecoded = 0, wrapped = 0, wrappedParsed = 0, markers = 0, signatures = 0, trackEqs = 0;
  670. int harmless = 0, harmlessDecoded = 0, harmlessParsed = 0, harmlessKind = 0, sytrus = 0, sytrusDecoded = 0;
  671. std::map<std::string, std::pair<int, int>> generators; // GMS/Ogun/Autogun/Sakura/DrumSynth: channels, decoded
  672. int ogunTrumpet = 0; // Ogun channels whose spectrum matches the REA "Trumpet" reference
  673. int peqSlots = 0, peqShaped = 0, reverbs = 0, reverbsDryless = 0, reverbsLowCut = 0;
  674. int dwChannels = 0, dwZones = 0, fpcKits = 0, padChannels = 0, padNotes = 0;
  675. // import with the installation's samples (realFlpDir is ...\Data): for DirectWave/FPC
  676. lynx::FlpImportOptions withFiles;
  677. const auto flRoot = std::filesystem::path (realFlpDir).parent_path().string();
  678. withFiles.roots = { flRoot, realFlpDir, "" };
  679. withFiles.fileExists = [] (const std::string& path) {
  680. auto local = path;
  681. std::replace (local.begin(), local.end(), '\\', '/');
  682. return std::filesystem::exists (local);
  683. };
  684. withFiles.readFile = [] (const std::string& path) {
  685. auto local = path;
  686. std::replace (local.begin(), local.end(), '\\', '/');
  687. std::ifstream in (local, std::ios::binary);
  688. return std::vector<std::uint8_t> ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  689. };
  690. int embeddedSaved = 0;
  691. withFiles.saveEmbedded = [&embeddedSaved] (const std::vector<std::uint8_t>& wav, const std::string&) {
  692. ++embeddedSaved;
  693. return wav.size() > 44 ? std::string ("embutido.wav") : std::string();
  694. };
  695. int slicedChannels = 0, flKeysChannels = 0;
  696. for (auto& entry : std::filesystem::recursive_directory_iterator (realFlpDir))
  697. {
  698. if (entry.path().extension() != ".flp")
  699. continue;
  700. std::ifstream in (entry.path(), std::ios::binary);
  701. std::vector<std::uint8_t> bytes ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  702. ++files;
  703. try
  704. {
  705. const auto p = flp::parseProject (bytes);
  706. CHECK (! p.version.empty());
  707. CHECK (p.tempo > 10.0 && p.tempo < 1000.0);
  708. const auto song = lynx::importFlp (p);
  709. CHECK (! song.patterns.empty());
  710. {
  711. const auto full = lynx::importFlp (p, withFiles);
  712. bool hasFpc = false;
  713. for (const auto& c : p.channels)
  714. hasFpc = hasFpc || c.pluginName == "FPC";
  715. for (const auto& c : full.channels)
  716. {
  717. flKeysChannels += c.zones.size() == 30 && c.zones.front().path.find ("CHANGPIANO") != std::string::npos ? 1 : 0;
  718. if (c.sampler.slices.size() >= 4)
  719. {
  720. ++slicedChannels;
  721. CHECK (std::is_sorted (c.sampler.slices.begin(), c.sampler.slices.end()));
  722. CHECK (c.sampler.slices.back() < 1.0f);
  723. }
  724. if (! c.zones.empty() && c.name.find (" - ") == std::string::npos)
  725. {
  726. ++dwChannels;
  727. dwZones += (int) c.zones.size();
  728. }
  729. padChannels += c.name.find (" - ") != std::string::npos && c.instrument == lynx::InstrumentKind::sampler ? 1 : 0;
  730. }
  731. fpcKits += hasFpc;
  732. for (const auto& pat : full.patterns)
  733. for (const auto& n : pat.notes)
  734. {
  735. CHECK (n.channel >= 0 && n.channel < (int) full.channels.size());
  736. padNotes += full.channels[(std::size_t) n.channel].name.find (" - ") != std::string::npos ? 1 : 0;
  737. }
  738. }
  739. const auto peqDefaults = lynx::makeEffectSlot (lynx::EffectKind::parametricEq).params;
  740. for (const auto& t : song.mixer)
  741. for (const auto& fx : t.effects)
  742. {
  743. if (fx.kind == lynx::EffectKind::parametricEq)
  744. {
  745. ++peqSlots;
  746. peqShaped += fx.params != peqDefaults;
  747. for (double hz : { 50.0, 1000.0, 10000.0 })
  748. CHECK (std::isfinite (lynx::peq::responseDb (fx.params, 48000.0, hz)));
  749. }
  750. if (fx.kind == lynx::EffectKind::reverb)
  751. {
  752. ++reverbs;
  753. reverbsDryless += fx.params[4] < 0.01f;
  754. reverbsLowCut += fx.params[5] > 0.0f;
  755. }
  756. }
  757. for (const auto& t : song.mixer)
  758. if (t.eq.active())
  759. {
  760. ++trackEqs;
  761. for (std::size_t b = 0; b < 3; ++b)
  762. CHECK (t.eq.hz[b] >= 10.0f && t.eq.hz[b] <= 16000.0f && std::abs (t.eq.gainDb[b]) <= 18.0f);
  763. }
  764. for (const auto& a : song.arrangements)
  765. for (const auto& m : a.markers)
  766. {
  767. ++markers;
  768. signatures += m.isSignature();
  769. CHECK (m.tick >= 0);
  770. }
  771. // Fruity Wrapper (channels and mixer slots): every blob in the demos is read
  772. auto countWrapper = [&] (const std::string& plugin, const std::vector<std::uint8_t>& state) {
  773. if (plugin != "Fruity Wrapper")
  774. return;
  775. ++wrapped;
  776. lynx::ForeignPlugin f;
  777. wrappedParsed += lynx::parseFlWrapper (state, f) && f.format != lynx::ForeignPlugin::Format::none && ! f.name.empty();
  778. };
  779. for (const auto& c : p.channels)
  780. countWrapper (c.pluginName, c.pluginState);
  781. for (const auto& insert : p.mixer)
  782. for (const auto& slot : insert.slots)
  783. countWrapper (slot.plugin, slot.state);
  784. // Harmless: every state in the demos becomes a synth, with finite values
  785. for (const auto& c : p.channels)
  786. if (c.pluginName == "Harmless")
  787. {
  788. ++harmless;
  789. lynx::SynthSettings hs;
  790. float g = 1.0f;
  791. if (lynx::synthFromHarmless (c.pluginState, 128.0, hs, g))
  792. {
  793. ++harmlessDecoded;
  794. CHECK (std::isfinite (g) && hs.cutoff >= 20.0f && hs.cutoff <= 20000.0f && std::isfinite (hs.decay) && std::isfinite (hs.release));
  795. }
  796. if (const auto hp = lynx::harmlessParams (c.pluginState))
  797. harmlessParsed += (int) hp->size() == lynx::harmlessParamCount ? 1 : 0;
  798. }
  799. for (const auto& c : song.channels)
  800. harmlessKind += c.instrument == lynx::InstrumentKind::harmless ? 1 : 0;
  801. // Sytrus: every state in the demos (zlib + 10 units) decodes, with finite values
  802. for (const auto& c : p.channels)
  803. if (c.pluginName == "Sytrus")
  804. {
  805. ++sytrus;
  806. lynx::SynthSettings ss;
  807. float g = 1.0f;
  808. if (lynx::synthFromSytrus (c.pluginState, 128.0, ss, g))
  809. {
  810. ++sytrusDecoded;
  811. CHECK (std::isfinite (g) && ss.cutoff >= 20.0f && ss.cutoff <= 20000.0f && std::isfinite (ss.attack) && std::isfinite (ss.decay)
  812. && std::isfinite (ss.release) && ss.sustain >= 0.0f && ss.sustain <= 1.0f && std::isfinite (ss.filterEnv.amount));
  813. for (const auto& o : ss.osc)
  814. CHECK (o.level >= 0.0f && o.level <= 1.0f && o.octave >= -3 && o.octave <= 3);
  815. }
  816. }
  817. // round 12 generators
  818. for (const auto& c : p.channels)
  819. {
  820. lynx::SynthSettings gs;
  821. float g = 1.0f;
  822. int decoded = -1;
  823. if (c.pluginName == "Harmor")
  824. {
  825. decoded = lynx::synthFromHarmor (c.pluginState, gs, g);
  826. if (decoded)
  827. {
  828. // REA_rodada25 §4: most resonant settings stay below Q ≈ 3, a few saturate
  829. CHECK (gs.resonance >= 0.0f && gs.resonance <= 1.0f);
  830. static int resonant = 0, strong = 0, total = 0;
  831. resonant += gs.resonance > 0.0f;
  832. strong += gs.resonance > 0.9f;
  833. if (++total % 50 == 0)
  834. std::printf (" Harmor resonance: %d with a peak, %d with Q > ~5 (of %d)\n", resonant, strong, total);
  835. }
  836. static int saw = 0, square = 0, other = 0, total = 0;
  837. if (decoded && std::any_of (gs.osc.begin(), gs.osc.end(), [] (const lynx::SynthOscillator& o) { return o.wave == lynx::Waveform::spectral; }))
  838. {
  839. auto isSaw = true, isSquare = true;
  840. for (int n = 1; n <= 16; ++n)
  841. {
  842. isSaw = isSaw && std::abs (gs.spectrum[(std::size_t) n - 1] - 1.0f / n) < 1e-3f;
  843. isSquare = isSquare && std::abs (gs.spectrum[(std::size_t) n - 1] - (n % 2 == 1 ? 1.1535f / n : 0.0f)) < 2e-3f;
  844. }
  845. ++(isSaw ? saw : isSquare ? square : other);
  846. if (++total % 20 == 0 || total == 100)
  847. std::printf (" Harmor spectrum: %d saw, %d square, %d other (of %d)\n", saw, square, other, total);
  848. }
  849. }
  850. else if (c.pluginName == "GMS")
  851. decoded = lynx::synthFromGms (c.pluginState, 128.0, gs, g);
  852. else if (c.pluginName == "Ogun" || c.pluginName == "Autogun")
  853. {
  854. decoded = lynx::synthFromOgun (c.pluginState, gs, g);
  855. // REA_rodada24 §1.9: the "Trumpet" preset (richness 7, no seeds) has partials 0.9087, 0.8610,
  856. // 0.8151… at the fixed seed-3 phases 0.919, 0.380, 0.130
  857. if (decoded && gs.osc[0].wave == lynx::Waveform::spectral)
  858. {
  859. CHECK (std::all_of (gs.spectrum.begin(), gs.spectrum.end(), [] (float a) { return std::isfinite (a) && a >= 0.0f; }));
  860. static constexpr float trumpet[3] { 0.9087f, 0.8610f, 0.8151f }, phases[3] { 0.919f, 0.380f, 0.130f };
  861. auto match = true;
  862. for (std::size_t k = 0; k < 3; ++k)
  863. match = match && std::abs (gs.spectrum[k] * 2.0f / 3.14159265f - trumpet[k]) < 1e-3f && std::abs (gs.spectrumPhase[k] - phases[k]) < 1e-3f;
  864. ogunTrumpet += match ? 1 : 0;
  865. }
  866. }
  867. else if (c.pluginName == "Sakura")
  868. decoded = lynx::synthFromSakura (c.pluginState, gs);
  869. else if (c.pluginName == "Kepler")
  870. decoded = lynx::synthFromKepler (c.pluginState, gs, g);
  871. else if (c.pluginName == "Wave Traveller")
  872. decoded = lynx::waveTravellerSample (c.pluginState).has_value() ? 2 : 0;
  873. else if (c.pluginName == "PoiZone")
  874. decoded = lynx::synthFromPoiZone (c.pluginState, gs, g);
  875. else if (c.pluginName == "BassDrum")
  876. decoded = lynx::synthFromBassDrum (c.pluginState, gs, g);
  877. else if (c.pluginName == "Toxic Biohazard")
  878. decoded = lynx::synthFromToxic (c.pluginState, gs, g);
  879. else if (c.pluginName == "Morphine")
  880. decoded = lynx::synthFromMorphine (c.pluginState, gs, g);
  881. else if (c.pluginName == "BooBass")
  882. decoded = lynx::synthFromBooBass (c.pluginState, gs);
  883. else if (c.pluginName == "Drumpad" || c.pluginName == "DrumPad")
  884. decoded = lynx::drumpadPatchName (c.pluginState).has_value() ? 2 : 0;
  885. else if (c.pluginName == "Fruity Envelope Controller" && c.pluginState.size() >= 4 && c.pluginState[2] >= 6) // v >= 6
  886. decoded = lynx::parseEnvelopeController (c.pluginState).has_value() ? 2 : 0;
  887. else if (c.pluginName == "FLEX")
  888. decoded = lynx::flexPresetName (c.pluginState).has_value() ? 2 : 0;
  889. else if (c.pluginName == "Fruity DrumSynth Live")
  890. decoded = lynx::drumSynthLiveParams (c.pluginState).has_value() ? 2 : 0;
  891. if (decoded < 0)
  892. continue;
  893. auto& counter = generators[c.pluginName];
  894. ++counter.first;
  895. counter.second += decoded != 0;
  896. if (decoded == 1 && c.pluginName != "Fruity DrumSynth Live")
  897. {
  898. CHECK (std::isfinite (g) && g >= 0.0f && gs.cutoff >= 20.0f && gs.cutoff <= 20000.0f && gs.sustain >= 0.0f && gs.sustain <= 1.0f);
  899. 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));
  900. for (const auto& o : gs.osc)
  901. CHECK (o.level >= 0.0f && o.level <= 4.0f && std::isfinite (o.detune) && std::isfinite (o.pan));
  902. }
  903. }
  904. // 3x Osc: every state in the demos decodes, with levels summing to at most 1
  905. for (const auto& c : p.channels)
  906. if (c.pluginName == "3x Osc")
  907. {
  908. ++threeOsc;
  909. lynx::SynthSettings s;
  910. if (lynx::synthFrom3xOsc (c.pluginState, s))
  911. {
  912. ++threeOscDecoded;
  913. // with AM, osc 3 is the modulation depth and is left out of the sum
  914. const auto sum = s.osc[0].level + s.osc[1].level + (s.am ? 0.0f : s.osc[2].level);
  915. CHECK (sum <= 1.001f && s.osc[2].level <= 1.0f);
  916. for (const auto& o : s.osc)
  917. CHECK (o.octave >= -2 && o.octave <= 2 && std::abs (o.semitones) <= 11 && std::abs (o.pan) <= 1.0f);
  918. }
  919. }
  920. for (auto& pat : p.patterns)
  921. if (! pat.notes.empty())
  922. {
  923. ++withNotes;
  924. break;
  925. }
  926. for (auto& a : p.arrangements)
  927. for (auto& item : a.items)
  928. CHECK (item.track >= 0 && item.track < 500);
  929. for (auto& clip : song.playlist)
  930. {
  931. CHECK (clip.pattern >= 0 && clip.pattern < (int) song.patterns.size());
  932. CHECK (clip.length > 0 && clip.offset >= 0);
  933. if (clip.kind == lynx::ClipKind::automation)
  934. CHECK (clip.automation >= 0 && clip.automation < (int) song.automations.size());
  935. }
  936. for (auto& a : song.automations)
  937. {
  938. ++automations;
  939. automationsWithTarget += a.target.kind != lynx::AutomationTargetKind::none;
  940. CHECK (a.isLive() || ! a.points.empty());
  941. for (std::size_t i = 1; i < a.points.size(); ++i)
  942. CHECK (a.points[i].tick >= a.points[i - 1].tick);
  943. }
  944. // imported routing has no cycles and valid destinations
  945. CHECK (song.mixerOrder().size() + 1 == song.mixer.size());
  946. for (auto& t : song.mixer)
  947. for (auto& s : t.sends)
  948. {
  949. ++sends;
  950. CHECK (s.target > 0 && s.target < (int) song.mixer.size());
  951. }
  952. if (! song.playlist.empty())
  953. ++withPlaylist;
  954. }
  955. catch (const flp::Error& e)
  956. {
  957. ++failures;
  958. std::printf (" FAILED %s: %s\n", entry.path().string().c_str(), e.what());
  959. }
  960. }
  961. CHECK (threeOscDecoded == threeOsc);
  962. std::printf (" Harmless: %d channels, %d decoded\n", harmless, harmlessDecoded);
  963. std::printf (" Sytrus: %d channels, %d decoded\n", sytrus, sytrusDecoded);
  964. for (const auto& [name, counter] : generators)
  965. {
  966. std::printf (" %s: %d channels, %d decoded\n", name.c_str(), counter.first, counter.second);
  967. CHECK (counter.second == counter.first);
  968. }
  969. std::printf (" Ogun spectra matching the Trumpet reference: %d\n", ogunTrumpet);
  970. CHECK (ogunTrumpet >= 1);
  971. // demo Gross Beat: the volume slot becomes the gate (those using an envelope slot get steps < 1)
  972. {
  973. int vocodexes = 0, vocodexSides = 0;
  974. int lovePhilterLinks[4] {}; // live links: cutoff, resonance; inside containers: cutoff, resonance
  975. int embeddedZones = 0, lovePhilters = 0, lovePhiltersRead = 0, lovePhiltersConverted = 0, gates = 0, shaped = 0, effectors = 0, patchers = 0, serial = 0, parallel = 0, generatorPatchers = 0;
  976. for (const auto& entry : std::filesystem::recursive_directory_iterator (std::filesystem::path (realFlpDir) / "Demo projects"))
  977. if (entry.path().extension() == ".flp")
  978. {
  979. std::ifstream in (entry.path(), std::ios::binary);
  980. const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  981. try
  982. {
  983. const auto project = flp::parseProject (file);
  984. for (const auto& insert : project.mixer)
  985. for (const auto& slot : insert.slots)
  986. if (slot.plugin == "Gross Beat")
  987. {
  988. const auto fx = lynx::effectFromFl (slot.plugin, slot.state);
  989. CHECK (fx && fx->kind == lynx::EffectKind::volumeGate);
  990. ++gates;
  991. if (fx && std::any_of (fx->params.begin(), fx->params.begin() + 32, [] (float v) { return v < 0.99f; }))
  992. ++shaped;
  993. }
  994. else if (slot.plugin == "Fruity Love Philter")
  995. {
  996. ++lovePhilters;
  997. lovePhiltersRead += lynx::parseLovePhilter (slot.state).has_value();
  998. if (const auto conv = lynx::lovePhilterEffects (slot.state))
  999. {
  1000. ++lovePhiltersConverted;
  1001. CHECK (! conv->slots.empty());
  1002. for (const auto& fx : conv->slots)
  1003. for (auto v : fx.params)
  1004. CHECK (std::isfinite (v) && v >= 0.0f && v <= 1.0f);
  1005. for (const auto& fx : conv->slots)
  1006. for (const auto& link : fx.links)
  1007. {
  1008. const auto& chain = fx.branches[(std::size_t) link.branch].chain;
  1009. CHECK (link.source < (int) chain.size() && chain[(std::size_t) link.target].kind == lynx::EffectKind::parametricEq);
  1010. lovePhilterLinks[2 + (link.param == lynx::peq::param (0, 3) ? 1 : 0)]++;
  1011. }
  1012. for (const auto& link : conv->links)
  1013. {
  1014. lovePhilterLinks[link.param == lynx::peq::param (0, 3) ? 1 : 0]++;
  1015. CHECK (link.curve.size() == 33);
  1016. for (auto v : link.curve)
  1017. CHECK (std::isfinite (v) && v >= 0.0f && v <= 1.0f);
  1018. }
  1019. }
  1020. }
  1021. else if (slot.plugin == "Vocodex")
  1022. {
  1023. const auto v = lynx::vocodexEffect (slot.state);
  1024. CHECK (v.has_value());
  1025. vocodexes += v.has_value();
  1026. vocodexSides += v && (v->modIn > 0 || v->carIn > 0);
  1027. }
  1028. else if (slot.plugin == "Effector")
  1029. effectors += lynx::effectFromFl (slot.plugin, slot.state).has_value();
  1030. else if (slot.plugin == "Patcher")
  1031. {
  1032. const auto graph = lynx::parsePatcher (slot.state);
  1033. CHECK (graph.has_value());
  1034. ++patchers;
  1035. if (graph && ! graph->serialChain.empty())
  1036. ++serial;
  1037. if (graph && graph->serialChain.empty() && graph->audio)
  1038. ++parallel;
  1039. }
  1040. for (const auto& c : project.channels)
  1041. if (c.pluginName == "DirectWave")
  1042. if (const auto program = lynx::directWaveProgram (c.pluginState))
  1043. for (const auto& wav : program->embeddedWav)
  1044. if (! wav.empty())
  1045. {
  1046. ++embeddedZones;
  1047. CHECK (wav.size() > 44 && std::memcmp (wav.data(), "RIFF", 4) == 0);
  1048. }
  1049. for (const auto& c : project.channels)
  1050. if (c.pluginName == "Patcher")
  1051. {
  1052. const auto graph = lynx::parsePatcher (c.pluginState);
  1053. CHECK (graph.has_value());
  1054. generatorPatchers += graph && graph->mainGenerator >= 0;
  1055. }
  1056. }
  1057. catch (const flp::Error&) {}
  1058. }
  1059. std::printf (" Gross Beat: %d slots, %d with gate; Effector: %d converted; Love Philter: %d, %d read\n", gates, shaped, effectors,
  1060. lovePhilters, lovePhiltersRead);
  1061. CHECK (lovePhiltersRead == lovePhilters && lovePhiltersConverted == lovePhilters);
  1062. std::printf (" Vocodex: %d converted, %d with side inputs\n", vocodexes, vocodexSides);
  1063. CHECK (vocodexes >= 9);
  1064. std::printf (" Love Philter live links: %d cutoff, %d resonance; in multi-unit containers: %d cutoff, %d resonance\n",
  1065. lovePhilterLinks[0], lovePhilterLinks[1], lovePhilterLinks[2], lovePhilterLinks[3]);
  1066. CHECK (lovePhilterLinks[2] + lovePhilterLinks[3] > 0);
  1067. std::printf (" DirectWave: %d zones with embedded audio\n", embeddedZones);
  1068. CHECK (embeddedZones == 12);
  1069. std::printf (" Patcher: %d in the mixer (%d serial, %d reduced to serial/parallel), %d as instrument with generator\n", patchers, serial,
  1070. parallel, generatorPatchers);
  1071. CHECK (gates == 0 || shaped > 0);
  1072. }
  1073. // Envelope Controller "Basic Sidechain" (Future House): drops on the note and returns to ~1 within ~1/3 s
  1074. {
  1075. const auto path = std::filesystem::path (realFlpDir) / "Demo projects" / "Demo songs" / "Asher Postman - Future House.flp";
  1076. if (std::filesystem::exists (path))
  1077. {
  1078. std::ifstream in (path, std::ios::binary);
  1079. const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1080. const auto song = lynx::importFlp (flp::parseProject (file));
  1081. const lynx::ChannelDef* controller = nullptr;
  1082. for (const auto& c : song.channels)
  1083. if (c.instrument == lynx::InstrumentKind::controller)
  1084. controller = &c;
  1085. CHECK (controller != nullptr);
  1086. if (controller != nullptr)
  1087. {
  1088. auto inst = lynx::makeInstrument (lynx::InstrumentKind::controller);
  1089. inst->prepare (48000.0);
  1090. inst->configure (*controller, song.bpm);
  1091. std::vector<float> l (480), r (480);
  1092. inst->render (l.data(), r.data(), 480, 1.0f, 1.0f);
  1093. inst->noteOn (60, 1.0f);
  1094. inst->render (l.data(), r.data(), 480, 1.0f, 1.0f); // 10 ms
  1095. const auto ducked = inst->controlOutput (0);
  1096. for (int i = 0; i < 100; ++i) // +1 s
  1097. inst->render (l.data(), r.data(), 480, 1.0f, 1.0f);
  1098. const auto recovered = inst->controlOutput (0);
  1099. std::printf (" Envelope Controller (Basic Sidechain): %.2f on the note, %.2f after 1 s\n", ducked, recovered);
  1100. CHECK (ducked < 0.3f && recovered > 0.9f);
  1101. }
  1102. }
  1103. }
  1104. // mutation fuzz: real states with flipped and truncated bytes must not crash the readers
  1105. {
  1106. std::map<std::string, std::vector<std::uint8_t>> samples; // one real blob per plugin
  1107. for (const auto& entry : std::filesystem::recursive_directory_iterator (std::filesystem::path (realFlpDir) / "Demo projects"))
  1108. {
  1109. if (entry.path().extension() != ".flp")
  1110. continue;
  1111. std::ifstream in (entry.path(), std::ios::binary);
  1112. const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1113. try
  1114. {
  1115. const auto project = flp::parseProject (file);
  1116. for (const auto& c : project.channels)
  1117. if (! c.pluginState.empty())
  1118. samples.emplace (c.pluginName, c.pluginState);
  1119. for (const auto& insert : project.mixer)
  1120. for (const auto& slot : insert.slots)
  1121. if (! slot.state.empty())
  1122. samples.emplace (slot.plugin, slot.state);
  1123. }
  1124. catch (const flp::Error&) {}
  1125. }
  1126. std::uint32_t seed = 12345;
  1127. auto rnd = [&seed] { seed = seed * 1664525u + 1013904223u; return seed >> 8; };
  1128. int mutations = 0;
  1129. for (const auto& [name, original] : samples)
  1130. for (int round = 0; round < 40; ++round)
  1131. {
  1132. auto blob = original;
  1133. if (round % 4 == 3 && ! blob.empty())
  1134. blob.resize (rnd() % blob.size()); // truncated
  1135. else
  1136. for (int k = 0; k < 1 + (int) (rnd() % 8) && ! blob.empty(); ++k)
  1137. blob[rnd() % blob.size()] = (std::uint8_t) rnd();
  1138. ++mutations;
  1139. lynx::SynthSettings synth;
  1140. float gain = 1.0f;
  1141. lynx::synthFromSytrus (blob, 120.0, synth, gain);
  1142. lynx::synthFromHarmor (blob, synth, gain);
  1143. lynx::synthFromGms (blob, 120.0, synth, gain);
  1144. lynx::synthFromOgun (blob, synth, gain);
  1145. lynx::synthFromMorphine (blob, synth, gain);
  1146. lynx::synthFromKepler (blob, synth, gain);
  1147. lynx::synthFromPoiZone (blob, synth, gain);
  1148. lynx::synthFromToxic (blob, synth, gain);
  1149. lynx::synthFromBassDrum (blob, synth, gain);
  1150. lynx::synthFromHarmless (blob, 120.0, synth, gain);
  1151. lynx::harmlessParams (blob);
  1152. lynx::parseEnvelopeController (blob);
  1153. lynx::parseKeyboardController (blob);
  1154. lynx::parseLovePhilter (blob);
  1155. lynx::parsePatcher (blob);
  1156. lynx::effectFromFl (name, blob);
  1157. lynx::fpcPads (blob);
  1158. lynx::directWaveProgram (blob);
  1159. CHECK (std::isfinite (gain) && std::isfinite (synth.cutoff));
  1160. }
  1161. std::printf (" mutation fuzz: %d blobs from %d plugins\n", mutations, (int) samples.size());
  1162. }
  1163. // WavPack (.wv) samples from FL packs: all decode, with finite, non-silent audio
  1164. {
  1165. int files = 0, decoded = 0, audible = 0;
  1166. double seconds = 0.0;
  1167. for (const auto& entry : std::filesystem::recursive_directory_iterator (std::filesystem::path (realFlpDir) / "Patches" / "Packs"))
  1168. if (entry.path().extension() == ".wv")
  1169. {
  1170. std::ifstream in (entry.path(), std::ios::binary);
  1171. const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1172. ++files;
  1173. lynx::DecodedAudio audio;
  1174. if (! lynx::decodeWavPack (file.data(), file.size(), audio))
  1175. continue;
  1176. ++decoded;
  1177. float peak = 0.0f;
  1178. bool finite = true;
  1179. for (const auto& ch : audio.channels)
  1180. for (auto v : ch)
  1181. {
  1182. finite = finite && std::isfinite (v);
  1183. peak = std::max (peak, std::abs (v));
  1184. }
  1185. CHECK (finite && peak <= 4.0f);
  1186. audible += peak > 1e-4f;
  1187. seconds += (double) audio.channels[0].size() / audio.sampleRate;
  1188. }
  1189. std::printf (" WavPack: %d .wv files, %d decoded, %d audible, %.0f s of audio\n", files, decoded, audible, seconds);
  1190. CHECK (decoded == files);
  1191. }
  1192. // native GMS presets (.gmsynth = the contents of 0xD5 without the "SSLF")
  1193. int gmsPresets = 0, gmsDecoded = 0;
  1194. const auto gmsFolder = std::filesystem::path (realFlpDir) / "Patches" / "Plugin presets" / "Generators" / "GMS";
  1195. if (std::filesystem::exists (gmsFolder))
  1196. for (const auto& entry : std::filesystem::recursive_directory_iterator (gmsFolder))
  1197. if (entry.path().extension() == ".gmsynth")
  1198. {
  1199. std::ifstream in (entry.path(), std::ios::binary);
  1200. std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1201. std::vector<std::uint8_t> blob { 'S', 'S', 'L', 'F' };
  1202. const auto n = (std::uint32_t) file.size();
  1203. blob.insert (blob.end(), reinterpret_cast<const std::uint8_t*> (&n), reinterpret_cast<const std::uint8_t*> (&n) + 4);
  1204. blob.insert (blob.end(), file.begin(), file.end());
  1205. lynx::SynthSettings gs;
  1206. float g = 1.0f;
  1207. ++gmsPresets;
  1208. if (lynx::synthFromGms (blob, 120.0, gs, g))
  1209. {
  1210. ++gmsDecoded;
  1211. CHECK (std::isfinite (g) && gs.cutoff >= 20.0f && std::isfinite (gs.pitchEnv.amount) && std::isfinite (gs.lfo[lynx::lfoPitch].period));
  1212. }
  1213. }
  1214. std::printf (" GMS presets: %d, %d decoded\n", gmsPresets, gmsDecoded);
  1215. // the synth's "FL presets" button: Sytrus/Harmor .fst and .gmsynth become synth settings
  1216. int presetFiles = 0, presetsRead = 0;
  1217. for (const auto* name : { "Sytrus", "Harmor", "GMS", "Harmless", "Ogun", "Sakura", "Fruit Kick", "Fruity DX10", "MiniSynth", "Kepler",
  1218. "PoiZone", "Toxic Biohazard", "BassDrum" })
  1219. {
  1220. const auto folder = std::filesystem::path (realFlpDir) / "Patches" / "Plugin presets" / "Generators" / name;
  1221. if (! std::filesystem::exists (folder))
  1222. continue;
  1223. for (const auto& entry : std::filesystem::recursive_directory_iterator (folder))
  1224. if (entry.path().extension() == ".fst" || entry.path().extension() == ".gmsynth")
  1225. {
  1226. std::ifstream in (entry.path(), std::ios::binary);
  1227. const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1228. ++presetFiles;
  1229. presetsRead += lynx::synthFromFlPreset (file).has_value();
  1230. }
  1231. }
  1232. std::printf (" FL synth presets: %d files, %d read\n", presetFiles, presetsRead);
  1233. CHECK (presetsRead >= presetFiles * 95 / 100);
  1234. CHECK (gmsDecoded == gmsPresets);
  1235. CHECK (sytrusDecoded == sytrus);
  1236. CHECK (harmlessDecoded == harmless && harmless > 100);
  1237. std::printf (" Harmless: %d states parsed for the engine, %d channels imported as Harmless\n", harmlessParsed, harmlessKind);
  1238. CHECK (harmlessParsed == harmless && harmlessKind >= harmless);
  1239. // 3x Osc channel presets shipped with FL (.fst): all become synth settings
  1240. int presets = 0, presetsDecoded = 0;
  1241. const auto presetDir = std::filesystem::path (realFlpDir) / "Patches" / "Channel presets" / "3x Osc";
  1242. if (std::filesystem::is_directory (presetDir))
  1243. for (auto& entry : std::filesystem::directory_iterator (presetDir))
  1244. if (entry.path().extension() == ".fst")
  1245. {
  1246. ++presets;
  1247. std::ifstream in (entry.path(), std::ios::binary);
  1248. std::vector<std::uint8_t> bytes ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  1249. if (auto synth = lynx::synthFromFlPreset (bytes))
  1250. {
  1251. ++presetsDecoded;
  1252. CHECK (synth->osc[0].level + synth->osc[1].level + (synth->am ? 0.0f : synth->osc[2].level) <= 1.001f);
  1253. }
  1254. }
  1255. std::printf (" %d 3x Osc presets, %d read\n", presets, presetsDecoded);
  1256. CHECK (presetsDecoded == presets);
  1257. // FL effect presets that become built-in effects
  1258. int fxPresets = 0, fxDecoded = 0;
  1259. for (auto kind : { lynx::EffectKind::parametricEq, lynx::EffectKind::limiter, lynx::EffectKind::reverb, lynx::EffectKind::delay,
  1260. lynx::EffectKind::utility })
  1261. for (const auto& plugin : lynx::flPluginsForEffect (kind))
  1262. {
  1263. const auto dir = std::filesystem::path (realFlpDir) / "Patches" / "Plugin presets" / "Effects" / plugin;
  1264. if (! std::filesystem::is_directory (dir))
  1265. continue;
  1266. for (auto& entry : std::filesystem::recursive_directory_iterator (dir))
  1267. if (entry.path().extension() == ".fst")
  1268. {
  1269. ++fxPresets;
  1270. std::ifstream in (entry.path(), std::ios::binary);
  1271. std::vector<std::uint8_t> bytes ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  1272. fxDecoded += lynx::effectFromFlPreset (bytes).has_value();
  1273. }
  1274. }
  1275. std::printf (" %d FL effect presets, %d read\n", fxPresets, fxDecoded);
  1276. CHECK (fxDecoded == fxPresets);
  1277. CHECK (wrappedParsed == wrapped);
  1278. std::printf (" %d plugins in Fruity Wrapper, %d read\n", wrapped, wrappedParsed);
  1279. std::printf (" %d markers, %d time signature changes, %d tracks with EQ\n", markers, signatures, trackEqs);
  1280. std::printf (" %d parametric EQs (%d with FL settings), %d reverbs (%d without dry)\n", peqSlots, peqShaped, reverbs, reverbsDryless);
  1281. std::printf (" DirectWave: %d channels, %d zones; FPC: %d projects, %d pad channels, %d pad notes\n", dwChannels, dwZones, fpcKits,
  1282. padChannels, padNotes);
  1283. CHECK (dwZones > 1000 && padChannels > 250 && padNotes > 500);
  1284. std::printf (" sliced channels (Slicer/Slicex): %d; embedded WAVs saved: %d\n", slicedChannels, embeddedSaved);
  1285. CHECK (slicedChannels >= 25 && embeddedSaved >= 10); // without decoding Ogg here, some loops have no duration
  1286. std::printf (" FL Keys (Grand Piano, 30 zones): %d channels\n", flKeysChannels);
  1287. CHECK (flKeysChannels >= 8);
  1288. CHECK (peqSlots > 1000 && peqShaped > 900 && reverbsDryless > 20 && reverbsLowCut > 250);
  1289. CHECK (markers > 300 && signatures > 60);
  1290. std::printf (" %d 3x Osc channels, %d decoded\n", threeOsc, threeOscDecoded);
  1291. std::printf (" %d .flp files read, %d with notes, %d with playlist, %d automations (%d with target), %d sends\n",
  1292. files, withNotes, withPlaylist, automations, automationsWithTarget, sends);
  1293. CHECK (files > 0);
  1294. CHECK (automations > 0 && sends > 0);
  1295. }
  1296. // ---------------------------------------------------------------------------
  1297. // Sequencer
  1298. TEST (pattern_toggle_step_and_length)
  1299. {
  1300. lynx::Pattern p;
  1301. CHECK (! p.hasStep (0, 4));
  1302. p.toggleStep (0, 4);
  1303. CHECK (p.hasStep (0, 4));
  1304. CHECK (p.notes.size() == 1 && p.notes[0].start == 4 * lynx::ticksPerStep);
  1305. CHECK (p.effectiveLength (4) == 4 * lynx::ppq); // one bar
  1306. p.toggleStep (1, 20); // second bar
  1307. CHECK (p.effectiveLength (4) == 8 * lynx::ppq);
  1308. p.toggleStep (0, 4);
  1309. CHECK (! p.hasStep (0, 4) && p.notes.size() == 1);
  1310. }
  1311. TEST (scheduler_places_events_at_exact_samples)
  1312. {
  1313. lynx::Pattern p;
  1314. p.toggleStep (0, 0);
  1315. p.toggleStep (0, 4); // tick 960 = 1 beat
  1316. const double sr = 48000.0, bpm = 120.0; // 1 beat = 0.5 s = 24000 samples
  1317. const auto tps = lynx::ticksPerSample (bpm, sr);
  1318. lynx::EventBuffer ev;
  1319. lynx::schedulePatternLoop (p, p.effectiveLength (4), 23900.0 * tps, 512, tps, ev);
  1320. // the beat-2 note starts at sample 24000 -> offset 100 in this block
  1321. int ons = 0;
  1322. for (auto& e : ev)
  1323. if (e.type == lynx::NoteEvent::Type::on)
  1324. {
  1325. ++ons;
  1326. CHECK (e.sampleOffset == 100);
  1327. }
  1328. CHECK (ons == 1);
  1329. }
  1330. TEST (scheduler_wraps_the_loop)
  1331. {
  1332. lynx::Pattern p;
  1333. p.toggleStep (2, 0);
  1334. const auto len = p.effectiveLength (4); // 3840 ticks
  1335. const double sr = 48000.0;
  1336. const auto tps = lynx::ticksPerSample (120.0, sr);
  1337. lynx::EventBuffer ev;
  1338. // block that crosses the loop end: starts 10 samples before
  1339. const auto start = (double) len - 10.0 * tps;
  1340. lynx::schedulePatternLoop (p, len, start, 64, tps, ev);
  1341. bool found = false;
  1342. for (auto& e : ev)
  1343. if (e.type == lynx::NoteEvent::Type::on && e.channel == 2)
  1344. {
  1345. found = true;
  1346. CHECK (e.sampleOffset == 10);
  1347. }
  1348. CHECK (found);
  1349. }
  1350. TEST (scheduler_off_before_on_at_same_sample)
  1351. {
  1352. lynx::Pattern p;
  1353. lynx::Note a;
  1354. a.start = 0; a.length = 240; a.channel = 0;
  1355. lynx::Note b = a;
  1356. b.start = 240;
  1357. p.notes = { a, b };
  1358. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  1359. lynx::EventBuffer ev;
  1360. lynx::schedulePatternLoop (p, p.effectiveLength (4), 200.0, 4000, tps, ev);
  1361. CHECK (ev.size() >= 2);
  1362. CHECK (ev[0].type == lynx::NoteEvent::Type::off);
  1363. CHECK (ev[1].type == lynx::NoteEvent::Type::on);
  1364. CHECK (ev[0].sampleOffset == ev[1].sampleOffset);
  1365. }
  1366. TEST (snapshot_exchange_hands_over_and_recycles)
  1367. {
  1368. struct Counted
  1369. {
  1370. int value;
  1371. int* alive;
  1372. Counted (int v, int* a) : value (v), alive (a) { ++*alive; }
  1373. ~Counted() { --*alive; }
  1374. };
  1375. int alive = 0;
  1376. {
  1377. lynx::SnapshotExchange<Counted> x;
  1378. CHECK (x.acquire() == nullptr);
  1379. x.publish (std::make_unique<Counted> (1, &alive));
  1380. CHECK (x.acquire()->value == 1);
  1381. x.publish (std::make_unique<Counted> (2, &alive));
  1382. x.publish (std::make_unique<Counted> (3, &alive)); // 2 was never read: freed immediately
  1383. CHECK (alive == 2);
  1384. CHECK (x.acquire()->value == 3);
  1385. CHECK (alive == 2); // 1 was returned, but only the UI frees it
  1386. x.collectGarbage();
  1387. CHECK (alive == 1);
  1388. // without collection, the return slots fill up and the audio side holds on to the current one
  1389. for (int i = 0; i < 20; ++i)
  1390. {
  1391. x.publish (std::make_unique<Counted> (10 + i, &alive));
  1392. CHECK (x.acquire() != nullptr);
  1393. }
  1394. }
  1395. CHECK (alive == 0);
  1396. }
  1397. TEST (rack_renderer_makes_sound_and_reuses_instruments)
  1398. {
  1399. auto song = lynx::Song::makeDefault();
  1400. song.bpm = 120.0;
  1401. const double sr = 48000.0;
  1402. auto state = lynx::RackState::build (song, nullptr, sr);
  1403. lynx::RackRenderer r;
  1404. r.prepare (sr);
  1405. std::vector<float> l (512), rr (512);
  1406. double tick = 0.0;
  1407. float peak = 0.0f;
  1408. int kicks = 0;
  1409. for (int block = 0; block < 93; ++block) // 47616 samples: just before 1 s
  1410. {
  1411. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  1412. for (auto& e : r.lastEvents())
  1413. if (e.type == lynx::NoteEvent::Type::on && e.channel == 0)
  1414. ++kicks;
  1415. for (int i = 0; i < 512; ++i)
  1416. {
  1417. CHECK (std::isfinite (l[(std::size_t) i]));
  1418. peak = std::max (peak, std::abs (l[(std::size_t) i]));
  1419. }
  1420. tick += 512 * lynx::ticksPerSample (song.bpm, sr);
  1421. }
  1422. CHECK (peak > 0.1f && peak < 4.0f);
  1423. CHECK (kicks == 2); // 120 BPM: beats at 0 and 0.5 s
  1424. // editing the song keeps the instruments of channels whose type didn't change
  1425. song.channels[4].instrument = lynx::InstrumentKind::kick;
  1426. auto next = lynx::RackState::build (song, state.get(), sr);
  1427. CHECK (next->instruments[0] == state->instruments[0]);
  1428. CHECK (next->instruments[4] != state->instruments[4]);
  1429. // stopping silences the synth and triggers no new notes
  1430. r.process (next.get(), false, tick, 512, l.data(), rr.data());
  1431. CHECK (r.lastEvents().size() == 0);
  1432. }
  1433. TEST (flp_import_maps_channels_and_rescales)
  1434. {
  1435. flp::Project p;
  1436. p.header.ppq = 96;
  1437. p.tempo = 150.0;
  1438. p.channels = { { 0, flp::ChannelType::sampler, "Kick 808", "", "", 1 },
  1439. { 1, flp::ChannelType::audioClip, "Vocal", "", "", 2 },
  1440. { 2, flp::ChannelType::instrument, "Lead", "FLEX", "", 3 } };
  1441. flp::Pattern pat;
  1442. pat.index = 1;
  1443. flp::Note n;
  1444. n.position = 96;
  1445. n.length = 0;
  1446. n.channel = 2;
  1447. n.key = 72;
  1448. n.velocity = 64;
  1449. pat.notes.push_back (n);
  1450. p.patterns.push_back (pat);
  1451. const auto s = lynx::importFlp (p);
  1452. CHECK (s.bpm == 150.0);
  1453. CHECK (s.channels.size() == 3); // audio clip channels stay in the rack, as in FL
  1454. CHECK (s.channels[0].instrument == lynx::InstrumentKind::kick);
  1455. CHECK (s.channels[1].instrument == lynx::InstrumentKind::audioClip);
  1456. CHECK (s.channels[2].instrument == lynx::InstrumentKind::synth);
  1457. CHECK (s.patterns.size() == 1);
  1458. CHECK (s.patterns[0].notes[0].start == lynx::ppq); // 96 @ PPQ 96 = 1 beat
  1459. CHECK (s.patterns[0].notes[0].channel == 2);
  1460. CHECK (s.patterns[0].notes[0].length == lynx::ticksPerStep); // step note
  1461. CHECK (std::abs (s.patterns[0].notes[0].velocity - 0.5f) < 1e-6f);
  1462. }
  1463. TEST (live_queue_is_fifo_and_bounded)
  1464. {
  1465. lynx::LiveEventQueue q;
  1466. lynx::NoteEvent e;
  1467. CHECK (! q.pop (e));
  1468. for (int i = 0; i < 10; ++i)
  1469. {
  1470. lynx::NoteEvent in;
  1471. in.key = i;
  1472. CHECK (q.push (in));
  1473. }
  1474. for (int i = 0; i < 10; ++i)
  1475. CHECK (q.pop (e) && e.key == i);
  1476. int pushed = 0;
  1477. while (q.push (e))
  1478. ++pushed;
  1479. CHECK (pushed == (int) lynx::LiveEventQueue::capacity - 1); // one slot stays free to tell full from empty
  1480. }
  1481. TEST (sampler_plays_pitched_one_shot)
  1482. {
  1483. // 1000-frame ramp sample: the position can be measured from the amplitude
  1484. auto data = std::make_shared<lynx::SampleData>();
  1485. data->sampleRate = 48000.0;
  1486. for (int i = 0; i < 1000; ++i)
  1487. data->left.push_back (1.0f);
  1488. auto sampler = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  1489. sampler->prepare (48000.0);
  1490. std::vector<float> l (2048, 0.0f), r (2048, 0.0f);
  1491. sampler->noteOn (60, 1.0f);
  1492. sampler->noteOff (60); // one-shot: noteOff doesn't cut
  1493. sampler->render (l.data(), r.data(), 2048, 1.0f, 1.0f);
  1494. int sounding = 0;
  1495. for (auto s : l)
  1496. sounding += s > 0.5f;
  1497. CHECK (sounding >= 995 && sounding <= 1000); // plays the whole sample at the original pitch
  1498. std::fill (l.begin(), l.end(), 0.0f);
  1499. sampler->noteOn (72, 1.0f); // one octave up: half the duration
  1500. sampler->render (l.data(), r.data(), 2048, 1.0f, 1.0f);
  1501. sounding = 0;
  1502. for (auto s : l)
  1503. sounding += s > 0.5f;
  1504. CHECK (sounding >= 495 && sounding <= 500);
  1505. CHECK (r[10] > 0.5f); // mono goes to both sides
  1506. auto silent = lynx::makeInstrument (lynx::InstrumentKind::sampler, nullptr);
  1507. silent->prepare (48000.0);
  1508. silent->noteOn (60, 1.0f);
  1509. std::fill (l.begin(), l.end(), 0.0f);
  1510. silent->render (l.data(), r.data(), 64, 1.0f, 1.0f);
  1511. CHECK (l[0] == 0.0f);
  1512. }
  1513. TEST (rack_live_notes_and_sample_provider)
  1514. {
  1515. lynx::Song song;
  1516. lynx::ChannelDef c;
  1517. c.name = "Smp";
  1518. c.instrument = lynx::InstrumentKind::sampler;
  1519. c.samplePath = "a.wav";
  1520. song.channels.push_back (c);
  1521. song.patterns.emplace_back();
  1522. int loads = 0;
  1523. auto provider = [&] (const std::string& path) -> std::shared_ptr<const lynx::SampleData> {
  1524. ++loads;
  1525. CHECK (path == "a.wav");
  1526. auto d = std::make_shared<lynx::SampleData>();
  1527. d->left.assign (4800, 0.5f);
  1528. return d;
  1529. };
  1530. auto state = lynx::RackState::build (song, nullptr, 48000.0, provider);
  1531. CHECK (loads == 1);
  1532. lynx::RackRenderer renderer;
  1533. renderer.prepare (48000.0);
  1534. lynx::LiveEventQueue live;
  1535. lynx::NoteEvent on;
  1536. on.channel = 0;
  1537. on.velocity = 1.0f;
  1538. live.push (on);
  1539. std::vector<float> l (256), r (256);
  1540. renderer.process (state.get(), false, 0.0, 256, l.data(), r.data(), &live); // stopped, but the live note plays
  1541. CHECK (l[0] > 0.1f);
  1542. // same sample: reused; different sample: reloaded
  1543. auto same = lynx::RackState::build (song, state.get(), 48000.0, provider);
  1544. CHECK (loads == 1 && same->instruments[0] == state->instruments[0]);
  1545. song.channels[0].samplePath = "b.wav";
  1546. auto other = lynx::RackState::build (song, state.get(), 48000.0, [&] (const std::string&) { ++loads; return nullptr; });
  1547. CHECK (loads == 2 && other->instruments[0] != state->instruments[0]);
  1548. }
  1549. TEST (flp_paths_resolve_and_samplers_import)
  1550. {
  1551. lynx::FlPathRoots roots { "C:\\FL", "C:\\FL\\Data", "D:\\User" };
  1552. CHECK (lynx::resolveFlPath ("%FLStudioFactoryData%\\Data\\x.wav", roots) == "C:\\FL\\Data\\x.wav");
  1553. CHECK (lynx::resolveFlPath ("%FLStudioData%\\Patches\\y.wav", roots) == "C:\\FL\\Data\\Patches\\y.wav");
  1554. CHECK (lynx::resolveFlPath ("%FLStudioUserData%\\z.wav", roots) == "D:\\User\\z.wav");
  1555. CHECK (lynx::resolveFlPath ("E:\\abs.wav", roots) == "E:\\abs.wav");
  1556. CHECK (lynx::resolveFlPath ("%FLStudioUserData%\\z.wav", {}) == "");
  1557. flp::Project p;
  1558. p.channels = { { 0, flp::ChannelType::sampler, "Kick", "", "%FLStudioData%\\k.wav", 1 },
  1559. { 1, flp::ChannelType::sampler, "Hat", "", "%FLStudioData%\\missing.wav", 1 } };
  1560. lynx::FlpImportOptions options;
  1561. options.roots = roots;
  1562. options.fileExists = [] (const std::string& path) { return path == "C:\\FL\\Data\\k.wav"; };
  1563. const auto s = lynx::importFlp (p, options);
  1564. CHECK (s.channels[0].instrument == lynx::InstrumentKind::sampler);
  1565. CHECK (s.channels[0].samplePath == "C:\\FL\\Data\\k.wav");
  1566. CHECK (s.channels[1].instrument == lynx::InstrumentKind::hat); // no file: built-in instrument
  1567. }
  1568. TEST (soft_clip_is_transparent_below_knee_and_bounded)
  1569. {
  1570. float s[] = { 0.5f, -0.89f, 1.5f, -3.0f, 0.95f };
  1571. lynx::softClip (s, 5);
  1572. CHECK (s[0] == 0.5f && s[1] == -0.89f);
  1573. CHECK (s[2] > 0.9f && s[2] <= 1.0f);
  1574. CHECK (s[3] < -0.9f && s[3] >= -1.0f);
  1575. CHECK (s[4] > 0.9f && s[4] < 0.95f);
  1576. }
  1577. TEST (song_scheduler_plays_clips_with_offset_and_cut)
  1578. {
  1579. lynx::Song s;
  1580. s.channels.resize (1);
  1581. auto& p = s.patterns.emplace_back();
  1582. for (int step : { 0, 4, 8, 12 }) // one note per beat
  1583. p.toggleStep (0, step);
  1584. // clip at bar 2 playing only the second half of the pattern (beats 3 and 4)
  1585. lynx::Clip c;
  1586. c.pattern = 0;
  1587. c.start = 4 * lynx::ppq;
  1588. c.length = 2 * lynx::ppq;
  1589. c.offset = 2 * lynx::ppq;
  1590. s.playlist.push_back (c);
  1591. CHECK (s.songLength() == 8 * lynx::ppq);
  1592. const double sr = 48000.0;
  1593. const auto tps = lynx::ticksPerSample (120.0, sr); // 1 beat = 24000 samples
  1594. lynx::EventBuffer ev;
  1595. // whole song in a single block (8 beats = 192000 samples)
  1596. lynx::scheduleSong (s, 0.0, 192000, tps, ev);
  1597. std::vector<int> ons;
  1598. for (auto& e : ev)
  1599. if (e.type == lynx::NoteEvent::Type::on)
  1600. ons.push_back (e.sampleOffset);
  1601. CHECK (ons.size() == 2);
  1602. CHECK (ons.size() == 2 && ons[0] == 4 * 24000 && ons[1] == 5 * 24000);
  1603. // crossing the loop: bar 1 is empty, so nothing at the start of the second pass
  1604. ev.clear();
  1605. lynx::scheduleSong (s, 8.0 * lynx::ppq - 100 * tps, 200, tps, ev);
  1606. CHECK (ev.size() == 0);
  1607. // a note longer than the clip is cut at the clip end
  1608. p.notes[3].length = 4 * lynx::ppq;
  1609. ev.clear();
  1610. lynx::scheduleSong (s, 0.0, 192000, tps, ev);
  1611. int lastOff = -1;
  1612. for (auto& e : ev)
  1613. if (e.type == lynx::NoteEvent::Type::off)
  1614. lastOff = std::max (lastOff, e.sampleOffset);
  1615. CHECK (lastOff == 6 * 24000);
  1616. }
  1617. TEST (remove_pattern_fixes_clips)
  1618. {
  1619. lynx::Song s;
  1620. s.patterns.resize (3);
  1621. s.currentPattern = 2;
  1622. s.playlist = { { 0, 0, 0, 100, 0 }, { 1, 0, 100, 100, 0 }, { 2, 1, 0, 100, 0 } };
  1623. s.removePattern (1);
  1624. CHECK (s.patterns.size() == 2);
  1625. CHECK (s.playlist.size() == 2 && s.playlist[1].pattern == 1);
  1626. CHECK (s.currentPattern == 1);
  1627. }
  1628. TEST (flp_import_3x_osc_state_and_channel_filter)
  1629. {
  1630. // new 3x Osc patch (version 14): osc 2 mix 64 coarse -12, osc 3 mix 32 coarse -24
  1631. std::vector<std::uint8_t> blob (460, 0);
  1632. auto put = [&] (std::size_t off, std::int32_t v) {
  1633. for (int b = 0; b < 4; ++b)
  1634. blob[off + (std::size_t) b] = (std::uint8_t) ((std::uint32_t) v >> (8 * b));
  1635. };
  1636. put (0x00, 14);
  1637. put (0x08, 3); // osc 1 saw
  1638. put (0x10, 7); // osc 1 fine +7
  1639. put (0x04, -32); // osc 1 pan -0.5
  1640. put (0x1C, 64); // osc 2 mix
  1641. put (0x28, -12); // osc 2 coarse
  1642. put (0x38, 32); // osc 3 mix
  1643. put (0x40, 2); // osc 3 square
  1644. put (0x44, -19); // osc 3 coarse: -1 octave and -7 semitones
  1645. lynx::SynthSettings s;
  1646. CHECK (lynx::synthFrom3xOsc (blob, s));
  1647. 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);
  1648. CHECK (s.osc[0].wave == lynx::Waveform::saw && s.osc[0].detune == 7.0f && s.osc[0].pan == -0.5f);
  1649. CHECK (s.osc[1].wave == lynx::Waveform::sine && s.osc[1].octave == -1 && s.osc[1].semitones == 0);
  1650. CHECK (s.osc[2].wave == lynx::Waveform::square && s.osc[2].octave == -1 && s.osc[2].semitones == -7);
  1651. CHECK (! lynx::synthFrom3xOsc (std::vector<std::uint8_t> (40, 0), s));
  1652. // channel filter: open by default; LP with Mod X 128 ~ 2.71 kHz; Fast LP with Mod X 128 ~ 280 Hz
  1653. float hz = 0.0f, res = 1.0f;
  1654. int mode = -1;
  1655. lynx::synthFilterFromChannel (256, 0, 0, hz, res, mode);
  1656. CHECK (hz >= 19999.0f && res == 0.0f);
  1657. lynx::synthFilterFromChannel (128, 0, 1, hz, res, mode);
  1658. CHECK (std::abs (hz - 2710.0f) < 30.0f && res == 0.0f);
  1659. lynx::synthFilterFromChannel (128, 0, 0, hz, res, mode);
  1660. CHECK (hz > 240.0f && hz < 320.0f);
  1661. lynx::synthFilterFromChannel (128, 256, 1, hz, res, mode);
  1662. CHECK (res > 0.8f);
  1663. CHECK (mode == 0);
  1664. lynx::synthFilterFromChannel (64, 0, 3, hz, res, mode); // high-pass at ~840 Hz
  1665. CHECK (mode == 2 && std::abs (hz - 840.0f) < 40.0f);
  1666. lynx::synthFilterFromChannel (128, 0, 2, hz, res, mode); // band-pass
  1667. CHECK (mode == 1);
  1668. }
  1669. TEST (synth_pitch_and_filter_envelopes)
  1670. {
  1671. auto render = [] (const lynx::SynthSettings& s, int frames) {
  1672. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  1673. inst->prepare (48000.0);
  1674. lynx::ChannelDef c;
  1675. c.synth = s;
  1676. inst->configure (c, 120.0);
  1677. inst->noteOn (45, 1.0f); // A2 = 110 Hz
  1678. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  1679. inst->render (l.data(), r.data(), frames, 1.0f, 1.0f);
  1680. return l;
  1681. };
  1682. auto crossings = [] (const std::vector<float>& b, int from, int to) {
  1683. int n = 0;
  1684. for (int i = from + 1; i < to; ++i)
  1685. n += (b[(std::size_t) i - 1] < 0.0f) != (b[(std::size_t) i] < 0.0f);
  1686. return n;
  1687. };
  1688. // 3x Osc "kick": sine with a +24 st pitch envelope falling fast
  1689. lynx::SynthSettings kick;
  1690. kick.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  1691. kick.cutoff = 20000.0f;
  1692. kick.pitchEnv = { 24.0f, 0.0f, 0.0f, 0.05f, 0.0f, 0.05f };
  1693. const auto k = render (kick, 48000);
  1694. const auto early = crossings (k, 0, 2400); // first 50 ms: well above 110 Hz
  1695. const auto late = crossings (k, 24000, 48000); // then back to 110 Hz (~110 crossings in 0.5 s)
  1696. CHECK (early > 20); // +24 st ramp over 50 ms: ~2.2x the average frequency (11 crossings without envelope)
  1697. CHECK (std::abs (late - 110) < 4);
  1698. // cutoff envelope: saw closed at 200 Hz opens +5 octaves on attack and closes again
  1699. lynx::SynthSettings pluck;
  1700. pluck.cutoff = 200.0f;
  1701. pluck.filterEnv = { 5.0f, 0.0f, 0.0f, 0.1f, 0.0f, 0.1f };
  1702. const auto p = render (pluck, 48000);
  1703. auto hf = [&] (int from, int to) { // energy of the difference (highs)
  1704. double e = 0.0;
  1705. for (int i = from + 1; i < to; ++i)
  1706. e += std::pow ((double) p[(std::size_t) i] - p[(std::size_t) i - 1], 2.0);
  1707. return e;
  1708. };
  1709. CHECK (hf (0, 2400) > 4.0 * hf (40000, 42400));
  1710. // Toxic Biohazard's envelope (REA_rodada33 §2): exponential towards 5 clipped at 1, so the cutoff is still near
  1711. // its base early in the attack, fully open at A = 0.2 s and back down after the exponential decay
  1712. lynx::SynthSettings toxic = pluck;
  1713. toxic.filterEnv = { 5.0f, 0.2f, 0.0f, 0.1f, 0.0f, 0.1f, 1 };
  1714. const auto t = render (toxic, 48000);
  1715. auto thf = [&] (int from, int to) {
  1716. double e = 0.0;
  1717. for (int i = from + 1; i < to; ++i)
  1718. e += std::pow ((double) t[(std::size_t) i] - t[(std::size_t) i - 1], 2.0);
  1719. return e;
  1720. };
  1721. CHECK (thf (9000, 9600) > 4.0 * thf (300, 900));
  1722. CHECK (thf (9000, 9600) > 4.0 * thf (40000, 40600));
  1723. }
  1724. TEST (synth_mono_reuses_the_sounding_voice)
  1725. {
  1726. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  1727. inst->prepare (48000.0);
  1728. lynx::ChannelDef c;
  1729. c.synth.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  1730. c.synth.cutoff = 20000.0f;
  1731. c.synth.mono = true;
  1732. inst->configure (c, 120.0);
  1733. std::vector<float> l (48000), r (48000);
  1734. inst->noteOn (57, 1.0f);
  1735. inst->render (l.data(), r.data(), 4800, 1.0f, 1.0f);
  1736. inst->noteOn (69, 1.0f); // A4 takes over the A3 voice: only one note sounding
  1737. inst->render (l.data() + 4800, r.data() + 4800, 43200, 1.0f, 1.0f);
  1738. int crossings = 0;
  1739. float peak = 0.0f;
  1740. for (std::size_t i = 24001; i < 48000; ++i)
  1741. {
  1742. crossings += (l[i - 1] < 0.0f) != (l[i] < 0.0f);
  1743. peak = std::max (peak, std::abs (l[i]));
  1744. }
  1745. CHECK (std::abs (crossings - 440) < 4); // 0.5 s of 440 Hz, without the A3 underneath
  1746. CHECK (peak < 0.35f); // one voice (0.3 level), not two summed
  1747. // no click on the handover: the jump between neighbouring samples stays sine-sized
  1748. float jump = 0.0f;
  1749. for (std::size_t i = 4790; i < 4810; ++i)
  1750. jump = std::max (jump, std::abs (l[i] - l[i - 1]));
  1751. CHECK (jump < 0.05f);
  1752. }
  1753. TEST (synth_porta_glides_and_am_modulates)
  1754. {
  1755. auto make = [] (const lynx::SynthSettings& s) {
  1756. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  1757. inst->prepare (48000.0);
  1758. lynx::ChannelDef c;
  1759. c.synth = s;
  1760. inst->configure (c, 120.0);
  1761. return inst;
  1762. };
  1763. auto crossings = [] (const std::vector<float>& b, std::size_t from, std::size_t to) {
  1764. int n = 0;
  1765. for (auto i = from + 1; i < to; ++i)
  1766. n += (b[i - 1] < 0.0f) != (b[i] < 0.0f);
  1767. return n;
  1768. };
  1769. // mono + 1-beat porta (0.5 s at 120 BPM): from A3 to A4, halfway ~E4 (329.6 Hz)
  1770. lynx::SynthSettings s;
  1771. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  1772. s.cutoff = 20000.0f;
  1773. s.mono = true;
  1774. s.porta = true;
  1775. s.portaBeats = 1.0f;
  1776. auto inst = make (s);
  1777. std::vector<float> l (96000), r (96000);
  1778. inst->noteOn (57, 1.0f);
  1779. inst->render (l.data(), r.data(), 4800, 1.0f, 1.0f);
  1780. inst->noteOn (69, 1.0f);
  1781. inst->render (l.data() + 4800, r.data() + 4800, 91200, 1.0f, 1.0f);
  1782. const auto middle = crossings (l, 4800 + 12000 - 2400, 4800 + 12000 + 2400); // 0.1 s around 0.25 s
  1783. CHECK (std::abs (middle - 66) < 6); // ~330 Hz * 0.1 s * 2
  1784. CHECK (std::abs (crossings (l, 48000, 96000) - 880) < 4); // reached A4 (1 s = 880 crossings)
  1785. // AM: osc 3 at level 1.0, slow sine, modulates osc 1 (the average level drops, the sum doesn't gain osc 3)
  1786. lynx::SynthSettings am;
  1787. am.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  1788. am.osc[2] = { lynx::Waveform::sine, -3, 0.0f, 1.0f };
  1789. am.cutoff = 20000.0f;
  1790. am.am = true;
  1791. auto modulated = make (am);
  1792. modulated->noteOn (69, 1.0f);
  1793. std::fill (l.begin(), l.end(), 0.0f);
  1794. modulated->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  1795. float peak = 0.0f;
  1796. for (std::size_t i = 4800; i < 48000; ++i)
  1797. peak = std::max (peak, std::abs (l[i]));
  1798. CHECK (peak > 0.45f && peak < 0.65f); // 0.3 · (1 + 1) at most: (1 − o3) goes up to 2
  1799. }
  1800. TEST (channel_lfo_vibrato_and_tremolo)
  1801. {
  1802. auto render = [] (const lynx::SynthSettings& s) {
  1803. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  1804. inst->prepare (48000.0);
  1805. lynx::ChannelDef c;
  1806. c.synth = s;
  1807. inst->configure (c, 120.0);
  1808. inst->noteOn (69, 1.0f);
  1809. std::vector<float> l (48000), r (48000);
  1810. inst->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  1811. return l;
  1812. };
  1813. lynx::SynthSettings s;
  1814. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  1815. s.cutoff = 20000.0f;
  1816. // tremolo: 100% volume LFO at 4 Hz (0.25 s period) -> the amplitude envelope goes from ~0 to ~2x
  1817. auto tremolo = s;
  1818. tremolo.lfo[lynx::lfoVolume] = { 1.0f, 0.25f, false, 0, 0.0f, 0.0f };
  1819. const auto t = render (tremolo);
  1820. float lowest = 1.0f, highest = 0.0f;
  1821. for (std::size_t w = 4800; w + 480 <= 48000; w += 480) // 10 ms windows (4.4 cycles of 440 Hz)
  1822. {
  1823. float peak = 0.0f;
  1824. for (auto i = w; i < w + 480; ++i)
  1825. peak = std::max (peak, std::abs (t[i]));
  1826. lowest = std::min (lowest, peak);
  1827. highest = std::max (highest, peak);
  1828. }
  1829. CHECK (lowest < 0.08f && highest > 0.5f);
  1830. // synced vibrato: ±1 semitone, 1-beat period (0.5 s at 120 BPM); the average stays at 440 Hz
  1831. auto vibrato = s;
  1832. vibrato.lfo[lynx::lfoPitch] = { 1.0f, 1.0f, true, 0, 0.0f, 0.0f };
  1833. const auto v = render (vibrato);
  1834. int crossings = 0;
  1835. for (std::size_t i = 1; i < 48000; ++i)
  1836. crossings += (v[i - 1] < 0.0f) != (v[i] < 0.0f);
  1837. CHECK (std::abs (crossings - 880) < 12);
  1838. int firstQuarter = 0; // first quarter of the cycle: rising sine -> higher than 440
  1839. for (std::size_t i = 1; i < 6000; ++i)
  1840. firstQuarter += (v[i - 1] < 0.0f) != (v[i] < 0.0f);
  1841. CHECK (firstQuarter > 112);
  1842. }
  1843. TEST (sampler_porta_glides_from_previous_note)
  1844. {
  1845. auto data = std::make_shared<lynx::SampleData>();
  1846. data->sampleRate = 48000.0;
  1847. data->left.resize (96000);
  1848. for (std::size_t i = 0; i < data->left.size(); ++i)
  1849. data->left[i] = 0.5f * (float) std::sin (6.283185307 * 220.0 * (double) i / 48000.0);
  1850. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  1851. inst->prepare (48000.0);
  1852. lynx::ChannelDef c;
  1853. c.sampler.cut = true;
  1854. c.sampler.porta = true;
  1855. c.sampler.portaBeats = 1.0f; // 0.5 s at 120 BPM
  1856. inst->configure (c, 120.0);
  1857. std::vector<float> l (24000), r (24000);
  1858. inst->noteOn (60, 1.0f);
  1859. inst->render (l.data(), r.data(), 2400, 1.0f, 1.0f);
  1860. inst->noteOn (72, 1.0f); // one octave up: starts at 220 Hz and rises
  1861. std::fill (l.begin(), l.end(), 0.0f);
  1862. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  1863. auto crossings = [&] (std::size_t from, std::size_t to) {
  1864. int n = 0;
  1865. for (auto i = from + 1; i < to; ++i)
  1866. n += (l[i - 1] < 0.0f) != (l[i] < 0.0f);
  1867. return n;
  1868. };
  1869. const auto start = crossings (600, 2400); // 37.5 ms still near 220 Hz: ~17 crossings (440 Hz would give 33)
  1870. const auto end = crossings (21600, 24000); // 50 ms at the end of the glide: near 440 Hz (~44; 220 Hz would give 22)
  1871. CHECK (start < 22);
  1872. CHECK (end > 36);
  1873. }
  1874. TEST (zoned_sampler_picks_zone_by_key_and_velocity)
  1875. {
  1876. auto sine = [] (double hz, float amp) {
  1877. auto d = std::make_shared<lynx::SampleData>();
  1878. d->sampleRate = 48000.0;
  1879. d->left.resize (48000);
  1880. for (std::size_t i = 0; i < d->left.size(); ++i)
  1881. d->left[i] = amp * (float) std::sin (6.283185307 * hz * (double) i / 48000.0);
  1882. return d;
  1883. };
  1884. // lows: 220 Hz sine recorded as A3 (57), up to key 69; highs: 880 Hz as A5 (81)
  1885. // hard layer on the highs: same tuning, louder
  1886. std::vector<lynx::LoadedZone> zones {
  1887. { { "graves.wav", 57, 0, 69, 0, 127, 0.0f, 1.0f }, sine (220.0, 0.5f) },
  1888. { { "agudos.wav", 81, 70, 127, 0, 99, 0.0f, 1.0f }, sine (880.0, 0.25f) },
  1889. { { "agudos forte.wav", 81, 70, 127, 100, 127, 0.0f, 1.0f }, sine (880.0, 0.9f) },
  1890. };
  1891. auto inst = lynx::makeZonedSampler (zones);
  1892. inst->prepare (48000.0);
  1893. inst->configure (lynx::ChannelDef {}, 120.0);
  1894. auto play = [&] (int key, float velocity) {
  1895. inst->allNotesOff();
  1896. std::vector<float> l (24000), r (24000);
  1897. inst->render (l.data(), r.data(), 2000, 1.0f, 1.0f); // let the old voices die out
  1898. std::fill (l.begin(), l.end(), 0.0f);
  1899. inst->noteOn (key, velocity);
  1900. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  1901. int crossings = 0;
  1902. float peak = 0.0f;
  1903. for (std::size_t i = 1; i < 24000; ++i)
  1904. {
  1905. crossings += (l[i - 1] < 0.0f) != (l[i] < 0.0f);
  1906. peak = std::max (peak, std::abs (l[i]));
  1907. }
  1908. return std::pair { crossings, peak };
  1909. };
  1910. const auto low = play (69, 0.5f); // A4 from root A3: 440 Hz -> 440 crossings in 0.5 s
  1911. CHECK (std::abs (low.first - 440) < 4);
  1912. const auto soft = play (81, 0.5f); // high zone at the root: 880 Hz
  1913. CHECK (std::abs (soft.first - 880) < 6);
  1914. const auto hard = play (81, 0.95f); // high velocity: hard layer
  1915. CHECK (hard.second > soft.second * 2.0f);
  1916. // overlapping layers round-robin: two identical zones at different levels, notes alternate
  1917. auto rr = lynx::makeZonedSampler ({ { { "a.wav", 60 }, sine (440.0, 0.2f) }, { { "b.wav", 60 }, sine (440.0, 0.8f) } });
  1918. rr->prepare (48000.0);
  1919. rr->configure (lynx::ChannelDef {}, 120.0);
  1920. float peaks[2] {};
  1921. for (int k = 0; k < 2; ++k)
  1922. {
  1923. rr->allNotesOff();
  1924. std::vector<float> l (4800), r (4800);
  1925. rr->render (l.data(), r.data(), 2000, 1.0f, 1.0f);
  1926. std::fill (l.begin(), l.end(), 0.0f);
  1927. rr->noteOn (60, 1.0f);
  1928. rr->render (l.data(), r.data(), 4800, 1.0f, 1.0f);
  1929. for (auto v : l)
  1930. peaks[k] = std::max (peaks[k], std::abs (v));
  1931. }
  1932. CHECK (std::abs (peaks[0] - peaks[1]) > 0.3f);
  1933. }
  1934. TEST (zoned_sampler_loops_while_held)
  1935. {
  1936. // 0.1 s sample with a loop in the middle: holding the note it keeps sounding well past the end of the file;
  1937. // on release, it leaves the loop and ends
  1938. auto data = std::make_shared<lynx::SampleData>();
  1939. data->sampleRate = 48000.0;
  1940. data->left.resize (4800);
  1941. for (std::size_t i = 0; i < data->left.size(); ++i)
  1942. data->left[i] = 0.5f * (float) std::sin (6.283185307 * 480.0 * (double) i / 48000.0); // 100 frames per cycle
  1943. lynx::SampleZone zone { "loop.wav", 60 };
  1944. zone.loopStart = 1000;
  1945. zone.loopEnd = 3000;
  1946. zone.loopMode = 2;
  1947. auto inst = lynx::makeZonedSampler ({ { zone, data } });
  1948. inst->prepare (48000.0);
  1949. lynx::ChannelDef c;
  1950. c.sampler.release = 0.01f;
  1951. inst->configure (c, 120.0);
  1952. inst->noteOn (60, 1.0f);
  1953. std::vector<float> l (48000), r (48000);
  1954. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f); // 0.5 s held
  1955. float held = 0.0f;
  1956. for (std::size_t i = 20000; i < 24000; ++i)
  1957. held = std::max (held, std::abs (l[i]));
  1958. CHECK (held > 0.3f);
  1959. inst->noteOff (60);
  1960. inst->render (l.data() + 24000, r.data() + 24000, 24000, 1.0f, 1.0f);
  1961. float after = 0.0f;
  1962. for (std::size_t i = 40000; i < 48000; ++i)
  1963. after = std::max (after, std::abs (l[i]));
  1964. CHECK (after == 0.0f);
  1965. }
  1966. TEST (global_lfo_follows_song_position)
  1967. {
  1968. // global volume LFO (1-beat period): a note mid-cycle starts mid-wave; the
  1969. // same note with a per-note LFO starts at phase 0
  1970. auto first = [] (bool global, double songTicks) {
  1971. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  1972. inst->prepare (48000.0);
  1973. lynx::ChannelDef c;
  1974. c.synth.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  1975. c.synth.cutoff = 20000.0f;
  1976. c.synth.lfo[lynx::lfoVolume] = { 1.0f, 1.0f, true, 2, 0.0f, 0.0f, global }; // pulse: +1 in the first half
  1977. inst->configure (c, 120.0);
  1978. inst->setSongPosition (songTicks);
  1979. inst->noteOn (69, 1.0f);
  1980. std::vector<float> l (4800), r (4800);
  1981. inst->render (l.data(), r.data(), 4800, 1.0f, 1.0f);
  1982. float peak = 0.0f;
  1983. for (std::size_t i = 2400; i < 4800; ++i)
  1984. peak = std::max (peak, std::abs (l[i]));
  1985. return peak;
  1986. };
  1987. // mid-cycle (phase 0.6) the pulse is at −1: volume ~0; per note (phase 0) it is at +1: ~2x
  1988. const auto globalLate = first (true, 0.6 * lynx::ppq);
  1989. const auto perNote = first (false, 0.6 * lynx::ppq);
  1990. CHECK (globalLate < 0.05f);
  1991. CHECK (perNote > 0.4f);
  1992. }
  1993. TEST (sampler_channel_filter_darkens_and_bypasses_when_open)
  1994. {
  1995. // white noise in the sampler: with a 300 Hz cutoff the energy drops a lot; open passes unchanged
  1996. auto data = std::make_shared<lynx::SampleData>();
  1997. data->sampleRate = 48000.0;
  1998. data->left.resize (48000);
  1999. std::uint32_t seed = 7;
  2000. for (auto& v : data->left)
  2001. {
  2002. seed = seed * 1664525u + 1013904223u;
  2003. v = ((float) (seed >> 8) / 16777216.0f - 0.5f);
  2004. }
  2005. data->right = data->left;
  2006. auto energy = [&] (float cutoff) {
  2007. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  2008. inst->prepare (48000.0);
  2009. lynx::ChannelDef c;
  2010. c.sampler.cutoff = cutoff;
  2011. inst->configure (c, 120.0);
  2012. inst->noteOn (60, 1.0f);
  2013. std::vector<float> l (24000), r (24000);
  2014. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  2015. double e = 0.0;
  2016. for (auto v : l)
  2017. e += (double) v * v;
  2018. return e;
  2019. };
  2020. const auto open = energy (20000.0f), dark = energy (300.0f);
  2021. {
  2022. // high-pass at 10 kHz: also removes most of the noise energy, but from the other side
  2023. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  2024. inst->prepare (48000.0);
  2025. lynx::ChannelDef hp;
  2026. hp.sampler.cutoff = 10000.0f;
  2027. hp.sampler.filterType = 2;
  2028. inst->configure (hp, 120.0);
  2029. inst->noteOn (60, 1.0f);
  2030. std::vector<float> l (24000), r (24000);
  2031. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  2032. double e = 0.0, lowE = 0.0;
  2033. float lp = 0.0f;
  2034. for (auto v : l)
  2035. {
  2036. e += (double) v * v;
  2037. lp += 0.01f * (v - lp); // crude low-pass: almost nothing should remain below
  2038. lowE += (double) lp * lp;
  2039. }
  2040. CHECK (e > 10.0 && e < 0.7 * energy (20000.0f));
  2041. CHECK (lowE < e * 0.01);
  2042. }
  2043. CHECK (open > 100.0);
  2044. CHECK (dark < open * 0.05);
  2045. // +12 st pitch envelope with sustain 1: the sample runs at double speed
  2046. // and ends in half the time (1 s of sample -> 0.5 s)
  2047. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  2048. inst->prepare (48000.0);
  2049. lynx::ChannelDef c;
  2050. c.sampler.pitchEnv = { 12.0f, 0.0f, 0.0f, 0.1f, 1.0f, 0.1f };
  2051. inst->configure (c, 120.0);
  2052. inst->noteOn (60, 1.0f);
  2053. std::vector<float> l (48000), r (48000);
  2054. inst->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  2055. float tail = 0.0f, body = 0.0f;
  2056. for (std::size_t i = 20000; i < 23000; ++i)
  2057. body = std::max (body, std::abs (l[i]));
  2058. for (std::size_t i = 25000; i < 48000; ++i)
  2059. tail = std::max (tail, std::abs (l[i]));
  2060. CHECK (body > 0.1f);
  2061. CHECK (tail == 0.0f);
  2062. }
  2063. TEST (synth_oscillator_pan_and_semitones)
  2064. {
  2065. auto render = [] (lynx::SynthSettings s, std::vector<float>& l, std::vector<float>& r) {
  2066. auto synth = lynx::makeInstrument (lynx::InstrumentKind::synth);
  2067. synth->prepare (48000.0);
  2068. lynx::ChannelDef c;
  2069. c.synth = s;
  2070. synth->configure (c, 120.0);
  2071. synth->noteOn (69, 1.0f);
  2072. l.assign (24000, 0.0f);
  2073. r.assign (24000, 0.0f);
  2074. synth->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  2075. };
  2076. lynx::SynthSettings s;
  2077. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f, 7, 1.0f }; // a fifth up, fully right
  2078. s.cutoff = 20000.0f;
  2079. std::vector<float> l, r;
  2080. render (s, l, r);
  2081. float peakL = 0.0f, peakR = 0.0f;
  2082. int crossings = 0;
  2083. for (std::size_t i = 4800; i < 24000; ++i)
  2084. {
  2085. peakL = std::max (peakL, std::abs (l[i]));
  2086. peakR = std::max (peakR, std::abs (r[i]));
  2087. crossings += (r[i - 1] < 0.0f) != (r[i] < 0.0f);
  2088. }
  2089. CHECK (peakL < 1e-4f && peakR > 0.1f);
  2090. // 440 * 2^(7/12) = 659.3 Hz; 0.4 s = 263.7 cycles = ~527 crossings
  2091. CHECK (std::abs (crossings - 527) < 6);
  2092. }
  2093. TEST (fl_wrapper_state_parses_records_and_vst3_state)
  2094. {
  2095. // Fruity Wrapper blob (version 12): VST3 generator type, class ID, name, path and state
  2096. std::vector<std::uint8_t> blob;
  2097. 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))); };
  2098. auto record = [&] (std::vector<std::uint8_t>& b, std::uint32_t id, const std::vector<std::uint8_t>& payload) {
  2099. u32 (b, id);
  2100. u32 (b, (std::uint32_t) payload.size());
  2101. u32 (b, 0);
  2102. b.insert (b.end(), payload.begin(), payload.end());
  2103. };
  2104. auto bytes = [] (const std::string& s) { return std::vector<std::uint8_t> (s.begin(), s.end()); };
  2105. std::vector<std::uint8_t> vst3State;
  2106. u32 (vst3State, 1);
  2107. record (vst3State, 1, std::vector<std::uint8_t> (64, 0));
  2108. record (vst3State, 3, bytes ("COMPONENTE"));
  2109. record (vst3State, 2, bytes ("CONTROLADOR"));
  2110. // record 4: 3 slots → ParamIDs 700, −1 (empty), 0xFFFFFF01
  2111. std::vector<std::uint8_t> slots;
  2112. for (auto v : { 3u, 700u, 0xFFFFFFFFu, 0xFFFFFF01u })
  2113. u32 (slots, v);
  2114. record (vst3State, 4, slots);
  2115. u32 (blob, 12);
  2116. record (blob, 0x01, std::vector<std::uint8_t> (20, 0xFF));
  2117. record (blob, 0x32, { 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });
  2118. std::vector<std::uint8_t> cid;
  2119. for (int i = 0; i < 16; ++i)
  2120. cid.push_back ((std::uint8_t) (0xA0 + i));
  2121. record (blob, 0x34, cid);
  2122. record (blob, 0x36, bytes ("Surge XT"));
  2123. record (blob, 0x37, bytes ("C:/Program Files/Common Files/VST3/Surge XT.vst3"));
  2124. record (blob, 0x35, vst3State);
  2125. lynx::ForeignPlugin p;
  2126. CHECK (lynx::parseFlWrapper (blob, p));
  2127. CHECK (p.format == lynx::ForeignPlugin::Format::vst3);
  2128. CHECK (p.hasClassId && p.classId[0] == 0xA0 && p.classId[15] == 0xAF);
  2129. CHECK (p.name == "Surge XT" && p.path.find ("Surge XT.vst3") != std::string::npos);
  2130. std::vector<std::uint8_t> component, controller;
  2131. CHECK (lynx::splitFlVst3State (p.state, component, controller));
  2132. CHECK (component == bytes ("COMPONENTE") && controller == bytes ("CONTROLADOR"));
  2133. const auto saved = lynx::flVst3ParamSlots (p.state);
  2134. CHECK (saved == (std::vector<std::int32_t> { 700, -1, (std::int32_t) 0xFFFFFF01u }));
  2135. // FL's slot assignment: saved slots keep their ParamID wherever it now sits; the empty slot stays empty;
  2136. // a vanished ParamID (0xFFFFFF01) leaves its slot dead; parameters without a slot get slots 3, 4… in list order
  2137. const auto positions = lynx::flVst3SlotPositions (saved, { 5u, 700u, 9u });
  2138. CHECK (positions == (std::vector<int> { 1, -1, -1, 0, 2 }));
  2139. CHECK (lynx::flVst3SlotPositions ({}, { 5u, 6u }) == (std::vector<int> { 0, 1 })); // new instance: slot = position
  2140. // version out of range or no type: not a usable wrapper
  2141. blob[0] = 13;
  2142. CHECK (! lynx::parseFlWrapper (blob, p));
  2143. CHECK (! lynx::parseFlWrapper ({ 12, 0, 0, 0 }, p));
  2144. }
  2145. TEST (schedule_index_matches_full_scan)
  2146. {
  2147. // random song (long notes, swing, clips with offset); indexed scheduling must yield
  2148. // exactly the same events as the full scan, including in the block that wraps around
  2149. lynx::Song s = lynx::Song::makeDefault();
  2150. s.swing = 0.6f;
  2151. std::uint32_t seed = 12345;
  2152. auto rnd = [&] (int n) { seed = seed * 1664525u + 1013904223u; return (int) ((seed >> 8) % (std::uint32_t) n); };
  2153. s.patterns.resize (3);
  2154. for (auto& p : s.patterns)
  2155. {
  2156. p.notes.clear();
  2157. for (int i = 0; i < 60; ++i)
  2158. {
  2159. lynx::Note n;
  2160. n.start = rnd (16 * lynx::ppq);
  2161. n.length = rnd (5) == 0 ? rnd (12 * lynx::ppq) + 1 : rnd (lynx::ppq) + 1;
  2162. n.channel = rnd (4);
  2163. n.key = 40 + rnd (40);
  2164. n.slide = rnd (20) == 0;
  2165. p.notes.push_back (n);
  2166. }
  2167. p.sortNotes();
  2168. }
  2169. s.playlist.clear();
  2170. for (int i = 0; i < 12; ++i)
  2171. {
  2172. lynx::Clip c;
  2173. c.pattern = rnd (3);
  2174. c.track = rnd (4);
  2175. c.start = rnd (40) * lynx::ppq;
  2176. c.length = (rnd (12) + 1) * lynx::ppq;
  2177. c.offset = rnd (4) * lynx::ppq;
  2178. s.playlist.push_back (c);
  2179. }
  2180. s.mode = lynx::PlayMode::song;
  2181. const auto index = lynx::makeScheduleIndex (s);
  2182. const auto tps = lynx::ticksPerSample (140.0, 48000.0);
  2183. const auto loop = (double) s.songLength();
  2184. int mismatches = 0, events = 0;
  2185. for (int block = 0; block < 400; ++block)
  2186. {
  2187. const auto start = block == 0 ? loop - 100.0 * tps : (double) rnd ((int) loop * 2);
  2188. const auto samples = 64 + rnd (24000); // up to ~1 beat per block
  2189. lynx::EventBuffer a, b;
  2190. lynx::scheduleSong (s, start, samples, tps, a, false, nullptr);
  2191. lynx::scheduleSong (s, start, samples, tps, b, false, &index);
  2192. events += a.size();
  2193. if (a.size() != b.size())
  2194. {
  2195. ++mismatches;
  2196. continue;
  2197. }
  2198. for (int i = 0; i < a.size(); ++i)
  2199. {
  2200. const auto& x = *(a.begin() + i);
  2201. const auto& y = *(b.begin() + i);
  2202. mismatches += x.sampleOffset != y.sampleOffset || x.type != y.type || x.key != y.key || x.channel != y.channel;
  2203. }
  2204. }
  2205. CHECK (events > 500);
  2206. CHECK (mismatches == 0);
  2207. }
  2208. TEST (mixer_track_eq_defaults_and_boost)
  2209. {
  2210. // FL defaults: 90 Hz, 1.5 kHz and 8 kHz; peak Q 0.632; shelf slope 0.607
  2211. lynx::TrackEq eq;
  2212. CHECK (std::abs (lynx::TrackEq::peakQ (eq.width[1]) - 0.632) < 0.01);
  2213. CHECK (std::abs (lynx::TrackEq::shelfSlope (eq.width[0]) - 0.607) < 0.01);
  2214. CHECK (! eq.active());
  2215. // +12 dB peak at 1.5 kHz on a track: a 1.5 kHz sine rises ~4x
  2216. lynx::Song song = lynx::Song::makeDefault();
  2217. song.mixer[1].eq.gainDb[1] = 12.0f;
  2218. for (auto& c : song.channels)
  2219. c.mixerTrack = 1;
  2220. song.channels[4].instrument = lynx::InstrumentKind::synth;
  2221. song.channels[4].synth = {};
  2222. song.channels[4].synth.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  2223. song.channels[4].synth.cutoff = 20000.0f;
  2224. auto render = [] (const lynx::Song& s) {
  2225. auto state = lynx::RackState::build (s, nullptr, 48000.0);
  2226. lynx::RackRenderer renderer;
  2227. renderer.prepare (48000.0);
  2228. lynx::LiveEventQueue live;
  2229. lynx::NoteEvent on; // 1.5 kHz ~ key 90.6: use 91 (1568 Hz), still within the wide peak
  2230. on.channel = 4;
  2231. on.key = 91;
  2232. on.velocity = 1.0f;
  2233. live.push (on);
  2234. std::vector<float> l (24000), r (24000);
  2235. for (int pos = 0; pos < 24000; pos += 480)
  2236. renderer.process (state.get(), false, 0.0, 480, l.data() + pos, r.data() + pos, pos == 0 ? &live : nullptr);
  2237. float peak = 0.0f;
  2238. for (std::size_t i = 12000; i < 24000; ++i)
  2239. peak = std::max (peak, std::abs (l[i]));
  2240. return peak;
  2241. };
  2242. const auto boosted = render (song);
  2243. song.mixer[1].eq.gainDb[1] = 0.0f;
  2244. const auto flat = render (song);
  2245. CHECK (flat > 0.01f);
  2246. CHECK (boosted / flat > 3.0f && boosted / flat < 4.2f);
  2247. }
  2248. TEST (bars_follow_time_signature_markers)
  2249. {
  2250. lynx::Song song;
  2251. song.beatsPerBar = 4;
  2252. const auto bar4 = (std::int64_t) lynx::ppq * 4;
  2253. auto bars = song.barsBetween (0, bar4 * 3);
  2254. CHECK (bars.size() == 3 && bars[2].tick == bar4 * 2 && bars[2].number == 3);
  2255. // 7/4 from bar 3, and 3/4 in the middle of a 7 bar (cuts and restarts)
  2256. song.addMarker ({ bar4 * 2, "Verso", 7, 4 });
  2257. song.addMarker ({ bar4, "Nome só", 0, 4 });
  2258. const auto seven = (std::int64_t) lynx::ppq * 7;
  2259. song.addMarker ({ bar4 * 2 + seven + lynx::ppq * 2, "", 3, 4 });
  2260. bars = song.barsBetween (0, bar4 * 2 + seven * 2);
  2261. CHECK (bars.size() >= 5);
  2262. CHECK (bars[1].length == bar4 && bars[2].tick == bar4 * 2 && bars[2].length == seven);
  2263. CHECK (bars[3].length == lynx::ppq * 2); // cut short by the change
  2264. CHECK (bars[4].length == lynx::ppq * 3 && bars[4].number == 5);
  2265. CHECK (song.markers()[0].name == "Nome só"); // sorted by tick
  2266. // from far away: starts at the right bar without losing the numbering
  2267. const auto far = song.barsBetween (lynx::ppq * 3000, lynx::ppq * 3001);
  2268. CHECK (far.size() == 1 && far[0].length == lynx::ppq * 3);
  2269. CHECK (song.barAt (lynx::ppq * 3000).number == far[0].number);
  2270. CHECK ((lynx::ppq * 3000 - far[0].tick) < far[0].length);
  2271. }
  2272. TEST (split_drum_channel_moves_notes_to_pads)
  2273. {
  2274. lynx::Song song = lynx::Song::makeDefault();
  2275. const auto channels = (int) song.channels.size();
  2276. song.patterns[0].notes.clear();
  2277. song.patterns[0].notes.push_back ({ 0, 240, 1, 36, 0.9f }); // kit kick (channel 1)
  2278. song.patterns[0].notes.push_back ({ 240, 240, 1, 38, 0.8f }); // snare
  2279. song.patterns[0].notes.push_back ({ 480, 240, 1, 50, 0.8f }); // key without a pad: dropped
  2280. song.patterns[0].notes.push_back ({ 480, 240, 3, 60, 0.8f }); // other channel: shifts by 1 position
  2281. lynx::Automation a;
  2282. a.target = { lynx::AutomationTargetKind::channelVolume, 3, 0, 0 };
  2283. song.automations.push_back (a);
  2284. std::vector<lynx::DrumPad> pads (2);
  2285. pads[0].name = "Kick";
  2286. pads[0].key = 36;
  2287. pads[0].layers = { { "kick.wav" } };
  2288. pads[1].name = "Snare";
  2289. pads[1].key = 38;
  2290. pads[1].layers = { { "snare soft.wav", 60, 0, 127, 0, 90 }, { "snare hard.wav", 60, 0, 127, 91, 127 } };
  2291. pads[1].cutGroup = 2;
  2292. pads[1].cutBy = 2;
  2293. lynx::splitDrumChannel (song, 1, pads);
  2294. CHECK ((int) song.channels.size() == channels + 1);
  2295. CHECK (song.channels[1].samplePath == "kick.wav" && song.channels[1].instrument == lynx::InstrumentKind::sampler);
  2296. CHECK (song.channels[2].zones.size() == 2 && song.channels[2].cutGroup == song.channels[2].cutBy && song.channels[2].cutGroup != 0);
  2297. const auto& notes = song.patterns[0].notes;
  2298. CHECK (notes.size() == 3);
  2299. CHECK (notes[0].channel == 1 && notes[0].key == 60);
  2300. CHECK (notes[1].channel == 2 && notes[1].key == 60);
  2301. CHECK (notes[2].channel == 4); // the old channel 3
  2302. CHECK (song.automations[0].target.index == 4);
  2303. }
  2304. TEST (flp_import_brings_playlist)
  2305. {
  2306. flp::Project p;
  2307. p.header.ppq = 96;
  2308. p.channels = { { 0, flp::ChannelType::sampler, "Kick", "", "", 1 } };
  2309. flp::Pattern empty;
  2310. empty.index = 1;
  2311. flp::Pattern full;
  2312. full.index = 2;
  2313. flp::Note n;
  2314. n.channel = 0;
  2315. full.notes.push_back (n);
  2316. p.patterns = { empty, full };
  2317. flp::Arrangement a;
  2318. flp::PlaylistItem item;
  2319. item.kind = flp::PlaylistItem::Kind::pattern;
  2320. item.index = 2;
  2321. item.position = 384;
  2322. item.length = 192;
  2323. item.track = 3;
  2324. item.patternStartTick = 96;
  2325. a.items.push_back (item);
  2326. item.index = 1; // empty pattern: discarded
  2327. a.items.push_back (item);
  2328. item.kind = flp::PlaylistItem::Kind::channelClip; // audio: not supported yet
  2329. a.items.push_back (item);
  2330. p.arrangements.push_back (a);
  2331. const auto s = lynx::importFlp (p);
  2332. CHECK (s.mode == lynx::PlayMode::song);
  2333. CHECK (s.playlist.size() == 1);
  2334. CHECK (s.playlist[0].pattern == 0 && s.playlist[0].track == 3);
  2335. CHECK (s.playlist[0].start == 4 * lynx::ppq && s.playlist[0].length == 2 * lynx::ppq && s.playlist[0].offset == lynx::ppq);
  2336. }
  2337. TEST (rack_releases_notes_on_position_jump)
  2338. {
  2339. lynx::Song s;
  2340. lynx::ChannelDef c;
  2341. c.instrument = lynx::InstrumentKind::synth;
  2342. s.channels.push_back (c);
  2343. auto& p = s.patterns.emplace_back();
  2344. lynx::Note n;
  2345. n.start = 0;
  2346. n.length = 4 * lynx::ppq; // long note
  2347. p.notes.push_back (n);
  2348. s.bpm = 120.0;
  2349. auto state = lynx::RackState::build (s, nullptr, 48000.0);
  2350. lynx::RackRenderer r;
  2351. r.prepare (48000.0);
  2352. std::vector<float> l (512), rr (512);
  2353. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  2354. double tick = 0.0;
  2355. for (int i = 0; i < 20; ++i, tick += 512 * tps)
  2356. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  2357. // jump to tick 2000 (mid-note, no new "on"): the synth must go silent
  2358. for (int i = 0; i < 40; ++i)
  2359. r.process (state.get(), true, 2000.0 + i * 512 * tps, 512, l.data(), rr.data());
  2360. float tail = 0.0f;
  2361. for (auto v : l)
  2362. tail = std::max (tail, std::abs (v));
  2363. CHECK (tail < 0.001f);
  2364. }
  2365. namespace
  2366. {
  2367. // Two samplers with a constant 0.5 signal on different inserts; returns the output peak.
  2368. float juce_db (float gain)
  2369. {
  2370. return 20.0f * std::log10 (gain);
  2371. }
  2372. float renderMixerCase (const std::function<void (lynx::Song&)>& tweak, lynx::MeterBank* meters = nullptr)
  2373. {
  2374. lynx::Song s;
  2375. s.mixer = lynx::Song::defaultMixer (4);
  2376. for (int i = 0; i < 2; ++i)
  2377. {
  2378. lynx::ChannelDef c;
  2379. c.instrument = lynx::InstrumentKind::sampler;
  2380. c.samplePath = "dc";
  2381. c.volume = 1.0f;
  2382. c.mixerTrack = i + 1;
  2383. s.channels.push_back (c);
  2384. }
  2385. s.patterns.emplace_back();
  2386. tweak (s);
  2387. auto provider = [] (const std::string&) {
  2388. auto d = std::make_shared<lynx::SampleData>();
  2389. d->left.assign (48000, 0.5f);
  2390. return std::shared_ptr<const lynx::SampleData> (d);
  2391. };
  2392. auto state = lynx::RackState::build (s, nullptr, 48000.0, provider);
  2393. lynx::RackRenderer r;
  2394. r.prepare (48000.0, 256);
  2395. lynx::LiveEventQueue live;
  2396. for (int ch = 0; ch < 2; ++ch)
  2397. {
  2398. lynx::NoteEvent on;
  2399. on.channel = ch;
  2400. on.velocity = 1.0f;
  2401. live.push (on);
  2402. }
  2403. std::vector<float> l (1000), rr (1000); // larger than the mixer block: tests the chunking
  2404. r.process (state.get(), false, 0.0, 1000, l.data(), rr.data(), &live, meters);
  2405. return std::max (std::abs (l[999]), std::abs (rr[999]));
  2406. }
  2407. } // namespace
  2408. TEST (mixer_routes_mutes_solos_and_meters)
  2409. {
  2410. // two 0.5 channels summed on the Master at 0 dB
  2411. CHECK (std::abs (renderMixerCase ([] (lynx::Song&) {}) - 1.0f) < 1e-4f);
  2412. // insert 1 muted: only channel 2 remains
  2413. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.mixer[1].muted = true; }) - 0.5f) < 1e-4f);
  2414. // solo on insert 2: same
  2415. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.mixer[2].solo = true; }) - 0.5f) < 1e-4f);
  2416. // FL fader curve: 0.8 = 0 dB, max ≈ +5.6 dB, half travel ≈ -12.7 dB
  2417. CHECK (std::abs (lynx::faderGain (0.8f) - 1.0f) < 1e-5f);
  2418. CHECK (std::abs (juce_db (lynx::faderGain (1.0f)) - 5.59f) < 0.05f);
  2419. CHECK (lynx::faderGain (0.0f) == 0.0f);
  2420. // Master fader at max
  2421. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.mixer[0].volume = 1.0f; }) - lynx::faderGain (1.0f)) < 1e-4f);
  2422. // both channels on the same insert, insert fader at 0.4
  2423. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) {
  2424. s.channels[1].mixerTrack = 1;
  2425. s.mixer[1].volume = 0.4f;
  2426. }) - lynx::faderGain (0.4f)) < 1e-4f);
  2427. // a route outside the mixer falls to the last existing insert, without crashing
  2428. CHECK (renderMixerCase ([] (lynx::Song& s) { s.channels[0].mixerTrack = 100; }) > 0.9f);
  2429. // no mixer: everything straight to the output at 0 dB
  2430. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.mixer.clear(); }) - 1.0f) < 1e-4f);
  2431. lynx::MeterBank meters;
  2432. renderMixerCase ([] (lynx::Song&) {}, &meters);
  2433. CHECK (std::abs (meters.takePeak (1, 0) - 0.5f) < 1e-4f);
  2434. CHECK (std::abs (meters.takePeak (0, 1) - 1.0f) < 1e-4f);
  2435. CHECK (meters.takePeak (1, 0) == 0.0f); // reading resets
  2436. CHECK (meters.takePeak (3, 0) == 0.0f); // insert with no channel
  2437. }
  2438. TEST (next_free_insert_and_flp_mixer_import)
  2439. {
  2440. auto s = lynx::Song::makeDefault();
  2441. CHECK (s.mixer.size() == 17 && s.mixer[0].name == "Master");
  2442. CHECK (s.nextFreeInsert() == 6); // the 5 default channels take 1..5
  2443. flp::Project p;
  2444. p.channels = { { 0, flp::ChannelType::sampler, "Kick", "", "", 30 } };
  2445. p.mixer = { { 0, "" }, { 30, "Drums" } };
  2446. const auto song = lynx::importFlp (p);
  2447. CHECK (song.channels[0].mixerTrack == 30);
  2448. CHECK (song.mixer.size() == 31);
  2449. CHECK (song.mixer[30].name == "Drums" && song.mixer[0].name == "Master");
  2450. }
  2451. namespace
  2452. {
  2453. float runEffectOnSine (lynx::EffectKind kind, const std::function<void (lynx::EffectSlot&)>& tweak, double hz, float amp,
  2454. int frames = 48000)
  2455. {
  2456. auto fx = lynx::makeEffect (kind);
  2457. fx->prepare (48000.0);
  2458. auto slot = lynx::makeEffectSlot (kind);
  2459. tweak (slot);
  2460. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  2461. for (int i = 0; i < frames; ++i)
  2462. l[(std::size_t) i] = r[(std::size_t) i] = amp * (float) std::sin (6.283185307 * hz * i / 48000.0);
  2463. for (int i = 0; i < frames; i += 480)
  2464. fx->process (l.data() + i, r.data() + i, std::min (480, frames - i), slot.params, 120.0);
  2465. float peak = 0.0f;
  2466. for (int i = frames / 2; i < frames; ++i) // second half: already settled
  2467. {
  2468. CHECK (std::isfinite (l[(std::size_t) i]));
  2469. peak = std::max (peak, std::abs (l[(std::size_t) i]));
  2470. }
  2471. return peak;
  2472. }
  2473. } // namespace
  2474. TEST (parametric_eq_bands_and_response)
  2475. {
  2476. // default: transparent
  2477. auto slot = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  2478. CHECK (std::abs (lynx::peq::responseDb (slot.params, 48000.0, 1000.0)) < 0.01);
  2479. CHECK (std::abs (runEffectOnSine (lynx::EffectKind::parametricEq, [] (auto&) {}, 1000.0, 0.5f) - 0.5f) < 0.005f);
  2480. // +12 dB peak at 1 kHz on band 4: the response and the signal agree
  2481. auto boost = [] (lynx::EffectSlot& s) {
  2482. s.params[(std::size_t) lynx::peq::param (3, 1)] = lynx::peq::hzValue (1000.0);
  2483. s.params[(std::size_t) lynx::peq::param (3, 2)] = lynx::peq::gainValue (12.0);
  2484. };
  2485. boost (slot);
  2486. CHECK (std::abs (lynx::peq::responseDb (slot.params, 48000.0, 1000.0) - 12.0) < 0.2);
  2487. CHECK (std::abs (lynx::peq::responseDb (slot.params, 48000.0, 100.0)) < 1.0);
  2488. const auto peak = runEffectOnSine (lynx::EffectKind::parametricEq, boost, 1000.0, 0.1f);
  2489. CHECK (std::abs (peak - 0.1f * std::pow (10.0f, 12.0f / 20.0f)) < 0.01f);
  2490. // low cut at 48 dB/oct at 200 Hz: 50 Hz (2 octaves below) drops ~96 dB; 2 kHz passes
  2491. auto cut = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  2492. cut.params[(std::size_t) lynx::peq::param (0, 0)] = lynx::peq::typeValue (lynx::peq::BandType::lowCut);
  2493. cut.params[(std::size_t) lynx::peq::param (0, 1)] = lynx::peq::hzValue (200.0);
  2494. cut.params[(std::size_t) lynx::peq::param (0, 3)] = lynx::peq::qValue (0.70710678); // Butterworth
  2495. cut.params[(std::size_t) (lynx::peq::slopeParam + 0)] = 1.0f;
  2496. CHECK (lynx::peq::responseDb (cut.params, 48000.0, 50.0) < -80.0);
  2497. CHECK (std::abs (lynx::peq::responseDb (cut.params, 48000.0, 200.0) + 3.0) < 0.5); // -3 dB at the cutoff (Butterworth)
  2498. CHECK (std::abs (lynx::peq::responseDb (cut.params, 48000.0, 2000.0)) < 0.1);
  2499. // round-trip conversions
  2500. CHECK (std::abs (lynx::peq::hz (lynx::peq::hzValue (440.0)) - 440.0) < 0.5);
  2501. CHECK (std::abs (lynx::peq::q (lynx::peq::qValue (2.5)) - 2.5) < 0.01);
  2502. CHECK (lynx::peq::type (lynx::peq::typeValue (lynx::peq::BandType::notch)) == lynx::peq::BandType::notch);
  2503. }
  2504. TEST (fl_parametric_eq2_state_maps_to_bands)
  2505. {
  2506. // v8 blob: band 1 low cut at 100 Hz "Steep 8", band 4 peak +6 dB at 1 kHz, output −3 dB
  2507. std::vector<std::uint8_t> blob (354, 0);
  2508. auto put = [&] (std::size_t off, std::int32_t v) { std::memcpy (blob.data() + off, &v, 4); };
  2509. put (0, 8);
  2510. auto param = [&] (int i, std::int32_t v) { put (4 + 4 * (std::size_t) i, v); };
  2511. auto hzRaw = [] (double hz) { return (std::int32_t) std::lround (std::log (hz / 20.0) / std::log (1000.0) * 65536.0); };
  2512. for (int b = 0; b < 7; ++b)
  2513. param (21 + b, 0); // all off
  2514. param (21 + 0, 3); // high pass (= low cut)
  2515. param (7 + 0, hzRaw (100.0));
  2516. param (14 + 0, 40124); // default width -> Q ~0.68
  2517. param (28 + 0, -3); // Steep 8 -> 4 biquads
  2518. param (21 + 3, 6); // peaking
  2519. param (7 + 3, hzRaw (1000.0));
  2520. param (3, 600); // +6 dB
  2521. param (14 + 3, 25412);
  2522. param (35, -300); // main level −3 dB
  2523. put (0x13E, 0x7F);
  2524. const auto slot = lynx::effectFromFl ("Fruity Parametric EQ 2", blob);
  2525. CHECK (slot.has_value() && slot->kind == lynx::EffectKind::parametricEq);
  2526. const auto& p = slot->params;
  2527. CHECK (lynx::peq::type (p[(std::size_t) lynx::peq::param (0, 0)]) == lynx::peq::BandType::lowCut);
  2528. CHECK (lynx::peq::slopeStages (p[(std::size_t) lynx::peq::slopeParam]) == 4);
  2529. CHECK (lynx::peq::type (p[(std::size_t) lynx::peq::param (3, 0)]) == lynx::peq::BandType::peak);
  2530. CHECK (lynx::peq::type (p[(std::size_t) lynx::peq::param (1, 0)]) == lynx::peq::BandType::off);
  2531. CHECK (std::abs (lynx::peq::responseDb (p, 48000.0, 1000.0) - 3.0) < 0.3); // +6 from the peak −3 from the output
  2532. CHECK (lynx::peq::responseDb (p, 48000.0, 30.0) < -40.0); // 48 dB/oct below 100 Hz
  2533. CHECK (std::abs (lynx::peq::responseDb (p, 48000.0, 8000.0) + 3.0) < 0.3);
  2534. // a band muted by the mask doesn't sound
  2535. put (0x13E, 0x7F & ~(1 << 3));
  2536. const auto muted = lynx::effectFromFl ("Fruity Parametric EQ 2", blob);
  2537. CHECK (lynx::peq::type (muted->params[(std::size_t) lynx::peq::param (3, 0)]) == lynx::peq::BandType::off);
  2538. }
  2539. TEST (reverb_low_cut_and_predelay)
  2540. {
  2541. // impulse: with 100 ms predelay the wet only starts later; with a 3 kHz low cut a
  2542. // 100 Hz sine barely enters the reverb
  2543. auto run = [] (const std::function<void (lynx::EffectSlot&)>& tweak, double hz, bool impulse) {
  2544. auto fx = lynx::makeEffect (lynx::EffectKind::reverb);
  2545. fx->prepare (48000.0);
  2546. auto slot = lynx::makeEffectSlot (lynx::EffectKind::reverb);
  2547. slot.params[4] = 0.0f; // wet only
  2548. slot.params[3] = 1.0f;
  2549. tweak (slot);
  2550. std::vector<float> l (48000), r (48000);
  2551. for (int i = 0; i < 48000; ++i)
  2552. 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);
  2553. for (int i = 0; i < 48000; i += 480)
  2554. fx->process (l.data() + i, r.data() + i, 480, slot.params, 120.0);
  2555. return l;
  2556. };
  2557. const auto delayed = run ([] (auto& s) { s.params[7] = 0.1f; }, 0.0, true);
  2558. float early = 0.0f, later = 0.0f;
  2559. for (std::size_t i = 0; i < 4800; ++i)
  2560. early = std::max (early, std::abs (delayed[i]));
  2561. for (std::size_t i = 4800; i < 24000; ++i)
  2562. later = std::max (later, std::abs (delayed[i]));
  2563. CHECK (early == 0.0f && later > 0.0f);
  2564. 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; };
  2565. const auto open = energy (run ([] (auto&) {}, 100.0, false));
  2566. const auto cut = energy (run ([] (auto& s) { s.params[5] = 1.0f; }, 100.0, false));
  2567. CHECK (cut < open * 0.01);
  2568. }
  2569. TEST (utility_effect_and_fl_stereo_tools)
  2570. {
  2571. // transparent by default; balance fully right silences the left
  2572. CHECK (std::abs (runEffectOnSine (lynx::EffectKind::utility, [] (auto&) {}, 440.0, 0.5f) - 0.5f) < 0.001f);
  2573. CHECK (runEffectOnSine (lynx::EffectKind::utility, [] (auto& s) { s.params[1] = 1.0f; }, 440.0, 0.5f) < 0.001f);
  2574. // Stereo Shaper in "mono": each output = 0.5 L + 0.5 R
  2575. std::vector<std::uint8_t> blob (36, 0);
  2576. auto put = [&] (std::size_t off, std::int32_t v) { std::memcpy (blob.data() + off, &v, 4); };
  2577. put (4, 6400); put (8, 6400); put (12, 6400); put (16, 6400);
  2578. const auto slot = lynx::effectFromFl ("Fruity Stereo Shaper", blob);
  2579. CHECK (slot && slot->kind == lynx::EffectKind::utility);
  2580. auto fx = lynx::makeEffect (lynx::EffectKind::utility);
  2581. float l = 1.0f, r = 0.0f;
  2582. fx->process (&l, &r, 1, slot->params, 120.0);
  2583. CHECK (std::abs (l - 0.5f) < 1e-4f && std::abs (r - 0.5f) < 1e-4f);
  2584. // Balance: volume 256 = 0 dB, pan −128 = fully left
  2585. std::vector<std::uint8_t> bal (8, 0);
  2586. std::int32_t pan = -128, vol = 256;
  2587. std::memcpy (bal.data(), &pan, 4);
  2588. std::memcpy (bal.data() + 4, &vol, 4);
  2589. const auto b = lynx::effectFromFl ("Fruity Balance", bal);
  2590. l = 0.5f; r = 0.5f;
  2591. fx->process (&l, &r, 1, b->params, 120.0);
  2592. CHECK (std::abs (l - 0.5f) < 1e-3f && std::abs (r) < 1e-4f);
  2593. }
  2594. TEST (effects_eq_compressor_behave)
  2595. {
  2596. // EQ at default is transparent
  2597. CHECK (std::abs (runEffectOnSine (lynx::EffectKind::eq, [] (auto&) {}, 1000.0, 0.5f) - 0.5f) < 0.01f);
  2598. // +18 dB on the lows: 60 Hz rises a lot, 5 kHz barely
  2599. CHECK (runEffectOnSine (lynx::EffectKind::eq, [] (auto& s) { s.params[0] = 1.0f; }, 60.0, 0.05f) > 0.3f);
  2600. CHECK (runEffectOnSine (lynx::EffectKind::eq, [] (auto& s) { s.params[0] = 1.0f; }, 5000.0, 0.05f) < 0.06f);
  2601. // compressor: threshold -20 dB, ratio 20:1 flattens a 0 dBFS signal to near the threshold
  2602. const auto squashed = runEffectOnSine (lynx::EffectKind::compressor, [] (auto& s) {
  2603. s.params[0] = 40.0f / 60.0f;
  2604. s.params[1] = 1.0f;
  2605. }, 200.0, 1.0f);
  2606. CHECK (squashed < 0.2f && squashed > 0.05f);
  2607. // a signal below the threshold passes intact
  2608. CHECK (std::abs (runEffectOnSine (lynx::EffectKind::compressor, [] (auto& s) { s.params[0] = 1.0f; }, 200.0, 0.3f) - 0.3f) < 0.01f);
  2609. }
  2610. TEST (effects_delay_echoes_on_tempo_and_reverb_has_tail)
  2611. {
  2612. auto delay = lynx::makeEffect (lynx::EffectKind::delay);
  2613. delay->prepare (48000.0);
  2614. auto slot = lynx::makeEffectSlot (lynx::EffectKind::delay);
  2615. slot.params[0] = 3.5f / 8.0f; // index 3 = 1/4 = 0.5 s at 120 BPM
  2616. slot.params[1] = 0.0f; // no feedback: a single echo
  2617. slot.params[2] = 1.0f;
  2618. slot.params[4] = 0.0f; // no damping
  2619. std::vector<float> l (48000, 0.0f), r (48000, 0.0f);
  2620. l[0] = r[0] = 1.0f;
  2621. delay->process (l.data(), r.data(), 48000, slot.params, 120.0);
  2622. CHECK (std::abs (l[24000] - 1.0f) < 1e-4f);
  2623. CHECK (std::abs (l[12000]) < 1e-6f);
  2624. auto reverb = lynx::makeEffect (lynx::EffectKind::reverb);
  2625. reverb->prepare (48000.0);
  2626. auto rs = lynx::makeEffectSlot (lynx::EffectKind::reverb);
  2627. rs.params[3] = 1.0f;
  2628. std::fill (l.begin(), l.end(), 0.0f);
  2629. std::fill (r.begin(), r.end(), 0.0f);
  2630. l[0] = r[0] = 1.0f;
  2631. reverb->process (l.data(), r.data(), 48000, rs.params, 120.0);
  2632. float tail = 0.0f;
  2633. for (int i = 4800; i < 9600; ++i) // between 100 and 200 ms after the impulse
  2634. tail = std::max (tail, std::abs (l[(std::size_t) i]));
  2635. CHECK (tail > 1e-4f && tail < 1.0f);
  2636. CHECK (lynx::formatEffectParam (lynx::EffectKind::delay, 0, slot.params[0], 120.0) == "1/4 (500 ms)");
  2637. }
  2638. TEST (rack_runs_insert_effects_and_reuses_them)
  2639. {
  2640. // an insert with EQ at -inf doesn't exist; we use the EQ output at -18 dB to see the effect act
  2641. const auto quiet = renderMixerCase ([] (lynx::Song& s) {
  2642. auto eq = lynx::makeEffectSlot (lynx::EffectKind::eq);
  2643. eq.params[4] = 0.0f; // output -18 dB
  2644. s.mixer[1].effects.push_back (eq);
  2645. });
  2646. CHECK (quiet > 0.55f && quiet < 0.6f); // 0.5 from channel 2 + 0.5 * 0.126 from channel 1
  2647. const auto bypassed = renderMixerCase ([] (lynx::Song& s) {
  2648. auto eq = lynx::makeEffectSlot (lynx::EffectKind::eq);
  2649. eq.params[4] = 0.0f;
  2650. eq.enabled = false;
  2651. s.mixer[1].effects.push_back (eq);
  2652. });
  2653. CHECK (std::abs (bypassed - 1.0f) < 1e-4f);
  2654. auto s = lynx::Song::makeDefault();
  2655. s.mixer[2].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::reverb));
  2656. auto a = lynx::RackState::build (s, nullptr, 48000.0);
  2657. s.mixer[2].effects[0].params[0] = 0.9f; // turning a knob doesn't recreate the effect
  2658. auto b = lynx::RackState::build (s, a.get(), 48000.0);
  2659. CHECK (b->effects[2][0] == a->effects[2][0]);
  2660. s.mixer[2].effects[0] = lynx::makeEffectSlot (lynx::EffectKind::delay);
  2661. auto c = lynx::RackState::build (s, b.get(), 48000.0);
  2662. CHECK (c->effects[2][0] != b->effects[2][0]);
  2663. }
  2664. TEST (audio_clips_trigger_cut_and_resume)
  2665. {
  2666. lynx::Song s;
  2667. s.bpm = 120.0; // 1 beat = 0.5 s = 24000 samples at 48 kHz
  2668. lynx::ChannelDef c;
  2669. c.instrument = lynx::InstrumentKind::audioClip;
  2670. c.samplePath = "ramp";
  2671. c.volume = 1.0f;
  2672. s.channels.push_back (c);
  2673. s.patterns.emplace_back();
  2674. lynx::Clip clip;
  2675. clip.kind = lynx::ClipKind::audio;
  2676. clip.channel = 0;
  2677. clip.start = lynx::ppq; // starts at beat 2
  2678. clip.length = 2 * lynx::ppq; // lasts 2 beats
  2679. clip.offset = lynx::ppq; // skips the first beat of the audio
  2680. s.playlist.push_back (clip);
  2681. s.mode = lynx::PlayMode::song;
  2682. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  2683. lynx::EventBuffer ev;
  2684. lynx::scheduleSong (s, 0.0, 4 * 24000, tps, ev);
  2685. CHECK (ev.size() == 2);
  2686. CHECK (ev[0].type == lynx::NoteEvent::Type::on && ev[0].sampleOffset == 24000 && std::abs (ev[0].startSeconds - 0.5) < 1e-9);
  2687. CHECK (ev[1].type == lynx::NoteEvent::Type::off && ev[1].sampleOffset == 3 * 24000);
  2688. // seek to the middle of the clip (beat 2.5): with resume, starts at the block's first sample
  2689. ev.clear();
  2690. lynx::scheduleSong (s, 1.5 * lynx::ppq, 256, tps, ev, true);
  2691. CHECK (ev.size() == 1 && ev[0].sampleOffset == 0 && std::abs (ev[0].startSeconds - 0.75) < 1e-9);
  2692. ev.clear();
  2693. lynx::scheduleSong (s, 1.5 * lynx::ppq, 256, tps, ev, false);
  2694. CHECK (ev.size() == 0);
  2695. // sample whose value = position in seconds: lets us check where playback started
  2696. auto provider = [] (const std::string&) {
  2697. auto d = std::make_shared<lynx::SampleData>();
  2698. d->sampleRate = 48000.0;
  2699. for (int i = 0; i < 48000 * 3; ++i)
  2700. d->left.push_back ((float) i / 48000.0f);
  2701. return std::shared_ptr<const lynx::SampleData> (d);
  2702. };
  2703. auto state = lynx::RackState::build (s, nullptr, 48000.0, provider);
  2704. lynx::RackRenderer r;
  2705. r.prepare (48000.0, 512);
  2706. std::vector<float> l (256), rr (256);
  2707. // first block already playing mid-clip
  2708. r.process (state.get(), true, 1.5 * lynx::ppq, 256, l.data(), rr.data());
  2709. CHECK (std::abs (l[0] - 0.75f) < 0.001f);
  2710. // the clip ends at beat 3: after the short fade, silence (the sample would still have audio)
  2711. double tick = 3.0 * lynx::ppq - 10 * tps;
  2712. r.process (state.get(), false, tick, 256, l.data(), rr.data()); // stops (fade)
  2713. for (int i = 0; i < 4; ++i)
  2714. r.process (state.get(), false, tick, 256, l.data(), rr.data());
  2715. CHECK (std::abs (l[255]) < 1e-6f);
  2716. }
  2717. TEST (remove_channel_fixes_notes_and_audio_clips)
  2718. {
  2719. lynx::Song s;
  2720. s.channels.resize (3);
  2721. s.patterns.resize (1);
  2722. s.patterns[0].notes = { { 0, 240, 0, 60, 1.0f }, { 0, 240, 1, 60, 1.0f }, { 0, 240, 2, 60, 1.0f } };
  2723. lynx::Clip a;
  2724. a.kind = lynx::ClipKind::audio;
  2725. a.channel = 1;
  2726. a.length = 100;
  2727. lynx::Clip b = a;
  2728. b.channel = 2;
  2729. s.playlist = { a, b };
  2730. s.removeChannel (1);
  2731. CHECK (s.channels.size() == 2);
  2732. CHECK (s.patterns[0].notes.size() == 2 && s.patterns[0].notes[1].channel == 1);
  2733. CHECK (s.playlist.size() == 1 && s.playlist[0].channel == 1);
  2734. }
  2735. TEST (flp_import_audio_clips_with_offsets)
  2736. {
  2737. flp::Project p;
  2738. p.header.ppq = 96;
  2739. p.tempo = 120.0;
  2740. p.channels = { { 0, flp::ChannelType::audioClip, "Vocal", "", "%FLStudioData%\\v.wav", 2 },
  2741. { 1, flp::ChannelType::audioClip, "Loop", "", "%FLStudioData%\\l.wav", 3 } };
  2742. flp::Arrangement arr;
  2743. flp::PlaylistItem beats; // offset in beats: end - start = duration in beats
  2744. beats.kind = flp::PlaylistItem::Kind::channelClip;
  2745. beats.index = 0;
  2746. beats.position = 192;
  2747. beats.length = 384; // 4 beats
  2748. beats.startOffset = 2.0f;
  2749. beats.endOffset = 6.0f;
  2750. flp::PlaylistItem ms = beats; // offset in ms: 4 beats at 120 BPM = 2000 ms
  2751. ms.index = 1;
  2752. ms.startOffset = 500.0f;
  2753. ms.endOffset = 2500.0f;
  2754. arr.items = { beats, ms };
  2755. p.arrangements.push_back (arr);
  2756. lynx::FlpImportOptions options;
  2757. options.roots = { "C:\\FL", "C:\\FL\\Data", "" };
  2758. options.fileExists = [] (const std::string&) { return true; };
  2759. const auto s = lynx::importFlp (p, options);
  2760. CHECK (s.channels.size() == 2 && s.channels[0].instrument == lynx::InstrumentKind::audioClip);
  2761. CHECK (s.channels[0].samplePath == "C:\\FL\\Data\\v.wav");
  2762. CHECK (s.playlist.size() == 2);
  2763. CHECK (s.playlist[0].kind == lynx::ClipKind::audio && s.playlist[0].start == 2 * lynx::ppq);
  2764. CHECK (s.playlist[0].offset == 2 * lynx::ppq);
  2765. CHECK (s.playlist[1].offset == lynx::ppq); // 500 ms at 120 BPM = 1 beat
  2766. CHECK (s.mode == lynx::PlayMode::song);
  2767. }
  2768. TEST (plugin_factories_create_reuse_and_fallback)
  2769. {
  2770. lynx::Song s;
  2771. s.mixer = lynx::Song::defaultMixer (2);
  2772. lynx::ChannelDef c;
  2773. c.instrument = lynx::InstrumentKind::plugin;
  2774. c.plugin.id = "VST3-Synth-123";
  2775. c.mixerTrack = 1;
  2776. s.channels.push_back (c);
  2777. lynx::ChannelDef missing = c;
  2778. missing.plugin.id = "VST3-Ausente-0";
  2779. s.channels.push_back (missing);
  2780. lynx::EffectSlot fx;
  2781. fx.kind = lynx::EffectKind::plugin;
  2782. fx.plugin.id = "VST3-Reverb-9";
  2783. s.mixer[1].effects.push_back (fx);
  2784. s.patterns.emplace_back();
  2785. int instrumentsMade = 0, effectsMade = 0;
  2786. lynx::RackState::Factories f;
  2787. f.pluginInstruments = [&] (const lynx::PluginRef& ref, double) -> std::shared_ptr<lynx::Instrument> {
  2788. if (ref.id != "VST3-Synth-123")
  2789. return nullptr;
  2790. ++instrumentsMade;
  2791. auto synth = lynx::makeInstrument (lynx::InstrumentKind::synth);
  2792. synth->prepare (48000.0);
  2793. return synth;
  2794. };
  2795. f.pluginEffects = [&] (const lynx::PluginRef&, double) -> std::shared_ptr<lynx::Effect> {
  2796. ++effectsMade;
  2797. auto eq = lynx::makeEffect (lynx::EffectKind::eq);
  2798. eq->prepare (48000.0);
  2799. return eq;
  2800. };
  2801. auto a = lynx::RackState::build (s, nullptr, 48000.0, f);
  2802. CHECK (instrumentsMade == 1 && effectsMade == 1);
  2803. CHECK (a->instruments.size() == 2 && a->instruments[1] != nullptr); // missing: muted, but it exists
  2804. // changing the saved state doesn't recreate; swapping the plugin does
  2805. s.channels[0].plugin.state = "abc";
  2806. auto b = lynx::RackState::build (s, a.get(), 48000.0, f);
  2807. CHECK (instrumentsMade == 1 && b->instruments[0] == a->instruments[0] && b->effects[1][0] == a->effects[1][0]);
  2808. s.mixer[1].effects[0].plugin.id = "VST3-Outro-1";
  2809. auto c2 = lynx::RackState::build (s, b.get(), 48000.0, f);
  2810. CHECK (effectsMade == 2);
  2811. // rendering with a missing plugin and a plugin slot breaks nothing
  2812. lynx::RackRenderer r;
  2813. r.prepare (48000.0, 256);
  2814. lynx::LiveEventQueue live;
  2815. lynx::NoteEvent on;
  2816. on.channel = 0;
  2817. on.velocity = 1.0f;
  2818. live.push (on);
  2819. on.channel = 1;
  2820. live.push (on);
  2821. std::vector<float> l (256), rr (256);
  2822. r.process (c2.get(), false, 0.0, 256, l.data(), rr.data(), &live);
  2823. float peak = 0.0f;
  2824. for (auto v : l)
  2825. {
  2826. CHECK (std::isfinite (v));
  2827. peak = std::max (peak, std::abs (v));
  2828. }
  2829. CHECK (peak > 0.0f);
  2830. }
  2831. TEST (export_song_adds_silent_tail_and_never_restarts)
  2832. {
  2833. auto s = lynx::Song::makeDefault();
  2834. s.playlist.clear();
  2835. std::int64_t length = 0;
  2836. auto pat = lynx::makeExportSong (s, true, lynx::ppq * 8, length); // empty Playlist: uses the pattern
  2837. CHECK (length == lynx::ppq * 4);
  2838. CHECK (pat.mode == lynx::PlayMode::song && pat.playlist.size() == 2);
  2839. CHECK (pat.songLength() >= length + lynx::ppq * 8);
  2840. // no new notes after the song ends, only silence until the end of the tail
  2841. lynx::EventBuffer events;
  2842. const auto tps = lynx::ticksPerSample (pat.bpm, 48000.0);
  2843. int onsAfterEnd = 0, onsBefore = 0;
  2844. for (double tick = 0.0; tick < (double) (length + lynx::ppq * 8); tick += 512 * tps)
  2845. {
  2846. events.clear();
  2847. lynx::scheduleSong (pat, tick, 512, tps, events);
  2848. for (const auto& e : events)
  2849. if (e.type == lynx::NoteEvent::Type::on)
  2850. (tick + e.sampleOffset * tps >= (double) length ? onsAfterEnd : onsBefore)++;
  2851. }
  2852. CHECK (onsBefore == (int) s.patterns[0].notes.size());
  2853. CHECK (onsAfterEnd == 0);
  2854. // with Playlist: the end is the last clip's, without rounding
  2855. s.playlist.push_back ({ 0, 0, lynx::ppq * 2, lynx::ppq * 3, 0 });
  2856. auto song = lynx::makeExportSong (s, true, 0, length);
  2857. CHECK (length == lynx::ppq * 5 && song.playlist.size() == 1);
  2858. song = lynx::makeExportSong (s, false, 0, length);
  2859. CHECK (length == lynx::ppq * 4 && song.playlist[0].start == 0);
  2860. }
  2861. TEST (note_edit_selection_operations)
  2862. {
  2863. namespace ne = lynx::noteedit;
  2864. lynx::Pattern p;
  2865. p.notes = { { 0, 240, 0, 60 }, { 480, 240, 0, 64 }, { 960, 480, 1, 67 } };
  2866. // sorting keeps the indices in step
  2867. p.notes[0].start = 1200;
  2868. std::vector<int> tracked { 0, 2 };
  2869. ne::sortTracking (p, tracked);
  2870. CHECK (p.notes[2].start == 1200 && p.notes[(std::size_t) tracked[0]].start == 1200);
  2871. CHECK (p.notes[(std::size_t) tracked[1]].key == 67);
  2872. // group move respects the limits
  2873. std::int64_t dt = -5000;
  2874. int dk = 100;
  2875. ne::move (p, { 0, 1 }, dt, dk);
  2876. CHECK (dt == -480 && dk == 127 - 67 && p.notes[0].start == 0 && p.notes[1].key == 127);
  2877. // duplicate: right after the selection, rounded to the grid
  2878. lynx::Pattern q;
  2879. q.notes = { { 0, 240, 0, 60 }, { 240, 300, 0, 62 } }; // 540-tick selection
  2880. const auto added = ne::duplicate (q, { 0, 1 }, 960);
  2881. CHECK (added.size() == 2 && q.notes[(std::size_t) added[0]].start == 960 && q.notes[(std::size_t) added[1]].start == 1200);
  2882. // paste onto another channel with an offset
  2883. const auto pasted = ne::paste (q, ne::copy (q, { 1 }), 100, 3);
  2884. CHECK (pasted.size() == 1 && q.notes.back().channel == 3 && q.notes.back().start == 340);
  2885. // quantize rounds to the nearest
  2886. q.notes[0].start = 130;
  2887. q.notes[1].start = 100;
  2888. ne::quantize (q, { 0, 1 }, 240);
  2889. CHECK (q.notes[0].start == 240 && q.notes[1].start == 0);
  2890. // remove several (order and duplicates don't matter)
  2891. const auto before = q.notes.size();
  2892. ne::remove (q, { 1, 0, 1 });
  2893. CHECK (q.notes.size() == before - 2);
  2894. }
  2895. TEST (recorder_builds_notes_in_pattern_and_song_mode)
  2896. {
  2897. auto song = lynx::Song::makeDefault();
  2898. const auto loop = song.patterns[0].effectiveLength (4); // 1 bar = 3840
  2899. lynx::NoteRecorder r;
  2900. r.add (song, { 100.0, 4, 60, 0.5f, true }); // no take: ignored
  2901. CHECK (r.takeFinished().empty());
  2902. r.begin (loop);
  2903. r.add (song, { 4000.0, 4, 60, 0.5f, true }); // second loop pass
  2904. r.add (song, { 4480.0, 4, 60, 0.0f, false });
  2905. r.add (song, { 5000.0, 4, 64, 0.9f, true }); // held until stop
  2906. r.end (song, 5240.0);
  2907. const auto notes = r.takeFinished();
  2908. CHECK (notes.size() == 2);
  2909. CHECK (notes[0].start == 4000 - 3840 && notes[0].length == 480 && notes[0].velocity == 0.5f && notes[0].channel == 4);
  2910. CHECK (notes[1].key == 64 && notes[1].start == 5000 - 3840 && notes[1].length == 240);
  2911. // song mode: position inside the current pattern's clip (with offset)
  2912. song.mode = lynx::PlayMode::song;
  2913. song.playlist = { { 0, 0, 7680, 3840, 960 } };
  2914. CHECK (lynx::patternPositionForTick (song, 7680.0 + 100.0, loop) == 1060);
  2915. CHECK (lynx::patternPositionForTick (song, 100.0, loop) == 100); // outside the clip: like loop
  2916. }
  2917. TEST (automation_curve_and_playback)
  2918. {
  2919. lynx::Automation a;
  2920. a.points = { { 0, 0.0f }, { 960, 1.0f }, { 1920, 0.5f, 0.0f } };
  2921. CHECK (a.valueAt (-10.0) == 0.0f && a.valueAt (480.0) == 0.5f && a.valueAt (5000.0) == 0.5f);
  2922. CHECK (a.length() == 1920);
  2923. a.points[0].tension = 1.0f; // curve: starts slow
  2924. CHECK (a.valueAt (480.0) < 0.2f && a.valueAt (480.0) > 0.0f);
  2925. // automated Master: silence in the first bar, sound in the second, and the last value
  2926. // keeps applying after the automation clip ends
  2927. auto song = lynx::Song::makeDefault();
  2928. song.bpm = 120.0;
  2929. song.mode = lynx::PlayMode::song;
  2930. const auto bar = (std::int64_t) lynx::ppq * 4;
  2931. for (int b = 0; b < 3; ++b)
  2932. song.playlist.push_back ({ 0, 0, bar * b, bar, 0 });
  2933. lynx::Automation master;
  2934. master.target = { lynx::AutomationTargetKind::mixerVolume, 0 };
  2935. master.points = { { 0, 0.0f }, { bar - 1, 0.0f }, { bar, 0.8f } };
  2936. song.automations.push_back (master);
  2937. lynx::Clip ac;
  2938. ac.kind = lynx::ClipKind::automation;
  2939. ac.automation = 0;
  2940. ac.track = 1;
  2941. ac.length = bar + bar / 2;
  2942. song.playlist.push_back (ac);
  2943. const double sr = 48000.0;
  2944. auto state = lynx::RackState::build (song, nullptr, sr);
  2945. CHECK (state->hasAutomation && state->mixerVolumeAuto[0] == 0 && state->automationClips[0].size() == 1);
  2946. lynx::RackRenderer r;
  2947. r.prepare (sr, 512);
  2948. std::vector<float> l (512), rr (512);
  2949. const auto tps = lynx::ticksPerSample (song.bpm, sr);
  2950. float peakBar1 = 0.0f, peakBar2 = 0.0f, peakBar3 = 0.0f;
  2951. for (double tick = 0.0; tick < (double) (bar * 3); tick += 512 * tps)
  2952. {
  2953. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  2954. auto& peak = tick < (double) bar - 512 * tps ? peakBar1 : tick < (double) bar * 2 ? peakBar2 : peakBar3;
  2955. for (auto v : l)
  2956. peak = std::max (peak, std::abs (v));
  2957. }
  2958. CHECK (peakBar1 < 1.0e-6f);
  2959. CHECK (peakBar2 > 0.05f);
  2960. CHECK (peakBar3 > 0.05f); // after the clip: keeps the last value
  2961. // target removed: automation disappears from the tables
  2962. song.removeChannel (0);
  2963. song.automations[0].target = { lynx::AutomationTargetKind::channelVolume, 0 };
  2964. song.removeChannel (0);
  2965. CHECK (song.automations[0].target.kind == lynx::AutomationTargetKind::none);
  2966. song.removeAutomation (0);
  2967. CHECK (song.automations.empty() && song.playlist.size() == 3);
  2968. }
  2969. TEST (mixer_sends_between_inserts)
  2970. {
  2971. // insert 1 goes only to 3; 3 goes to the Master: same sum (0.5 + 0.5)
  2972. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.setRoute (1, 3, true); s.setRoute (1, 0, false); }) - 1.0f) < 1e-4f);
  2973. // send at 50% and muted destination
  2974. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.setRoute (1, 3, true, 0.5f); s.setRoute (1, 0, false); }) - 0.75f) < 1e-4f);
  2975. 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);
  2976. // going to the Master and to 3: the signal doubles
  2977. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.setRoute (1, 3, true); }) - 1.5f) < 1e-4f);
  2978. // solo on 3 lets what reaches it sound (insert 1), but not 2
  2979. 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);
  2980. // solo on 1 lets the path to the Master (3) sound
  2981. 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);
  2982. // order and cycles
  2983. auto song = lynx::Song::makeDefault();
  2984. song.setRoute (4, 2, true);
  2985. song.setRoute (2, 1, true);
  2986. CHECK (! song.canRoute (1, 4) && ! song.canRoute (1, 2) && song.canRoute (1, 5));
  2987. song.setRoute (1, 4, true); // ignored: would create a cycle
  2988. CHECK (! song.routes (1, 4));
  2989. const auto order = song.mixerOrder();
  2990. const auto pos = [&] (int t) { return std::find (order.begin(), order.end(), t) - order.begin(); };
  2991. CHECK ((int) order.size() == (int) song.mixer.size() - 1);
  2992. CHECK (pos (4) < pos (2) && pos (2) < pos (1));
  2993. song.setRoute (4, 2, false);
  2994. CHECK (! song.routes (4, 2) && song.routes (4, 0));
  2995. }
  2996. namespace
  2997. {
  2998. // Test effect: delays the signal by `latency` samples and reports that latency (like a lookahead plugin).
  2999. class LatentEffect final : public lynx::Effect
  3000. {
  3001. public:
  3002. explicit LatentEffect (int samples) : latency (samples), line (samples) {}
  3003. void prepare (double) noexcept override {}
  3004. void reset() noexcept override {}
  3005. void process (float* l, float* r, int n, const lynx::EffectParams&, double) noexcept override { line.process (l, r, n); }
  3006. int latencySamples() const noexcept override { return latency; }
  3007. private:
  3008. int latency;
  3009. lynx::DelayLine line;
  3010. };
  3011. } // namespace
  3012. TEST (delay_line_mix_into_matches_process_and_drains_tail)
  3013. {
  3014. // mixInto = process over source*level, added to the destination; in stretches that cross the ring
  3015. lynx::DelayLine a (37), b (37);
  3016. std::vector<float> sl (300), sr (300), dl (300, 0.5f), dr (300, -0.5f), xl (300), xr (300);
  3017. for (int i = 0; i < 300; ++i)
  3018. {
  3019. sl[(std::size_t) i] = (float) std::sin (i * 0.1);
  3020. sr[(std::size_t) i] = (float) std::cos (i * 0.07);
  3021. }
  3022. for (int start = 0; start < 300; start += 100)
  3023. {
  3024. b.mixInto (sl.data() + start, sr.data() + start, 0.25f, dl.data() + start, dr.data() + start, 100);
  3025. for (int i = start; i < start + 100; ++i)
  3026. {
  3027. xl[(std::size_t) i] = sl[(std::size_t) i] * 0.25f;
  3028. xr[(std::size_t) i] = sr[(std::size_t) i] * 0.25f;
  3029. }
  3030. a.process (xl.data() + start, xr.data() + start, 100);
  3031. }
  3032. float worst = 0.0f;
  3033. for (int i = 0; i < 300; ++i)
  3034. worst = std::max ({ worst, std::abs (dl[(std::size_t) i] - 0.5f - xl[(std::size_t) i]),
  3035. std::abs (dr[(std::size_t) i] + 0.5f - xr[(std::size_t) i]) });
  3036. CHECK (worst < 1e-6f);
  3037. // silenced source: the tail still in the line comes out, then nothing remains
  3038. std::vector<float> tl (64, 0.0f), tr (64, 0.0f);
  3039. b.mixInto (nullptr, nullptr, 1.0f, tl.data(), tr.data(), 64);
  3040. CHECK (std::abs (tl[0] - sl[263] * 0.25f) < 1e-6f);
  3041. std::vector<float> zl (64, 0.0f), zr (64, 0.0f);
  3042. b.mixInto (nullptr, nullptr, 1.0f, zl.data(), zr.data(), 64);
  3043. CHECK (*std::max_element (zl.begin(), zl.end()) == 0.0f && *std::min_element (zl.begin(), zl.end()) == 0.0f);
  3044. }
  3045. TEST (limiter_lookahead_holds_ceiling_on_bursts)
  3046. {
  3047. // short bursts over a low floor: the sliding maximum must see each peak before it leaves
  3048. auto fx = lynx::makeEffect (lynx::EffectKind::limiter);
  3049. fx->prepare (48000.0);
  3050. auto slot = lynx::makeEffectSlot (lynx::EffectKind::limiter);
  3051. slot.params[2] = 0.0f; // 10 ms release
  3052. std::vector<float> l (48000), r (48000);
  3053. std::uint32_t seed = 1;
  3054. for (int i = 0; i < 48000; ++i)
  3055. {
  3056. seed = seed * 1664525u + 1013904223u;
  3057. const auto noise = ((float) (seed >> 8) / 16777216.0f - 0.5f) * 0.1f;
  3058. l[(std::size_t) i] = noise + ((i % 9973) < 3 ? 3.0f : 0.0f);
  3059. r[(std::size_t) i] = -noise;
  3060. }
  3061. for (int i = 0; i < 48000; i += 333)
  3062. fx->process (l.data() + i, r.data() + i, std::min (333, 48000 - i), slot.params, 120.0);
  3063. float peak = 0.0f, quiet = 0.0f;
  3064. for (int i = 0; i < 48000; ++i)
  3065. peak = std::max (peak, std::abs (l[(std::size_t) i]));
  3066. for (int i = 9973 * 2 + 2000; i < 9973 * 2 + 2400; ++i) // 40 ms after the burst the gain has already recovered
  3067. quiet = std::max (quiet, std::abs (r[(std::size_t) i]));
  3068. const auto ceiling = 1.0f; // the default ceiling is at 0 dBFS or below
  3069. CHECK (peak <= ceiling + 1e-5f);
  3070. CHECK (quiet > 0.03f);
  3071. }
  3072. TEST (pdc_aligns_paths_through_latent_effects)
  3073. {
  3074. // plan: channel 0 -> insert 1 (effect of 100) -> insert 3; channel 1 -> insert 2 -> Master
  3075. lynx::Song s;
  3076. s.mixer = lynx::Song::defaultMixer (4);
  3077. s.channels.resize (3);
  3078. s.channels[0].mixerTrack = 1;
  3079. s.channels[1].mixerTrack = 2;
  3080. s.channels[2].mixerTrack = 3;
  3081. s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::eq));
  3082. s.setRoute (1, 3, true);
  3083. s.setRoute (1, 0, false);
  3084. auto plan = lynx::computePdc (s, { 0, 0, 30 }, { {}, { 100 } });
  3085. CHECK (plan.inAlign[1] == 0 && plan.outLat[1] == 100);
  3086. CHECK (plan.inAlign[3] == 100 && plan.channelDelay[2] == 70); // instrument of 30 on insert 3
  3087. CHECK (plan.sendDelay[1][1] == 0); // the slowest path isn't delayed
  3088. CHECK (plan.sendDelay[2][0] == 100 && plan.sendDelay[3][0] == 0 && plan.total == 100);
  3089. // bypass zeroes the slot's latency
  3090. s.mixer[1].effects[0].enabled = false;
  3091. CHECK (lynx::computePdc (s, { 0, 0, 30 }, { {}, { 100 } }).total == 30);
  3092. // rendered: two impulses played together come out together
  3093. lynx::Song r;
  3094. r.mixer = lynx::Song::defaultMixer (2);
  3095. for (int i = 0; i < 2; ++i)
  3096. {
  3097. lynx::ChannelDef c;
  3098. c.instrument = lynx::InstrumentKind::sampler;
  3099. c.samplePath = "impulso";
  3100. c.volume = 1.0f;
  3101. c.mixerTrack = i + 1;
  3102. r.channels.push_back (c);
  3103. }
  3104. r.patterns.emplace_back();
  3105. lynx::EffectSlot fx;
  3106. fx.kind = lynx::EffectKind::plugin;
  3107. fx.plugin.id = "latente";
  3108. r.mixer[1].effects.push_back (fx);
  3109. lynx::RackState::Factories f;
  3110. f.samples = [] (const std::string&) {
  3111. auto d = std::make_shared<lynx::SampleData>();
  3112. d->left.assign (64, 0.0f);
  3113. d->left[0] = 1.0f;
  3114. return std::shared_ptr<const lynx::SampleData> (d);
  3115. };
  3116. f.pluginEffects = [] (const lynx::PluginRef&, double) -> std::shared_ptr<lynx::Effect> { return std::make_shared<LatentEffect> (100); };
  3117. auto state = lynx::RackState::build (r, nullptr, 48000.0, f);
  3118. CHECK (state->pdc.total == 100 && state->sendDelays[2][0] != nullptr && state->sendDelays[2][0]->length() == 100);
  3119. lynx::RackRenderer renderer;
  3120. renderer.prepare (48000.0, 256);
  3121. lynx::LiveEventQueue live;
  3122. for (int ch = 0; ch < 2; ++ch)
  3123. {
  3124. lynx::NoteEvent on;
  3125. on.channel = ch;
  3126. on.key = 60;
  3127. on.velocity = 1.0f;
  3128. live.push (on);
  3129. }
  3130. std::vector<float> l (256), rr (256);
  3131. renderer.process (state.get(), false, 0.0, 256, l.data(), rr.data(), &live);
  3132. int first = -1;
  3133. for (int i = 0; i < 256 && first < 0; ++i)
  3134. if (std::abs (l[(std::size_t) i]) > 0.01f)
  3135. first = i;
  3136. CHECK (first == 100 && std::abs (l[100] - 2.0f) < 1e-3f); // both impulses arrive together, summed
  3137. // editing without changing latencies reuses the lines
  3138. r.channels[0].volume = 0.5f;
  3139. auto next = lynx::RackState::build (r, state.get(), 48000.0, f);
  3140. CHECK (next->sendDelays[2][0] == state->sendDelays[2][0]);
  3141. }
  3142. TEST (mixer_mute_fades_instead_of_clicking)
  3143. {
  3144. lynx::Song s;
  3145. s.mixer = lynx::Song::defaultMixer (2);
  3146. lynx::ChannelDef c;
  3147. c.instrument = lynx::InstrumentKind::sampler;
  3148. c.samplePath = "dc";
  3149. c.volume = 1.0f;
  3150. c.mixerTrack = 1;
  3151. s.channels.push_back (c);
  3152. s.patterns.emplace_back();
  3153. auto provider = [] (const std::string&) {
  3154. auto d = std::make_shared<lynx::SampleData>();
  3155. d->left.assign (48000, 0.5f);
  3156. return std::shared_ptr<const lynx::SampleData> (d);
  3157. };
  3158. auto on = lynx::RackState::build (s, nullptr, 48000.0, provider);
  3159. s.mixer[1].muted = true;
  3160. auto off = lynx::RackState::build (s, on.get(), 48000.0, provider);
  3161. lynx::RackRenderer r;
  3162. r.prepare (48000.0, 256);
  3163. lynx::LiveEventQueue live;
  3164. lynx::NoteEvent note;
  3165. note.velocity = 1.0f;
  3166. live.push (note);
  3167. std::vector<float> l (256), rr (256);
  3168. r.process (on.get(), false, 0.0, 256, l.data(), rr.data(), &live);
  3169. CHECK (std::abs (l[255] - 0.5f) < 1e-3f);
  3170. r.process (off.get(), false, 0.0, 256, l.data(), rr.data());
  3171. CHECK (l[0] > 0.45f && l[128] > 0.2f && l[128] < 0.3f && std::abs (l[255]) < 1e-6f); // ramp down to zero
  3172. r.process (off.get(), false, 0.0, 256, l.data(), rr.data());
  3173. CHECK (std::abs (l[0]) < 1e-9f);
  3174. }
  3175. TEST (dither_quantizes_to_lsb_grid_with_small_error)
  3176. {
  3177. lynx::Dither d (16);
  3178. std::vector<float> x (4800);
  3179. for (std::size_t i = 0; i < x.size(); ++i)
  3180. x[i] = 0.25f * std::sin ((float) i * 0.05f);
  3181. auto y = x;
  3182. d.process (y.data(), (int) y.size(), 0);
  3183. double errorSum = 0.0;
  3184. bool onGrid = true;
  3185. for (std::size_t i = 0; i < x.size(); ++i)
  3186. {
  3187. const auto steps = y[i] * 32768.0f;
  3188. onGrid = onGrid && std::abs (steps - std::round (steps)) < 1e-3f;
  3189. errorSum += std::abs (y[i] - x[i]);
  3190. }
  3191. CHECK (onGrid);
  3192. CHECK (errorSum / (double) x.size() < 4.0 / 32768.0); // a few LSBs of noise on average
  3193. }
  3194. TEST (parallel_rendering_matches_sequential)
  3195. {
  3196. // 32 channels (worth parallelizing), inserts with chained sends
  3197. auto song = lynx::Song::makeDefault();
  3198. song.mixer = lynx::Song::defaultMixer (16);
  3199. for (int i = 5; i < 32; ++i)
  3200. {
  3201. lynx::ChannelDef c;
  3202. c.instrument = i % 2 ? lynx::InstrumentKind::synth : lynx::InstrumentKind::hat;
  3203. c.mixerTrack = 1 + i % 12;
  3204. c.volume = 0.3f;
  3205. song.channels.push_back (c);
  3206. for (int step = i % 4; step < 16; step += 3)
  3207. song.patterns[0].notes.push_back ({ (std::int64_t) step * lynx::ticksPerStep, 200, i, 48 + i, 0.7f });
  3208. }
  3209. song.patterns[0].sortNotes();
  3210. song.setRoute (3, 7, true, 0.6f);
  3211. song.setRoute (7, 9, true, 0.5f);
  3212. song.setRoute (2, 9, true);
  3213. song.mixer[9].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::reverb));
  3214. auto seqState = lynx::RackState::build (song, nullptr, 48000.0);
  3215. auto parState = lynx::RackState::build (song, nullptr, 48000.0);
  3216. CHECK (parState->parallel && parState->mixerLayers.size() == 3);
  3217. lynx::WorkerPool pool (3);
  3218. lynx::RackRenderer seq, par;
  3219. seq.prepare (48000.0, 512);
  3220. par.prepare (48000.0, 512);
  3221. par.setWorkerPool (&pool);
  3222. std::vector<float> l1 (512), r1 (512), l2 (512), r2 (512);
  3223. const auto tps = lynx::ticksPerSample (song.bpm, 48000.0);
  3224. bool same = true;
  3225. float peak = 0.0f;
  3226. for (int block = 0; block < 200; ++block)
  3227. {
  3228. seq.process (seqState.get(), true, block * 512 * tps, 512, l1.data(), r1.data());
  3229. par.process (parState.get(), true, block * 512 * tps, 512, l2.data(), r2.data());
  3230. same = same && l1 == l2 && r1 == r2;
  3231. for (auto v : l1)
  3232. peak = std::max (peak, std::abs (v));
  3233. }
  3234. CHECK (same);
  3235. CHECK (peak > 0.05f);
  3236. // the pool handles many small rounds in a row
  3237. std::atomic<int> sum { 0 };
  3238. auto add = [&sum] (int i) { sum.fetch_add (i + 1); };
  3239. for (int round = 0; round < 2000; ++round)
  3240. pool.parallelFor (5, add);
  3241. CHECK (sum.load() == 2000 * 15);
  3242. }
  3243. TEST (arrangements_switch_and_keep_clip_indices)
  3244. {
  3245. auto s = lynx::Song::makeDefault();
  3246. s.patterns.emplace_back().name = "B";
  3247. s.playlist = { { 1, 0, 0, 960, 0 } };
  3248. s.loopEnd = 960;
  3249. CHECK (s.arrangements.size() == 1 && s.currentArrangement == 0);
  3250. const auto second = s.addArrangement ("Versão curta", true);
  3251. CHECK (second == 1 && s.currentArrangement == 1 && s.playlist.size() == 1 && s.loopEnd == 960);
  3252. s.playlist.push_back ({ 0, 1, 960, 960, 0 });
  3253. s.loopEnd = 0;
  3254. s.selectArrangement (0);
  3255. CHECK (s.playlist.size() == 1 && s.loopEnd == 960 && s.arrangements[1].clips.size() == 2);
  3256. // removing pattern 0 fixes the clips stored in the other arrangement
  3257. s.removePattern (0);
  3258. CHECK (s.playlist.size() == 1 && s.playlist[0].pattern == 0);
  3259. CHECK (s.arrangements[1].clips.size() == 1 && s.arrangements[1].clips[0].pattern == 0);
  3260. s.removeArrangement (0);
  3261. CHECK (s.arrangements.size() == 1 && s.currentArrangement == 0 && s.playlist.size() == 1 && s.loopEnd == 0);
  3262. }
  3263. namespace
  3264. {
  3265. // Test effect that inverts the signal and counts how many times it processed.
  3266. class CountingInverter final : public lynx::Effect
  3267. {
  3268. public:
  3269. void prepare (double) noexcept override {}
  3270. void reset() noexcept override {}
  3271. void process (float* l, float* r, int n, const lynx::EffectParams&, double) noexcept override
  3272. {
  3273. ++calls;
  3274. for (int i = 0; i < n; ++i)
  3275. {
  3276. l[i] = -l[i];
  3277. r[i] = -r[i];
  3278. }
  3279. }
  3280. int calls = 0;
  3281. };
  3282. } // namespace
  3283. TEST (keyboard_controller_outputs_key_value)
  3284. {
  3285. std::vector<std::uint8_t> blob (554, 0);
  3286. const std::uint32_t version = 3;
  3287. std::memcpy (blob.data(), &version, 4);
  3288. const float key60 = 0.7f, off = 0.2f;
  3289. std::memcpy (blob.data() + 12 + 60 * 4, &key60, 4);
  3290. std::memcpy (blob.data() + 548, &off, 4);
  3291. blob[552] = 1; // auto release
  3292. lynx::ChannelDef c;
  3293. c.instrument = lynx::InstrumentKind::controller;
  3294. c.controllerState = blob;
  3295. auto inst = lynx::makeInstrument (lynx::InstrumentKind::controller);
  3296. inst->prepare (48000.0);
  3297. inst->configure (c, 120.0);
  3298. std::vector<float> l (64), r (64);
  3299. inst->noteOn (60, 1.0f);
  3300. inst->render (l.data(), r.data(), 64, 1.0f, 1.0f);
  3301. CHECK (std::abs (inst->controlOutput (0) - 0.7f) < 1e-6f);
  3302. inst->noteOff (60);
  3303. CHECK (std::abs (inst->controlOutput (0) - 0.2f) < 1e-6f);
  3304. }
  3305. TEST (envelope_controller_ducks_on_each_note)
  3306. {
  3307. // a unipolar articulator like "Basic Sidechain": base 0.05, drops to 0 on the note and rises to 1 in 0.3 s
  3308. lynx::ControllerArticulator a;
  3309. a.envOn = true;
  3310. a.base = 0.05f;
  3311. a.envLevel = 1.0f;
  3312. a.count = 3;
  3313. a.time = { 0.0f, 0.2f, 0.3f };
  3314. a.level = { 0.0f, 0.75f, 1.0f };
  3315. CHECK (std::abs (lynx::controllerValue (a, 0.0, -1.0) - 0.05f) < 1e-4f);
  3316. CHECK (std::abs (lynx::controllerValue (a, 0.1, -1.0) - 0.425f) < 1e-3f);
  3317. CHECK (lynx::controllerValue (a, 1.0, -1.0) > 0.99f); // no sustain: runs to the end and stays
  3318. a.sustain = 1;
  3319. CHECK (std::abs (lynx::controllerValue (a, 1.0, -1.0) - 0.8f) < 1e-3f); // held at sustain
  3320. CHECK (lynx::controllerValue (a, 1.0, 0.5) > 0.99f); // released: continues to the end
  3321. a.bipolar = true;
  3322. a.base = 0.5f;
  3323. a.sustain = -1;
  3324. CHECK (std::abs (lynx::controllerValue (a, 0.0, -1.0) - 0.0f) < 1e-4f); // bipolar: 0.5 + (0 − 0.5)
  3325. }
  3326. TEST (peak_controller_drives_live_automation)
  3327. {
  3328. // track 1: source (DC 0.5) with Peak Controller; track 2: DC 0.5 with volume linked to the controller
  3329. auto render = [] (bool linked) {
  3330. lynx::Song s;
  3331. s.mixer = lynx::Song::defaultMixer (2);
  3332. for (int t = 1; t <= 2; ++t)
  3333. {
  3334. lynx::ChannelDef c;
  3335. c.instrument = lynx::InstrumentKind::sampler;
  3336. c.samplePath = "dc";
  3337. c.volume = 1.0f;
  3338. c.mixerTrack = t;
  3339. s.channels.push_back (c);
  3340. }
  3341. s.patterns.emplace_back();
  3342. auto peak = lynx::makeEffectSlot (lynx::EffectKind::peakController);
  3343. peak.params[0] = 1.0f; // base 1
  3344. peak.params[1] = 0.0f; // amount −1: 1 − peak
  3345. peak.params[2] = 0.5f; // no tension
  3346. s.mixer[1].effects.push_back (peak);
  3347. if (linked)
  3348. {
  3349. lynx::Automation a;
  3350. a.name = "Peak";
  3351. a.target = { lynx::AutomationTargetKind::mixerVolume, 2 };
  3352. a.source = { 1, 0, 0 };
  3353. s.automations.push_back (a);
  3354. }
  3355. lynx::RackState::Factories f;
  3356. f.samples = [] (const std::string&) {
  3357. auto d = std::make_shared<lynx::SampleData>();
  3358. d->left.assign (48000, 0.5f);
  3359. return std::shared_ptr<const lynx::SampleData> (d);
  3360. };
  3361. auto state = lynx::RackState::build (s, nullptr, 48000.0, f);
  3362. lynx::RackRenderer r;
  3363. r.prepare (48000.0, 512);
  3364. lynx::LiveEventQueue live;
  3365. for (int ch = 0; ch < 2; ++ch)
  3366. {
  3367. lynx::NoteEvent on;
  3368. on.channel = ch;
  3369. on.velocity = 1.0f;
  3370. live.push (on);
  3371. }
  3372. std::vector<float> l (4800), rr (4800);
  3373. r.process (state.get(), false, 0.0, 4800, l.data(), rr.data(), &live);
  3374. return l[4000];
  3375. };
  3376. const auto free = render (false), ducked = render (true);
  3377. CHECK (std::isfinite (ducked) && ducked > 0.0f);
  3378. CHECK (ducked < free - 0.05f); // the 0.5 peak on track 1 lowers track 2's volume
  3379. }
  3380. TEST (effect_slot_dry_wet_and_smart_disable)
  3381. {
  3382. lynx::Song s;
  3383. s.mixer = lynx::Song::defaultMixer (1);
  3384. lynx::ChannelDef c;
  3385. c.instrument = lynx::InstrumentKind::sampler;
  3386. c.samplePath = "dc";
  3387. c.volume = 1.0f;
  3388. c.mixerTrack = 1;
  3389. s.channels.push_back (c);
  3390. s.patterns.emplace_back();
  3391. lynx::EffectSlot fx;
  3392. fx.kind = lynx::EffectKind::plugin;
  3393. fx.plugin.id = "inversor";
  3394. fx.mix = 0.25f; // 75% dry (+0.5) and 25% wet (-0.5) = +0.25
  3395. s.mixer[1].effects.push_back (fx);
  3396. auto inverter = std::make_shared<CountingInverter>();
  3397. lynx::RackState::Factories f;
  3398. f.samples = [] (const std::string&) {
  3399. auto d = std::make_shared<lynx::SampleData>();
  3400. d->left.assign (4800, 0.5f);
  3401. return std::shared_ptr<const lynx::SampleData> (d);
  3402. };
  3403. f.pluginEffects = [inverter] (const lynx::PluginRef&, double) -> std::shared_ptr<lynx::Effect> { return inverter; };
  3404. auto state = lynx::RackState::build (s, nullptr, 48000.0, f);
  3405. lynx::RackRenderer r;
  3406. r.prepare (48000.0, 512);
  3407. lynx::LiveEventQueue live;
  3408. lynx::NoteEvent on;
  3409. on.velocity = 1.0f;
  3410. live.push (on);
  3411. std::vector<float> l (480), rr (480);
  3412. r.process (state.get(), false, 0.0, 480, l.data(), rr.data(), &live);
  3413. CHECK (std::abs (l[100] - 0.25f) < 1e-4f);
  3414. // after the sample ends: 4 s of silence and the plugin stops being called
  3415. for (int i = 0; i < 100 * 6; ++i) // 6 s
  3416. r.process (state.get(), false, 0.0, 480, l.data(), rr.data());
  3417. const auto callsAfterSilence = inverter->calls;
  3418. for (int i = 0; i < 100; ++i)
  3419. r.process (state.get(), false, 0.0, 480, l.data(), rr.data());
  3420. CHECK (inverter->calls == callsAfterSilence);
  3421. CHECK (callsAfterSilence < 100 * 6);
  3422. // sound again: processing resumes in the same block
  3423. live.push (on);
  3424. r.process (state.get(), false, 0.0, 480, l.data(), rr.data(), &live);
  3425. CHECK (inverter->calls == callsAfterSilence + 1 && std::abs (l[100] - 0.25f) < 1e-4f);
  3426. }
  3427. TEST (swing_delays_offbeat_sixteenths)
  3428. {
  3429. CHECK (lynx::swingDelay (0, 1.0f) == 0);
  3430. CHECK (lynx::swingDelay (lynx::ticksPerStep, 1.0f) == lynx::ticksPerStep / 2);
  3431. CHECK (lynx::swingDelay (lynx::ticksPerStep * 2, 1.0f) == 0);
  3432. CHECK (lynx::swingDelay (lynx::ticksPerStep + 10, 1.0f) == (lynx::ticksPerStep - 20) / 2); // off the grid: triangular weight (FL)
  3433. CHECK (lynx::swingDelay (lynx::ticksPerStep, 1.0f, 0.5f) == lynx::ticksPerStep / 4); // channel mix
  3434. CHECK (lynx::swingDelay (lynx::ticksPerStep * 3, 0.5f) == lynx::ticksPerStep / 4);
  3435. lynx::Pattern p;
  3436. p.notes = { { 0, 100, 0, 60 }, { lynx::ticksPerStep, 100, 0, 62 } };
  3437. lynx::EventBuffer ev;
  3438. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  3439. lynx::schedulePatternLoop (p, p.effectiveLength (4), 0.0, 12000, tps, ev, 1.0f);
  3440. int onOffset = -1;
  3441. for (auto& e : ev)
  3442. if (e.type == lynx::NoteEvent::Type::on && e.key == 62)
  3443. onOffset = e.sampleOffset;
  3444. CHECK (onOffset == (int) std::floor ((lynx::ticksPerStep * 1.5) / tps));
  3445. }
  3446. TEST (sampler_settings_pitch_reverse_envelope_cut)
  3447. {
  3448. auto ramp = std::make_shared<lynx::SampleData>();
  3449. for (int i = 0; i < 48000; ++i)
  3450. ramp->left.push_back ((float) i / 48000.0f); // ramp: the value tells where the read position is
  3451. ramp->sampleRate = 48000.0;
  3452. auto play = [&] (const lynx::SamplerSettings& s, int key, int frames, bool releaseAfterHalf) {
  3453. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  3454. inst->prepare (48000.0);
  3455. lynx::ChannelDef c;
  3456. c.sampler = s;
  3457. inst->configure (c, 120.0);
  3458. inst->noteOn (key, 1.0f);
  3459. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  3460. inst->render (l.data(), r.data(), frames / 2, 1.0f, 1.0f);
  3461. if (releaseAfterHalf)
  3462. inst->noteOff (key);
  3463. inst->render (l.data() + frames / 2, r.data() + frames / 2, frames - frames / 2, 1.0f, 1.0f);
  3464. return l;
  3465. };
  3466. // +12 semitones: reads twice as fast
  3467. lynx::SamplerSettings up;
  3468. up.pitch = 12.0f;
  3469. CHECK (std::abs (play (up, 60, 1000, false)[999] - 2.0f * 999.0f / 48000.0f) < 1e-3f);
  3470. // reversed: starts from the end
  3471. lynx::SamplerSettings back;
  3472. back.reverse = true;
  3473. CHECK (play (back, 60, 100, false)[10] > 0.99f);
  3474. // 10 ms attack: starts silent and reaches full level
  3475. lynx::SamplerSettings slow;
  3476. slow.attack = 0.01f;
  3477. const auto a = play (slow, 60, 2000, false);
  3478. CHECK (a[10] < 0.2f * (10.0f / 48000.0f) + 1e-6f && std::abs (a[1500] - 1500.0f / 48000.0f) < 1e-4f);
  3479. // 5 ms release: gone right after release; without release it plays in full
  3480. lynx::SamplerSettings rel;
  3481. rel.release = 0.005f;
  3482. CHECK (play (rel, 60, 2000, true)[1999] == 0.0f);
  3483. CHECK (play (lynx::SamplerSettings {}, 60, 2000, true)[1999] > 0.0f);
  3484. // cut itself: the second note cuts the first (one voice remains)
  3485. lynx::SamplerSettings cut;
  3486. cut.cut = true;
  3487. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  3488. inst->prepare (48000.0);
  3489. lynx::ChannelDef cutChannel;
  3490. cutChannel.sampler = cut;
  3491. inst->configure (cutChannel, 120.0);
  3492. inst->noteOn (60, 1.0f);
  3493. std::vector<float> l (2000), r (2000);
  3494. inst->render (l.data(), r.data(), 1000, 1.0f, 1.0f);
  3495. inst->noteOn (60, 1.0f);
  3496. std::fill (l.begin(), l.end(), 0.0f);
  3497. inst->render (l.data(), r.data(), 2000, 1.0f, 1.0f);
  3498. CHECK (std::abs (l[1999] - 1999.0f / 48000.0f) < 1e-4f); // only the new note
  3499. }
  3500. TEST (playlist_split_and_track_mute)
  3501. {
  3502. lynx::Clip c { 0, 3, 960, 3840, 480 };
  3503. const auto rest = lynx::splitClip (c, 2000);
  3504. CHECK (c.start == 960 && c.length == 1040 && c.offset == 480);
  3505. CHECK (rest.start == 2000 && rest.length == 2800 && rest.offset == 480 + 1040 && rest.track == 3);
  3506. auto s = lynx::Song::makeDefault();
  3507. s.mode = lynx::PlayMode::song;
  3508. s.playlist = { { 0, 0, 0, 3840, 0 } };
  3509. lynx::EventBuffer ev;
  3510. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  3511. lynx::scheduleSong (s, 0.0, 48000, tps, ev);
  3512. CHECK (ev.size() > 0);
  3513. s.playlistTracks.resize (1);
  3514. s.playlistTracks[0].muted = true;
  3515. ev.clear();
  3516. lynx::scheduleSong (s, 0.0, 48000, tps, ev);
  3517. CHECK (ev.size() == 0);
  3518. }
  3519. TEST (note_pan_pitch_and_mute)
  3520. {
  3521. lynx::Pattern p;
  3522. lynx::Note a { 0, 240, 0, 60 };
  3523. a.pan = -1.0f;
  3524. a.finePitch = 50.0f;
  3525. lynx::Note b { 240, 240, 0, 62 };
  3526. b.muted = true;
  3527. p.notes = { a, b };
  3528. lynx::EventBuffer ev;
  3529. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  3530. lynx::schedulePatternLoop (p, p.effectiveLength (4), 0.0, 48000, tps, ev);
  3531. int ons = 0;
  3532. for (auto& e : ev)
  3533. if (e.type == lynx::NoteEvent::Type::on)
  3534. {
  3535. ++ons;
  3536. CHECK (e.key == 60 && e.pan == -1.0f && e.cents == 50.0f);
  3537. }
  3538. CHECK (ons == 1); // the muted one doesn't play
  3539. // note pan in the sampler: fully left
  3540. auto dc = std::make_shared<lynx::SampleData>();
  3541. dc->left.assign (4800, 0.5f);
  3542. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, dc);
  3543. inst->prepare (48000.0);
  3544. inst->setNextNoteExpression (-1.0f, 0.0f);
  3545. inst->noteOn (60, 1.0f);
  3546. std::vector<float> l (100), r (100);
  3547. inst->render (l.data(), r.data(), 100, 1.0f, 1.0f);
  3548. CHECK (l[50] > 0.6f && std::abs (r[50]) < 1e-6f);
  3549. }
  3550. TEST (tempo_automation_changes_speed_and_duration)
  3551. {
  3552. auto song = lynx::Song::makeDefault();
  3553. song.bpm = 120.0;
  3554. song.mode = lynx::PlayMode::song;
  3555. const auto bar = (std::int64_t) lynx::ppq * 4;
  3556. song.playlist = { { 0, 0, 0, bar, 0 }, { 0, 0, bar, bar, 0 } };
  3557. lynx::Automation tempo;
  3558. tempo.target = { lynx::AutomationTargetKind::tempo, 0 };
  3559. const auto v120 = lynx::valueFromTempo (120.0), v240 = lynx::valueFromTempo (240.0);
  3560. tempo.points = { { 0, v120 }, { bar - 1, v120 }, { bar, v240 } }; // step: 120 -> 240 at bar 2
  3561. song.automations.push_back (tempo);
  3562. lynx::Clip clip;
  3563. clip.kind = lynx::ClipKind::automation;
  3564. clip.automation = 0;
  3565. clip.track = 1;
  3566. clip.length = bar * 2;
  3567. song.playlist.push_back (clip);
  3568. CHECK (std::abs (song.tempoAt (100.0) - 120.0) < 0.01 && std::abs (song.tempoAt ((double) bar + 100.0) - 240.0) < 0.01);
  3569. // 1 bar at 120 (2 s) + 1 at 240 (1 s)
  3570. CHECK (std::abs (song.secondsForTicks (bar * 2) - 3.0) < 0.01);
  3571. auto state = lynx::RackState::build (song, nullptr, 48000.0);
  3572. CHECK (state->tempoAutomation == 0);
  3573. lynx::RackRenderer r;
  3574. r.prepare (48000.0, 512);
  3575. std::vector<float> l (512), rr (512);
  3576. r.process (state.get(), true, 10.0, 512, l.data(), rr.data());
  3577. CHECK (std::abs (r.currentBpm() - 120.0) < 0.01);
  3578. r.process (state.get(), true, (double) bar + 10.0, 512, l.data(), rr.data());
  3579. CHECK (std::abs (r.currentBpm() - 240.0) < 0.01);
  3580. }
  3581. TEST (bounce_insert_song_and_apply)
  3582. {
  3583. auto s = lynx::Song::makeDefault();
  3584. s.setRoute (3, 7, true, 0.5f);
  3585. s.mixer[0].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::reverb));
  3586. s.mixer[2].solo = true;
  3587. const auto b = lynx::makeBounceSong (s, 3);
  3588. CHECK (b.mixer[3].solo && ! b.mixer[2].solo && b.mixer[3].toMaster && b.mixer[3].sends.empty());
  3589. CHECK (b.mixer[0].effects.empty() && b.mode == lynx::PlayMode::song);
  3590. const auto audible = b.soloAudible();
  3591. CHECK (audible[3] && ! audible[1] && ! audible[7]);
  3592. const auto channels = s.channels.size();
  3593. const auto inserts = s.mixer.size();
  3594. const auto created = lynx::applyBounce (s, 3, "C:/x.wav", 3840);
  3595. CHECK (created == (int) inserts && s.mixer.size() == inserts + 1 && s.mixer[3].muted);
  3596. CHECK (s.mixer[(std::size_t) created].sends.size() == 1 && s.mixer[(std::size_t) created].sends[0].target == 7);
  3597. CHECK (s.channels.size() == channels + 1 && s.channels.back().mixerTrack == created);
  3598. CHECK (s.playlist.back().kind == lynx::ClipKind::audio && s.playlist.back().length == 3840);
  3599. }
  3600. TEST (mixer_stereo_separation_phase_swap)
  3601. {
  3602. lynx::MixerTrack t;
  3603. std::vector<float> l { 1.0f }, r { 0.0f };
  3604. t.stereo = 1.0f; // mono
  3605. lynx::RackRenderer::applyStereoForTest (t, l.data(), r.data(), 1);
  3606. CHECK (std::abs (l[0] - 0.5f) < 1e-6f && std::abs (r[0] - 0.5f) < 1e-6f);
  3607. l = { 1.0f };
  3608. r = { 0.0f };
  3609. t.stereo = -1.0f; // doubled side: 1.5 L - 0.5 R
  3610. lynx::RackRenderer::applyStereoForTest (t, l.data(), r.data(), 1);
  3611. CHECK (std::abs (l[0] - 1.5f) < 1e-6f && std::abs (r[0] + 0.5f) < 1e-6f);
  3612. l = { 1.0f };
  3613. r = { 0.25f };
  3614. t.stereo = 0.0f;
  3615. t.swapChannels = true;
  3616. t.invertPhase = true;
  3617. lynx::RackRenderer::applyStereoForTest (t, l.data(), r.data(), 1);
  3618. CHECK (l[0] == -0.25f && r[0] == -1.0f);
  3619. }
  3620. TEST (effects_limiter_filter_distortion_chorus)
  3621. {
  3622. const double sr = 48000.0;
  3623. auto sine = [] (float hz, float amp, int n) {
  3624. std::vector<float> v ((std::size_t) n);
  3625. for (int i = 0; i < n; ++i)
  3626. v[(std::size_t) i] = amp * std::sin (2.0f * 3.14159265f * hz * (float) i / 48000.0f);
  3627. return v;
  3628. };
  3629. auto peak = [] (const std::vector<float>& v, int from) {
  3630. float p = 0.0f;
  3631. for (std::size_t i = (std::size_t) from; i < v.size(); ++i)
  3632. p = std::max (p, std::abs (v[i]));
  3633. return p;
  3634. };
  3635. // limiter: +12 dB on a 0.9 sine never exceeds the ceiling (-1 dB) and reports the latency
  3636. auto lim = lynx::makeEffect (lynx::EffectKind::limiter);
  3637. lim->prepare (sr);
  3638. auto slot = lynx::makeEffectSlot (lynx::EffectKind::limiter);
  3639. slot.params[0] = 11.0f / 12.0f; // -1 dB
  3640. slot.params[1] = 0.5f; // +12 dB
  3641. auto l = sine (100.0f, 0.9f, 48000), r = l;
  3642. lim->process (l.data(), r.data(), 48000, slot.params, 120.0);
  3643. CHECK (peak (l, 0) <= std::pow (10.0f, -1.0f / 20.0f) + 1e-4f);
  3644. CHECK (peak (l, 4800) > 0.8f);
  3645. CHECK (lim->latencySamples() == 72);
  3646. // low-pass filter at 500 Hz knocks down an 8 kHz sine
  3647. auto lp = lynx::makeEffect (lynx::EffectKind::filter);
  3648. lp->prepare (sr);
  3649. auto fs = lynx::makeEffectSlot (lynx::EffectKind::filter);
  3650. fs.params[1] = std::log (500.0f / 20.0f) / std::log (1000.0f);
  3651. l = sine (8000.0f, 1.0f, 9600);
  3652. r = l;
  3653. lp->process (l.data(), r.data(), 9600, fs.params, 120.0);
  3654. CHECK (peak (l, 4800) < 0.05f);
  3655. // distortion and chorus: finite, audible output
  3656. for (auto kind : { lynx::EffectKind::distortion, lynx::EffectKind::chorus })
  3657. {
  3658. auto fx = lynx::makeEffect (kind);
  3659. fx->prepare (sr);
  3660. auto ps = lynx::makeEffectSlot (kind);
  3661. l = sine (220.0f, 0.5f, 9600);
  3662. r = l;
  3663. fx->process (l.data(), r.data(), 9600, ps.params, 120.0);
  3664. bool finite = true;
  3665. for (auto v : l)
  3666. finite = finite && std::isfinite (v);
  3667. CHECK (finite && peak (l, 2400) > 0.1f && peak (l, 0) < 2.0f);
  3668. }
  3669. }
  3670. TEST (slide_notes_glide_without_retrigger)
  3671. {
  3672. // sampler with a ramp: the read speed doubles after a one-octave slide
  3673. auto ramp = std::make_shared<lynx::SampleData>();
  3674. for (int i = 0; i < 96000; ++i)
  3675. ramp->left.push_back ((float) i / 96000.0f);
  3676. ramp->sampleRate = 48000.0;
  3677. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  3678. inst->prepare (48000.0);
  3679. inst->noteOn (60, 1.0f);
  3680. std::vector<float> l (2000), r (2000);
  3681. inst->render (l.data(), r.data(), 1000, 1.0f, 1.0f);
  3682. const auto stepBefore = l[999] - l[998];
  3683. inst->slideTo (72, 0.0f, 100.0f);
  3684. std::fill (l.begin(), l.end(), 0.0f);
  3685. inst->render (l.data(), r.data(), 1000, 1.0f, 1.0f);
  3686. const auto stepAfter = l[999] - l[998];
  3687. CHECK (std::abs (stepAfter / stepBefore - 2.0f) < 0.01f);
  3688. // the sequencer sends "slide" (no off) for the slide note
  3689. lynx::Pattern p;
  3690. lynx::Note base { 0, 960, 0, 48 };
  3691. lynx::Note glide { 480, 240, 0, 55 };
  3692. glide.slide = true;
  3693. p.notes = { base, glide };
  3694. lynx::EventBuffer ev;
  3695. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  3696. lynx::schedulePatternLoop (p, p.effectiveLength (4), 0.0, 30000, tps, ev);
  3697. int ons = 0, offs = 0, slides = 0;
  3698. for (auto& e : ev)
  3699. {
  3700. ons += e.type == lynx::NoteEvent::Type::on;
  3701. offs += e.type == lynx::NoteEvent::Type::off;
  3702. if (e.type == lynx::NoteEvent::Type::slide)
  3703. {
  3704. ++slides;
  3705. CHECK (e.key == 55 && std::abs (e.slideSamples - 240.0f / (float) tps) < 1.0f);
  3706. }
  3707. }
  3708. CHECK (ons == 1 && offs == 1 && slides == 1);
  3709. }
  3710. TEST (synth_fm_phase_modulation)
  3711. {
  3712. auto render = [] (const lynx::SynthSettings& s) {
  3713. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  3714. inst->prepare (48000.0);
  3715. lynx::ChannelDef c;
  3716. c.synth = s;
  3717. inst->configure (c, 120.0);
  3718. inst->noteOn (69, 1.0f); // 440 Hz
  3719. std::vector<float> l (48000), r (48000);
  3720. inst->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  3721. return l;
  3722. };
  3723. // energy (Goertzel) at frequency f over frames [from, to)
  3724. auto energy = [] (const std::vector<float>& x, double f, int from, int to) {
  3725. const auto w = 2.0 * 3.141592653589793 * f / 48000.0, k = 2.0 * std::cos (w);
  3726. double s1 = 0.0, s2 = 0.0;
  3727. for (int i = from; i < to; ++i)
  3728. {
  3729. const auto s0 = x[(std::size_t) i] + k * s1 - s2;
  3730. s2 = s1;
  3731. s1 = s0;
  3732. }
  3733. return s1 * s1 + s2 * s2 - k * s1 * s2;
  3734. };
  3735. lynx::SynthSettings plain;
  3736. plain.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  3737. plain.osc[2] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  3738. plain.cutoff = 20000.0f;
  3739. auto fm = plain;
  3740. fm.fm = 1.0f;
  3741. const auto a = render (plain), b = render (fm);
  3742. // no FM: osc 3 adds (same pitch) and there's no 2nd harmonic; with FM the sidebands appear
  3743. CHECK (energy (a, 880.0, 4800, 24000) < 1e-3 * energy (a, 440.0, 4800, 24000));
  3744. CHECK (energy (b, 880.0, 4800, 24000) > 0.1 * energy (b, 440.0, 4800, 24000));
  3745. CHECK (energy (b, 1320.0, 4800, 24000) > 0.01 * energy (b, 440.0, 4800, 24000));
  3746. for (auto v : b)
  3747. CHECK (std::isfinite (v) && std::abs (v) < 1.0f);
  3748. // index decaying to 0: the start is bright, the end is nearly a sine again
  3749. auto decaying = fm;
  3750. decaying.fmDecay = 0.1f;
  3751. decaying.fmSustain = 0.0f;
  3752. const auto c = render (decaying);
  3753. const auto early = energy (c, 880.0, 0, 2400) / energy (c, 440.0, 0, 2400);
  3754. const auto late = energy (c, 880.0, 36000, 48000) / energy (c, 440.0, 36000, 48000);
  3755. CHECK (early > 0.05 && late < 1e-3);
  3756. }
  3757. TEST (synth_three_oscillators_adsr_filter)
  3758. {
  3759. auto render = [] (const lynx::SynthSettings& s, int frames, int releaseAt) {
  3760. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  3761. inst->prepare (48000.0);
  3762. lynx::ChannelDef c;
  3763. c.synth = s;
  3764. inst->configure (c, 120.0);
  3765. inst->noteOn (69, 1.0f); // A4 = 440 Hz
  3766. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  3767. inst->render (l.data(), r.data(), releaseAt, 1.0f, 1.0f);
  3768. inst->noteOff (69);
  3769. inst->render (l.data() + releaseAt, r.data() + releaseAt, frames - releaseAt, 1.0f, 1.0f);
  3770. return l;
  3771. };
  3772. auto peakIn = [] (const std::vector<float>& v, int from, int to) {
  3773. float p = 0.0f;
  3774. for (int i = from; i < to; ++i)
  3775. p = std::max (p, std::abs (v[(std::size_t) i]));
  3776. return p;
  3777. };
  3778. // default: sounds and fades after the release
  3779. const lynx::SynthSettings standard;
  3780. const auto a = render (standard, 48000, 24000);
  3781. CHECK (peakIn (a, 1000, 20000) > 0.05f && peakIn (a, 40000, 48000) < 1e-3f);
  3782. // pure sine with an open filter: zero-crossing count gives ~440 Hz
  3783. lynx::SynthSettings sine;
  3784. sine.osc[0].wave = lynx::Waveform::sine;
  3785. sine.cutoff = 20000.0f;
  3786. const auto b = render (sine, 48000, 47000);
  3787. int crossings = 0;
  3788. for (int i = 4800; i < 4800 + 48000 / 2; ++i)
  3789. crossings += (b[(std::size_t) i - 1] < 0.0f) != (b[(std::size_t) i] < 0.0f);
  3790. CHECK (std::abs (crossings - 440) < 6); // half a second = 220 cycles = 440 crossings
  3791. float sinePeak = 0.0f;
  3792. for (int i = 4800; i < 9600; ++i)
  3793. sinePeak = std::max (sinePeak, std::abs (b[(std::size_t) i]));
  3794. CHECK (sinePeak > 0.2f && sinePeak < 0.35f); // 0.3 level, approximated sine without clipping
  3795. // second oscillator an octave up adds energy; sustain 0 makes the note decay on its own
  3796. lynx::SynthSettings two = sine;
  3797. two.osc[1] = { lynx::Waveform::sine, 1, 0.0f, 1.0f };
  3798. two.sustain = 0.0f;
  3799. two.decay = 0.1f;
  3800. const auto c = render (two, 48000, 47000);
  3801. CHECK (peakIn (c, 100, 2000) > peakIn (b, 100, 2000) && peakIn (c, 30000, 40000) < 1e-3f);
  3802. }
  3803. TEST (set_target_value_round_trips)
  3804. {
  3805. auto s = lynx::Song::makeDefault();
  3806. s.mixer[2].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay));
  3807. const lynx::AutomationTarget targets[] = {
  3808. { lynx::AutomationTargetKind::channelVolume, 1 }, { lynx::AutomationTargetKind::channelPan, 2 },
  3809. { lynx::AutomationTargetKind::mixerVolume, 3 }, { lynx::AutomationTargetKind::mixerPan, 0 },
  3810. { lynx::AutomationTargetKind::effectParam, 2, 0, 1 }, { lynx::AutomationTargetKind::tempo, 0 },
  3811. };
  3812. for (const auto& t : targets)
  3813. {
  3814. CHECK (s.setTargetValue (t, 0.25f));
  3815. CHECK (std::abs (s.targetValue (t) - 0.25f) < 1e-5f);
  3816. }
  3817. CHECK (! s.setTargetValue ({ lynx::AutomationTargetKind::channelParam, 0, 0, 3 }, 0.5f)); // lives in the plugin
  3818. }
  3819. TEST (cut_groups_stretch_and_envelope_import)
  3820. {
  3821. // open hat (cut by 1) is cut when the closed one (group 1) plays
  3822. lynx::Song s;
  3823. s.mixer = lynx::Song::defaultMixer (2);
  3824. for (int i = 0; i < 2; ++i)
  3825. {
  3826. lynx::ChannelDef c;
  3827. c.instrument = lynx::InstrumentKind::sampler;
  3828. c.samplePath = "dc";
  3829. c.volume = 1.0f;
  3830. c.mixerTrack = i + 1;
  3831. s.channels.push_back (c);
  3832. }
  3833. s.channels[0].cutBy = 1; // open
  3834. s.channels[1].cutGroup = 1; // closed
  3835. auto& p = s.patterns.emplace_back();
  3836. p.notes = { { 0, 100, 0, 60 }, { 960, 100, 1, 60 } };
  3837. auto provider = [] (const std::string&) {
  3838. auto d = std::make_shared<lynx::SampleData>();
  3839. d->left.assign (96000, 0.5f);
  3840. return std::shared_ptr<const lynx::SampleData> (d);
  3841. };
  3842. auto state = lynx::RackState::build (s, nullptr, 48000.0, provider);
  3843. CHECK (state->hasCutGroups && state->cutTargets[1].size() == 1 && state->cutTargets[1][0] == 0);
  3844. lynx::RackRenderer r;
  3845. r.prepare (48000.0, 512);
  3846. std::vector<float> l (512), rr (512);
  3847. const auto tps = lynx::ticksPerSample (s.bpm, 48000.0);
  3848. float afterCut = 0.0f;
  3849. for (double tick = 0.0; tick < 960.0 * 3; tick += 512 * tps)
  3850. {
  3851. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  3852. if (tick > 960.0 * 2) // the closed one continues; the open one has stopped
  3853. afterCut = std::max (afterCut, std::abs (l[256]));
  3854. }
  3855. CHECK (std::abs (afterCut - 0.5f * 0.78f) < 0.01f); // only the closed one (default velocity 0.78)
  3856. // resampling stretch: 1 s of sample stretched to 4 beats at 120 BPM = 2 s
  3857. auto ramp = std::make_shared<lynx::SampleData>();
  3858. for (int i = 0; i < 48000; ++i)
  3859. ramp->left.push_back ((float) i / 48000.0f);
  3860. ramp->sampleRate = 48000.0;
  3861. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  3862. inst->prepare (48000.0);
  3863. lynx::ChannelDef c;
  3864. c.sampler.stretchBeats = 4.0f;
  3865. inst->configure (c, 120.0);
  3866. inst->noteOn (72, 1.0f); // the note pitch doesn't change the speed
  3867. std::vector<float> a (48000), b (48000);
  3868. inst->render (a.data(), b.data(), 48000, 1.0f, 1.0f);
  3869. CHECK (std::abs (a[47999] - 0.5f) < 0.01f); // after 1 s it has read half
  3870. // FL envelope time: 32950 = 2 s; < 101 = 0
  3871. CHECK (std::abs (flp::Channel::envelopeTime (32950) - 2.0) < 0.01 && flp::Channel::envelopeTime (50) == 0.0);
  3872. }
  3873. TEST (time_stretch_keeps_pitch)
  3874. {
  3875. lynx::SampleData sine;
  3876. sine.sampleRate = 48000.0;
  3877. for (int i = 0; i < 48000; ++i)
  3878. sine.left.push_back (0.5f * std::sin (2.0f * 3.14159265f * 440.0f * (float) i / 48000.0f));
  3879. auto crossingsPerSecond = [] (const lynx::SampleData& d) {
  3880. int c = 0;
  3881. const auto n = (int) d.frames();
  3882. for (int i = 4800; i < n - 4800; ++i)
  3883. c += (d.left[(std::size_t) i - 1] < 0.0f) != (d.left[(std::size_t) i] < 0.0f);
  3884. return (double) c / ((double) (n - 9600) / d.sampleRate);
  3885. };
  3886. for (double ratio : { 2.0, 0.5, 1.37 })
  3887. {
  3888. const auto out = lynx::timeStretch (sine, ratio);
  3889. CHECK (std::abs ((double) out->frames() - 48000.0 * ratio) < 2.0);
  3890. CHECK (std::abs (crossingsPerSecond (*out) - 880.0) < 15.0); // 440 Hz stays 440 Hz
  3891. float peak = 0.0f;
  3892. for (std::size_t i = 4800; i + 4800 < out->frames(); ++i)
  3893. peak = std::max (peak, std::abs (out->left[i]));
  3894. CHECK (peak > 0.4f && peak < 0.6f); // no gaps or clipping in the overlap
  3895. }
  3896. }
  3897. TEST (sampler_region_start_and_end)
  3898. {
  3899. auto ramp = std::make_shared<lynx::SampleData>();
  3900. for (int i = 0; i < 10000; ++i)
  3901. ramp->left.push_back ((float) i / 10000.0f);
  3902. ramp->sampleRate = 48000.0;
  3903. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  3904. inst->prepare (48000.0);
  3905. lynx::ChannelDef c;
  3906. c.sampler.regionStart = 0.25f;
  3907. c.sampler.regionEnd = 0.5f;
  3908. inst->configure (c, 120.0);
  3909. inst->noteOn (60, 1.0f);
  3910. std::vector<float> l (6000), r (6000);
  3911. inst->render (l.data(), r.data(), 6000, 1.0f, 1.0f);
  3912. CHECK (std::abs (l[0] - 0.25f) < 0.001f); // starts at the beginning of the slice
  3913. CHECK (l[2400] > 0.48f && l[2600] == 0.0f); // and stops at its end
  3914. }
  3915. TEST (arpeggiator_plays_held_chord_in_steps)
  3916. {
  3917. auto song = lynx::Song::makeDefault();
  3918. song.bpm = 120.0;
  3919. song.patterns[0].notes.clear();
  3920. for (int key : { 60, 64, 67 })
  3921. song.patterns[0].notes.push_back ({ 0, lynx::ppq * 4, 4, key, 0.8f }); // chord held for 1 bar
  3922. song.channels[4].arp.direction = 1; // up
  3923. song.channels[4].arp.stepBeats = 0.25f;
  3924. auto state = lynx::RackState::build (song, nullptr, 48000.0);
  3925. CHECK (state->arpeggiators[4] != nullptr && state->arpeggiators[0] == nullptr);
  3926. // the arpeggiator generates the notes; we count what it hands to the instrument
  3927. auto& arp = *state->arpeggiators[4];
  3928. const auto tps = lynx::ticksPerSample (song.bpm, 48000.0);
  3929. std::vector<int> keys;
  3930. lynx::EventBuffer ev;
  3931. for (double tick = 0.0; tick < lynx::ppq * 2.0; tick += 512 * tps)
  3932. {
  3933. ev.clear();
  3934. lynx::schedulePatternLoop (song.patterns[0], song.patterns[0].effectiveLength (4), tick, 512, tps, ev);
  3935. int in = 0, out = 0;
  3936. for (auto& e : ev)
  3937. if (e.channel == 4)
  3938. arp.input[(std::size_t) in++] = e;
  3939. arp.process (4, arp.input.data(), in, tick, tps, 512, song.channels[4].arp, arp.output.data(), out);
  3940. for (int i = 0; i < out; ++i)
  3941. if (arp.output[(std::size_t) i].type == lynx::NoteEvent::Type::on)
  3942. keys.push_back (arp.output[(std::size_t) i].key);
  3943. }
  3944. // 2 beats = 8 sixteenth steps: 60 64 67 60 64 67 60 64
  3945. CHECK (keys.size() >= 8); // the last block goes slightly past 2 beats
  3946. const int expected[] = { 60, 64, 67, 60, 64, 67, 60, 64 };
  3947. for (std::size_t i = 0; i < keys.size() && i < 8; ++i)
  3948. CHECK (keys[i] == expected[i]);
  3949. // actually rendering also makes sound
  3950. lynx::RackRenderer r;
  3951. r.prepare (48000.0, 512);
  3952. std::vector<float> l (512), rr (512);
  3953. float peak = 0.0f;
  3954. for (double tick = 0.0; tick < lynx::ppq; tick += 512 * tps)
  3955. {
  3956. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  3957. for (auto v : l)
  3958. peak = std::max (peak, std::abs (v));
  3959. }
  3960. CHECK (peak > 0.01f);
  3961. }
  3962. TEST (audio_clip_fades_and_gain)
  3963. {
  3964. lynx::Song s;
  3965. s.bpm = 120.0;
  3966. s.mode = lynx::PlayMode::song;
  3967. s.mixer = lynx::Song::defaultMixer (1);
  3968. lynx::ChannelDef c;
  3969. c.instrument = lynx::InstrumentKind::audioClip;
  3970. c.samplePath = "dc";
  3971. c.volume = 1.0f;
  3972. c.mixerTrack = 1;
  3973. s.channels.push_back (c);
  3974. s.patterns.emplace_back();
  3975. lynx::Clip clip;
  3976. clip.kind = lynx::ClipKind::audio;
  3977. clip.channel = 0;
  3978. clip.length = lynx::ppq * 4; // 2 s at 120 BPM
  3979. clip.fadeIn = lynx::ppq; // 0.5 s
  3980. clip.fadeOut = lynx::ppq;
  3981. clip.gain = 0.5f;
  3982. s.playlist.push_back (clip);
  3983. auto provider = [] (const std::string&) {
  3984. auto d = std::make_shared<lynx::SampleData>();
  3985. d->left.assign (48000 * 4, 1.0f);
  3986. return std::shared_ptr<const lynx::SampleData> (d);
  3987. };
  3988. auto state = lynx::RackState::build (s, nullptr, 48000.0, provider);
  3989. lynx::RackRenderer r;
  3990. r.prepare (48000.0, 512);
  3991. std::vector<float> all;
  3992. std::vector<float> l (512), rr (512);
  3993. const auto tps = lynx::ticksPerSample (s.bpm, 48000.0);
  3994. for (double tick = 0.0; tick < lynx::ppq * 4.0; tick += 512 * tps)
  3995. {
  3996. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  3997. all.insert (all.end(), l.begin(), l.end());
  3998. }
  3999. CHECK (all[100] < 0.01f); // fade-in start
  4000. CHECK (std::abs (all[12000] - 0.25f) < 0.02f); // fade-in midpoint: half of 0.5
  4001. CHECK (std::abs (all[48000] - 0.5f) < 0.01f); // body: the clip gain
  4002. CHECK (std::abs (all[96000 - 12000] - 0.25f) < 0.02f); // fade-out midpoint
  4003. }
  4004. TEST (slicer_detects_hits_and_plays_slices_by_key)
  4005. {
  4006. // 4 hits (decaying noise) every 0.25 s
  4007. lynx::SampleData loop;
  4008. loop.sampleRate = 48000.0;
  4009. loop.left.assign (48000, 0.0f);
  4010. lynx::Noise noise;
  4011. for (int hit = 0; hit < 4; ++hit)
  4012. for (int i = 0; i < 6000; ++i)
  4013. loop.left[(std::size_t) (hit * 12000 + i)] = noise.next() * 0.8f * std::exp (-(float) i / 1500.0f);
  4014. const auto slices = lynx::detectSlices (loop, 0.5f);
  4015. CHECK (slices.size() == 4);
  4016. for (std::size_t i = 0; i < slices.size(); ++i)
  4017. CHECK (std::abs (slices[i] - 0.25f * (float) i) < 0.01f);
  4018. // key 61 plays the second slice, which starts at 0.25 and ends before 0.5
  4019. auto ramp = std::make_shared<lynx::SampleData>();
  4020. for (int i = 0; i < 48000; ++i)
  4021. ramp->left.push_back ((float) i / 48000.0f);
  4022. ramp->sampleRate = 48000.0;
  4023. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  4024. inst->prepare (48000.0);
  4025. lynx::ChannelDef c;
  4026. c.sampler.slices = slices;
  4027. inst->configure (c, 120.0);
  4028. inst->noteOn (61, 1.0f);
  4029. std::vector<float> l (20000), r (20000);
  4030. inst->render (l.data(), r.data(), 20000, 1.0f, 1.0f);
  4031. CHECK (std::abs (l[0] - 0.25f) < 0.01f && l[11000] > 0.45f && l[13000] == 0.0f);
  4032. }
  4033. TEST (project_templates_render_sound)
  4034. {
  4035. const auto names = lynx::templateNames();
  4036. CHECK (names.size() == 4);
  4037. for (int t = 1; t < (int) names.size(); ++t)
  4038. {
  4039. auto song = lynx::makeTemplate (t);
  4040. auto state = lynx::RackState::build (song, nullptr, 48000.0);
  4041. lynx::RackRenderer r;
  4042. r.prepare (48000.0, 512);
  4043. std::vector<float> l (512), rr (512);
  4044. const auto tps = lynx::ticksPerSample (song.bpm, 48000.0);
  4045. float peak = 0.0f;
  4046. for (double tick = 0.0; tick < lynx::ppq * 4.0; tick += 512 * tps)
  4047. {
  4048. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  4049. for (auto v : l)
  4050. peak = std::max (peak, std::abs (v));
  4051. }
  4052. CHECK (peak > 0.05f && peak < 4.0f);
  4053. }
  4054. CHECK (lynx::makeTemplate (0).patterns[0].notes.empty());
  4055. }
  4056. int main (int argc, char** argv)
  4057. {
  4058. if (argc > 1)
  4059. realFlpDir = argv[1];
  4060. for (auto& [name, fn] : registry())
  4061. {
  4062. std::printf ("%s\n", name);
  4063. fn();
  4064. }
  4065. std::printf ("\n%d checks, %d failures\n", checks, failures);
  4066. return failures == 0 ? 0 : 1;
  4067. }
  4068. TEST (synth_cutoff_keytrack)
  4069. {
  4070. // the cutoff follows the note from key 48 (130.81 Hz), like Harmor's "Key to filter frequency"
  4071. auto rms = [] (float keyTrack, int key) {
  4072. lynx::SynthSettings s;
  4073. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  4074. s.cutoff = 130.81f;
  4075. s.keyTrack = keyTrack;
  4076. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  4077. inst->prepare (48000.0);
  4078. lynx::ChannelDef c;
  4079. c.synth = s;
  4080. inst->configure (c, 120.0);
  4081. inst->noteOn (key, 1.0f);
  4082. std::vector<float> l (24000), r (24000);
  4083. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  4084. double e = 0.0;
  4085. for (int i = 4800; i < 24000; ++i)
  4086. e += (double) l[(std::size_t) i] * l[(std::size_t) i];
  4087. return std::sqrt (e / 19200.0);
  4088. };
  4089. const auto fixed = rms (0.0f, 72), tracked = rms (1.0f, 72);
  4090. CHECK (tracked > 4.0 * fixed); // 2 octaves up: without keytrack the low-pass cuts
  4091. CHECK (std::abs (rms (1.0f, 48) - rms (0.0f, 48)) < 0.05 * rms (0.0f, 48)); // unchanged at the reference key
  4092. }
  4093. namespace
  4094. {
  4095. std::vector<float> renderSynthNote (const lynx::SynthSettings& s, int key, int frames)
  4096. {
  4097. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  4098. inst->prepare (48000.0);
  4099. lynx::ChannelDef c;
  4100. c.synth = s;
  4101. inst->configure (c, 120.0);
  4102. inst->noteOn (key, 1.0f);
  4103. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  4104. inst->render (l.data(), r.data(), frames, 1.0f, 1.0f);
  4105. return l;
  4106. }
  4107. double goertzel (const std::vector<float>& x, double f, int from, int to)
  4108. {
  4109. const auto w = 2.0 * 3.141592653589793 * f / 48000.0, k = 2.0 * std::cos (w);
  4110. double s1 = 0.0, s2 = 0.0;
  4111. for (int i = from; i < to; ++i)
  4112. {
  4113. const auto s0 = x[(std::size_t) i] + k * s1 - s2;
  4114. s2 = s1;
  4115. s1 = s0;
  4116. }
  4117. return s1 * s1 + s2 * s2 - k * s1 * s2;
  4118. }
  4119. } // namespace
  4120. TEST (synth_pitch_sweep_ring_and_bands)
  4121. {
  4122. lynx::SynthSettings sine;
  4123. sine.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  4124. sine.cutoff = 20000.0f;
  4125. // sweep: starts at f·(1 + sweep) and returns to f (time constant s = 10 ms; s⁴ falls 4× faster)
  4126. auto sweep = sine;
  4127. sweep.sweep = 1.0f;
  4128. sweep.sweepTime = 0.01f;
  4129. const auto a = renderSynthNote (sweep, 69, 24000);
  4130. auto crossings = [] (const std::vector<float>& x, int to) {
  4131. int n = 0;
  4132. for (int i = 1; i < to; ++i)
  4133. n += (x[(std::size_t) i - 1] < 0.0f) != (x[(std::size_t) i] < 0.0f);
  4134. return n;
  4135. };
  4136. CHECK (crossings (a, 480) > 1.3 * crossings (renderSynthNote (sine, 69, 480), 480)); // 10 ms: much higher
  4137. CHECK (goertzel (a, 440.0, 12000, 24000) > 100.0 * goertzel (a, 880.0, 12000, 24000));
  4138. // ring with |a| = 1: carrier 440 × modulator 110 -> only 330 and 550, no 440
  4139. auto ring = sine;
  4140. ring.am = ring.ring = true;
  4141. ring.osc[2] = { lynx::Waveform::sine, -2, 0.0f, 1.0f };
  4142. const auto b = renderSynthNote (ring, 69, 24000);
  4143. CHECK (goertzel (b, 330.0, 4800, 24000) > 100.0 * goertzel (b, 440.0, 4800, 24000));
  4144. CHECK (goertzel (b, 550.0, 4800, 24000) > 100.0 * goertzel (b, 440.0, 4800, 24000));
  4145. // 3 bands: muting the high knocks down a 4 kHz note and barely touches an 80 Hz one
  4146. auto bands = sine;
  4147. bands.bandGain = { 1.0f, 1.0f, 0.0f };
  4148. auto rms = [] (const std::vector<float>& x) {
  4149. double e = 0.0;
  4150. for (std::size_t i = 4800; i < x.size(); ++i)
  4151. e += (double) x[i] * x[i];
  4152. return std::sqrt (e / (double) (x.size() - 4800));
  4153. };
  4154. CHECK (rms (renderSynthNote (bands, 107, 24000)) < 0.3 * rms (renderSynthNote (sine, 107, 24000)));
  4155. CHECK (rms (renderSynthNote (bands, 28, 24000)) > 0.85 * rms (renderSynthNote (sine, 28, 24000)));
  4156. }
  4157. TEST (love_philter_map_evaluation)
  4158. {
  4159. lynx::LovePhilterMap line { { { 0.0, 0.0 }, { 1.0, 1.0 } } };
  4160. CHECK (std::abs (lynx::lovePhilterMapAt (line, 0.5) - 0.5) < 1e-9);
  4161. CHECK (std::abs (lynx::lovePhilterMapAt (line, 1.0) - 1.0) < 1e-9);
  4162. // steps (Δx = 0): 1 until 0.4375, ramp to 0 at 0.5, then 0
  4163. lynx::LovePhilterMap steps { { { 0.0, 1.0 }, { 0.4375, 1.0 }, { 0.0625, 0.0 }, { 0.5, 0.0 } } };
  4164. CHECK (lynx::lovePhilterMapAt (steps, 0.27) == 1.0);
  4165. CHECK (lynx::lovePhilterMapAt (steps, 0.75) == 0.0);
  4166. CHECK (std::abs (lynx::lovePhilterMapAt (steps, 0.46875) - 0.5) < 1e-9);
  4167. CHECK (lynx::lovePhilterMapAt ({}, 0.3) == 1.0);
  4168. }
  4169. TEST (lofi_holds_and_quantizes)
  4170. {
  4171. auto fx = lynx::makeEffect (lynx::EffectKind::lofi);
  4172. fx->prepare (48000.0);
  4173. auto slot = lynx::makeEffectSlot (lynx::EffectKind::lofi);
  4174. slot.params[0] = 0.5f; // 128·0.125 + 1 = 17 samples
  4175. slot.params[1] = 1.0f; // 65536/2049 ≈ 32 levels
  4176. std::vector<float> l (170), r (170);
  4177. for (std::size_t i = 0; i < l.size(); ++i)
  4178. l[i] = r[i] = 0.9f * (float) std::sin (0.05 * (double) i);
  4179. const auto original = l;
  4180. fx->process (l.data(), r.data(), 170, slot.params, 120.0);
  4181. for (int i = 0; i < 17; ++i)
  4182. CHECK (l[(std::size_t) i] == l[0]);
  4183. CHECK (l[17] != l[16]);
  4184. const auto step = 2.0f * 2049.0f / 65536.0f;
  4185. for (auto v : l)
  4186. CHECK (std::abs (v / step - std::round (v / step)) < 1e-3f);
  4187. CHECK (std::abs (l[0] - original[0]) <= step);
  4188. CHECK (lynx::formatEffectParam (lynx::EffectKind::lofi, 1, 0.0f, 120.0) == "16.0 bits");
  4189. }
  4190. namespace
  4191. {
  4192. lynx::EffectParams effectorParams (int type, float x, float y)
  4193. {
  4194. auto slot = lynx::makeEffectSlot (lynx::EffectKind::effector);
  4195. slot.params[0] = (float) type / 11.0f;
  4196. slot.params[3] = x;
  4197. slot.params[4] = y;
  4198. return slot.params;
  4199. }
  4200. } // namespace
  4201. TEST (effector_algorithms)
  4202. {
  4203. CHECK (lynx::effector::typeOf (8.0f / 11.0f) == 8);
  4204. CHECK (std::string (lynx::effector::typeName (11)) == "Ring");
  4205. CHECK (std::abs (lynx::effector::rateBeats (0.5f, 0.0f) - 0.75) < 1e-9); // trunc(8·0.5 + 0.5) = 4 -> 3/4
  4206. CHECK (std::abs (lynx::effector::rateBeats (1.0f, 0.5f) - 2.0) < 1e-9); // 8 × (1 − 0.5)²
  4207. auto run = [] (const lynx::EffectParams& p, std::vector<float> in, double bpm = 120.0) {
  4208. auto fx = lynx::makeEffect (lynx::EffectKind::effector);
  4209. fx->prepare (48000.0);
  4210. fx->setSongPosition (0.0);
  4211. auto r = in;
  4212. fx->process (in.data(), r.data(), (int) in.size(), p, bpm);
  4213. return in;
  4214. };
  4215. // Distort with Y = 1 (everything goes to the cascade): 0.5 comes out 0.5 (compensation G = 0.5/F(0.5))
  4216. {
  4217. auto p = effectorParams (0, 0.5f, 1.0f);
  4218. const auto out = run (p, std::vector<float> (4800, 0.5f));
  4219. CHECK (std::abs (out.back() - 0.5f) < 1e-3f);
  4220. const auto small = run (p, std::vector<float> (4800, 0.05f));
  4221. CHECK (small.back() > 0.45f && small.back() < 0.5f); // saturates near ±0.5
  4222. }
  4223. // Ring: DC 1 becomes the carrier sine, 2^(8.7·0 + 5) = 32 Hz -> 32 cycles per second
  4224. {
  4225. auto p = effectorParams (11, 0.0f, 0.0f);
  4226. const auto out = run (p, std::vector<float> (48000, 1.0f));
  4227. int crossings = 0;
  4228. for (std::size_t i = 4800; i < out.size(); ++i)
  4229. crossings += (out[i - 1] < 0.0f) != (out[i] < 0.0f);
  4230. CHECK (crossings >= 56 && crossings <= 60); // 0.9 s × 32 Hz × 2
  4231. }
  4232. // Trancer, Y = 0: at the start of the period the gain drops to zero; X = 1 returns only at the end of the period
  4233. {
  4234. auto p = effectorParams (8, 1.0f, 0.0f);
  4235. p[5] = 1.0f; // 8/1 = 8 beats = 4 s at 120 BPM
  4236. const auto out = run (p, std::vector<float> (48000, 1.0f));
  4237. CHECK (out[100] > 0.3f); // still rising on the "and" (1% of the period = 40 ms)
  4238. CHECK (out[24000] < 0.05f); // 0.5 s: trough
  4239. }
  4240. // Reverb with Wet = 0: the dry passes intact
  4241. {
  4242. auto p = effectorParams (6, 0.5f, 0.5f);
  4243. p[2] = 0.0f;
  4244. std::vector<float> in (4800);
  4245. for (std::size_t i = 0; i < in.size(); ++i)
  4246. in[i] = (float) std::sin (0.01 * (double) i);
  4247. const auto out = run (p, in);
  4248. for (std::size_t i = 0; i < in.size(); ++i)
  4249. CHECK (std::abs (out[i] - in[i]) < 1e-6f);
  4250. }
  4251. // Delay: the echo arrives after the Mod Rate period (1/4 beat at 120 BPM = 125 ms), at level X²
  4252. {
  4253. auto p = effectorParams (5, 0.7f, 0.5f);
  4254. p[5] = 1.0f / 8.0f; // index 1 = 1/4
  4255. std::vector<float> in (12000, 0.0f);
  4256. in[0] = 1.0f;
  4257. const auto out = run (p, in);
  4258. CHECK (std::abs (out[6000] - 0.49f) < 0.02f);
  4259. CHECK (std::abs (out[3000]) < 1e-6f);
  4260. }
  4261. // Stutter: repeats the recorded start every period
  4262. {
  4263. auto p = effectorParams (9, 0.0f, 0.0f);
  4264. p[5] = 0.0f; // 1/8 beat = 62.5 ms = 3000 samples
  4265. std::vector<float> in (9000);
  4266. for (std::size_t i = 0; i < in.size(); ++i)
  4267. in[i] = (float) i / 9000.0f;
  4268. const auto out = run (p, in);
  4269. CHECK (std::abs (out[3000 + 500] - in[500]) < 0.01f); // after the crossfade, it's the start again
  4270. CHECK (std::abs (out[1000] - in[1000]) < 1e-6f);
  4271. }
  4272. }
  4273. TEST (crossover_linkwitz_riley_sums_flat)
  4274. {
  4275. // low band + high band of the same crossover: sum with magnitude 1 (Linkwitz-Riley; for 12 and 36 dB the HP is inverted)
  4276. for (const auto combo : { 1, 3, 4, 5, 6, 7 })
  4277. for (const auto testHz : { 200.0, 1000.0, 5000.0 })
  4278. {
  4279. auto run = [&] (bool high) {
  4280. auto fx = lynx::makeEffect (lynx::EffectKind::crossover);
  4281. fx->prepare (48000.0);
  4282. auto slot = lynx::makeEffectSlot (lynx::EffectKind::crossover);
  4283. const auto value = (float) (std::log2 (1000.0 / 30.0) / 9.0589);
  4284. slot.params[high ? 0 : 3] = 1.0f;
  4285. slot.params[high ? 1 : 4] = value;
  4286. slot.params[high ? 2 : 5] = (float) combo / 7.0f;
  4287. std::vector<float> l (24000), r (24000);
  4288. for (std::size_t i = 0; i < l.size(); ++i)
  4289. l[i] = r[i] = (float) std::sin (2.0 * 3.141592653589793 * testHz * (double) i / 48000.0);
  4290. fx->process (l.data(), r.data(), 24000, slot.params, 120.0);
  4291. return l;
  4292. };
  4293. const auto low = run (false), high = run (true);
  4294. double peak = 0.0;
  4295. for (std::size_t i = 12000; i < low.size(); ++i)
  4296. peak = std::max (peak, (double) std::abs (low[i] + high[i]));
  4297. CHECK (std::abs (peak - 1.0) < 0.02);
  4298. }
  4299. // 96 dB/oct: two octaves above the cutoff the low-pass is already below −150 dB... in practice, very low
  4300. auto fx = lynx::makeEffect (lynx::EffectKind::crossover);
  4301. fx->prepare (48000.0);
  4302. auto slot = lynx::makeEffectSlot (lynx::EffectKind::crossover);
  4303. slot.params[3] = 1.0f;
  4304. slot.params[4] = (float) (std::log2 (500.0 / 30.0) / 9.0589);
  4305. slot.params[5] = 1.0f;
  4306. std::vector<float> l (24000), r (24000);
  4307. for (std::size_t i = 0; i < l.size(); ++i)
  4308. l[i] = r[i] = (float) std::sin (2.0 * 3.141592653589793 * 2000.0 * (double) i / 48000.0);
  4309. fx->process (l.data(), r.data(), 24000, slot.params, 120.0);
  4310. float peak = 0.0f;
  4311. for (std::size_t i = 12000; i < l.size(); ++i)
  4312. peak = std::max (peak, std::abs (l[i]));
  4313. CHECK (peak < 1e-4f);
  4314. }
  4315. TEST (rhythm_gain_and_autopan)
  4316. {
  4317. // 1-beat gate: 1 → 0 at 0.5 beat (linear) → 1 at the end; at 120 BPM 1 beat = 24000 samples at 48 kHz
  4318. auto slot = lynx::makeEffectSlot (lynx::EffectKind::rhythmGain);
  4319. slot.params[0] = 1.0f / 64.0f;
  4320. slot.params[1] = 3.0f / 12.0f;
  4321. const float pts[3][3] = { { 0.0f, 1.0f, 0.5f }, { 0.5f, 0.0f, 0.5f }, { 1.0f, 1.0f, 0.5f } };
  4322. for (int k = 0; k < 3; ++k)
  4323. for (int j = 0; j < 3; ++j)
  4324. slot.params[(std::size_t) (2 + 3 * k + j)] = pts[k][j];
  4325. auto fx = lynx::makeEffect (lynx::EffectKind::rhythmGain);
  4326. fx->prepare (48000.0);
  4327. fx->setSongPosition (960.0 * 2.0); // beat 2: phase 0
  4328. std::vector<float> l (24000, 1.0f), r (24000, 1.0f);
  4329. fx->process (l.data(), r.data(), 24000, slot.params, 120.0);
  4330. CHECK (std::abs (l[0] - 1.0f) < 1e-3f);
  4331. CHECK (std::abs (l[6000] - 0.5f) < 1e-3f);
  4332. CHECK (l[12000] < 1e-3f);
  4333. CHECK (std::abs (l[18000] - 0.5f) < 1e-3f);
  4334. // positive tension: changes quickly at the start of the segment
  4335. CHECK (lynx::effectInfo (lynx::EffectKind::rhythmGain).params.size() == 39);
  4336. // auto-pan: 1-beat period, full depth; start phase 0.75 -> W = 0 rising (pan centered)
  4337. auto pan = lynx::makeEffectSlot (lynx::EffectKind::autoPan);
  4338. pan.params[0] = 1.0f / 64.0f;
  4339. pan.params[1] = 1.0f;
  4340. auto ap = lynx::makeEffect (lynx::EffectKind::autoPan);
  4341. ap->prepare (48000.0);
  4342. ap->setSongPosition (0.0);
  4343. std::vector<float> a (24000, 1.0f), b (24000, 1.0f);
  4344. ap->process (a.data(), b.data(), 24000, pan.params, 120.0);
  4345. CHECK (std::abs (a[0] - 1.0f) < 1e-3f && std::abs (b[0] - 1.0f) < 1e-3f);
  4346. CHECK (a[6000] < 0.01f && std::abs (b[6000] - 1.0f) < 1e-3f); // ¼ cycle later: fully right
  4347. }
  4348. TEST (vocoder_side_inputs_split_modulator_and_carrier)
  4349. {
  4350. // "Side inputs" mode (Vocodex): modulator from side input 1 (noise in the first half), carrier from side input 2
  4351. // (saw), own input silent → the output follows the side modulator; with input 1 silent, the output is silent
  4352. auto slot = lynx::makeEffectSlot (lynx::EffectKind::vocoder);
  4353. slot.params[16] = 1.0f;
  4354. auto fx = lynx::makeEffect (lynx::EffectKind::vocoder);
  4355. fx->prepare (48000.0);
  4356. std::vector<float> modL (48000), car (48000), l (48000, 0.0f), r (48000, 0.0f);
  4357. std::uint32_t seed = 1;
  4358. for (std::size_t i = 0; i < modL.size(); ++i)
  4359. {
  4360. seed = seed * 1664525u + 1013904223u;
  4361. modL[i] = i < 24000 ? ((float) (seed >> 8) / 16777216.0f - 0.5f) : 0.0f;
  4362. car[i] = (float) (2.0 * std::fmod ((double) i * 220.0 / 48000.0, 1.0) - 1.0) * 0.5f;
  4363. }
  4364. for (int done = 0; done < 48000; done += 480)
  4365. {
  4366. fx->setSidechain (modL.data() + done, modL.data() + done);
  4367. fx->setSidechain2 (car.data() + done, car.data() + done);
  4368. fx->process (l.data() + done, r.data() + done, 480, slot.params, 120.0);
  4369. }
  4370. auto rms = [&] (int from, int to) {
  4371. double e = 0.0;
  4372. for (int i = from; i < to; ++i)
  4373. e += (double) l[(std::size_t) i] * l[(std::size_t) i];
  4374. return std::sqrt (e / (to - from));
  4375. };
  4376. CHECK (rms (6000, 20000) > 0.01);
  4377. CHECK (rms (40000, 48000) < 0.1 * rms (6000, 20000));
  4378. // the side modulator configured but silent: nothing comes out (the own input is not used instead)
  4379. std::vector<float> a (4800, 0.3f), b (4800, 0.3f);
  4380. for (int done = 0; done < 4800; done += 480)
  4381. {
  4382. fx->setSidechain (nullptr, nullptr);
  4383. fx->setSidechain2 (car.data() + done, car.data() + done);
  4384. fx->process (a.data() + done, b.data() + done, 480, slot.params, 120.0);
  4385. }
  4386. CHECK (std::abs (a[4700]) < 0.05f);
  4387. }
  4388. TEST (vocoder_follows_modulator)
  4389. {
  4390. // modulator (L) plays only in the first half; carrier (R) is a continuous saw: the wet follows the modulator
  4391. auto slot = lynx::makeEffectSlot (lynx::EffectKind::vocoder);
  4392. auto fx = lynx::makeEffect (lynx::EffectKind::vocoder);
  4393. fx->prepare (48000.0);
  4394. std::vector<float> l (48000), r (48000);
  4395. std::uint32_t seed = 1;
  4396. for (std::size_t i = 0; i < l.size(); ++i)
  4397. {
  4398. seed = seed * 1664525u + 1013904223u;
  4399. l[i] = i < 24000 ? ((float) (seed >> 8) / 16777216.0f - 0.5f) : 0.0f;
  4400. r[i] = (float) (2.0 * std::fmod ((double) i * 220.0 / 48000.0, 1.0) - 1.0) * 0.5f;
  4401. }
  4402. fx->process (l.data(), r.data(), 48000, slot.params, 120.0);
  4403. auto rms = [&] (int from, int to) {
  4404. double e = 0.0;
  4405. for (int i = from; i < to; ++i)
  4406. e += (double) l[(std::size_t) i] * l[(std::size_t) i];
  4407. return std::sqrt (e / (to - from));
  4408. };
  4409. CHECK (rms (6000, 20000) > 0.01);
  4410. CHECK (rms (40000, 48000) < 0.1 * rms (6000, 20000)); // modulator silent: the vocoder fades out (100 ms release)
  4411. for (std::size_t i = 0; i < l.size(); ++i)
  4412. CHECK (l[i] == r[i] && std::isfinite (l[i])); // mono output
  4413. }
  4414. // Vocodex (REA_rodada35): a synthetic state in FL's layout (version 8, 13 maps, 20 parameters, the 0x24 block,
  4415. // 13 map-axis bytes, tone, notes)
  4416. struct VocodexSpec
  4417. {
  4418. // Wet, SG, ModVol, ModHP, CarVol, CarLP, CarNoise, CarNoiseHP, Hold, Att, AttCurve, Rel, RelCurve, Freeze, BW,
  4419. // Flatness, ModBW, ModPitch, FatPitch, FatPan
  4420. 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 };
  4421. std::array<std::int32_t, 7> block { 0, 2, 0, 24, 1, 1, 2 }; // hold mode, order, unison, bands, draft field, ModIn, CarIn
  4422. 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
  4423. std::vector<std::uint8_t> bytes() const
  4424. {
  4425. std::vector<std::uint8_t> d;
  4426. 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); };
  4427. auto i32 = [&] (std::int32_t v) { put (&v, 4); };
  4428. i32 (8 << 16);
  4429. for (int m = 0; m < 13; ++m)
  4430. {
  4431. const double y0 = m == 8 ? 0.1429 : (m == 3 || m == 4 || m == 11) ? 0.0 : 0.5;
  4432. const double y1 = m == 8 ? 0.9918 : y0;
  4433. i32 (1), i32 (0), i32 (2);
  4434. for (const auto& [dx, y] : { std::pair { 0.0, y0 }, std::pair { 1.0, y1 } })
  4435. {
  4436. put (&dx, 8), put (&y, 8);
  4437. i32 (0), i32 (0); // tension (f32 0), flags
  4438. }
  4439. const std::array<std::uint8_t, 20> tail {};
  4440. put (tail.data(), tail.size());
  4441. }
  4442. for (auto v : params)
  4443. i32 (v);
  4444. for (auto v : block)
  4445. i32 (v);
  4446. put (flags.data(), flags.size());
  4447. const std::array<std::uint8_t, 13> axis {};
  4448. put (axis.data(), axis.size());
  4449. d.push_back (3), put ("PWM", 3);
  4450. i32 (1), i32 (60);
  4451. return d;
  4452. }
  4453. };
  4454. std::vector<float> vocodexSaw (int n, double hz, double fs)
  4455. {
  4456. std::vector<float> out ((std::size_t) n);
  4457. for (int i = 0; i < n; ++i)
  4458. out[(std::size_t) i] = (float) (2.0 * std::fmod (i * hz / fs, 1.0) - 1.0) * 0.4f;
  4459. return out;
  4460. }
  4461. TEST (vocodex_state_parse_and_conversion)
  4462. {
  4463. VocodexSpec spec;
  4464. spec.block = { 1, 3, 2, 40, 0, 2, 1 };
  4465. spec.params[17] = -1200;
  4466. const auto raw = spec.bytes();
  4467. const auto s = lynx::vocodex::parseState (raw);
  4468. CHECK (s.has_value());
  4469. if (! s)
  4470. return;
  4471. CHECK (s->version == 8 && s->holdMode == 1 && s->order == 3 && s->unison == 2 && s->bands == 40);
  4472. CHECK (s->draft() && s->modIn == 2 && s->carIn == 1 && s->minTimes && s->subtractiveGate && ! s->lrEncoding);
  4473. CHECK (s->params[lynx::vocodex::modPitch] == -1200 && s->params[lynx::vocodex::carLp] == 65536);
  4474. 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);
  4475. CHECK (s->tone == "PWM" && s->notes.size() == 1 && s->notes[0] == 60);
  4476. const auto v = lynx::vocodexEffect (raw);
  4477. CHECK (v && v->slot.kind == lynx::EffectKind::vocodex && v->slot.state == raw && v->modIn == 2 && v->carIn == 1 && v->notes.empty());
  4478. spec.block[6] = -1; // internal synth carrier: not available yet → reported
  4479. spec.params[1] = 150; // Soundgoodizer stage
  4480. const auto w = lynx::vocodexEffect (spec.bytes());
  4481. CHECK (w && w->carIn == -1 && w->notes.size() == 2);
  4482. CHECK (! lynx::vocodex::parseState ({ 1, 2, 3 }).has_value());
  4483. }
  4484. TEST (vocodex_vocodes_side_inputs)
  4485. {
  4486. // modulator on side input 1 (noise in the first half), carrier on side input 2 (saw), own input silent: the
  4487. // output follows the modulator's envelope and fades after it stops
  4488. VocodexSpec spec;
  4489. lynx::EffectSlot slot = lynx::makeEffectSlot (lynx::EffectKind::vocodex);
  4490. slot.state = spec.bytes();
  4491. auto fx = lynx::makeEffect (slot);
  4492. fx->prepare (48000.0);
  4493. CHECK (fx->latencySamples() == 0);
  4494. const auto car = vocodexSaw (48000, 110.0, 48000.0);
  4495. std::vector<float> mod (48000), l (48000, 0.0f), r (48000, 0.0f);
  4496. std::uint32_t seed = 7;
  4497. for (std::size_t i = 0; i < mod.size(); ++i)
  4498. {
  4499. seed = seed * 1664525u + 1013904223u;
  4500. mod[i] = i < 24000 ? ((float) (seed >> 8) / 16777216.0f - 0.5f) : 0.0f;
  4501. }
  4502. for (int done = 0; done < 48000; done += 512)
  4503. {
  4504. const int n = std::min (512, 48000 - done);
  4505. fx->setSidechain (mod.data() + done, mod.data() + done);
  4506. fx->setSidechain2 (car.data() + done, car.data() + done);
  4507. fx->process (l.data() + done, r.data() + done, n, slot.params, 120.0);
  4508. }
  4509. auto rms = [&] (int from, int to) {
  4510. double e = 0.0;
  4511. for (int i = from; i < to; ++i)
  4512. e += (double) l[(std::size_t) i] * l[(std::size_t) i] + (double) r[(std::size_t) i] * r[(std::size_t) i];
  4513. return std::sqrt (e / (2.0 * (to - from)));
  4514. };
  4515. CHECK (rms (6000, 20000) > 0.02);
  4516. CHECK (rms (40000, 48000) < 0.01 * rms (6000, 20000));
  4517. CHECK (std::abs (l[0]) < 1e-6f); // the gains ramp up from 0 when the plugin is created
  4518. }
  4519. TEST (vocodex_draft_latency_and_pass_through)
  4520. {
  4521. // carrier pass-through at unit gain only (Wet 0): after a Flush the gains snap, so the output is the carrier,
  4522. // 16 samples late in Draft
  4523. VocodexSpec spec;
  4524. spec.params[0] = 0; // Wet
  4525. spec.params[4] = 12800; // CarVol = 1
  4526. for (const int draftField : { 1, 0 })
  4527. {
  4528. spec.block[4] = draftField;
  4529. const auto s = lynx::vocodex::parseState (spec.bytes());
  4530. CHECK (s.has_value());
  4531. lynx::vocodex::Engine engine;
  4532. engine.prepare (*s, 44100.0, 300, s->draft());
  4533. CHECK (engine.latencySamples() == (draftField == 0 ? 16 : 0));
  4534. engine.flush();
  4535. const auto saw = vocodexSaw (3000, 220.0, 44100.0);
  4536. std::vector<float> car (6000), mod (6000, 0.0f), out (6000);
  4537. for (int i = 0; i < 3000; ++i)
  4538. car[(std::size_t) (2 * i)] = car[(std::size_t) (2 * i + 1)] = saw[(std::size_t) i];
  4539. static constexpr int sizes[] { 300, 37, 128, 1, 255, 16, 299 }; // uneven blocks exercise the FIFOs
  4540. for (int done = 0, k = 0, n = 0; done < 3000; done += n, ++k)
  4541. {
  4542. n = std::min (sizes[k % 7], 3000 - done);
  4543. engine.process (mod.data() + 2 * done, mod.data() + 2 * done, car.data() + 2 * done, out.data() + 2 * done, n);
  4544. }
  4545. const int lag = engine.latencySamples();
  4546. auto maxError = 0.0f;
  4547. for (int i = lag; i < 3000; ++i)
  4548. maxError = std::max (maxError, std::abs (out[(std::size_t) (2 * i)] - saw[(std::size_t) (i - lag)]));
  4549. CHECK (maxError == 0.0f);
  4550. }
  4551. }
  4552. TEST (vocodex_soundgoodizer_stage_limits_the_output)
  4553. {
  4554. // SG > 0: the vocoder's output (loud here: Wet 2000) goes through the Soundgoodizer approximation, whose
  4555. // master limiter keeps the peaks under −0.2 dBFS; its look-ahead is reported as latency
  4556. VocodexSpec spec;
  4557. spec.params[0] = 2000;
  4558. spec.params[1] = 250;
  4559. lynx::EffectSlot slot = lynx::makeEffectSlot (lynx::EffectKind::vocodex);
  4560. slot.state = spec.bytes();
  4561. auto fx = lynx::makeEffect (slot);
  4562. fx->prepare (48000.0);
  4563. CHECK (fx->latencySamples() == 72); // 1.5 ms at 48 kHz
  4564. const auto car = vocodexSaw (48000, 110.0, 48000.0);
  4565. std::vector<float> mod (48000), l (48000, 0.0f), r (48000, 0.0f);
  4566. for (std::size_t i = 0; i < mod.size(); ++i)
  4567. mod[i] = 0.9f * (float) std::sin (0.07 * (double) i) * (float) std::sin (0.0003 * (double) i);
  4568. auto peak = 0.0f;
  4569. for (int done = 0; done < 48000; done += 512)
  4570. {
  4571. const int n = std::min (512, 48000 - done);
  4572. fx->setSidechain (mod.data() + done, mod.data() + done);
  4573. fx->setSidechain2 (car.data() + done, car.data() + done);
  4574. fx->process (l.data() + done, r.data() + done, n, slot.params, 120.0);
  4575. }
  4576. for (std::size_t i = 0; i < l.size(); ++i)
  4577. peak = std::max ({ peak, std::abs (l[i]), std::abs (r[i]) });
  4578. CHECK (peak > 0.5f && peak <= 0.9775f);
  4579. }
  4580. TEST (vocodex_tail_bypass_and_noise)
  4581. {
  4582. // both inputs silent for longer than 0.5 s + hold + release: the own input passes unchanged
  4583. VocodexSpec spec;
  4584. const auto s = lynx::vocodex::parseState (spec.bytes());
  4585. CHECK (s.has_value());
  4586. lynx::vocodex::Engine engine;
  4587. engine.prepare (*s, 44100.0, 512, false);
  4588. std::vector<float> zero (1024, 0.0f), own (1024), out (1024);
  4589. for (std::size_t i = 0; i < own.size(); ++i)
  4590. own[i] = 0.25f * (float) std::sin (0.01 * (double) i);
  4591. for (int b = 0; b < 80; ++b)
  4592. engine.process (own.data(), zero.data(), zero.data(), out.data(), 512);
  4593. CHECK (out == own);
  4594. // carrier noise: the IPP-compatible generator restarts from the same seed after a Flush
  4595. spec.params[6] = 9000;
  4596. const auto noisy = lynx::vocodex::parseState (spec.bytes());
  4597. lynx::vocodex::Engine a;
  4598. a.prepare (*noisy, 44100.0, 512, false);
  4599. std::vector<float> mod (1024), first (1024), second (1024);
  4600. for (std::size_t i = 0; i < mod.size(); ++i)
  4601. mod[i] = 0.3f * (float) std::sin (0.05 * (double) i);
  4602. a.flush();
  4603. a.process (own.data(), mod.data(), zero.data(), first.data(), 512);
  4604. a.flush();
  4605. a.process (own.data(), mod.data(), zero.data(), second.data(), 512);
  4606. CHECK (first == second);
  4607. auto energy = 0.0;
  4608. for (auto v : first)
  4609. energy += (double) v * v;
  4610. CHECK (energy > 1e-6 && std::isfinite (energy));
  4611. }
  4612. TEST (synth_spectral_oscillator)
  4613. {
  4614. // 1/n spectrum = saw: same harmonic proportions and same level as LYNX's saw
  4615. lynx::SynthSettings saw;
  4616. saw.osc[0] = { lynx::Waveform::saw, 0, 0.0f, 1.0f };
  4617. saw.cutoff = 20000.0f;
  4618. auto spectral = saw;
  4619. spectral.osc[0].wave = lynx::Waveform::spectral;
  4620. for (int n = 1; n <= lynx::SynthSettings::spectrumSize; ++n)
  4621. spectral.spectrum[(std::size_t) n - 1] = 1.0f / (float) n;
  4622. const auto a = renderSynthNote (saw, 57, 24000), b = renderSynthNote (spectral, 57, 24000); // 220 Hz
  4623. for (const auto h : { 1, 2, 3, 5 })
  4624. {
  4625. const auto ea = goertzel (a, 220.0 * h, 4800, 24000), eb = goertzel (b, 220.0 * h, 4800, 24000);
  4626. CHECK (std::abs (10.0 * std::log10 (eb / ea)) < 0.5); // within 0.5 dB
  4627. }
  4628. // odd only: no 2nd harmonic
  4629. auto odd = spectral;
  4630. for (int n = 2; n <= lynx::SynthSettings::spectrumSize; n += 2)
  4631. odd.spectrum[(std::size_t) n - 1] = 0.0f;
  4632. const auto c = renderSynthNote (odd, 57, 24000);
  4633. CHECK (goertzel (c, 440.0, 4800, 24000) < 1e-4 * goertzel (c, 220.0, 4800, 24000));
  4634. // high note: the band-limited tables don't pass Nyquist (no aliasing below the fundamental)
  4635. const auto d = renderSynthNote (spectral, 105, 24000); // 3520 Hz
  4636. CHECK (goertzel (d, 1000.0, 4800, 24000) < 1e-3 * goertzel (d, 3520.0, 4800, 24000));
  4637. }
  4638. TEST (compressor_sidechain_ducks_and_orders_mixer)
  4639. {
  4640. // the detector listens to the side input: quiet signal on the track, loud kick on the sidechain -> reduction
  4641. auto slot = lynx::makeEffectSlot (lynx::EffectKind::compressor);
  4642. slot.params[0] = 0.5f; // threshold
  4643. slot.params[1] = 1.0f; // high ratio
  4644. slot.params[4] = 0.0f;
  4645. auto run = [&] (bool withSidechain) {
  4646. auto fx = lynx::makeEffect (lynx::EffectKind::compressor);
  4647. fx->prepare (48000.0);
  4648. std::vector<float> l (4800, 0.1f), r (4800, 0.1f), kick (4800, 1.0f);
  4649. if (withSidechain)
  4650. fx->setSidechain (kick.data(), kick.data());
  4651. fx->process (l.data(), r.data(), 4800, slot.params, 120.0);
  4652. return l.back();
  4653. };
  4654. const auto alone = run (false), ducked = run (true);
  4655. CHECK (ducked < 0.5f * alone);
  4656. // order: track 5 listens to 7 via sidechain -> 7 comes before 5
  4657. auto song = lynx::Song::makeDefault();
  4658. while (song.mixer.size() < 8)
  4659. song.mixer.push_back ({});
  4660. auto comp = lynx::makeEffectSlot (lynx::EffectKind::compressor);
  4661. comp.sidechain = 7;
  4662. song.mixer[5].effects.push_back (comp);
  4663. const auto order = song.mixerOrder();
  4664. const auto at = [&] (int t) { return std::find (order.begin(), order.end(), t) - order.begin(); };
  4665. CHECK (at (7) < at (5));
  4666. }
  4667. TEST (pitch_correction_pulls_to_allowed_note)
  4668. {
  4669. auto run = [] (const lynx::EffectParams& p, double hz) {
  4670. auto fx = lynx::makeEffect (lynx::EffectKind::pitchCorrect);
  4671. fx->prepare (48000.0);
  4672. std::vector<float> l (48000 * 2), r;
  4673. for (std::size_t i = 0; i < l.size(); ++i)
  4674. l[i] = 0.5f * (float) std::sin (2.0 * 3.141592653589793 * hz * (double) i / 48000.0);
  4675. r = l;
  4676. fx->process (l.data(), r.data(), (int) l.size(), p, 120.0);
  4677. // frequency from zero crossings in the last second
  4678. int crossings = 0;
  4679. for (std::size_t i = 48000 + 1; i < l.size(); ++i)
  4680. crossings += (l[i - 1] < 0.0f) != (l[i] < 0.0f);
  4681. return crossings / 2.0;
  4682. };
  4683. auto slot = lynx::makeEffectSlot (lynx::EffectKind::pitchCorrect); // chromatic, instant, A 440
  4684. CHECK (std::abs (run (slot.params, 452.0) - 440.0) < 4.0);
  4685. for (int k = 0; k < 12; ++k)
  4686. slot.params[(std::size_t) (5 + k)] = k == 0 ? 1.0f : 0.0f; // only C
  4687. CHECK (std::abs (run (slot.params, 452.0) - 523.25) < 5.0); // C5 (523 Hz) is closer than C4 (262)
  4688. slot.params[2] = 1.0f; // turn everything off: passes unchanged
  4689. CHECK (std::abs (run (slot.params, 452.0) - 452.0) < 4.0);
  4690. }
  4691. TEST (pitch_correction_bypass_is_a_pure_delay)
  4692. {
  4693. // FL's Pitcher with Bypass All still runs its shifter: the plain path is an exact 9-sample delay, the formant
  4694. // path (256-Hann overlap-add) an exact 257-sample delay, and Gender changes nothing without a shift
  4695. // (REA_rodada30 §2.4/2.5); both are reported as latency
  4696. std::vector<float> in (48000);
  4697. for (std::size_t i = 0; i < in.size(); ++i)
  4698. in[i] = 0.5f * (float) std::sin (2.0 * 3.141592653589793 * 440.0 * (double) i / 48000.0)
  4699. + 0.2f * (float) std::sin (2.0 * 3.141592653589793 * 1234.5 * (double) i / 48000.0);
  4700. auto run = [&] (bool formant, float gender, int& latency) {
  4701. auto fx = lynx::makeEffect (lynx::EffectKind::pitchCorrect);
  4702. fx->prepare (48000.0);
  4703. auto slot = lynx::makeEffectSlot (lynx::EffectKind::pitchCorrect);
  4704. slot.params[2] = 1.0f;
  4705. slot.params[29] = formant ? 1.0f : 0.0f;
  4706. slot.params[30] = gender;
  4707. auto l = in, r = in;
  4708. for (std::size_t i = 0; i < l.size(); i += 480)
  4709. fx->process (l.data() + i, r.data() + i, 480, slot.params, 120.0);
  4710. latency = fx->latencySamples();
  4711. return l;
  4712. };
  4713. int latency = 0;
  4714. auto plain = run (false, 0.5f, latency);
  4715. CHECK (latency == 9);
  4716. auto worst = 0.0f;
  4717. for (std::size_t i = 4000; i < in.size(); ++i)
  4718. worst = std::max (worst, std::abs (plain[i] - in[i - 9]));
  4719. CHECK (worst < 1e-5f);
  4720. auto formant = run (true, 0.8f, latency);
  4721. CHECK (latency == 257);
  4722. worst = 0.0f;
  4723. for (std::size_t i = 4000; i < in.size(); ++i)
  4724. worst = std::max (worst, std::abs (formant[i] - in[i - 257]));
  4725. CHECK (worst < 1e-5f);
  4726. }
  4727. TEST (pitch_correction_formant_path)
  4728. {
  4729. // Formant on: PSOLA keeps the correction (output pitch = grain spacing) while Gender resamples the grains:
  4730. // the spectrum of a saw moves up with Gender > 0.5 and down with Gender < 0.5
  4731. auto run = [] (float gender) {
  4732. auto fx = lynx::makeEffect (lynx::EffectKind::pitchCorrect);
  4733. fx->prepare (48000.0);
  4734. auto slot = lynx::makeEffectSlot (lynx::EffectKind::pitchCorrect); // chromatic, instant, A 440
  4735. slot.params[29] = 1.0f;
  4736. slot.params[30] = gender;
  4737. std::vector<float> l (48000 * 2), r;
  4738. for (std::size_t i = 0; i < l.size(); ++i)
  4739. l[i] = 0.5f * (float) (2.0 * std::fmod (452.0 * (double) i / 48000.0, 1.0) - 1.0); // saw
  4740. r = l;
  4741. fx->process (l.data(), r.data(), (int) l.size(), slot.params, 120.0);
  4742. l.erase (l.begin(), l.begin() + 48000);
  4743. return l;
  4744. };
  4745. // period by autocorrelation (lags 60…160 = 300…800 Hz)
  4746. auto pitch = [] (const std::vector<float>& x) {
  4747. auto best = 0.0, bestLag = 0.0;
  4748. for (int lag = 60; lag <= 160; ++lag)
  4749. {
  4750. auto sum = 0.0;
  4751. for (std::size_t i = 0; i + (std::size_t) lag < x.size(); ++i)
  4752. sum += (double) x[i] * x[i + (std::size_t) lag];
  4753. if (sum > best)
  4754. {
  4755. best = sum;
  4756. bestLag = lag;
  4757. }
  4758. }
  4759. return 48000.0 / bestLag;
  4760. };
  4761. // brightness: energy of the first difference relative to the energy
  4762. auto brightness = [] (const std::vector<float>& x) {
  4763. auto e = 0.0, d = 0.0;
  4764. for (std::size_t i = 1; i < x.size(); ++i)
  4765. {
  4766. e += (double) x[i] * x[i];
  4767. d += (double) (x[i] - x[i - 1]) * (x[i] - x[i - 1]);
  4768. }
  4769. return d / e;
  4770. };
  4771. const auto neutral = run (0.5f), up = run (0.8f), down = run (0.3f);
  4772. CHECK (std::abs (pitch (neutral) - 440.0) < 5.0); // 452 Hz pulled to A
  4773. CHECK (std::abs (pitch (up) - 440.0) < 5.0); // Gender does not move the pitch
  4774. CHECK (brightness (up) > 1.5 * brightness (neutral));
  4775. CHECK (brightness (down) < 0.7 * brightness (neutral));
  4776. }
  4777. TEST (parallel_container_inner_links_modulate)
  4778. {
  4779. // one branch: utility (gain) + a control-only auto-pan LFO (1 beat); the link maps the LFO 0..1 onto the
  4780. // utility gain −24 dB..0 dB, so the level must swing; without the link it stays put
  4781. auto container = lynx::makeEffectSlot (lynx::EffectKind::parallel);
  4782. auto gain = lynx::makeEffectSlot (lynx::EffectKind::utility);
  4783. auto lfo = lynx::makeEffectSlot (lynx::EffectKind::autoPan);
  4784. lfo.params[0] = 1.0f / 64.0f;
  4785. lfo.params[4] = 1.0f; // control only: audio passes unchanged
  4786. container.branches.push_back ({ { gain, lfo }, 1.0f });
  4787. lynx::EffectLink link;
  4788. link.source = 1;
  4789. link.param = 0;
  4790. for (int i = 0; i <= 32; ++i)
  4791. link.curve.push_back (0.5f * (float) i / 32.0f);
  4792. auto levels = [&] (bool linked) {
  4793. auto slot = container;
  4794. if (linked)
  4795. slot.links.push_back (link);
  4796. auto fx = lynx::makeParallelEffect (slot);
  4797. fx->prepare (48000.0);
  4798. float lo = 1e9f, hi = 0.0f;
  4799. for (int block = 0; block < 94; ++block) // ~1 beat at 120 BPM in 256-sample blocks
  4800. {
  4801. std::vector<float> l (256, 1.0f), r (256, 1.0f);
  4802. fx->setSongPosition (block * 256.0 / 48000.0 * 2.0 * 960.0); // the engine positions every block
  4803. fx->process (l.data(), r.data(), 256, slot.params, 120.0);
  4804. lo = std::min (lo, std::abs (l[128]));
  4805. hi = std::max (hi, std::abs (l[128]));
  4806. }
  4807. return std::pair { lo, hi };
  4808. };
  4809. const auto [lo, hi] = levels (true);
  4810. CHECK (hi > 0.8f && lo < 0.12f);
  4811. const auto [lo0, hi0] = levels (false);
  4812. CHECK (std::abs (hi0 - lo0) < 1e-4f);
  4813. }
  4814. TEST (synth_spectrum_decays_per_harmonic)
  4815. {
  4816. // 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
  4817. lynx::SynthSettings s;
  4818. s.osc[0] = { lynx::Waveform::spectral, 0, 0.0f, 1.0f };
  4819. s.cutoff = 20000.0f;
  4820. s.decay = 0.0f;
  4821. s.sustain = 1.0f;
  4822. s.spectrum[0] = 1.0f;
  4823. s.spectrum[2] = 1.0f;
  4824. s.spectrumDecay[2] = 0.2f;
  4825. const auto x = renderSynthNote (s, 57, 48000); // 220 Hz, 48 kHz, 1 s
  4826. // equal 2400-sample windows (Goertzel power grows with the window): 10…60 ms and 500…550 ms
  4827. const auto early1 = goertzel (x, 220.0, 480, 2880), early3 = goertzel (x, 660.0, 480, 2880);
  4828. const auto late1 = goertzel (x, 220.0, 24000, 26400), late3 = goertzel (x, 660.0, 24000, 26400);
  4829. CHECK (early3 > 0.05 * early1); // ≈ −9 dB on average over 10…60 ms
  4830. CHECK (late3 < 1e-4 * late1);
  4831. CHECK (std::abs (10.0 * std::log10 (late1 / early1)) < 1.0); // the 1st holds
  4832. // without per-harmonic decay the spectrum stays as it is
  4833. s.spectrumDecay[2] = 0.0f;
  4834. const auto y = renderSynthNote (s, 57, 48000);
  4835. CHECK (std::abs (10.0 * std::log10 (goertzel (y, 660.0, 24000, 26400) / goertzel (y, 660.0, 480, 2880))) < 1.0);
  4836. }
  4837. TEST (worker_pool_runs_each_index_once_per_round)
  4838. {
  4839. // rounds of alternating sizes (a stalled worker must never run an index of a later round), each index
  4840. // exactly once, and nothing running after parallelFor returns
  4841. lynx::WorkerPool pool (3);
  4842. std::vector<std::atomic<int>> hits (64);
  4843. std::atomic<int> round { 0 }, outside { 0 }, wrongRound { 0 };
  4844. std::atomic<bool> open { false };
  4845. int failures = 0;
  4846. for (int r = 1; r <= 20000; ++r)
  4847. {
  4848. const auto n = (r % 3 == 0) ? 64 : (r % 3 == 1 ? 2 : 9);
  4849. for (int i = 0; i < n; ++i)
  4850. hits[(std::size_t) i].store (0);
  4851. round.store (r);
  4852. open.store (true);
  4853. auto fn = [&, r] (int i) {
  4854. if (! open.load())
  4855. outside.fetch_add (1);
  4856. if (round.load() != r)
  4857. wrongRound.fetch_add (1);
  4858. hits[(std::size_t) i].fetch_add (1);
  4859. };
  4860. pool.parallelFor (n, fn);
  4861. open.store (false);
  4862. for (int i = 0; i < n; ++i)
  4863. failures += hits[(std::size_t) i].load() != 1;
  4864. }
  4865. CHECK (failures == 0);
  4866. CHECK (outside.load() == 0);
  4867. CHECK (wrongRound.load() == 0);
  4868. }
  4869. TEST (ladder_filter_follows_toxic_law)
  4870. {
  4871. // the 4-pole ladder: −24 dB/oct far above the cutoff (vs −12 for the SVF), resonance raises the corner, and
  4872. // the input saturation keeps it bounded even at full resonance
  4873. auto level = [] (bool ladder, float res, double hz) {
  4874. lynx::SynthSettings s;
  4875. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  4876. s.cutoff = 500.0f;
  4877. s.resonance = res;
  4878. s.ladder = ladder;
  4879. const auto key = (int) std::lround (69.0 + 12.0 * std::log2 (hz / 440.0));
  4880. const auto x = renderSynthNote (s, key, 48000);
  4881. double e = 0.0, peak = 0.0;
  4882. for (std::size_t i = 24000; i < 48000; ++i)
  4883. e += (double) x[i] * x[i], peak = std::max (peak, (double) std::abs (x[i]));
  4884. return std::pair { std::sqrt (e / 24000.0), peak };
  4885. };
  4886. 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
  4887. const auto svfHigh = level (false, 0.0f, 3520.0).first / level (false, 0.0f, 110.0).first;
  4888. CHECK (20.0 * std::log10 (high / low) < -55.0); // ≈ 24 dB/oct over ~2.8 octaves
  4889. CHECK (20.0 * std::log10 (svfHigh) > -45.0); // the 2-pole SVF falls much less
  4890. const auto corner0 = level (true, 0.0f, 523.25).first, corner1 = level (true, 0.6f, 523.25).first;
  4891. CHECK (corner1 > 1.5 * corner0); // resonance boosts near the cutoff
  4892. const auto loud = level (true, 1.0f, 523.25);
  4893. CHECK (std::isfinite (loud.first) && loud.second < 20.0); // self-oscillation stays bounded
  4894. }
  4895. TEST (synth_spectrum_settles_on_target)
  4896. {
  4897. // ALT DECAY-like morph: harmonic 3 starts at 1 and settles on 0.25 (−12 dB) instead of fading out
  4898. lynx::SynthSettings s;
  4899. s.osc[0] = { lynx::Waveform::spectral, 0, 0.0f, 1.0f };
  4900. s.cutoff = 20000.0f;
  4901. s.decay = 0.0f;
  4902. s.sustain = 1.0f;
  4903. s.spectrum[0] = 1.0f;
  4904. s.spectrum[2] = 1.0f;
  4905. s.spectrumDecay[2] = 0.1f;
  4906. s.spectrumTarget[2] = 0.25f;
  4907. const auto x = renderSynthNote (s, 57, 48000);
  4908. const auto ratio = goertzel (x, 660.0, 24000, 26400) / goertzel (x, 220.0, 24000, 26400);
  4909. CHECK (std::abs (10.0 * std::log10 (ratio) - 20.0 * std::log10 (0.25)) < 1.0);
  4910. }
  4911. TEST (kepler_chorus_is_stereo_and_keeps_level)
  4912. {
  4913. // chorus I on a sine: L and R differ (opposite LFO phases), the level stays close to the dry one
  4914. lynx::SynthSettings s;
  4915. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  4916. s.cutoff = 20000.0f;
  4917. auto dry = s;
  4918. s.chorus = 1;
  4919. auto render = [] (const lynx::SynthSettings& set) {
  4920. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  4921. inst->prepare (48000.0);
  4922. lynx::ChannelDef c;
  4923. c.synth = set;
  4924. inst->configure (c, 120.0);
  4925. inst->noteOn (69, 1.0f);
  4926. std::vector<float> l (96000), r (96000);
  4927. inst->render (l.data(), r.data(), 96000, 1.0f, 1.0f);
  4928. return std::pair { l, r };
  4929. };
  4930. const auto [l, r] = render (s);
  4931. const auto [dl, dr] = render (dry);
  4932. double diff = 0.0, e = 0.0, ed = 0.0;
  4933. for (std::size_t i = 48000; i < 96000; ++i)
  4934. diff += std::abs (l[i] - r[i]), e += (double) l[i] * l[i], ed += (double) dl[i] * dl[i];
  4935. CHECK (diff / 48000.0 > 1e-3);
  4936. CHECK (std::abs (10.0 * std::log10 (e / ed)) < 3.0);
  4937. }
  4938. TEST (fl_pan_law_matches_love_philter_dll)
  4939. {
  4940. // values printed by the installation's Love Philter pan routine for vol 0.8 (REA_rodada27 §3.1, lppan.txt)
  4941. struct Row { double pan, ll, rr, rl, lr; };
  4942. const Row rows[] = { { -1.5, 0.239782482, -0.432956904, 0.805467963, 0.0 }, { -0.5, 0.805467963, 0.432956904, 0.239782482, 0.0 },
  4943. { 0.0, 0.8, 0.8, 0.0, 0.0 }, { 0.75, 0.220719516, 0.707889318, 0.0, 0.401742548 },
  4944. { 1.0, 0.0, 0.565685451, 0.0, 0.565685451 } };
  4945. for (const auto& row : rows)
  4946. {
  4947. float ll, rl, lr, rr;
  4948. lynx::flPanMatrix (row.pan, ll, rl, lr, rr);
  4949. CHECK (std::abs (0.8 * ll - row.ll) < 1e-6 && std::abs (0.8 * rr - row.rr) < 1e-6);
  4950. CHECK (std::abs (0.8 * rl - row.rl) < 1e-6 && std::abs (0.8 * lr - row.lr) < 1e-6);
  4951. }
  4952. }
  4953. TEST (effector_units_match_fl_dll_impulse_responses)
  4954. {
  4955. // impulse responses of the installation's Effector engine (REA_rodada27 §2, eu_<kind>_<X>_<Y>.txt; LFO off,
  4956. // wet 1, blocks of 256): samples 1, 10, 100 and 1000
  4957. struct Case { int kind; float x, y; double v[4]; };
  4958. const Case cases[] = { { 3, 0.5f, 0.5f, { -0.603055418, 0.159798339, -0.0055043716, -1.06241259e-06 } },
  4959. { 4, 0.2f, 0.5f, { 4.68885949e-26, 4.20032622e-19, 0.000487731799, 2.27715846e-09 } },
  4960. { 4, 0.8f, 0.3f, { -0.293783396, -0.0306414738, -0.00068128563, 1.358577e-15 } } };
  4961. for (const auto& c : cases)
  4962. {
  4963. auto fx = lynx::effector::make();
  4964. fx->prepare (44100.0);
  4965. lynx::EffectParams p {};
  4966. p[lynx::effector::type] = c.kind / 11.0f;
  4967. p[lynx::effector::wetMix] = 1.0f;
  4968. p[lynx::effector::paramX] = c.x;
  4969. p[lynx::effector::paramY] = c.y;
  4970. p[lynx::effector::modX] = p[lynx::effector::modY] = 0.5f;
  4971. p[lynx::effector::modRate] = 0.5f;
  4972. p[lynx::effector::inputLevel] = 1.0f;
  4973. p[lynx::effector::outputGain] = 0.5f;
  4974. std::vector<float> l (1024, 0.0f), r (1024, 0.0f);
  4975. l[0] = r[0] = 1.0f;
  4976. for (int d = 0; d < 1024; d += 256)
  4977. fx->process (l.data() + d, r.data() + d, 256, p, 120.0);
  4978. const int at[4] { 1, 10, 100, 1000 };
  4979. for (int k = 0; k < 4; ++k)
  4980. CHECK (std::abs (l[(std::size_t) at[k]] - c.v[k]) < 2e-7 + 1e-5 * std::abs (c.v[k]));
  4981. }
  4982. }
  4983. TEST (harmless_stereo_tremolo_and_vibrato)
  4984. {
  4985. // tremolo d = 1: each side swings between 0 and 1.25 at 5 Hz, L and R in anti-phase; vibrato modulates the pitch
  4986. lynx::SynthSettings s;
  4987. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  4988. s.cutoff = 20000.0f;
  4989. s.stereoTremolo = 1.0f;
  4990. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  4991. inst->prepare (48000.0);
  4992. lynx::ChannelDef c;
  4993. c.synth = s;
  4994. inst->configure (c, 120.0);
  4995. inst->noteOn (69, 1.0f);
  4996. std::vector<float> l (48000), r (48000);
  4997. inst->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  4998. 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; };
  4999. // θ = 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
  5000. CHECK (envelope (l, 19200) > 4.0f * envelope (r, 19200));
  5001. CHECK (envelope (r, 24000) > 4.0f * envelope (l, 24000));
  5002. // vibrato 100 cents: zero crossings vary in spacing; without it they are regular
  5003. auto crossingsSpread = [] (float cents) {
  5004. lynx::SynthSettings v;
  5005. v.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  5006. v.cutoff = 20000.0f;
  5007. v.vibratoCents = cents;
  5008. const auto x = renderSynthNote (v, 69, 48000);
  5009. std::vector<int> zc;
  5010. for (int i = 24000; i < 48000; ++i)
  5011. if (x[(std::size_t) i - 1] < 0.0f && x[(std::size_t) i] >= 0.0f)
  5012. zc.push_back (i);
  5013. int lo = 1 << 30, hi = 0;
  5014. for (std::size_t k = 1; k < zc.size(); ++k)
  5015. lo = std::min (lo, zc[k] - zc[k - 1]), hi = std::max (hi, zc[k] - zc[k - 1]);
  5016. return hi - lo;
  5017. };
  5018. CHECK (crossingsSpread (0.0f) <= 1);
  5019. CHECK (crossingsSpread (100.0f) >= 4);
  5020. }
  5021. TEST (physical_models_sound_and_end)
  5022. {
  5023. // Sakura: a plucked string with default-ish parameters rings and fades after the release; Drumpad: a hit decays
  5024. for (const auto kind : { lynx::InstrumentKind::sakura, lynx::InstrumentKind::drumpad })
  5025. {
  5026. lynx::ChannelDef c;
  5027. c.instrument = kind;
  5028. if (kind == lynx::InstrumentKind::sakura)
  5029. {
  5030. c.modelParams.assign (146, 0.5f);
  5031. c.modelParams[111] = 3.0f; // both strings at the note
  5032. c.modelParams[113] = 0.5f; // octave ×1
  5033. c.modelParams[6] = c.modelParams[11] = 0.99f; // long decay
  5034. c.modelParams[31] = 0.0f; // noise exciter
  5035. }
  5036. else
  5037. {
  5038. c.modelParams.assign (38, 0.5f);
  5039. c.modelParams[0] = 1.0f; // retrigger noise
  5040. c.modelParams[30] = c.modelParams[31] = c.modelParams[32] = c.modelParams[33] = 0.0f; // no velocity morph
  5041. }
  5042. auto inst = lynx::makeInstrument (kind);
  5043. inst->prepare (48000.0);
  5044. inst->configure (c, 120.0);
  5045. inst->noteOn (60, 0.8f);
  5046. std::vector<float> l (48000), r (48000);
  5047. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  5048. inst->noteOff (60);
  5049. inst->render (l.data() + 24000, r.data() + 24000, 24000, 1.0f, 1.0f);
  5050. double early = 0.0;
  5051. for (int i = 0; i < 12000; ++i)
  5052. early += (double) l[(std::size_t) i] * l[(std::size_t) i];
  5053. CHECK (early > 1e-6);
  5054. CHECK (std::all_of (l.begin(), l.end(), [] (float v) { return std::isfinite (v); }));
  5055. std::vector<float> tail (480000), tailR (480000);
  5056. inst->render (tail.data(), tailR.data(), 480000, 1.0f, 1.0f); // 10 s later the voice has ended
  5057. CHECK (inst->idle());
  5058. }
  5059. }
  5060. TEST (squeeze_matches_fl_model)
  5061. {
  5062. // Fruity Squeeze: Steps quantises, Mix 0 passes the input dry ×Volume/127; a silent block is left untouched
  5063. auto slot = lynx::makeEffectSlot (lynx::EffectKind::squeeze);
  5064. slot.params[1] = 0.0f; // mix 0: dry only
  5065. auto fx = lynx::makeEffect (lynx::EffectKind::squeeze);
  5066. fx->prepare (44100.0);
  5067. std::vector<float> l (512, 0.3f), r (512, -0.2f);
  5068. fx->process (l.data(), r.data(), 512, slot.params, 120.0);
  5069. CHECK (std::abs (l[100] - 0.3f) < 1e-6f && std::abs (r[100] + 0.2f) < 1e-6f); // Volume 127/127
  5070. slot.params[1] = 1.0f; // wet only
  5071. slot.params[2] = 32000.0f / 32768.0f; // 32768^(1 − 32000/32768) ≈ 1.27 levels per unit → heavy quantisation
  5072. std::vector<float> a (512), b (512);
  5073. for (int i = 0; i < 512; ++i)
  5074. a[(std::size_t) i] = b[(std::size_t) i] = 0.4f * (float) std::sin (i * 0.05);
  5075. fx->process (a.data(), b.data(), 512, slot.params, 120.0);
  5076. const auto levels = std::pow (32768.0f, 1.0f - 32000.0f / 32768.0f);
  5077. for (int i = 0; i < 512; i += 37)
  5078. CHECK (std::abs (a[(std::size_t) i] * levels - std::nearbyint (a[(std::size_t) i] * levels)) < 1e-3f);
  5079. std::vector<float> z (512, 0.0f), z2 (512, 0.0f);
  5080. fx->process (z.data(), z2.data(), 512, slot.params, 120.0);
  5081. CHECK (z[10] == 0.0f);
  5082. }
  5083. TEST (sakura_matrix_and_effects)
  5084. {
  5085. // REA_rodada29 §1: velocity → level follows 10^(2m)·0.05 (vel 1 vs 0.5 → ×10 in amplitude); the delay leaves
  5086. // an echo after the note has ended and keeps the instrument from going idle until its tail is silent
  5087. auto base = [] {
  5088. lynx::ChannelDef c;
  5089. c.instrument = lynx::InstrumentKind::sakura;
  5090. c.modelParams.assign (146, 0.0f);
  5091. const std::pair<int, float> values[] { { 0, 0.375f }, { 1, 0.5f }, { 3, 0.5f }, { 4, 1.0f }, { 6, 0.95f }, { 9, 0.3f },
  5092. { 11, 0.95f }, { 14, 0.3f }, { 18, 0.5f }, { 19, 0.5f }, { 27, 0.5f }, { 28, 1.0f },
  5093. { 29, 0.7f }, { 31, 1.0f }, { 32, 0.5f }, { 111, 3.0f }, { 113, 0.5f } };
  5094. for (const auto& [i, v] : values)
  5095. c.modelParams[(std::size_t) i] = v;
  5096. return c;
  5097. };
  5098. auto render = [] (const lynx::ChannelDef& c, float velocity, int held, int total) {
  5099. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sakura);
  5100. inst->prepare (48000.0);
  5101. inst->configure (c, 120.0);
  5102. inst->noteOn (60, velocity);
  5103. std::vector<float> l ((std::size_t) total), r ((std::size_t) total);
  5104. for (int s = 0; s < total; s += 256)
  5105. {
  5106. if (s == held)
  5107. inst->noteOff (60);
  5108. inst->render (l.data() + s, r.data() + s, std::min (256, total - s), 1.0f, 1.0f);
  5109. }
  5110. return std::make_pair (l, std::move (inst));
  5111. };
  5112. auto energy = [] (const std::vector<float>& x, int from, int to) {
  5113. double e = 0.0;
  5114. for (int i = from; i < to; ++i)
  5115. e += (double) x[(std::size_t) i] * x[(std::size_t) i];
  5116. return e;
  5117. };
  5118. auto c = base();
  5119. c.modelParams[79] = 6.0f; // slot 1: velocity → level, amount 1
  5120. c.modelParams[80] = 1.0f;
  5121. c.modelParams[82] = 1.0f;
  5122. const auto loud = energy (render (c, 1.0f, 24064, 24064).first, 0, 24064);
  5123. const auto soft = energy (render (c, 0.5f, 24064, 24064).first, 0, 24064);
  5124. CHECK (loud > 1e-6 && std::abs (loud / soft - 100.0) < 1.0);
  5125. auto d = base();
  5126. auto [dry, dryInst] = render (d, 0.8f, 4864, 72000);
  5127. d.modelParams[63] = 1.0f; // delay on: time 0.5 → ≈ 0.52 s, wet 1, no feedback: one echo
  5128. d.modelParams[64] = 0.5f;
  5129. d.modelParams[69] = 1.0f;
  5130. auto [wet, wetInst] = render (d, 0.8f, 4864, 72000);
  5131. CHECK (energy (wet, 26000, 40000) > 100.0 * energy (dry, 26000, 40000) + 1e-9); // the note ends near 0.2 s
  5132. CHECK (dryInst->idle() || energy (dry, 70000, 72000) < 1e-12);
  5133. CHECK (! wetInst->idle()); // the echo tail has not been silent for 3 s yet
  5134. }
  5135. TEST (drumsynth_live_engine)
  5136. {
  5137. // REA_rodada30 §1: key → patch slot, state parsing, the engine against our reference model (no DLL: synthesised
  5138. // sources only, noise from the fallback seed), voice modes, patch level/pan
  5139. CHECK (lynx::drumSynthKeyToSlot (48) == 0 && lynx::drumSynthKeyToSlot (71) == 23 && lynx::drumSynthKeyToSlot (0) == 24);
  5140. CHECK (lynx::drumSynthKeyToSlot (47) == 71 && lynx::drumSynthKeyToSlot (72) == 72 && lynx::drumSynthKeyToSlot (119) == 119);
  5141. CHECK (lynx::drumSynthKeyToSlot (120) == -1);
  5142. // a version 3 state: 120 names, 120 × 38 ints (send track −1 becomes 0 below version 4), flags
  5143. std::vector<std::uint8_t> blob;
  5144. auto put = [&] (std::uint32_t v) { for (int k = 0; k < 4; ++k) blob.push_back ((std::uint8_t) (v >> (8 * k))); };
  5145. put (3);
  5146. put (66);
  5147. for (int i = 0; i < 120; ++i)
  5148. blob.push_back (2), blob.push_back ('a'), blob.push_back ((std::uint8_t) ('0' + i % 10));
  5149. for (int i = 0; i < 120 * 38; ++i)
  5150. put ((std::uint32_t) (i % 38 == 36 ? -1 : i % 38 == 4 ? 300 : 0));
  5151. put (0);
  5152. const auto parsed = lynx::drumSynthLiveParams (blob);
  5153. CHECK (parsed && (int) parsed->size() == lynx::drumSynthParamCount);
  5154. CHECK (parsed && (*parsed)[36] == 0.0f && (*parsed)[38 * 7 + 4] == 300.0f && (*parsed)[(std::size_t) lynx::drumSynthEditorKeyIndex] == 66.0f);
  5155. blob.resize (500);
  5156. CHECK (! lynx::drumSynthLiveParams (blob));
  5157. // patch on key 60 (slot 12): tone-mode Osc1 with sweep and click, noise-band Osc2, ring, 2 retriggers
  5158. 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,
  5159. 0, 0, 0, 0, 0, 0, 30, -1, 0, 0, 64 };
  5160. lynx::ChannelDef c;
  5161. c.instrument = lynx::InstrumentKind::drumsynth;
  5162. c.modelParams.assign ((std::size_t) lynx::drumSynthParamCount, 0.0f);
  5163. for (int s = 0; s < 120; ++s)
  5164. c.modelParams[(std::size_t) (38 * s + 15)] = c.modelParams[(std::size_t) (38 * s + 34)] = -1.0f;
  5165. for (int i = 0; i < 38; ++i)
  5166. c.modelParams[(std::size_t) (38 * 12 + i)] = (float) patch[i];
  5167. auto render = [] (const lynx::ChannelDef& def, std::vector<int> keys, int total, float gl = 1.0f, float gr = 1.0f) {
  5168. auto inst = lynx::makeInstrument (lynx::InstrumentKind::drumsynth);
  5169. inst->configure (def, 120.0);
  5170. inst->prepare (48000.0);
  5171. std::vector<float> l ((std::size_t) total), r ((std::size_t) total);
  5172. for (int s = 0; s < total; s += 512)
  5173. {
  5174. for (std::size_t k = 0; k + 1 < keys.size(); k += 2)
  5175. if (keys[k + 1] == s)
  5176. inst->noteOn (keys[k], 100.0f / 128.0f);
  5177. inst->render (l.data() + s, r.data() + s, std::min (512, total - s), gl, gr);
  5178. }
  5179. return std::make_tuple (l, r, std::move (inst));
  5180. };
  5181. {
  5182. auto [l, r, inst] = render (c, { 60, 0 }, 9600);
  5183. // reference model (REA round 30 dsl_model.py, seed 0x56CE, FL velocity 100, V = 1, centre: × g(100)·cos(π/4))
  5184. const std::pair<int, float> golden[] { { 0, -0.0074092713f }, { 10, -0.13961405f }, { 100, -0.47290668f }, { 1000, -0.29188696f },
  5185. { 3000, -0.22130175f }, { 6000, -0.049537566f }, { 9599, 0.010392102f } };
  5186. for (const auto& [i, v] : golden)
  5187. CHECK (std::abs (l[(std::size_t) i] - v) < 2e-6f && std::abs (r[(std::size_t) i] - v) < 2e-6f);
  5188. std::vector<float> tail (48000 * 4), tailR (tail.size());
  5189. inst->render (tail.data(), tailR.data(), (int) tail.size(), 1.0f, 1.0f);
  5190. CHECK (inst->idle()); // the engine reported the voice finished
  5191. }
  5192. auto energy = [] (const std::vector<float>& x, int from, int to) {
  5193. double e = 0.0;
  5194. for (int i = from; i < to; ++i)
  5195. e += (double) x[(std::size_t) i] * x[(std::size_t) i];
  5196. return e;
  5197. };
  5198. // a key without a patch level (slot 0, level 0) and a key outside the 120 patches are silent
  5199. CHECK (energy (std::get<0> (render (c, { 48, 0, 125, 0 }, 4096)), 0, 4096) == 0.0);
  5200. // mono: a second hit on the same key cuts the first; poly: both ring together (Osc2 off: no noise, deterministic)
  5201. auto tone = c;
  5202. tone.modelParams[38 * 12 + 14] = 0.0f;
  5203. const auto single = std::get<0> (render (tone, { 60, 0 }, 8192));
  5204. const auto mono = std::get<0> (render (tone, { 60, 0, 60, 2048 }, 8192));
  5205. auto poly = tone;
  5206. poly.modelParams[38 * 12 + 24] = 1.0f;
  5207. const auto both = std::get<0> (render (poly, { 60, 0, 60, 2048 }, 8192));
  5208. double monoDiff = 0.0, polyDiff = 0.0;
  5209. for (int i = 2048 + 300; i < 8192; ++i) // after the cut fade: mono = only the second hit, a copy of the first
  5210. 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]);
  5211. CHECK (monoDiff < 1e-3 && polyDiff > 1.0);
  5212. // patch pan +64 → right only; channel volume counts twice (FL applies Final.Vol in the engine and at the host)
  5213. auto right = c;
  5214. right.modelParams[38 * 12 + 1] = 64.0f;
  5215. const auto [pl, pr, pi] = render (right, { 60, 0 }, 4096);
  5216. CHECK (energy (pl, 0, 4096) < 1e-12 * energy (pr, 0, 4096) && energy (pr, 0, 4096) > 1.0);
  5217. const auto full = std::get<0> (render (tone, { 60, 0 }, 4096));
  5218. const auto half = std::get<0> (render (tone, { 60, 0 }, 4096, 0.5f, 0.5f));
  5219. CHECK (std::abs (half[100] - 0.25f * full[100]) < 1e-6f && std::abs (full[100]) > 0.01f);
  5220. }
  5221. TEST (kepler_lfo_bpm_sync)
  5222. {
  5223. // 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)
  5224. std::vector<std::uint8_t> state (0x21 + 34 * 4, 0);
  5225. auto putU32 = [&] (std::size_t o, std::uint32_t v) { std::memcpy (state.data() + o, &v, 4); };
  5226. putU32 (12, 9);
  5227. std::memcpy (state.data() + 16, "Kepler-1", 9);
  5228. putU32 (0x19, 4);
  5229. putU32 (0x1D, 34);
  5230. float k[34] {};
  5231. k[5] = 0.602085769f; // "Pads - Kepler" demo: n = 286
  5232. k[6] = 1.0f;
  5233. k[10] = 1.0f; // vibrato on
  5234. k[33] = 1.0f;
  5235. std::memcpy (state.data() + 0x21, k, sizeof k);
  5236. lynx::SynthSettings s;
  5237. float gain = 0.0f;
  5238. CHECK (lynx::synthFromKepler (state, s, gain));
  5239. CHECK (s.lfo[lynx::lfoPitch].sync && s.lfo[lynx::lfoPitch].secondsTiming);
  5240. CHECK (std::abs (s.lfo[lynx::lfoPitch].period - 286.0f / 192.0f) < 1e-6f);
  5241. k[5] = 0.0f; // slowest: 32 beats
  5242. std::memcpy (state.data() + 0x21, k, sizeof k);
  5243. CHECK (lynx::synthFromKepler (state, s, gain) && std::abs (s.lfo[lynx::lfoPitch].period - 32.0f) < 1e-6f);
  5244. k[6] = 0.0f; // free rate in seconds
  5245. std::memcpy (state.data() + 0x21, k, sizeof k);
  5246. CHECK (lynx::synthFromKepler (state, s, gain) && ! s.lfo[lynx::lfoPitch].sync);
  5247. }
  5248. TEST (harmless_engine)
  5249. {
  5250. // REA_rodada32: state parsing, the additive engine against our reference model (hlmodel.py), host levels, voice end
  5251. std::vector<std::uint8_t> blob;
  5252. 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))); };
  5253. std::array<std::int32_t, 100> p {}; // the reference's clean patch: Saw, open filter, no modulation
  5254. for (int i = 11; i < 23; ++i)
  5255. p[(std::size_t) i] = 1000;
  5256. 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;
  5257. 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;
  5258. // + resonance, pluck, 3-voice unison, tremolo, LFO on pitch
  5259. 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;
  5260. put (12);
  5261. for (auto v : p)
  5262. put (v);
  5263. for (int i = 0; i < 7; ++i)
  5264. put (0);
  5265. put (524); // Custom colour table: 524 × (amplitude, phase)
  5266. for (int i = 0; i < 1048; ++i)
  5267. {
  5268. const auto f = i < 524 ? 1.0f / (float) (i + 1) : 0.25f;
  5269. std::uint32_t bits = 0;
  5270. std::memcpy (&bits, &f, 4);
  5271. put ((std::int32_t) bits);
  5272. }
  5273. const auto parsed = lynx::harmlessParams (blob);
  5274. CHECK (parsed && (int) parsed->size() == lynx::harmlessParamCount);
  5275. CHECK (parsed && (*parsed)[54] == 3500.0f && (*parsed)[99] == 0.0f && (*parsed)[lynx::harmlessCustomFlagIndex] == 1.0f);
  5276. CHECK (parsed && (*parsed)[lynx::harmlessCustomIndex + 1] == 0.5f && (*parsed)[lynx::harmlessCustomIndex + 524] == 0.25f);
  5277. auto old = blob;
  5278. old[0] = 3; // versions below 4 are not Harmless states we know
  5279. CHECK (! lynx::harmlessParams (old));
  5280. old = blob;
  5281. old.resize (300);
  5282. CHECK (! lynx::harmlessParams (old));
  5283. lynx::ChannelDef c;
  5284. c.instrument = lynx::InstrumentKind::harmless;
  5285. c.modelParams = *parsed;
  5286. c.modelParams[lynx::harmlessCustomFlagIndex] = 0.0f; // colour 0 (Saw): the custom table is not read
  5287. auto render = [] (const lynx::ChannelDef& def, int total, float gl, float gr, int offAt) {
  5288. auto inst = lynx::makeInstrument (lynx::InstrumentKind::harmless);
  5289. inst->configure (def, 120.0);
  5290. inst->prepare (44100.0);
  5291. std::vector<float> l ((std::size_t) total), r ((std::size_t) total);
  5292. inst->noteOn (60, 0.78125f);
  5293. for (int s = 0; s < total; s += 512)
  5294. {
  5295. if (s == offAt)
  5296. inst->noteOff (60);
  5297. inst->render (l.data() + s, r.data() + s, std::min (512, total - s), gl, gr);
  5298. }
  5299. return std::make_tuple (l, r, std::move (inst));
  5300. };
  5301. {
  5302. // reference model (REA round 32 hlmodel.py, C5 at FL velocity 100, channel volume 1, centre, released at 6144)
  5303. auto [l, r, inst] = render (c, 8192, 1.0f, 1.0f, 6144);
  5304. const std::tuple<int, float, float> golden[] {
  5305. { 0, 0.0f, 0.0f }, { 10, -0.02220994f, -0.06232700f }, { 100, 0.40623373f, 0.17308202f }, { 1000, -0.04091963f, -0.26821208f },
  5306. { 3000, 0.14519004f, 0.11027778f }, { 6000, 0.50411958f, 0.27901855f }, { 8191, 0.02117692f, -0.01466602f } };
  5307. for (const auto& [i, gl, gr] : golden)
  5308. CHECK (std::abs (l[(std::size_t) i] - gl) < 2e-6f && std::abs (r[(std::size_t) i] - gr) < 2e-6f);
  5309. // after the release the record fades out (below 1e-4, then 30 ms) and the instrument goes idle
  5310. std::vector<float> tail (44100), tailR (tail.size());
  5311. inst->render (tail.data(), tailR.data(), (int) tail.size(), 1.0f, 1.0f);
  5312. CHECK (inst->idle());
  5313. }
  5314. // FL's level law applied once: half the channel volume halves the output; full right pan silences the left side
  5315. const auto full = std::get<0> (render (c, 2048, 1.0f, 1.0f, -1));
  5316. const auto half = std::get<0> (render (c, 2048, 0.5f, 0.5f, -1));
  5317. CHECK (std::abs (half[100] - 0.5f * full[100]) < 1e-6f && std::abs (full[100]) > 0.1f);
  5318. auto mono = c;
  5319. mono.modelParams[25] = 0.0f; // no tremolo, no unison pan spread
  5320. mono.modelParams[65] = 1.0f;
  5321. const auto [pl, pr, pi] = render (mono, 2048, 0.0f, 1.41421356f, -1);
  5322. double el = 0.0, er = 0.0;
  5323. for (int i = 0; i < 2048; ++i)
  5324. el += (double) pl[(std::size_t) i] * pl[(std::size_t) i], er += (double) pr[(std::size_t) i] * pr[(std::size_t) i];
  5325. CHECK (el < 1e-10 * er && er > 1.0);
  5326. }