tests.cpp 247 KB

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