tests.cpp 219 KB

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