tests.cpp 291 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682
  1. // Core tests (no JUCE). Usage: lynx_tests [folder-with-flp-files]
  2. #include <atomic>
  3. #include <cctype>
  4. #include <cmath>
  5. #include <cstdio>
  6. #include <cstring>
  7. #include <filesystem>
  8. #include <map>
  9. #include <set>
  10. #include <sstream>
  11. #include <fstream>
  12. #include <functional>
  13. #include <iterator>
  14. #include <string>
  15. #include <tuple>
  16. #include <vector>
  17. #include "core/Dither.h"
  18. #include "core/DrumSynthLive.h"
  19. #include "core/Effects.h"
  20. #include "core/Effector.h"
  21. #include "core/FlpImport.h"
  22. #include "core/FlEffects.h"
  23. #include "core/FlPatcher.h"
  24. #include "core/FlSamplers.h"
  25. #include "core/FlSynths.h"
  26. #include "core/Inflate.h"
  27. #include "core/WavPack.h"
  28. #include "core/FlWrapper.h"
  29. #include "core/Harmless.h"
  30. #include "core/HarmlessFx.h"
  31. #include "core/LiveEventQueue.h"
  32. #include "core/RackRenderer.h"
  33. #include "core/Scheduler.h"
  34. #include "core/SnapshotExchange.h"
  35. #include "core/SoftClip.h"
  36. #include "core/Slicer.h"
  37. #include "core/SytrusEngine.h"
  38. #include "core/Templates.h"
  39. #include "core/Vocodex.h"
  40. #include "core/TimeStretch.h"
  41. #include "core/WorkerPool.h"
  42. #include "core/Song.h"
  43. #include "core/NoteEdit.h"
  44. #include "core/Recorder.h"
  45. #include "core/KeyMap.h"
  46. #include "core/RackOps.h"
  47. #include "core/ValueMath.h"
  48. #include "core/Workspace.h"
  49. #include "flp/Flp.h"
  50. #include "ui/I18nData.h"
  51. namespace
  52. {
  53. int failures = 0;
  54. int checks = 0;
  55. std::vector<std::pair<const char*, std::function<void()>>>& registry()
  56. {
  57. static std::vector<std::pair<const char*, std::function<void()>>> r;
  58. return r;
  59. }
  60. struct Register
  61. {
  62. Register (const char* name, std::function<void()> fn) { registry().emplace_back (name, std::move (fn)); }
  63. };
  64. #define TEST(name) \
  65. static void name(); \
  66. static Register reg_##name (#name, name); \
  67. static void name()
  68. #define CHECK(cond) \
  69. do \
  70. { \
  71. ++checks; \
  72. if (! (cond)) \
  73. { \
  74. ++failures; \
  75. std::printf (" FAILED %s:%d: %s\n", __FILE__, __LINE__, #cond); \
  76. } \
  77. } while (false)
  78. std::string realFlpDir;
  79. // --- helpers for building synthetic .flp files -----------------------------
  80. struct FlpBuilder
  81. {
  82. std::vector<std::uint8_t> bytes;
  83. FlpBuilder (std::uint16_t ppq = 96)
  84. {
  85. put ("FLhd");
  86. u32 (6);
  87. u16 (0);
  88. u16 (1);
  89. u16 (ppq);
  90. put ("FLdt");
  91. u32 (0); // size is not used by the reader
  92. }
  93. void put (const char* s) { bytes.insert (bytes.end(), s, s + std::strlen (s)); }
  94. void u8 (std::uint8_t v) { bytes.push_back (v); }
  95. void u16 (std::uint16_t v) { u8 ((std::uint8_t) v); u8 ((std::uint8_t) (v >> 8)); }
  96. void u32 (std::uint32_t v) { u16 ((std::uint16_t) v); u16 ((std::uint16_t) (v >> 16)); }
  97. void varint (std::size_t n)
  98. {
  99. do
  100. {
  101. auto b = (std::uint8_t) (n & 0x7F);
  102. n >>= 7;
  103. u8 (n ? (std::uint8_t) (b | 0x80) : b);
  104. } while (n);
  105. }
  106. void data (std::uint8_t id, const std::vector<std::uint8_t>& payload)
  107. {
  108. u8 (id);
  109. varint (payload.size());
  110. bytes.insert (bytes.end(), payload.begin(), payload.end());
  111. }
  112. void ascii (std::uint8_t id, const std::string& s)
  113. {
  114. std::vector<std::uint8_t> p (s.begin(), s.end());
  115. p.push_back (0);
  116. data (id, p);
  117. }
  118. void utf16 (std::uint8_t id, const std::u16string& s)
  119. {
  120. std::vector<std::uint8_t> p;
  121. for (auto c : s)
  122. {
  123. p.push_back ((std::uint8_t) c);
  124. p.push_back ((std::uint8_t) (c >> 8));
  125. }
  126. p.push_back (0);
  127. p.push_back (0);
  128. data (id, p);
  129. }
  130. };
  131. std::vector<std::uint8_t> noteRecord (std::uint32_t pos, std::uint16_t channel, std::uint32_t len, std::uint16_t key,
  132. std::uint8_t velocity)
  133. {
  134. std::vector<std::uint8_t> r (24, 0);
  135. std::memcpy (&r[0], &pos, 4);
  136. std::memcpy (&r[6], &channel, 2);
  137. std::memcpy (&r[8], &len, 4);
  138. std::memcpy (&r[12], &key, 2);
  139. r[16] = 120;
  140. r[20] = 64;
  141. r[21] = velocity;
  142. return r;
  143. }
  144. } // namespace
  145. // ---------------------------------------------------------------------------
  146. // FLP
  147. TEST (flp_rejects_garbage)
  148. {
  149. std::vector<std::uint8_t> junk (64, 0x41);
  150. bool threw = false;
  151. try { flp::EventReader r (junk); } catch (const flp::Error&) { threw = true; }
  152. CHECK (threw);
  153. }
  154. TEST (flp_reads_size_classes_varint_and_extended_ids)
  155. {
  156. FlpBuilder b;
  157. b.u8 (0x15); b.u8 (2); // u8
  158. b.u8 (0x40); b.u16 (513); // u16
  159. b.u8 (0x9C); b.u32 (128500); // u32
  160. b.data (0xD5, std::vector<std::uint8_t> (300, 7)); // 2-byte varint
  161. b.u8 (0xAC); b.u32 (0xC0000100); b.varint (3); b.u8 (1); b.u8 (2); b.u8 (3); // extended ID
  162. flp::EventReader r (b.bytes);
  163. flp::Event e;
  164. CHECK (r.header().ppq == 96);
  165. CHECK (r.next (e) && e.id == 0x15 && e.value == 2);
  166. CHECK (r.next (e) && e.id == 0x40 && e.value == 513);
  167. CHECK (r.next (e) && e.id == 0x9C && e.value == 128500);
  168. CHECK (r.next (e) && e.id == 0xD5 && e.data.size() == 300 && e.data[299] == 7);
  169. CHECK (r.next (e) && e.id == 0xC0000100 && e.isData() && e.data.size() == 3 && e.data[2] == 3);
  170. CHECK (! r.next (e));
  171. }
  172. TEST (flp_truncated_file_throws)
  173. {
  174. FlpBuilder b;
  175. b.u8 (0x9C); b.u8 (1); // u32 with only 1 byte
  176. flp::EventReader r (b.bytes);
  177. flp::Event e;
  178. bool threw = false;
  179. try { r.next (e); } catch (const flp::Error&) { threw = true; }
  180. CHECK (threw);
  181. }
  182. TEST (flp_version_numbers)
  183. {
  184. CHECK (flp::parseVersionNumber ("25.2.5.5319") == 25002005u);
  185. CHECK (flp::parseVersionNumber ("20.99.3000.3031") == 20102000u);
  186. CHECK (flp::parseVersionNumber ("11.0.3") == 11000003u);
  187. }
  188. TEST (flp_playlist_record_size_by_version)
  189. {
  190. CHECK (flp::playlistRecordSize (12009003, 64) == 32);
  191. CHECK (flp::playlistRecordSize (21000000, 120) == 60);
  192. CHECK (flp::playlistRecordSize (25002005, 160) == 80);
  193. CHECK (flp::playlistRecordSize (25002005, 60) == 60); // size doesn't match the version -> tries the others
  194. CHECK (flp::playlistRecordSize (25002005, 7) == 0);
  195. }
  196. TEST (flp_parses_project_model)
  197. {
  198. FlpBuilder b (96);
  199. b.ascii (0xC7, "25.2.5.5319");
  200. b.u8 (0x9C); b.u32 (174500);
  201. b.utf16 (0xC2, u"Título");
  202. b.u8 (0x41); b.u16 (3);
  203. b.u8 (0x96); b.u32 (0x00A14547); // BGR in the file
  204. auto notes = noteRecord (96, 1, 48, 64, 100);
  205. auto n2 = noteRecord (0, 0, 0, 60, 128);
  206. notes.insert (notes.end(), n2.begin(), n2.end());
  207. b.data (0xE0, notes);
  208. b.u8 (0x40); b.u16 (0);
  209. b.u8 (0x15); b.u8 (0);
  210. b.utf16 (0xCB, u"Kick");
  211. {
  212. std::vector<std::uint8_t> levels (24, 0);
  213. const std::int32_t lv[] = { 3200, 12800, -150 };
  214. std::memcpy (levels.data(), lv, sizeof (lv));
  215. b.data (0xDB, levels);
  216. }
  217. b.u8 (0x68); b.u16 (5);
  218. b.u8 (0x40); b.u16 (1);
  219. b.u8 (0x15); b.u8 (2);
  220. b.utf16 (0xC9, u"FLEX");
  221. b.utf16 (0xCB, u"Lead");
  222. b.u8 (0x63); b.u16 (0);
  223. std::vector<std::uint8_t> item (80, 0);
  224. std::uint32_t pos = 384, len = 768;
  225. std::uint16_t base = 20480, idx = 20480 + 3, rv = 499 - 2;
  226. std::memcpy (&item[0], &pos, 4);
  227. std::memcpy (&item[4], &base, 2);
  228. std::memcpy (&item[6], &idx, 2);
  229. std::memcpy (&item[8], &len, 4);
  230. std::memcpy (&item[12], &rv, 2);
  231. b.data (0xE9, item);
  232. b.utf16 (0xCC, u"Drums");
  233. b.data (0xEC, std::vector<std::uint8_t> (12, 0));
  234. b.data (0xEC, std::vector<std::uint8_t> (12, 0));
  235. const auto p = flp::parseProject (b.bytes);
  236. CHECK (p.version == "25.2.5.5319");
  237. CHECK (std::abs (p.tempo - 174.5) < 1e-9);
  238. CHECK (p.title == "Título");
  239. CHECK (p.channels.size() == 2);
  240. CHECK (p.channels[0].name == "Kick" && p.channels[0].mixerTrack == 5);
  241. CHECK (p.channels[0].hasLevels && p.channels[0].pan == 3200 && p.channels[0].volume == 12800 && p.channels[0].pitchCents == -150);
  242. CHECK (p.channels[1].type == flp::ChannelType::instrument && p.channels[1].pluginName == "FLEX");
  243. CHECK (p.patterns.size() == 1 && p.patterns[0].index == 3);
  244. CHECK (p.patterns[0].colour && *p.patterns[0].colour == 0x4745A1);
  245. CHECK (p.patterns[0].notes.size() == 2 && p.patterns[0].notes[0].position == 0); // sorted
  246. CHECK (p.patterns[0].notes[1].key == 64 && p.patterns[0].notes[1].length == 48);
  247. CHECK (p.arrangements.size() == 1 && p.arrangements[0].items.size() == 1);
  248. const auto& it = p.arrangements[0].items[0];
  249. CHECK (it.kind == flp::PlaylistItem::Kind::pattern && it.index == 3 && it.track == 2 && it.position == 384);
  250. CHECK (p.mixer.size() == 2 && p.mixer[0].name == "Drums" && p.mixer[1].name.empty());
  251. CHECK (p.warnings.empty());
  252. }
  253. TEST (flp_fuzz_corrupted_files_do_not_crash)
  254. {
  255. if (realFlpDir.empty())
  256. return;
  257. // some real .flp files, corrupted in various ways: the parser may reject them (flp::Error), but
  258. // must never hang, read past the buffer or produce a Song with invalid indices
  259. std::vector<std::vector<std::uint8_t>> sources;
  260. for (auto& entry : std::filesystem::recursive_directory_iterator (realFlpDir))
  261. if (entry.path().extension() == ".flp" && sources.size() < 6 && std::filesystem::file_size (entry.path()) < 3'000'000)
  262. {
  263. std::ifstream in (entry.path(), std::ios::binary);
  264. sources.emplace_back ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  265. }
  266. std::uint32_t seed = 2024;
  267. auto rnd = [&] (std::uint32_t n) { seed = seed * 1664525u + 1013904223u; return n == 0 ? 0u : (seed >> 8) % n; };
  268. int parsed = 0, rejected = 0;
  269. for (int round = 0; round < 240 && ! sources.empty(); ++round)
  270. {
  271. auto bytes = sources[(std::size_t) rnd ((std::uint32_t) sources.size())];
  272. switch (round % 4)
  273. {
  274. case 0: bytes.resize (rnd ((std::uint32_t) bytes.size())); break; // truncated
  275. 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;
  276. case 2: // absurd event size
  277. for (int k = 0; k < 5; ++k)
  278. bytes[(std::size_t) rnd ((std::uint32_t) bytes.size())] = 0xFF;
  279. break;
  280. default: // shuffled block
  281. {
  282. const auto a = rnd ((std::uint32_t) bytes.size()), b = rnd ((std::uint32_t) bytes.size());
  283. std::reverse (bytes.begin() + std::min (a, b), bytes.begin() + std::max (a, b));
  284. break;
  285. }
  286. }
  287. try
  288. {
  289. const auto project = flp::parseProject (bytes);
  290. const auto song = lynx::importFlp (project);
  291. ++parsed;
  292. for (const auto& p : song.patterns)
  293. for (const auto& n : p.notes)
  294. CHECK (n.channel >= 0 && n.channel < (int) song.channels.size());
  295. for (const auto& c : song.playlist)
  296. CHECK (c.kind != lynx::ClipKind::pattern || (c.pattern >= 0 && c.pattern < (int) song.patterns.size()));
  297. }
  298. catch (const flp::Error&)
  299. {
  300. ++rejected;
  301. }
  302. }
  303. std::printf (" fuzz: %d imported, %d rejected\n", parsed, rejected);
  304. CHECK (parsed + rejected == 240);
  305. }
  306. TEST (plugin_state_decoders_survive_garbage)
  307. {
  308. // random blobs (varied sizes, including valid headers followed by garbage)
  309. std::uint32_t seed = 77;
  310. auto rnd = [&] { seed = seed * 1664525u + 1013904223u; return seed >> 8; };
  311. const char* plugins[] = { "Fruity Parametric EQ 2", "Fruity Limiter", "Fruity Reeverb 2", "Fruity Delay 2", "Fruity Delay 3",
  312. "Fruity Compressor", "Fruity Balance", "Fruity PanOMatic", "Fruity Stereo Shaper", "Fruity Phase Inverter" };
  313. int decoded = 0;
  314. for (int round = 0; round < 3000; ++round)
  315. {
  316. std::vector<std::uint8_t> blob ((std::size_t) (rnd() % 600));
  317. for (auto& b : blob)
  318. b = (std::uint8_t) rnd();
  319. if (blob.size() >= 4 && round % 3 == 0) // versions the readers accept
  320. {
  321. const std::uint32_t versions[] = { 8, 10001, 10000, 12, 14, 6, 1 };
  322. const auto v = versions[rnd() % 7];
  323. std::memcpy (blob.data(), &v, 4);
  324. }
  325. if (auto fx = lynx::effectFromFl (plugins[rnd() % 10], blob))
  326. {
  327. ++decoded;
  328. for (auto v : fx->params)
  329. CHECK (std::isfinite (v) && v >= 0.0f && v <= 1.0f);
  330. }
  331. lynx::SynthSettings synth;
  332. if (lynx::synthFrom3xOsc (blob, synth))
  333. for (const auto& o : synth.osc)
  334. CHECK (std::isfinite (o.level) && o.level >= 0.0f && o.level <= 1.0f);
  335. float harmlessGain = 1.0f;
  336. if (lynx::synthFromHarmless (blob, 120.0, synth, harmlessGain))
  337. CHECK (std::isfinite (harmlessGain) && std::isfinite (synth.cutoff) && std::isfinite (synth.attack));
  338. if (lynx::synthFromFruitKick (blob, synth))
  339. CHECK (std::isfinite (synth.decay) && std::isfinite (synth.pitchEnv.amount));
  340. if (lynx::synthFromGms (blob, 120.0, synth, harmlessGain) || lynx::synthFromHarmor (blob, synth, harmlessGain) || lynx::synthFromOgun (blob, synth, harmlessGain)
  341. || lynx::synthFromSakura (blob, synth) || lynx::synthFromKepler (blob, synth, harmlessGain))
  342. CHECK (std::isfinite (synth.cutoff) && std::isfinite (synth.attack) && std::isfinite (harmlessGain));
  343. if (auto sound = lynx::drumSynthLiveSound (blob))
  344. CHECK (sound->size() < 256);
  345. if (auto wave = lynx::waveTravellerSample (blob))
  346. CHECK (! wave->first.empty() && wave->second >= 0 && wave->second <= 127);
  347. lynx::synthFromBooBass (blob, synth);
  348. if (lynx::synthFromPoiZone (blob, synth, harmlessGain) || lynx::synthFromBassDrum (blob, synth, harmlessGain) || lynx::synthFromToxic (blob, synth, harmlessGain)
  349. || lynx::synthFromMorphine (blob, synth, harmlessGain))
  350. CHECK (std::isfinite (synth.cutoff) && std::isfinite (harmlessGain));
  351. if (auto patch = lynx::drumpadPatchName (blob))
  352. CHECK (patch->size() <= 0x30 && std::isfinite (lynx::drumToneForName (*patch).decay));
  353. if (auto flex = lynx::flexPresetName (blob))
  354. CHECK ((! flex->first.empty() || ! flex->second.empty()) && flex->second.size() <= 1024);
  355. if (lynx::synthFromSytrus (blob, 120.0, synth, harmlessGain))
  356. CHECK (std::isfinite (synth.cutoff) && std::isfinite (synth.attack));
  357. if (lynx::synthFromDX10 (blob, synth))
  358. CHECK (std::isfinite (synth.decay) && std::isfinite (synth.release) && std::isfinite (synth.osc[1].level));
  359. if (blob.size() >= 4 && round % 5 == 0) // MiniSynth header followed by garbage
  360. {
  361. std::memcpy (blob.data(), "SSLF", 4);
  362. if (blob.size() > 220)
  363. {
  364. std::memcpy (blob.data() + 40, "DATA", 4);
  365. std::memcpy (blob.data() + 48, "0rev", 4);
  366. }
  367. }
  368. if (lynx::synthFromMiniSynth (blob, 120.0, synth))
  369. CHECK (std::isfinite (synth.cutoff) && std::isfinite (synth.decay) && std::isfinite (synth.attack));
  370. lynx::ForeignPlugin foreign;
  371. lynx::parseFlWrapper (blob, foreign);
  372. std::vector<std::uint8_t> component, controller;
  373. lynx::splitFlVst3State (blob, component, controller);
  374. }
  375. CHECK (decoded == 3000); // every known name yields an effect (default when the blob is unusable)
  376. }
  377. TEST (inflate_zlib)
  378. {
  379. // fixed Huffman with back-references
  380. const std::uint8_t fixed[] = { 0x78, 0xda, 0x4b, 0x4c, 0x4a, 0x4e, 0xc4, 0x86, 0x22, 0x00, 0x7c, 0x69, 0x09, 0x89 };
  381. const auto a = lynx::inflateZlib (fixed, sizeof (fixed));
  382. CHECK (a && std::string (a->begin(), a->end()) == "abcabcabcabcabcabcabcabcX");
  383. // stored (uncompressed) block
  384. const std::uint8_t stored[] = { 0x78, 0x01, 0x01, 0x03, 0x00, 0xfc, 0xff, 'L', 'Y', 'N', 0x00, 0x00, 0x00, 0x00 };
  385. const auto b = lynx::inflateZlib (stored, sizeof (stored));
  386. CHECK (b && std::string (b->begin(), b->end()) == "LYN");
  387. // truncated, bad header and size limit
  388. CHECK (! lynx::inflateZlib (fixed, 6));
  389. const std::uint8_t bad[] = { 0x12, 0x34, 0x00 };
  390. CHECK (! lynx::inflateZlib (bad, sizeof (bad)));
  391. CHECK (! lynx::inflateZlib (fixed, sizeof (fixed), false, 10));
  392. }
  393. TEST (fl_round15_effects_convert_known_values)
  394. {
  395. auto blob = [] (std::vector<std::int32_t> words) {
  396. std::vector<std::uint8_t> b (words.size() * 4);
  397. std::memcpy (b.data(), words.data(), b.size());
  398. return b;
  399. };
  400. // Frequency Shifter "+800 Hz": frequency 51542 in the 20 kHz range, 100% wet
  401. const auto fs = lynx::effectFromFl ("Frequency Shifter", blob ({ 4, 10000, 0, 51542, 0, 10000, 10000, 5000, 10000, 0, 5000, 0, 0 }));
  402. CHECK (fs && fs->kind == lynx::EffectKind::freqShift);
  403. if (fs)
  404. {
  405. const auto x = (fs->params[0] - 0.5) * 2.0;
  406. CHECK (std::abs (2000.0 * x * std::abs (x) - 800.0) < 10.0);
  407. CHECK (std::abs (fs->params[1] - 1.0f) < 1e-4f);
  408. }
  409. // Emphasis: input 0.0625 (= +1.5 dB) and ceiling 0.9308 (≈ −1.6 dB) -> limiter
  410. const auto em = lynx::effectFromFl ("Emphasis", blob ({ 8, 0, 0, 2, 1, 0, 0, 625, 10000, 10000, 9308, 0, 2, 7, 0 }));
  411. CHECK (em && em->kind == lynx::EffectKind::limiter && em->enabled);
  412. if (em)
  413. {
  414. CHECK (std::abs (em->params[1] * 24.0f - 1.5f) < 0.05f);
  415. CHECK (std::abs (em->params[0] * 12.0f - 12.0f + 1.6f) < 0.1f);
  416. }
  417. // Pitch Shifter +12 st, mix 100%
  418. 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 }));
  419. CHECK (ps && ps->kind == lynx::EffectKind::pitchShift && std::abs (ps->params[0] - (0.5f + 12.0f / 48.0f)) < 1e-4f);
  420. }
  421. TEST (frequency_shifter_moves_spectrum_by_hz)
  422. {
  423. auto fx = lynx::makeEffect (lynx::EffectKind::freqShift);
  424. fx->prepare (48000.0);
  425. auto slot = lynx::makeEffectSlot (lynx::EffectKind::freqShift);
  426. // +200 Hz: x·|x|·2000 = 200 -> x = sqrt(0.1)
  427. slot.params[0] = (float) (0.5 + std::sqrt (0.1) / 2.0);
  428. std::vector<float> l (48000), r (48000);
  429. for (int i = 0; i < 48000; ++i)
  430. l[(std::size_t) i] = r[(std::size_t) i] = (float) std::sin (2.0 * 3.141592653589793 * 1000.0 * i / 48000.0);
  431. for (int done = 0; done < 48000; done += 480)
  432. fx->process (l.data() + done, r.data() + done, 480, slot.params, 120.0);
  433. auto energy = [&] (double f) {
  434. const auto w = 2.0 * 3.141592653589793 * f / 48000.0, k = 2.0 * std::cos (w);
  435. double s1 = 0.0, s2 = 0.0;
  436. for (int i = 9600; i < 48000; ++i)
  437. {
  438. const auto s0 = l[(std::size_t) i] + k * s1 - s2;
  439. s2 = s1;
  440. s1 = s0;
  441. }
  442. return s1 * s1 + s2 * s2 - k * s1 * s2;
  443. };
  444. // the energy moves to 1200 Hz; little remains at 1000 and almost nothing at the image (800)
  445. CHECK (energy (1200.0) > 50.0 * energy (1000.0));
  446. CHECK (energy (1200.0) > 50.0 * energy (800.0));
  447. }
  448. TEST (pitch_shift_moves_frequency_keeps_length)
  449. {
  450. auto fx = lynx::makeEffect (lynx::EffectKind::pitchShift);
  451. fx->prepare (48000.0);
  452. auto slot = lynx::makeEffectSlot (lynx::EffectKind::pitchShift);
  453. auto crossingsAfter = [&] (float semitoneParam) {
  454. fx->reset();
  455. slot.params[0] = semitoneParam;
  456. std::vector<float> l (48000), r (48000);
  457. for (int i = 0; i < 48000; ++i)
  458. l[(std::size_t) i] = r[(std::size_t) i] = (float) std::sin (2.0 * 3.141592653589793 * 220.0 * i / 48000.0);
  459. for (int done = 0; done < 48000; done += 512)
  460. fx->process (l.data() + done, r.data() + done, std::min (512, 48000 - done), slot.params, 120.0);
  461. int crossings = 0;
  462. for (int i = 9600; i < 48000; ++i)
  463. crossings += (l[(std::size_t) i - 1] < 0.0f) != (l[(std::size_t) i] < 0.0f);
  464. for (auto v : l)
  465. CHECK (std::isfinite (v) && std::abs (v) < 1.6f);
  466. return crossings / 0.8 / 2.0; // cycles per second
  467. };
  468. CHECK (std::abs (crossingsAfter (0.5f) - 220.0) < 8.0); // 0 st
  469. CHECK (std::abs (crossingsAfter (0.5f + 12.0f / 48.0f) - 440.0) < 25.0); // +12 st
  470. CHECK (std::abs (crossingsAfter (0.5f - 12.0f / 48.0f) - 110.0) < 12.0); // −12 st
  471. }
  472. TEST (volume_gate_follows_bar_position)
  473. {
  474. auto fx = lynx::makeEffect (lynx::EffectKind::volumeGate);
  475. fx->prepare (48000.0);
  476. auto slot = lynx::makeEffectSlot (lynx::EffectKind::volumeGate);
  477. for (int i = 0; i < 32; ++i)
  478. slot.params[(std::size_t) i] = i < 16 ? 1.0f : 0.0f; // first two beats open, two closed
  479. slot.params[33] = slot.params[34] = 0.0f; // no smoothing
  480. // 120 BPM: one beat = 0.5 s = 24000 samples; the 4-beat bar starts at tick 0
  481. std::vector<float> l (96000, 1.0f), r (96000, 1.0f);
  482. fx->setSongPosition (0.0);
  483. for (int done = 0; done < 96000; done += 512)
  484. fx->process (l.data() + done, r.data() + done, std::min (512, 96000 - done), slot.params, 120.0);
  485. CHECK (l[10000] > 0.99f && l[40000] > 0.99f); // beats 1 and 2
  486. CHECK (l[60000] < 0.01f && l[90000] < 0.01f); // beats 3 and 4
  487. // starting mid-bar (beat 3): already closed
  488. std::vector<float> l2 (4800, 1.0f), r2 (4800, 1.0f);
  489. fx->reset();
  490. fx->setSongPosition (2.0 * lynx::ppq);
  491. fx->process (l2.data(), r2.data(), 4800, slot.params, 120.0);
  492. CHECK (l2[4000] < 0.01f);
  493. // mix 0: transparent
  494. slot.params[32] = 0.0f;
  495. std::vector<float> l3 (4800, 1.0f), r3 (4800, 1.0f);
  496. fx->setSongPosition (2.0 * lynx::ppq);
  497. fx->process (l3.data(), r3.data(), 4800, slot.params, 120.0);
  498. CHECK (l3[4000] > 0.99f);
  499. }
  500. TEST (patcher_branch_heads_follow_rea)
  501. {
  502. auto words = [] (std::vector<std::int32_t> v) {
  503. std::vector<std::uint8_t> b (v.size() * 4);
  504. std::memcpy (b.data(), v.data(), b.size());
  505. return b;
  506. };
  507. // Frequency Splitter, 2 bands, destinations 1/2/3, slope combo 3 (24 dB/oct), high send −6 dB
  508. std::vector<std::int32_t> fs (18, 0);
  509. fs[0] = 4;
  510. fs[1] = 32768;
  511. fs[3] = 3;
  512. fs[6] = 0;
  513. fs[11] = -600;
  514. fs[15] = 1;
  515. fs[16] = 2;
  516. fs[17] = 3;
  517. const auto split = words (fs);
  518. const auto low = lynx::patcherBranchHead ("Frequency Splitter", split, 1);
  519. CHECK (low.valid && low.slot && low.note.empty());
  520. if (low.slot)
  521. {
  522. // low band = just the Crossover low-pass, combo 3 (24 dB/oct)
  523. CHECK (low.slot->kind == lynx::EffectKind::crossover && low.slot->params[0] == 0.0f && low.slot->params[3] == 1.0f);
  524. CHECK (std::lround (low.slot->params[5] * 7.0f) == 3);
  525. }
  526. const auto mid = lynx::patcherBranchHead ("Frequency Splitter", split, 2);
  527. CHECK (mid.valid && mid.gain == 0.0f); // with 2 bands the mid is silent
  528. const auto high = lynx::patcherBranchHead ("Frequency Splitter", split, 3);
  529. CHECK (high.valid && std::abs (high.gain - std::pow (10.0f, -6.0f / 20.0f)) < 1e-4f);
  530. CHECK (! lynx::patcherBranchHead ("Frequency Splitter", split, 7).valid);
  531. // Stereo Shaper with identity matrix: the difference (destination 4) is zero
  532. const auto shaper = words ({ 3, 0, 12800, 12800, 0, 0, 0, 4, 0 });
  533. const auto diff = lynx::patcherBranchHead ("Fruity Stereo Shaper", shaper, 4);
  534. 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);
  535. CHECK (! lynx::patcherBranchHead ("Fruity Stereo Shaper", shaper, 2).valid);
  536. }
  537. TEST (parallel_container_sums_branches)
  538. {
  539. // two branches: dry with gain 0.5 and a utility that flips phase (matrix −1) with gain 0.5 -> silence
  540. auto slot = lynx::makeEffectSlot (lynx::EffectKind::parallel);
  541. lynx::EffectBranch dry;
  542. dry.gain = 0.5f;
  543. lynx::EffectBranch inverted;
  544. inverted.gain = 0.5f;
  545. auto flip = lynx::makeEffectSlot (lynx::EffectKind::utility);
  546. flip.params[2] = flip.params[5] = 0.25f; // (−1 + 2)/4
  547. inverted.chain.push_back (flip);
  548. slot.branches = { dry, inverted };
  549. auto fx = lynx::makeParallelEffect (slot);
  550. fx->prepare (48000.0);
  551. std::vector<float> l (9000, 0.8f), r (9000, -0.4f);
  552. fx->process (l.data(), r.data(), 9000, slot.params, 120.0);
  553. CHECK (std::abs (l[100]) < 1e-5f && std::abs (r[8999]) < 1e-5f);
  554. // only the dry branch with gain 2: doubles
  555. slot.branches = { lynx::EffectBranch { {}, 2.0f } };
  556. auto doubler = lynx::makeParallelEffect (slot);
  557. doubler->prepare (48000.0);
  558. std::fill (l.begin(), l.end(), 0.25f);
  559. doubler->process (l.data(), r.data(), 9000, slot.params, 120.0);
  560. CHECK (std::abs (l[5000] - 0.5f) < 1e-6f);
  561. }
  562. TEST (fl_controller_constant_outputs)
  563. {
  564. std::vector<std::int32_t> xy { 2, 32768, 0, 65536, 0, 16384, 0, 65536, 0, 1024, 256 };
  565. std::vector<std::uint8_t> blob (xy.size() * 4 + 8, 0);
  566. std::memcpy (blob.data(), xy.data(), xy.size() * 4);
  567. CHECK (std::abs (lynx::controllerConstantOutput ("Fruity X-Y Controller", blob, 0).value_or (-1.0f) - 0.5f) < 1e-4f);
  568. CHECK (std::abs (lynx::controllerConstantOutput ("Fruity X-Y Controller", blob, 1).value_or (-1.0f) - 0.25f) < 1e-4f);
  569. // Control Surface: version + group { 0x836: value 0.75, -, output 2 }
  570. std::vector<std::uint8_t> cs (4, 0);
  571. cs[0] = 1;
  572. auto chunk = [] (std::vector<std::uint8_t>& out, std::uint32_t id, const std::vector<std::uint8_t>& body) {
  573. const auto size = (std::uint64_t) body.size();
  574. out.insert (out.end(), reinterpret_cast<const std::uint8_t*> (&id), reinterpret_cast<const std::uint8_t*> (&id) + 4);
  575. out.insert (out.end(), reinterpret_cast<const std::uint8_t*> (&size), reinterpret_cast<const std::uint8_t*> (&size) + 8);
  576. out.insert (out.end(), body.begin(), body.end());
  577. };
  578. std::vector<std::uint8_t> value (12, 0);
  579. const float v = 0.75f;
  580. const std::int32_t out = 2;
  581. std::memcpy (value.data(), &v, 4);
  582. std::memcpy (value.data() + 8, &out, 4);
  583. std::vector<std::uint8_t> group;
  584. chunk (group, 0x836, value);
  585. chunk (cs, 0, group);
  586. CHECK (std::abs (lynx::controllerConstantOutput ("Control Surface", cs, 2).value_or (-1.0f) - 0.75f) < 1e-6f);
  587. CHECK (! lynx::controllerConstantOutput ("Control Surface", cs, 0).has_value());
  588. }
  589. TEST (flp_midi_out_notes_reach_wrapper_on_same_port)
  590. {
  591. auto record = [] (std::vector<std::uint8_t>& out, std::uint32_t id, std::vector<std::uint8_t> body) {
  592. const auto size = (std::uint64_t) body.size();
  593. out.insert (out.end(), reinterpret_cast<const std::uint8_t*> (&id), reinterpret_cast<const std::uint8_t*> (&id) + 4);
  594. out.insert (out.end(), reinterpret_cast<const std::uint8_t*> (&size), reinterpret_cast<const std::uint8_t*> (&size) + 8);
  595. out.insert (out.end(), body.begin(), body.end());
  596. };
  597. auto i32s = [] (std::vector<std::int32_t> v) {
  598. std::vector<std::uint8_t> b (v.size() * 4);
  599. std::memcpy (b.data(), v.data(), b.size());
  600. return b;
  601. };
  602. flp::Project p;
  603. flp::Channel midiOut;
  604. midiOut.index = 0;
  605. midiOut.type = flp::ChannelType::native;
  606. midiOut.pluginName = "MIDI Out";
  607. midiOut.pluginState = i32s ({ 7, 0, -1, -1, -1, 0, 3, 0 }); // channel 1, port 3 (@24)
  608. flp::Channel wrapper;
  609. wrapper.index = 1;
  610. wrapper.type = flp::ChannelType::native;
  611. wrapper.pluginName = "Fruity Wrapper";
  612. wrapper.pluginState = i32s ({ 9 });
  613. record (wrapper.pluginState, 0x32, i32s ({ 7 })); // VST3
  614. record (wrapper.pluginState, 0x01, i32s ({ 3, -1, 0, 0, 0 })); // input port 3
  615. p.channels = { midiOut, wrapper };
  616. flp::Pattern pattern;
  617. pattern.index = 1;
  618. flp::Note note;
  619. note.channel = 0;
  620. note.key = 64;
  621. note.length = 96;
  622. pattern.notes.push_back (note);
  623. p.patterns.push_back (pattern);
  624. const auto song = lynx::importFlp (p);
  625. CHECK (song.channels.size() == 2 && song.channels[0].muted);
  626. CHECK (song.channels[1].plugin.foreign.midiInPort == 3);
  627. int toWrapper = 0;
  628. for (const auto& pat : song.patterns)
  629. for (const auto& n : pat.notes)
  630. toWrapper += n.channel == 1 && n.key == 64;
  631. CHECK (toWrapper == 1);
  632. }
  633. TEST (flp_effect_automation_follows_slots_and_params)
  634. {
  635. // track 1: slot 0 with an effect that has no equivalent (dropped), slot 2 with Parametric EQ 2
  636. flp::Project p;
  637. flp::MixerInsert insert;
  638. insert.index = 1;
  639. insert.slots.push_back ({ 0, "Some Unknown FX", {} });
  640. insert.slots.push_back ({ 2, "Fruity Parametric EQ 2", {} });
  641. p.mixer.push_back (insert);
  642. auto clip = [&] (int index, std::uint32_t target) {
  643. flp::Channel c;
  644. c.index = index;
  645. c.type = flp::ChannelType::automationClip;
  646. c.automation = { { 0.0, 0.0 }, { 96.0, 1.0 } };
  647. p.channels.push_back (c);
  648. p.automationLinks.push_back ({ index, { target } });
  649. };
  650. 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; };
  651. clip (0, mixer (1, 2, 0x8000 + 7)); // EQ band 1 frequency
  652. clip (1, mixer (1, 2, 0x1F01)); // EQ slot mix
  653. clip (2, mixer (1, 0, 0x8000)); // parameter of the dropped effect
  654. clip (3, mixer (1, 2, 0x8000 + 21)); // band type: no equivalent
  655. const auto song = lynx::importFlp (p);
  656. CHECK (song.automations.size() == 4);
  657. CHECK (song.mixer[1].effects.size() == 1 && song.mixer[1].effects[0].kind == lynx::EffectKind::parametricEq);
  658. const auto& freq = song.automations[0];
  659. CHECK (freq.target.kind == lynx::AutomationTargetKind::effectParam && freq.target.index == 1 && freq.target.slot == 0);
  660. CHECK (freq.target.param == lynx::peq::param (0, 1));
  661. // FL's 0..1 (20 Hz..20 kHz) becomes our frequency scale
  662. CHECK (std::abs (freq.points.front().value - lynx::peq::hzValue (20.0)) < 1e-4f);
  663. CHECK (std::abs (freq.points.back().value - lynx::peq::hzValue (20000.0)) < 1e-4f);
  664. CHECK (song.automations[1].target.kind == lynx::AutomationTargetKind::effectMix && song.automations[1].target.slot == 0);
  665. CHECK (song.automations[2].target.kind == lynx::AutomationTargetKind::none);
  666. CHECK (song.automations[3].target.kind == lynx::AutomationTargetKind::none);
  667. // the automated mix is read/written through the target
  668. auto copy = song;
  669. CHECK (copy.setTargetValue (song.automations[1].target, 0.25f) && std::abs (copy.mixer[1].effects[0].mix - 0.25f) < 1e-6f);
  670. CHECK (std::abs (copy.targetValue (song.automations[1].target) - 0.25f) < 1e-6f);
  671. }
  672. TEST (flp_real_files)
  673. {
  674. if (realFlpDir.empty())
  675. {
  676. std::printf (" (skipped: pass a folder with .flp files as argument)\n");
  677. return;
  678. }
  679. int files = 0, withNotes = 0, withPlaylist = 0, automations = 0, automationsWithTarget = 0, sends = 0;
  680. int threeOsc = 0, threeOscDecoded = 0, wrapped = 0, wrappedParsed = 0, markers = 0, signatures = 0, trackEqs = 0;
  681. int harmless = 0, harmlessDecoded = 0, harmlessParsed = 0, harmlessKind = 0, sytrus = 0, sytrusDecoded = 0, sytrusEngine = 0, sytrusRendered = 0,
  682. sytrusSounding = 0;
  683. std::map<std::string, std::pair<int, int>> generators; // GMS/Ogun/Autogun/Sakura/DrumSynth: channels, decoded
  684. int ogunTrumpet = 0; // Ogun channels whose spectrum matches the REA "Trumpet" reference
  685. int peqSlots = 0, peqShaped = 0, reverbs = 0, reverbsDryless = 0, reverbsLowCut = 0;
  686. int dwChannels = 0, dwZones = 0, fpcKits = 0, padChannels = 0, padNotes = 0;
  687. int harmlessCompWanted = 0, harmlessCompLoaded = 0; // Harmless rack compressors / presets read from the installation
  688. // import with the installation's samples (realFlpDir is ...\Data): for DirectWave/FPC
  689. lynx::FlpImportOptions withFiles;
  690. const auto flRoot = std::filesystem::path (realFlpDir).parent_path().string();
  691. withFiles.roots = { flRoot, realFlpDir, "" };
  692. withFiles.fileExists = [] (const std::string& path) {
  693. auto local = path;
  694. std::replace (local.begin(), local.end(), '\\', '/');
  695. return std::filesystem::exists (local);
  696. };
  697. withFiles.readFile = [] (const std::string& path) {
  698. auto local = path;
  699. std::replace (local.begin(), local.end(), '\\', '/');
  700. std::ifstream in (local, std::ios::binary);
  701. return std::vector<std::uint8_t> ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  702. };
  703. int embeddedSaved = 0;
  704. withFiles.saveEmbedded = [&embeddedSaved] (const std::vector<std::uint8_t>& wav, const std::string&) {
  705. ++embeddedSaved;
  706. return wav.size() > 44 ? std::string ("embutido.wav") : std::string();
  707. };
  708. int slicedChannels = 0, flKeysChannels = 0;
  709. for (auto& entry : std::filesystem::recursive_directory_iterator (realFlpDir))
  710. {
  711. if (entry.path().extension() != ".flp")
  712. continue;
  713. std::ifstream in (entry.path(), std::ios::binary);
  714. std::vector<std::uint8_t> bytes ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  715. ++files;
  716. try
  717. {
  718. const auto p = flp::parseProject (bytes);
  719. CHECK (! p.version.empty());
  720. CHECK (p.tempo > 10.0 && p.tempo < 1000.0);
  721. const auto song = lynx::importFlp (p);
  722. CHECK (! song.patterns.empty());
  723. {
  724. const auto full = lynx::importFlp (p, withFiles);
  725. bool hasFpc = false;
  726. for (const auto& c : p.channels)
  727. hasFpc = hasFpc || c.pluginName == "FPC";
  728. for (const auto& c : full.channels)
  729. {
  730. if (c.instrument == lynx::InstrumentKind::harmless && c.modelParams.size() >= (std::size_t) lynx::harmlessParamCount
  731. && c.modelParams[(std::size_t) lynx::harmlessComboIndex + 3] > 0.5f)
  732. {
  733. ++harmlessCompWanted;
  734. harmlessCompLoaded += c.modelParams.size() > (std::size_t) lynx::harmlessCompIndex + 1000 ? 1 : 0;
  735. }
  736. flKeysChannels += c.zones.size() == 30 && c.zones.front().path.find ("CHANGPIANO") != std::string::npos ? 1 : 0;
  737. if (c.sampler.slices.size() >= 4)
  738. {
  739. ++slicedChannels;
  740. CHECK (std::is_sorted (c.sampler.slices.begin(), c.sampler.slices.end()));
  741. CHECK (c.sampler.slices.back() < 1.0f);
  742. }
  743. if (! c.zones.empty() && c.name.find (" - ") == std::string::npos)
  744. {
  745. ++dwChannels;
  746. dwZones += (int) c.zones.size();
  747. }
  748. padChannels += c.name.find (" - ") != std::string::npos && c.instrument == lynx::InstrumentKind::sampler ? 1 : 0;
  749. }
  750. fpcKits += hasFpc;
  751. for (const auto& pat : full.patterns)
  752. for (const auto& n : pat.notes)
  753. {
  754. CHECK (n.channel >= 0 && n.channel < (int) full.channels.size());
  755. padNotes += full.channels[(std::size_t) n.channel].name.find (" - ") != std::string::npos ? 1 : 0;
  756. }
  757. }
  758. const auto peqDefaults = lynx::makeEffectSlot (lynx::EffectKind::parametricEq).params;
  759. for (const auto& t : song.mixer)
  760. for (const auto& fx : t.effects)
  761. {
  762. if (fx.kind == lynx::EffectKind::parametricEq)
  763. {
  764. ++peqSlots;
  765. peqShaped += fx.params != peqDefaults;
  766. for (double hz : { 50.0, 1000.0, 10000.0 })
  767. CHECK (std::isfinite (lynx::peq::responseDb (fx.params, 48000.0, hz)));
  768. }
  769. if (fx.kind == lynx::EffectKind::reverb)
  770. {
  771. ++reverbs;
  772. reverbsDryless += fx.params[4] < 0.01f;
  773. reverbsLowCut += fx.params[5] > 0.0f;
  774. }
  775. }
  776. for (const auto& t : song.mixer)
  777. if (t.eq.active())
  778. {
  779. ++trackEqs;
  780. for (std::size_t b = 0; b < 3; ++b)
  781. CHECK (t.eq.hz[b] >= 10.0f && t.eq.hz[b] <= 16000.0f && std::abs (t.eq.gainDb[b]) <= 18.0f);
  782. }
  783. for (const auto& a : song.arrangements)
  784. for (const auto& m : a.markers)
  785. {
  786. ++markers;
  787. signatures += m.isSignature();
  788. CHECK (m.tick >= 0);
  789. }
  790. // Fruity Wrapper (channels and mixer slots): every blob in the demos is read
  791. auto countWrapper = [&] (const std::string& plugin, const std::vector<std::uint8_t>& state) {
  792. if (plugin != "Fruity Wrapper")
  793. return;
  794. ++wrapped;
  795. lynx::ForeignPlugin f;
  796. wrappedParsed += lynx::parseFlWrapper (state, f) && f.format != lynx::ForeignPlugin::Format::none && ! f.name.empty();
  797. };
  798. for (const auto& c : p.channels)
  799. countWrapper (c.pluginName, c.pluginState);
  800. for (const auto& insert : p.mixer)
  801. for (const auto& slot : insert.slots)
  802. countWrapper (slot.plugin, slot.state);
  803. // Harmless: every state in the demos becomes a synth, with finite values
  804. for (const auto& c : p.channels)
  805. if (c.pluginName == "Harmless")
  806. {
  807. ++harmless;
  808. lynx::SynthSettings hs;
  809. float g = 1.0f;
  810. if (lynx::synthFromHarmless (c.pluginState, 128.0, hs, g))
  811. {
  812. ++harmlessDecoded;
  813. CHECK (std::isfinite (g) && hs.cutoff >= 20.0f && hs.cutoff <= 20000.0f && std::isfinite (hs.decay) && std::isfinite (hs.release));
  814. }
  815. if (const auto hp = lynx::harmlessParams (c.pluginState))
  816. harmlessParsed += (int) hp->size() == lynx::harmlessParamCount ? 1 : 0;
  817. }
  818. for (const auto& c : song.channels)
  819. harmlessKind += c.instrument == lynx::InstrumentKind::harmless ? 1 : 0;
  820. // Sytrus: every state in the demos (zlib + 10 units) decodes, with finite values
  821. for (const auto& c : p.channels)
  822. if (c.pluginName == "Sytrus")
  823. {
  824. ++sytrus;
  825. lynx::SynthSettings ss;
  826. float g = 1.0f;
  827. // the Sytrus engine (REA_rodada31) reads every demo state; the first 24 play a short note (render settings)
  828. if (lynx::sytrus::stateUsable (c.pluginState))
  829. {
  830. ++sytrusEngine;
  831. if (sytrusRendered < 24)
  832. {
  833. ++sytrusRendered;
  834. lynx::sytrus::Engine e;
  835. e.prepare (44100.0, true, 512);
  836. e.setPatch (lynx::sytrus::parsePatch (c.pluginState));
  837. lynx::sytrus::NoteParams note;
  838. e.noteOn (note);
  839. std::vector<float> l (8192), r (8192);
  840. e.render (l.data(), r.data(), 8192, 0.551f, 0.0f);
  841. bool finite = true;
  842. double energy = 0.0;
  843. for (std::size_t k = 0; k < l.size(); ++k)
  844. finite = finite && std::isfinite (l[k]) && std::isfinite (r[k]), energy += (double) l[k] * l[k];
  845. CHECK (finite);
  846. sytrusSounding += energy > 1e-6;
  847. }
  848. }
  849. if (lynx::synthFromSytrus (c.pluginState, 128.0, ss, g))
  850. {
  851. ++sytrusDecoded;
  852. CHECK (std::isfinite (g) && ss.cutoff >= 20.0f && ss.cutoff <= 20000.0f && std::isfinite (ss.attack) && std::isfinite (ss.decay)
  853. && std::isfinite (ss.release) && ss.sustain >= 0.0f && ss.sustain <= 1.0f && std::isfinite (ss.filterEnv.amount));
  854. for (const auto& o : ss.osc)
  855. CHECK (o.level >= 0.0f && o.level <= 1.0f && o.octave >= -3 && o.octave <= 3);
  856. }
  857. }
  858. // round 12 generators
  859. for (const auto& c : p.channels)
  860. {
  861. lynx::SynthSettings gs;
  862. float g = 1.0f;
  863. int decoded = -1;
  864. if (c.pluginName == "Harmor")
  865. {
  866. decoded = lynx::synthFromHarmor (c.pluginState, gs, g);
  867. if (decoded)
  868. {
  869. // REA_rodada25 §4: most resonant settings stay below Q ≈ 3, a few saturate
  870. CHECK (gs.resonance >= 0.0f && gs.resonance <= 1.0f);
  871. static int resonant = 0, strong = 0, total = 0;
  872. resonant += gs.resonance > 0.0f;
  873. strong += gs.resonance > 0.9f;
  874. if (++total % 50 == 0)
  875. std::printf (" Harmor resonance: %d with a peak, %d with Q > ~5 (of %d)\n", resonant, strong, total);
  876. }
  877. static int saw = 0, square = 0, other = 0, total = 0;
  878. if (decoded && std::any_of (gs.osc.begin(), gs.osc.end(), [] (const lynx::SynthOscillator& o) { return o.wave == lynx::Waveform::spectral; }))
  879. {
  880. auto isSaw = true, isSquare = true;
  881. for (int n = 1; n <= 16; ++n)
  882. {
  883. isSaw = isSaw && std::abs (gs.spectrum[(std::size_t) n - 1] - 1.0f / n) < 1e-3f;
  884. isSquare = isSquare && std::abs (gs.spectrum[(std::size_t) n - 1] - (n % 2 == 1 ? 1.1535f / n : 0.0f)) < 2e-3f;
  885. }
  886. ++(isSaw ? saw : isSquare ? square : other);
  887. if (++total % 20 == 0 || total == 100)
  888. std::printf (" Harmor spectrum: %d saw, %d square, %d other (of %d)\n", saw, square, other, total);
  889. }
  890. }
  891. else if (c.pluginName == "GMS")
  892. decoded = lynx::synthFromGms (c.pluginState, 128.0, gs, g);
  893. else if (c.pluginName == "Ogun" || c.pluginName == "Autogun")
  894. {
  895. decoded = lynx::synthFromOgun (c.pluginState, gs, g);
  896. // REA_rodada24 §1.9: the "Trumpet" preset (richness 7, no seeds) has partials 0.9087, 0.8610,
  897. // 0.8151… at the fixed seed-3 phases 0.919, 0.380, 0.130
  898. if (decoded && gs.osc[0].wave == lynx::Waveform::spectral)
  899. {
  900. CHECK (std::all_of (gs.spectrum.begin(), gs.spectrum.end(), [] (float a) { return std::isfinite (a) && a >= 0.0f; }));
  901. static constexpr float trumpet[3] { 0.9087f, 0.8610f, 0.8151f }, phases[3] { 0.919f, 0.380f, 0.130f };
  902. auto match = true;
  903. for (std::size_t k = 0; k < 3; ++k)
  904. match = match && std::abs (gs.spectrum[k] * 2.0f / 3.14159265f - trumpet[k]) < 1e-3f && std::abs (gs.spectrumPhase[k] - phases[k]) < 1e-3f;
  905. ogunTrumpet += match ? 1 : 0;
  906. }
  907. }
  908. else if (c.pluginName == "Sakura")
  909. decoded = lynx::synthFromSakura (c.pluginState, gs);
  910. else if (c.pluginName == "Kepler")
  911. decoded = lynx::synthFromKepler (c.pluginState, gs, g);
  912. else if (c.pluginName == "Wave Traveller")
  913. decoded = lynx::waveTravellerSample (c.pluginState).has_value() ? 2 : 0;
  914. else if (c.pluginName == "PoiZone")
  915. decoded = lynx::synthFromPoiZone (c.pluginState, gs, g);
  916. else if (c.pluginName == "BassDrum")
  917. decoded = lynx::synthFromBassDrum (c.pluginState, gs, g);
  918. else if (c.pluginName == "Toxic Biohazard")
  919. decoded = lynx::synthFromToxic (c.pluginState, gs, g);
  920. else if (c.pluginName == "Morphine")
  921. decoded = lynx::synthFromMorphine (c.pluginState, gs, g);
  922. else if (c.pluginName == "BooBass")
  923. decoded = lynx::synthFromBooBass (c.pluginState, gs);
  924. else if (c.pluginName == "Drumpad" || c.pluginName == "DrumPad")
  925. decoded = lynx::drumpadPatchName (c.pluginState).has_value() ? 2 : 0;
  926. else if (c.pluginName == "Fruity Envelope Controller" && c.pluginState.size() >= 4 && c.pluginState[2] >= 6) // v >= 6
  927. decoded = lynx::parseEnvelopeController (c.pluginState).has_value() ? 2 : 0;
  928. else if (c.pluginName == "FLEX")
  929. decoded = lynx::flexPresetName (c.pluginState).has_value() ? 2 : 0;
  930. else if (c.pluginName == "Fruity DrumSynth Live")
  931. decoded = lynx::drumSynthLiveParams (c.pluginState).has_value() ? 2 : 0;
  932. if (decoded < 0)
  933. continue;
  934. auto& counter = generators[c.pluginName];
  935. ++counter.first;
  936. counter.second += decoded != 0;
  937. if (decoded == 1 && c.pluginName != "Fruity DrumSynth Live")
  938. {
  939. CHECK (std::isfinite (g) && g >= 0.0f && gs.cutoff >= 20.0f && gs.cutoff <= 20000.0f && gs.sustain >= 0.0f && gs.sustain <= 1.0f);
  940. 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));
  941. for (const auto& o : gs.osc)
  942. CHECK (o.level >= 0.0f && o.level <= 4.0f && std::isfinite (o.detune) && std::isfinite (o.pan));
  943. }
  944. }
  945. // 3x Osc: every state in the demos decodes, with levels summing to at most 1
  946. for (const auto& c : p.channels)
  947. if (c.pluginName == "3x Osc")
  948. {
  949. ++threeOsc;
  950. lynx::SynthSettings s;
  951. if (lynx::synthFrom3xOsc (c.pluginState, s))
  952. {
  953. ++threeOscDecoded;
  954. // with AM, osc 3 is the modulation depth and is left out of the sum
  955. const auto sum = s.osc[0].level + s.osc[1].level + (s.am ? 0.0f : s.osc[2].level);
  956. CHECK (sum <= 1.001f && s.osc[2].level <= 1.0f);
  957. for (const auto& o : s.osc)
  958. CHECK (o.octave >= -2 && o.octave <= 2 && std::abs (o.semitones) <= 11 && std::abs (o.pan) <= 1.0f);
  959. }
  960. }
  961. for (auto& pat : p.patterns)
  962. if (! pat.notes.empty())
  963. {
  964. ++withNotes;
  965. break;
  966. }
  967. for (auto& a : p.arrangements)
  968. for (auto& item : a.items)
  969. CHECK (item.track >= 0 && item.track < 500);
  970. for (auto& clip : song.playlist)
  971. {
  972. CHECK (clip.pattern >= 0 && clip.pattern < (int) song.patterns.size());
  973. CHECK (clip.length > 0 && clip.offset >= 0);
  974. if (clip.kind == lynx::ClipKind::automation)
  975. CHECK (clip.automation >= 0 && clip.automation < (int) song.automations.size());
  976. }
  977. for (auto& a : song.automations)
  978. {
  979. ++automations;
  980. automationsWithTarget += a.target.kind != lynx::AutomationTargetKind::none;
  981. CHECK (a.isLive() || ! a.points.empty());
  982. for (std::size_t i = 1; i < a.points.size(); ++i)
  983. CHECK (a.points[i].tick >= a.points[i - 1].tick);
  984. }
  985. // imported routing has no cycles and valid destinations
  986. CHECK (song.mixerOrder().size() + 1 == song.mixer.size());
  987. for (auto& t : song.mixer)
  988. for (auto& s : t.sends)
  989. {
  990. ++sends;
  991. CHECK (s.target > 0 && s.target < (int) song.mixer.size());
  992. }
  993. if (! song.playlist.empty())
  994. ++withPlaylist;
  995. }
  996. catch (const flp::Error& e)
  997. {
  998. ++failures;
  999. std::printf (" FAILED %s: %s\n", entry.path().string().c_str(), e.what());
  1000. }
  1001. }
  1002. CHECK (threeOscDecoded == threeOsc);
  1003. std::printf (" Harmless: %d channels, %d decoded\n", harmless, harmlessDecoded);
  1004. std::printf (" Sytrus: %d channels, %d decoded, %d by the engine (%d of %d rendered sound)\n", sytrus, sytrusDecoded, sytrusEngine,
  1005. sytrusSounding, sytrusRendered);
  1006. CHECK (sytrusEngine == sytrus);
  1007. CHECK (sytrusSounding >= sytrusRendered * 3 / 4);
  1008. for (const auto& [name, counter] : generators)
  1009. {
  1010. std::printf (" %s: %d channels, %d decoded\n", name.c_str(), counter.first, counter.second);
  1011. CHECK (counter.second == counter.first);
  1012. }
  1013. std::printf (" Ogun spectra matching the Trumpet reference: %d\n", ogunTrumpet);
  1014. CHECK (ogunTrumpet >= 1);
  1015. // demo Gross Beat: the volume slot becomes the gate (those using an envelope slot get steps < 1)
  1016. {
  1017. int vocodexes = 0, vocodexSides = 0;
  1018. int lovePhilterLinks[4] {}; // live links: cutoff, resonance; inside containers: cutoff, resonance
  1019. int embeddedZones = 0, lovePhilters = 0, lovePhiltersRead = 0, lovePhiltersConverted = 0, gates = 0, shaped = 0, effectors = 0, patchers = 0, serial = 0, parallel = 0, generatorPatchers = 0;
  1020. for (const auto& entry : std::filesystem::recursive_directory_iterator (std::filesystem::path (realFlpDir) / "Demo projects"))
  1021. if (entry.path().extension() == ".flp")
  1022. {
  1023. std::ifstream in (entry.path(), std::ios::binary);
  1024. const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1025. try
  1026. {
  1027. const auto project = flp::parseProject (file);
  1028. for (const auto& insert : project.mixer)
  1029. for (const auto& slot : insert.slots)
  1030. if (slot.plugin == "Gross Beat")
  1031. {
  1032. const auto fx = lynx::effectFromFl (slot.plugin, slot.state);
  1033. CHECK (fx && fx->kind == lynx::EffectKind::volumeGate);
  1034. ++gates;
  1035. if (fx && std::any_of (fx->params.begin(), fx->params.begin() + 32, [] (float v) { return v < 0.99f; }))
  1036. ++shaped;
  1037. }
  1038. else if (slot.plugin == "Fruity Love Philter")
  1039. {
  1040. ++lovePhilters;
  1041. lovePhiltersRead += lynx::parseLovePhilter (slot.state).has_value();
  1042. if (const auto conv = lynx::lovePhilterEffects (slot.state))
  1043. {
  1044. ++lovePhiltersConverted;
  1045. CHECK (! conv->slots.empty());
  1046. for (const auto& fx : conv->slots)
  1047. for (auto v : fx.params)
  1048. CHECK (std::isfinite (v) && v >= 0.0f && v <= 1.0f);
  1049. for (const auto& fx : conv->slots)
  1050. for (const auto& link : fx.links)
  1051. {
  1052. const auto& chain = fx.branches[(std::size_t) link.branch].chain;
  1053. CHECK (link.source < (int) chain.size() && chain[(std::size_t) link.target].kind == lynx::EffectKind::parametricEq);
  1054. lovePhilterLinks[2 + (link.param == lynx::peq::param (0, 3) ? 1 : 0)]++;
  1055. }
  1056. for (const auto& link : conv->links)
  1057. {
  1058. lovePhilterLinks[link.param == lynx::peq::param (0, 3) ? 1 : 0]++;
  1059. CHECK (link.curve.size() == 33);
  1060. for (auto v : link.curve)
  1061. CHECK (std::isfinite (v) && v >= 0.0f && v <= 1.0f);
  1062. }
  1063. }
  1064. }
  1065. else if (slot.plugin == "Vocodex")
  1066. {
  1067. const auto v = lynx::vocodexEffect (slot.state);
  1068. CHECK (v.has_value());
  1069. vocodexes += v.has_value();
  1070. vocodexSides += v && (v->modIn > 0 || v->carIn > 0);
  1071. }
  1072. else if (slot.plugin == "Effector")
  1073. effectors += lynx::effectFromFl (slot.plugin, slot.state).has_value();
  1074. else if (slot.plugin == "Patcher")
  1075. {
  1076. const auto graph = lynx::parsePatcher (slot.state);
  1077. CHECK (graph.has_value());
  1078. ++patchers;
  1079. if (graph && ! graph->serialChain.empty())
  1080. ++serial;
  1081. if (graph && graph->serialChain.empty() && graph->audio)
  1082. ++parallel;
  1083. }
  1084. for (const auto& c : project.channels)
  1085. if (c.pluginName == "DirectWave")
  1086. if (const auto program = lynx::directWaveProgram (c.pluginState))
  1087. for (const auto& wav : program->embeddedWav)
  1088. if (! wav.empty())
  1089. {
  1090. ++embeddedZones;
  1091. CHECK (wav.size() > 44 && std::memcmp (wav.data(), "RIFF", 4) == 0);
  1092. }
  1093. for (const auto& c : project.channels)
  1094. if (c.pluginName == "Patcher")
  1095. {
  1096. const auto graph = lynx::parsePatcher (c.pluginState);
  1097. CHECK (graph.has_value());
  1098. generatorPatchers += graph && graph->mainGenerator >= 0;
  1099. }
  1100. }
  1101. catch (const flp::Error&) {}
  1102. }
  1103. std::printf (" Gross Beat: %d slots, %d with gate; Effector: %d converted; Love Philter: %d, %d read\n", gates, shaped, effectors,
  1104. lovePhilters, lovePhiltersRead);
  1105. CHECK (lovePhiltersRead == lovePhilters && lovePhiltersConverted == lovePhilters);
  1106. std::printf (" Vocodex: %d converted, %d with side inputs\n", vocodexes, vocodexSides);
  1107. CHECK (vocodexes >= 9);
  1108. std::printf (" Love Philter live links: %d cutoff, %d resonance; in multi-unit containers: %d cutoff, %d resonance\n",
  1109. lovePhilterLinks[0], lovePhilterLinks[1], lovePhilterLinks[2], lovePhilterLinks[3]);
  1110. CHECK (lovePhilterLinks[2] + lovePhilterLinks[3] > 0);
  1111. std::printf (" DirectWave: %d zones with embedded audio\n", embeddedZones);
  1112. CHECK (embeddedZones == 12);
  1113. std::printf (" Patcher: %d in the mixer (%d serial, %d reduced to serial/parallel), %d as instrument with generator\n", patchers, serial,
  1114. parallel, generatorPatchers);
  1115. CHECK (gates == 0 || shaped > 0);
  1116. }
  1117. // Envelope Controller "Basic Sidechain" (Future House): drops on the note and returns to ~1 within ~1/3 s
  1118. {
  1119. const auto path = std::filesystem::path (realFlpDir) / "Demo projects" / "Demo songs" / "Asher Postman - Future House.flp";
  1120. if (std::filesystem::exists (path))
  1121. {
  1122. std::ifstream in (path, std::ios::binary);
  1123. const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1124. const auto song = lynx::importFlp (flp::parseProject (file));
  1125. const lynx::ChannelDef* controller = nullptr;
  1126. for (const auto& c : song.channels)
  1127. if (c.instrument == lynx::InstrumentKind::controller)
  1128. controller = &c;
  1129. CHECK (controller != nullptr);
  1130. if (controller != nullptr)
  1131. {
  1132. auto inst = lynx::makeInstrument (lynx::InstrumentKind::controller);
  1133. inst->prepare (48000.0);
  1134. inst->configure (*controller, song.bpm);
  1135. std::vector<float> l (480), r (480);
  1136. inst->render (l.data(), r.data(), 480, 1.0f, 1.0f);
  1137. inst->noteOn (60, 1.0f);
  1138. inst->render (l.data(), r.data(), 480, 1.0f, 1.0f); // 10 ms
  1139. const auto ducked = inst->controlOutput (0);
  1140. for (int i = 0; i < 100; ++i) // +1 s
  1141. inst->render (l.data(), r.data(), 480, 1.0f, 1.0f);
  1142. const auto recovered = inst->controlOutput (0);
  1143. std::printf (" Envelope Controller (Basic Sidechain): %.2f on the note, %.2f after 1 s\n", ducked, recovered);
  1144. CHECK (ducked < 0.3f && recovered > 0.9f);
  1145. }
  1146. }
  1147. }
  1148. // mutation fuzz: real states with flipped and truncated bytes must not crash the readers
  1149. {
  1150. std::map<std::string, std::vector<std::uint8_t>> samples; // one real blob per plugin
  1151. for (const auto& entry : std::filesystem::recursive_directory_iterator (std::filesystem::path (realFlpDir) / "Demo projects"))
  1152. {
  1153. if (entry.path().extension() != ".flp")
  1154. continue;
  1155. std::ifstream in (entry.path(), std::ios::binary);
  1156. const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1157. try
  1158. {
  1159. const auto project = flp::parseProject (file);
  1160. for (const auto& c : project.channels)
  1161. if (! c.pluginState.empty())
  1162. samples.emplace (c.pluginName, c.pluginState);
  1163. for (const auto& insert : project.mixer)
  1164. for (const auto& slot : insert.slots)
  1165. if (! slot.state.empty())
  1166. samples.emplace (slot.plugin, slot.state);
  1167. }
  1168. catch (const flp::Error&) {}
  1169. }
  1170. std::uint32_t seed = 12345;
  1171. auto rnd = [&seed] { seed = seed * 1664525u + 1013904223u; return seed >> 8; };
  1172. int mutations = 0;
  1173. for (const auto& [name, original] : samples)
  1174. for (int round = 0; round < 40; ++round)
  1175. {
  1176. auto blob = original;
  1177. if (round % 4 == 3 && ! blob.empty())
  1178. blob.resize (rnd() % blob.size()); // truncated
  1179. else
  1180. for (int k = 0; k < 1 + (int) (rnd() % 8) && ! blob.empty(); ++k)
  1181. blob[rnd() % blob.size()] = (std::uint8_t) rnd();
  1182. ++mutations;
  1183. lynx::SynthSettings synth;
  1184. float gain = 1.0f;
  1185. lynx::synthFromSytrus (blob, 120.0, synth, gain);
  1186. lynx::synthFromHarmor (blob, synth, gain);
  1187. lynx::synthFromGms (blob, 120.0, synth, gain);
  1188. lynx::synthFromOgun (blob, synth, gain);
  1189. lynx::synthFromMorphine (blob, synth, gain);
  1190. lynx::synthFromKepler (blob, synth, gain);
  1191. lynx::synthFromPoiZone (blob, synth, gain);
  1192. lynx::synthFromToxic (blob, synth, gain);
  1193. lynx::synthFromBassDrum (blob, synth, gain);
  1194. lynx::synthFromHarmless (blob, 120.0, synth, gain);
  1195. lynx::harmlessParams (blob);
  1196. lynx::parseEnvelopeController (blob);
  1197. lynx::parseKeyboardController (blob);
  1198. lynx::parseLovePhilter (blob);
  1199. lynx::parsePatcher (blob);
  1200. lynx::effectFromFl (name, blob);
  1201. lynx::fpcPads (blob);
  1202. lynx::directWaveProgram (blob);
  1203. CHECK (std::isfinite (gain) && std::isfinite (synth.cutoff));
  1204. }
  1205. std::printf (" mutation fuzz: %d blobs from %d plugins\n", mutations, (int) samples.size());
  1206. }
  1207. // WavPack (.wv) samples from FL packs: all decode, with finite, non-silent audio
  1208. {
  1209. int files = 0, decoded = 0, audible = 0;
  1210. double seconds = 0.0;
  1211. for (const auto& entry : std::filesystem::recursive_directory_iterator (std::filesystem::path (realFlpDir) / "Patches" / "Packs"))
  1212. if (entry.path().extension() == ".wv")
  1213. {
  1214. std::ifstream in (entry.path(), std::ios::binary);
  1215. const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1216. ++files;
  1217. lynx::DecodedAudio audio;
  1218. if (! lynx::decodeWavPack (file.data(), file.size(), audio))
  1219. continue;
  1220. ++decoded;
  1221. float peak = 0.0f;
  1222. bool finite = true;
  1223. for (const auto& ch : audio.channels)
  1224. for (auto v : ch)
  1225. {
  1226. finite = finite && std::isfinite (v);
  1227. peak = std::max (peak, std::abs (v));
  1228. }
  1229. CHECK (finite && peak <= 4.0f);
  1230. audible += peak > 1e-4f;
  1231. seconds += (double) audio.channels[0].size() / audio.sampleRate;
  1232. }
  1233. std::printf (" WavPack: %d .wv files, %d decoded, %d audible, %.0f s of audio\n", files, decoded, audible, seconds);
  1234. CHECK (decoded == files);
  1235. }
  1236. // native GMS presets (.gmsynth = the contents of 0xD5 without the "SSLF")
  1237. int gmsPresets = 0, gmsDecoded = 0;
  1238. const auto gmsFolder = std::filesystem::path (realFlpDir) / "Patches" / "Plugin presets" / "Generators" / "GMS";
  1239. if (std::filesystem::exists (gmsFolder))
  1240. for (const auto& entry : std::filesystem::recursive_directory_iterator (gmsFolder))
  1241. if (entry.path().extension() == ".gmsynth")
  1242. {
  1243. std::ifstream in (entry.path(), std::ios::binary);
  1244. std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1245. std::vector<std::uint8_t> blob { 'S', 'S', 'L', 'F' };
  1246. const auto n = (std::uint32_t) file.size();
  1247. blob.insert (blob.end(), reinterpret_cast<const std::uint8_t*> (&n), reinterpret_cast<const std::uint8_t*> (&n) + 4);
  1248. blob.insert (blob.end(), file.begin(), file.end());
  1249. lynx::SynthSettings gs;
  1250. float g = 1.0f;
  1251. ++gmsPresets;
  1252. if (lynx::synthFromGms (blob, 120.0, gs, g))
  1253. {
  1254. ++gmsDecoded;
  1255. CHECK (std::isfinite (g) && gs.cutoff >= 20.0f && std::isfinite (gs.pitchEnv.amount) && std::isfinite (gs.lfo[lynx::lfoPitch].period));
  1256. }
  1257. }
  1258. std::printf (" GMS presets: %d, %d decoded\n", gmsPresets, gmsDecoded);
  1259. // the synth's "FL presets" button: Sytrus/Harmor .fst and .gmsynth become synth settings
  1260. int presetFiles = 0, presetsRead = 0;
  1261. for (const auto* name : { "Sytrus", "Harmor", "GMS", "Harmless", "Ogun", "Sakura", "Fruit Kick", "Fruity DX10", "MiniSynth", "Kepler",
  1262. "PoiZone", "Toxic Biohazard", "BassDrum" })
  1263. {
  1264. const auto folder = std::filesystem::path (realFlpDir) / "Patches" / "Plugin presets" / "Generators" / name;
  1265. if (! std::filesystem::exists (folder))
  1266. continue;
  1267. for (const auto& entry : std::filesystem::recursive_directory_iterator (folder))
  1268. if (entry.path().extension() == ".fst" || entry.path().extension() == ".gmsynth")
  1269. {
  1270. std::ifstream in (entry.path(), std::ios::binary);
  1271. const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1272. ++presetFiles;
  1273. presetsRead += lynx::synthFromFlPreset (file).has_value();
  1274. }
  1275. }
  1276. std::printf (" FL synth presets: %d files, %d read\n", presetFiles, presetsRead);
  1277. CHECK (presetsRead >= presetFiles * 95 / 100);
  1278. CHECK (gmsDecoded == gmsPresets);
  1279. CHECK (sytrusDecoded == sytrus);
  1280. CHECK (harmlessDecoded == harmless && harmless > 100);
  1281. std::printf (" Harmless: %d states parsed for the engine, %d channels imported as Harmless\n", harmlessParsed, harmlessKind);
  1282. CHECK (harmlessParsed == harmless && harmlessKind >= harmless);
  1283. std::printf (" Harmless rack compressor: %d of %d presets read from the installation\n", harmlessCompLoaded, harmlessCompWanted);
  1284. CHECK (harmlessCompLoaded == harmlessCompWanted && harmlessCompWanted > 100);
  1285. // 3x Osc channel presets shipped with FL (.fst): all become synth settings
  1286. int presets = 0, presetsDecoded = 0;
  1287. const auto presetDir = std::filesystem::path (realFlpDir) / "Patches" / "Channel presets" / "3x Osc";
  1288. if (std::filesystem::is_directory (presetDir))
  1289. for (auto& entry : std::filesystem::directory_iterator (presetDir))
  1290. if (entry.path().extension() == ".fst")
  1291. {
  1292. ++presets;
  1293. std::ifstream in (entry.path(), std::ios::binary);
  1294. std::vector<std::uint8_t> bytes ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  1295. if (auto synth = lynx::synthFromFlPreset (bytes))
  1296. {
  1297. ++presetsDecoded;
  1298. CHECK (synth->osc[0].level + synth->osc[1].level + (synth->am ? 0.0f : synth->osc[2].level) <= 1.001f);
  1299. }
  1300. }
  1301. std::printf (" %d 3x Osc presets, %d read\n", presets, presetsDecoded);
  1302. CHECK (presetsDecoded == presets);
  1303. // FL effect presets that become built-in effects
  1304. int fxPresets = 0, fxDecoded = 0;
  1305. for (auto kind : { lynx::EffectKind::parametricEq, lynx::EffectKind::limiter, lynx::EffectKind::reverb, lynx::EffectKind::delay,
  1306. lynx::EffectKind::utility })
  1307. for (const auto& plugin : lynx::flPluginsForEffect (kind))
  1308. {
  1309. const auto dir = std::filesystem::path (realFlpDir) / "Patches" / "Plugin presets" / "Effects" / plugin;
  1310. if (! std::filesystem::is_directory (dir))
  1311. continue;
  1312. for (auto& entry : std::filesystem::recursive_directory_iterator (dir))
  1313. if (entry.path().extension() == ".fst")
  1314. {
  1315. ++fxPresets;
  1316. std::ifstream in (entry.path(), std::ios::binary);
  1317. std::vector<std::uint8_t> bytes ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  1318. fxDecoded += lynx::effectFromFlPreset (bytes).has_value();
  1319. }
  1320. }
  1321. std::printf (" %d FL effect presets, %d read\n", fxPresets, fxDecoded);
  1322. CHECK (fxDecoded == fxPresets);
  1323. CHECK (wrappedParsed == wrapped);
  1324. std::printf (" %d plugins in Fruity Wrapper, %d read\n", wrapped, wrappedParsed);
  1325. std::printf (" %d markers, %d time signature changes, %d tracks with EQ\n", markers, signatures, trackEqs);
  1326. std::printf (" %d parametric EQs (%d with FL settings), %d reverbs (%d without dry)\n", peqSlots, peqShaped, reverbs, reverbsDryless);
  1327. std::printf (" DirectWave: %d channels, %d zones; FPC: %d projects, %d pad channels, %d pad notes\n", dwChannels, dwZones, fpcKits,
  1328. padChannels, padNotes);
  1329. CHECK (dwZones > 1000 && padChannels > 250 && padNotes > 500);
  1330. std::printf (" sliced channels (Slicer/Slicex): %d; embedded WAVs saved: %d\n", slicedChannels, embeddedSaved);
  1331. CHECK (slicedChannels >= 25 && embeddedSaved >= 10); // without decoding Ogg here, some loops have no duration
  1332. std::printf (" FL Keys (Grand Piano, 30 zones): %d channels\n", flKeysChannels);
  1333. CHECK (flKeysChannels >= 8);
  1334. CHECK (peqSlots > 1000 && peqShaped > 900 && reverbsDryless > 20 && reverbsLowCut > 250);
  1335. CHECK (markers > 300 && signatures > 60);
  1336. std::printf (" %d 3x Osc channels, %d decoded\n", threeOsc, threeOscDecoded);
  1337. std::printf (" %d .flp files read, %d with notes, %d with playlist, %d automations (%d with target), %d sends\n",
  1338. files, withNotes, withPlaylist, automations, automationsWithTarget, sends);
  1339. CHECK (files > 0);
  1340. CHECK (automations > 0 && sends > 0);
  1341. }
  1342. // ---------------------------------------------------------------------------
  1343. // Sequencer
  1344. TEST (pattern_toggle_step_and_length)
  1345. {
  1346. lynx::Pattern p;
  1347. CHECK (! p.hasStep (0, 4));
  1348. p.toggleStep (0, 4);
  1349. CHECK (p.hasStep (0, 4));
  1350. CHECK (p.notes.size() == 1 && p.notes[0].start == 4 * lynx::ticksPerStep);
  1351. CHECK (p.effectiveLength (4) == 4 * lynx::ppq); // one bar
  1352. p.toggleStep (1, 20); // second bar
  1353. CHECK (p.effectiveLength (4) == 8 * lynx::ppq);
  1354. p.toggleStep (0, 4);
  1355. CHECK (! p.hasStep (0, 4) && p.notes.size() == 1);
  1356. }
  1357. TEST (scheduler_places_events_at_exact_samples)
  1358. {
  1359. lynx::Pattern p;
  1360. p.toggleStep (0, 0);
  1361. p.toggleStep (0, 4); // tick 960 = 1 beat
  1362. const double sr = 48000.0, bpm = 120.0; // 1 beat = 0.5 s = 24000 samples
  1363. const auto tps = lynx::ticksPerSample (bpm, sr);
  1364. lynx::EventBuffer ev;
  1365. lynx::schedulePatternLoop (p, p.effectiveLength (4), 23900.0 * tps, 512, tps, ev);
  1366. // the beat-2 note starts at sample 24000 -> offset 100 in this block
  1367. int ons = 0;
  1368. for (auto& e : ev)
  1369. if (e.type == lynx::NoteEvent::Type::on)
  1370. {
  1371. ++ons;
  1372. CHECK (e.sampleOffset == 100);
  1373. }
  1374. CHECK (ons == 1);
  1375. }
  1376. TEST (scheduler_wraps_the_loop)
  1377. {
  1378. lynx::Pattern p;
  1379. p.toggleStep (2, 0);
  1380. const auto len = p.effectiveLength (4); // 3840 ticks
  1381. const double sr = 48000.0;
  1382. const auto tps = lynx::ticksPerSample (120.0, sr);
  1383. lynx::EventBuffer ev;
  1384. // block that crosses the loop end: starts 10 samples before
  1385. const auto start = (double) len - 10.0 * tps;
  1386. lynx::schedulePatternLoop (p, len, start, 64, tps, ev);
  1387. bool found = false;
  1388. for (auto& e : ev)
  1389. if (e.type == lynx::NoteEvent::Type::on && e.channel == 2)
  1390. {
  1391. found = true;
  1392. CHECK (e.sampleOffset == 10);
  1393. }
  1394. CHECK (found);
  1395. }
  1396. TEST (scheduler_off_before_on_at_same_sample)
  1397. {
  1398. lynx::Pattern p;
  1399. lynx::Note a;
  1400. a.start = 0; a.length = 240; a.channel = 0;
  1401. lynx::Note b = a;
  1402. b.start = 240;
  1403. p.notes = { a, b };
  1404. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  1405. lynx::EventBuffer ev;
  1406. lynx::schedulePatternLoop (p, p.effectiveLength (4), 200.0, 4000, tps, ev);
  1407. CHECK (ev.size() >= 2);
  1408. CHECK (ev[0].type == lynx::NoteEvent::Type::off);
  1409. CHECK (ev[1].type == lynx::NoteEvent::Type::on);
  1410. CHECK (ev[0].sampleOffset == ev[1].sampleOffset);
  1411. }
  1412. TEST (snapshot_exchange_hands_over_and_recycles)
  1413. {
  1414. struct Counted
  1415. {
  1416. int value;
  1417. int* alive;
  1418. Counted (int v, int* a) : value (v), alive (a) { ++*alive; }
  1419. ~Counted() { --*alive; }
  1420. };
  1421. int alive = 0;
  1422. {
  1423. lynx::SnapshotExchange<Counted> x;
  1424. CHECK (x.acquire() == nullptr);
  1425. x.publish (std::make_unique<Counted> (1, &alive));
  1426. CHECK (x.acquire()->value == 1);
  1427. x.publish (std::make_unique<Counted> (2, &alive));
  1428. x.publish (std::make_unique<Counted> (3, &alive)); // 2 was never read: freed immediately
  1429. CHECK (alive == 2);
  1430. CHECK (x.acquire()->value == 3);
  1431. CHECK (alive == 2); // 1 was returned, but only the UI frees it
  1432. x.collectGarbage();
  1433. CHECK (alive == 1);
  1434. // without collection, the return slots fill up and the audio side holds on to the current one
  1435. for (int i = 0; i < 20; ++i)
  1436. {
  1437. x.publish (std::make_unique<Counted> (10 + i, &alive));
  1438. CHECK (x.acquire() != nullptr);
  1439. }
  1440. }
  1441. CHECK (alive == 0);
  1442. }
  1443. TEST (rack_renderer_makes_sound_and_reuses_instruments)
  1444. {
  1445. auto song = lynx::Song::makeDefault();
  1446. song.bpm = 120.0;
  1447. const double sr = 48000.0;
  1448. auto state = lynx::RackState::build (song, nullptr, sr);
  1449. lynx::RackRenderer r;
  1450. r.prepare (sr);
  1451. std::vector<float> l (512), rr (512);
  1452. double tick = 0.0;
  1453. float peak = 0.0f;
  1454. int kicks = 0;
  1455. for (int block = 0; block < 93; ++block) // 47616 samples: just before 1 s
  1456. {
  1457. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  1458. for (auto& e : r.lastEvents())
  1459. if (e.type == lynx::NoteEvent::Type::on && e.channel == 0)
  1460. ++kicks;
  1461. for (int i = 0; i < 512; ++i)
  1462. {
  1463. CHECK (std::isfinite (l[(std::size_t) i]));
  1464. peak = std::max (peak, std::abs (l[(std::size_t) i]));
  1465. }
  1466. tick += 512 * lynx::ticksPerSample (song.bpm, sr);
  1467. }
  1468. CHECK (peak > 0.1f && peak < 4.0f);
  1469. CHECK (kicks == 2); // 120 BPM: beats at 0 and 0.5 s
  1470. // editing the song keeps the instruments of channels whose type didn't change
  1471. song.channels[4].instrument = lynx::InstrumentKind::kick;
  1472. auto next = lynx::RackState::build (song, state.get(), sr);
  1473. CHECK (next->instruments[0] == state->instruments[0]);
  1474. CHECK (next->instruments[4] != state->instruments[4]);
  1475. // stopping silences the synth and triggers no new notes
  1476. r.process (next.get(), false, tick, 512, l.data(), rr.data());
  1477. CHECK (r.lastEvents().size() == 0);
  1478. }
  1479. TEST (flp_import_maps_channels_and_rescales)
  1480. {
  1481. flp::Project p;
  1482. p.header.ppq = 96;
  1483. p.tempo = 150.0;
  1484. p.channels = { { 0, flp::ChannelType::sampler, "Kick 808", "", "", 1 },
  1485. { 1, flp::ChannelType::audioClip, "Vocal", "", "", 2 },
  1486. { 2, flp::ChannelType::instrument, "Lead", "FLEX", "", 3 } };
  1487. flp::Pattern pat;
  1488. pat.index = 1;
  1489. flp::Note n;
  1490. n.position = 96;
  1491. n.length = 0;
  1492. n.channel = 2;
  1493. n.key = 72;
  1494. n.velocity = 64;
  1495. pat.notes.push_back (n);
  1496. p.patterns.push_back (pat);
  1497. const auto s = lynx::importFlp (p);
  1498. CHECK (s.bpm == 150.0);
  1499. CHECK (s.channels.size() == 3); // audio clip channels stay in the rack, as in FL
  1500. CHECK (s.channels[0].instrument == lynx::InstrumentKind::kick);
  1501. CHECK (s.channels[1].instrument == lynx::InstrumentKind::audioClip);
  1502. CHECK (s.channels[2].instrument == lynx::InstrumentKind::synth);
  1503. CHECK (s.patterns.size() == 1);
  1504. CHECK (s.patterns[0].notes[0].start == lynx::ppq); // 96 @ PPQ 96 = 1 beat
  1505. CHECK (s.patterns[0].notes[0].channel == 2);
  1506. CHECK (s.patterns[0].notes[0].length == lynx::ticksPerStep); // step note
  1507. CHECK (std::abs (s.patterns[0].notes[0].velocity - 0.5f) < 1e-6f);
  1508. }
  1509. TEST (live_queue_is_fifo_and_bounded)
  1510. {
  1511. lynx::LiveEventQueue q;
  1512. lynx::NoteEvent e;
  1513. CHECK (! q.pop (e));
  1514. for (int i = 0; i < 10; ++i)
  1515. {
  1516. lynx::NoteEvent in;
  1517. in.key = i;
  1518. CHECK (q.push (in));
  1519. }
  1520. for (int i = 0; i < 10; ++i)
  1521. CHECK (q.pop (e) && e.key == i);
  1522. int pushed = 0;
  1523. while (q.push (e))
  1524. ++pushed;
  1525. CHECK (pushed == (int) lynx::LiveEventQueue::capacity - 1); // one slot stays free to tell full from empty
  1526. }
  1527. TEST (sampler_plays_pitched_one_shot)
  1528. {
  1529. // 1000-frame ramp sample: the position can be measured from the amplitude
  1530. auto data = std::make_shared<lynx::SampleData>();
  1531. data->sampleRate = 48000.0;
  1532. for (int i = 0; i < 1000; ++i)
  1533. data->left.push_back (1.0f);
  1534. auto sampler = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  1535. sampler->prepare (48000.0);
  1536. std::vector<float> l (2048, 0.0f), r (2048, 0.0f);
  1537. sampler->noteOn (60, 1.0f);
  1538. sampler->noteOff (60); // one-shot: noteOff doesn't cut
  1539. sampler->render (l.data(), r.data(), 2048, 1.0f, 1.0f);
  1540. int sounding = 0;
  1541. for (auto s : l)
  1542. sounding += s > 0.5f;
  1543. CHECK (sounding >= 995 && sounding <= 1000); // plays the whole sample at the original pitch
  1544. std::fill (l.begin(), l.end(), 0.0f);
  1545. sampler->noteOn (72, 1.0f); // one octave up: half the duration
  1546. sampler->render (l.data(), r.data(), 2048, 1.0f, 1.0f);
  1547. sounding = 0;
  1548. for (auto s : l)
  1549. sounding += s > 0.5f;
  1550. CHECK (sounding >= 495 && sounding <= 500);
  1551. CHECK (r[10] > 0.5f); // mono goes to both sides
  1552. auto silent = lynx::makeInstrument (lynx::InstrumentKind::sampler, nullptr);
  1553. silent->prepare (48000.0);
  1554. silent->noteOn (60, 1.0f);
  1555. std::fill (l.begin(), l.end(), 0.0f);
  1556. silent->render (l.data(), r.data(), 64, 1.0f, 1.0f);
  1557. CHECK (l[0] == 0.0f);
  1558. }
  1559. TEST (rack_live_notes_and_sample_provider)
  1560. {
  1561. lynx::Song song;
  1562. lynx::ChannelDef c;
  1563. c.name = "Smp";
  1564. c.instrument = lynx::InstrumentKind::sampler;
  1565. c.samplePath = "a.wav";
  1566. song.channels.push_back (c);
  1567. song.patterns.emplace_back();
  1568. int loads = 0;
  1569. auto provider = [&] (const std::string& path) -> std::shared_ptr<const lynx::SampleData> {
  1570. ++loads;
  1571. CHECK (path == "a.wav");
  1572. auto d = std::make_shared<lynx::SampleData>();
  1573. d->left.assign (4800, 0.5f);
  1574. return d;
  1575. };
  1576. auto state = lynx::RackState::build (song, nullptr, 48000.0, provider);
  1577. CHECK (loads == 1);
  1578. lynx::RackRenderer renderer;
  1579. renderer.prepare (48000.0);
  1580. lynx::LiveEventQueue live;
  1581. lynx::NoteEvent on;
  1582. on.channel = 0;
  1583. on.velocity = 1.0f;
  1584. live.push (on);
  1585. std::vector<float> l (256), r (256);
  1586. renderer.process (state.get(), false, 0.0, 256, l.data(), r.data(), &live); // stopped, but the live note plays
  1587. CHECK (l[0] > 0.1f);
  1588. // same sample: reused; different sample: reloaded
  1589. auto same = lynx::RackState::build (song, state.get(), 48000.0, provider);
  1590. CHECK (loads == 1 && same->instruments[0] == state->instruments[0]);
  1591. song.channels[0].samplePath = "b.wav";
  1592. auto other = lynx::RackState::build (song, state.get(), 48000.0, [&] (const std::string&) { ++loads; return nullptr; });
  1593. CHECK (loads == 2 && other->instruments[0] != state->instruments[0]);
  1594. }
  1595. TEST (flp_paths_resolve_and_samplers_import)
  1596. {
  1597. lynx::FlPathRoots roots { "C:\\FL", "C:\\FL\\Data", "D:\\User" };
  1598. CHECK (lynx::resolveFlPath ("%FLStudioFactoryData%\\Data\\x.wav", roots) == "C:\\FL\\Data\\x.wav");
  1599. CHECK (lynx::resolveFlPath ("%FLStudioData%\\Patches\\y.wav", roots) == "C:\\FL\\Data\\Patches\\y.wav");
  1600. CHECK (lynx::resolveFlPath ("%FLStudioUserData%\\z.wav", roots) == "D:\\User\\z.wav");
  1601. CHECK (lynx::resolveFlPath ("E:\\abs.wav", roots) == "E:\\abs.wav");
  1602. CHECK (lynx::resolveFlPath ("%FLStudioUserData%\\z.wav", {}) == "");
  1603. flp::Project p;
  1604. p.channels = { { 0, flp::ChannelType::sampler, "Kick", "", "%FLStudioData%\\k.wav", 1 },
  1605. { 1, flp::ChannelType::sampler, "Hat", "", "%FLStudioData%\\missing.wav", 1 } };
  1606. lynx::FlpImportOptions options;
  1607. options.roots = roots;
  1608. options.fileExists = [] (const std::string& path) { return path == "C:\\FL\\Data\\k.wav"; };
  1609. const auto s = lynx::importFlp (p, options);
  1610. CHECK (s.channels[0].instrument == lynx::InstrumentKind::sampler);
  1611. CHECK (s.channels[0].samplePath == "C:\\FL\\Data\\k.wav");
  1612. CHECK (s.channels[1].instrument == lynx::InstrumentKind::hat); // no file: built-in instrument
  1613. }
  1614. TEST (soft_clip_is_transparent_below_knee_and_bounded)
  1615. {
  1616. float s[] = { 0.5f, -0.89f, 1.5f, -3.0f, 0.95f };
  1617. lynx::softClip (s, 5);
  1618. CHECK (s[0] == 0.5f && s[1] == -0.89f);
  1619. CHECK (s[2] > 0.9f && s[2] <= 1.0f);
  1620. CHECK (s[3] < -0.9f && s[3] >= -1.0f);
  1621. CHECK (s[4] > 0.9f && s[4] < 0.95f);
  1622. }
  1623. TEST (song_scheduler_plays_clips_with_offset_and_cut)
  1624. {
  1625. lynx::Song s;
  1626. s.channels.resize (1);
  1627. auto& p = s.patterns.emplace_back();
  1628. for (int step : { 0, 4, 8, 12 }) // one note per beat
  1629. p.toggleStep (0, step);
  1630. // clip at bar 2 playing only the second half of the pattern (beats 3 and 4)
  1631. lynx::Clip c;
  1632. c.pattern = 0;
  1633. c.start = 4 * lynx::ppq;
  1634. c.length = 2 * lynx::ppq;
  1635. c.offset = 2 * lynx::ppq;
  1636. s.playlist.push_back (c);
  1637. CHECK (s.songLength() == 8 * lynx::ppq);
  1638. const double sr = 48000.0;
  1639. const auto tps = lynx::ticksPerSample (120.0, sr); // 1 beat = 24000 samples
  1640. lynx::EventBuffer ev;
  1641. // whole song in a single block (8 beats = 192000 samples)
  1642. lynx::scheduleSong (s, 0.0, 192000, tps, ev);
  1643. std::vector<int> ons;
  1644. for (auto& e : ev)
  1645. if (e.type == lynx::NoteEvent::Type::on)
  1646. ons.push_back (e.sampleOffset);
  1647. CHECK (ons.size() == 2);
  1648. CHECK (ons.size() == 2 && ons[0] == 4 * 24000 && ons[1] == 5 * 24000);
  1649. // crossing the loop: bar 1 is empty, so nothing at the start of the second pass
  1650. ev.clear();
  1651. lynx::scheduleSong (s, 8.0 * lynx::ppq - 100 * tps, 200, tps, ev);
  1652. CHECK (ev.size() == 0);
  1653. // a note longer than the clip is cut at the clip end
  1654. p.notes[3].length = 4 * lynx::ppq;
  1655. ev.clear();
  1656. lynx::scheduleSong (s, 0.0, 192000, tps, ev);
  1657. int lastOff = -1;
  1658. for (auto& e : ev)
  1659. if (e.type == lynx::NoteEvent::Type::off)
  1660. lastOff = std::max (lastOff, e.sampleOffset);
  1661. CHECK (lastOff == 6 * 24000);
  1662. }
  1663. TEST (remove_pattern_fixes_clips)
  1664. {
  1665. lynx::Song s;
  1666. s.patterns.resize (3);
  1667. s.currentPattern = 2;
  1668. s.playlist = { { 0, 0, 0, 100, 0 }, { 1, 0, 100, 100, 0 }, { 2, 1, 0, 100, 0 } };
  1669. s.removePattern (1);
  1670. CHECK (s.patterns.size() == 2);
  1671. CHECK (s.playlist.size() == 2 && s.playlist[1].pattern == 1);
  1672. CHECK (s.currentPattern == 1);
  1673. }
  1674. TEST (flp_import_3x_osc_state_and_channel_filter)
  1675. {
  1676. // new 3x Osc patch (version 14): osc 2 mix 64 coarse -12, osc 3 mix 32 coarse -24
  1677. std::vector<std::uint8_t> blob (460, 0);
  1678. auto put = [&] (std::size_t off, std::int32_t v) {
  1679. for (int b = 0; b < 4; ++b)
  1680. blob[off + (std::size_t) b] = (std::uint8_t) ((std::uint32_t) v >> (8 * b));
  1681. };
  1682. put (0x00, 14);
  1683. put (0x08, 3); // osc 1 saw
  1684. put (0x10, 7); // osc 1 fine +7
  1685. put (0x04, -32); // osc 1 pan -0.5
  1686. put (0x1C, 64); // osc 2 mix
  1687. put (0x28, -12); // osc 2 coarse
  1688. put (0x38, 32); // osc 3 mix
  1689. put (0x40, 2); // osc 3 square
  1690. put (0x44, -19); // osc 3 coarse: -1 octave and -7 semitones
  1691. lynx::SynthSettings s;
  1692. CHECK (lynx::synthFrom3xOsc (blob, s));
  1693. 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);
  1694. CHECK (s.osc[0].wave == lynx::Waveform::saw && s.osc[0].detune == 7.0f && s.osc[0].pan == -0.5f);
  1695. CHECK (s.osc[1].wave == lynx::Waveform::sine && s.osc[1].octave == -1 && s.osc[1].semitones == 0);
  1696. CHECK (s.osc[2].wave == lynx::Waveform::square && s.osc[2].octave == -1 && s.osc[2].semitones == -7);
  1697. CHECK (! lynx::synthFrom3xOsc (std::vector<std::uint8_t> (40, 0), s));
  1698. // channel filter: open by default; LP with Mod X 128 ~ 2.71 kHz; Fast LP with Mod X 128 ~ 280 Hz
  1699. float hz = 0.0f, res = 1.0f;
  1700. int mode = -1;
  1701. lynx::synthFilterFromChannel (256, 0, 0, hz, res, mode);
  1702. CHECK (hz >= 19999.0f && res == 0.0f);
  1703. lynx::synthFilterFromChannel (128, 0, 1, hz, res, mode);
  1704. CHECK (std::abs (hz - 2710.0f) < 30.0f && res == 0.0f);
  1705. lynx::synthFilterFromChannel (128, 0, 0, hz, res, mode);
  1706. CHECK (hz > 240.0f && hz < 320.0f);
  1707. lynx::synthFilterFromChannel (128, 256, 1, hz, res, mode);
  1708. CHECK (res > 0.8f);
  1709. CHECK (mode == 0);
  1710. lynx::synthFilterFromChannel (64, 0, 3, hz, res, mode); // high-pass at ~840 Hz
  1711. CHECK (mode == 2 && std::abs (hz - 840.0f) < 40.0f);
  1712. lynx::synthFilterFromChannel (128, 0, 2, hz, res, mode); // band-pass
  1713. CHECK (mode == 1);
  1714. }
  1715. TEST (synth_pitch_and_filter_envelopes)
  1716. {
  1717. auto render = [] (const lynx::SynthSettings& s, int frames) {
  1718. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  1719. inst->prepare (48000.0);
  1720. lynx::ChannelDef c;
  1721. c.synth = s;
  1722. inst->configure (c, 120.0);
  1723. inst->noteOn (45, 1.0f); // A2 = 110 Hz
  1724. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  1725. inst->render (l.data(), r.data(), frames, 1.0f, 1.0f);
  1726. return l;
  1727. };
  1728. auto crossings = [] (const std::vector<float>& b, int from, int to) {
  1729. int n = 0;
  1730. for (int i = from + 1; i < to; ++i)
  1731. n += (b[(std::size_t) i - 1] < 0.0f) != (b[(std::size_t) i] < 0.0f);
  1732. return n;
  1733. };
  1734. // 3x Osc "kick": sine with a +24 st pitch envelope falling fast
  1735. lynx::SynthSettings kick;
  1736. kick.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  1737. kick.cutoff = 20000.0f;
  1738. kick.pitchEnv = { 24.0f, 0.0f, 0.0f, 0.05f, 0.0f, 0.05f };
  1739. const auto k = render (kick, 48000);
  1740. const auto early = crossings (k, 0, 2400); // first 50 ms: well above 110 Hz
  1741. const auto late = crossings (k, 24000, 48000); // then back to 110 Hz (~110 crossings in 0.5 s)
  1742. CHECK (early > 20); // +24 st ramp over 50 ms: ~2.2x the average frequency (11 crossings without envelope)
  1743. CHECK (std::abs (late - 110) < 4);
  1744. // cutoff envelope: saw closed at 200 Hz opens +5 octaves on attack and closes again
  1745. lynx::SynthSettings pluck;
  1746. pluck.cutoff = 200.0f;
  1747. pluck.filterEnv = { 5.0f, 0.0f, 0.0f, 0.1f, 0.0f, 0.1f };
  1748. const auto p = render (pluck, 48000);
  1749. auto hf = [&] (int from, int to) { // energy of the difference (highs)
  1750. double e = 0.0;
  1751. for (int i = from + 1; i < to; ++i)
  1752. e += std::pow ((double) p[(std::size_t) i] - p[(std::size_t) i - 1], 2.0);
  1753. return e;
  1754. };
  1755. CHECK (hf (0, 2400) > 4.0 * hf (40000, 42400));
  1756. // Toxic Biohazard's envelope (REA_rodada33 §2): exponential towards 5 clipped at 1, so the cutoff is still near
  1757. // its base early in the attack, fully open at A = 0.2 s and back down after the exponential decay
  1758. lynx::SynthSettings toxic = pluck;
  1759. toxic.filterEnv = { 5.0f, 0.2f, 0.0f, 0.1f, 0.0f, 0.1f, 1 };
  1760. const auto t = render (toxic, 48000);
  1761. auto thf = [&] (int from, int to) {
  1762. double e = 0.0;
  1763. for (int i = from + 1; i < to; ++i)
  1764. e += std::pow ((double) t[(std::size_t) i] - t[(std::size_t) i - 1], 2.0);
  1765. return e;
  1766. };
  1767. CHECK (thf (9000, 9600) > 4.0 * thf (300, 900));
  1768. CHECK (thf (9000, 9600) > 4.0 * thf (40000, 40600));
  1769. }
  1770. TEST (synth_mono_reuses_the_sounding_voice)
  1771. {
  1772. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  1773. inst->prepare (48000.0);
  1774. lynx::ChannelDef c;
  1775. c.synth.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  1776. c.synth.cutoff = 20000.0f;
  1777. c.synth.mono = true;
  1778. inst->configure (c, 120.0);
  1779. std::vector<float> l (48000), r (48000);
  1780. inst->noteOn (57, 1.0f);
  1781. inst->render (l.data(), r.data(), 4800, 1.0f, 1.0f);
  1782. inst->noteOn (69, 1.0f); // A4 takes over the A3 voice: only one note sounding
  1783. inst->render (l.data() + 4800, r.data() + 4800, 43200, 1.0f, 1.0f);
  1784. int crossings = 0;
  1785. float peak = 0.0f;
  1786. for (std::size_t i = 24001; i < 48000; ++i)
  1787. {
  1788. crossings += (l[i - 1] < 0.0f) != (l[i] < 0.0f);
  1789. peak = std::max (peak, std::abs (l[i]));
  1790. }
  1791. CHECK (std::abs (crossings - 440) < 4); // 0.5 s of 440 Hz, without the A3 underneath
  1792. CHECK (peak < 0.35f); // one voice (0.3 level), not two summed
  1793. // no click on the handover: the jump between neighbouring samples stays sine-sized
  1794. float jump = 0.0f;
  1795. for (std::size_t i = 4790; i < 4810; ++i)
  1796. jump = std::max (jump, std::abs (l[i] - l[i - 1]));
  1797. CHECK (jump < 0.05f);
  1798. }
  1799. TEST (synth_porta_glides_and_am_modulates)
  1800. {
  1801. auto make = [] (const lynx::SynthSettings& s) {
  1802. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  1803. inst->prepare (48000.0);
  1804. lynx::ChannelDef c;
  1805. c.synth = s;
  1806. inst->configure (c, 120.0);
  1807. return inst;
  1808. };
  1809. auto crossings = [] (const std::vector<float>& b, std::size_t from, std::size_t to) {
  1810. int n = 0;
  1811. for (auto i = from + 1; i < to; ++i)
  1812. n += (b[i - 1] < 0.0f) != (b[i] < 0.0f);
  1813. return n;
  1814. };
  1815. // mono + 1-beat porta (0.5 s at 120 BPM): from A3 to A4, halfway ~E4 (329.6 Hz)
  1816. lynx::SynthSettings s;
  1817. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  1818. s.cutoff = 20000.0f;
  1819. s.mono = true;
  1820. s.porta = true;
  1821. s.portaBeats = 1.0f;
  1822. auto inst = make (s);
  1823. std::vector<float> l (96000), r (96000);
  1824. inst->noteOn (57, 1.0f);
  1825. inst->render (l.data(), r.data(), 4800, 1.0f, 1.0f);
  1826. inst->noteOn (69, 1.0f);
  1827. inst->render (l.data() + 4800, r.data() + 4800, 91200, 1.0f, 1.0f);
  1828. const auto middle = crossings (l, 4800 + 12000 - 2400, 4800 + 12000 + 2400); // 0.1 s around 0.25 s
  1829. CHECK (std::abs (middle - 66) < 6); // ~330 Hz * 0.1 s * 2
  1830. CHECK (std::abs (crossings (l, 48000, 96000) - 880) < 4); // reached A4 (1 s = 880 crossings)
  1831. // AM: osc 3 at level 1.0, slow sine, modulates osc 1 (the average level drops, the sum doesn't gain osc 3)
  1832. lynx::SynthSettings am;
  1833. am.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  1834. am.osc[2] = { lynx::Waveform::sine, -3, 0.0f, 1.0f };
  1835. am.cutoff = 20000.0f;
  1836. am.am = true;
  1837. auto modulated = make (am);
  1838. modulated->noteOn (69, 1.0f);
  1839. std::fill (l.begin(), l.end(), 0.0f);
  1840. modulated->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  1841. float peak = 0.0f;
  1842. for (std::size_t i = 4800; i < 48000; ++i)
  1843. peak = std::max (peak, std::abs (l[i]));
  1844. CHECK (peak > 0.45f && peak < 0.65f); // 0.3 · (1 + 1) at most: (1 − o3) goes up to 2
  1845. }
  1846. TEST (channel_lfo_vibrato_and_tremolo)
  1847. {
  1848. auto render = [] (const lynx::SynthSettings& s) {
  1849. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  1850. inst->prepare (48000.0);
  1851. lynx::ChannelDef c;
  1852. c.synth = s;
  1853. inst->configure (c, 120.0);
  1854. inst->noteOn (69, 1.0f);
  1855. std::vector<float> l (48000), r (48000);
  1856. inst->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  1857. return l;
  1858. };
  1859. lynx::SynthSettings s;
  1860. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  1861. s.cutoff = 20000.0f;
  1862. // tremolo: 100% volume LFO at 4 Hz (0.25 s period) -> the amplitude envelope goes from ~0 to ~2x
  1863. auto tremolo = s;
  1864. tremolo.lfo[lynx::lfoVolume] = { 1.0f, 0.25f, false, 0, 0.0f, 0.0f };
  1865. const auto t = render (tremolo);
  1866. float lowest = 1.0f, highest = 0.0f;
  1867. for (std::size_t w = 4800; w + 480 <= 48000; w += 480) // 10 ms windows (4.4 cycles of 440 Hz)
  1868. {
  1869. float peak = 0.0f;
  1870. for (auto i = w; i < w + 480; ++i)
  1871. peak = std::max (peak, std::abs (t[i]));
  1872. lowest = std::min (lowest, peak);
  1873. highest = std::max (highest, peak);
  1874. }
  1875. CHECK (lowest < 0.08f && highest > 0.5f);
  1876. // synced vibrato: ±1 semitone, 1-beat period (0.5 s at 120 BPM); the average stays at 440 Hz
  1877. auto vibrato = s;
  1878. vibrato.lfo[lynx::lfoPitch] = { 1.0f, 1.0f, true, 0, 0.0f, 0.0f };
  1879. const auto v = render (vibrato);
  1880. int crossings = 0;
  1881. for (std::size_t i = 1; i < 48000; ++i)
  1882. crossings += (v[i - 1] < 0.0f) != (v[i] < 0.0f);
  1883. CHECK (std::abs (crossings - 880) < 12);
  1884. int firstQuarter = 0; // first quarter of the cycle: rising sine -> higher than 440
  1885. for (std::size_t i = 1; i < 6000; ++i)
  1886. firstQuarter += (v[i - 1] < 0.0f) != (v[i] < 0.0f);
  1887. CHECK (firstQuarter > 112);
  1888. }
  1889. TEST (sampler_porta_glides_from_previous_note)
  1890. {
  1891. auto data = std::make_shared<lynx::SampleData>();
  1892. data->sampleRate = 48000.0;
  1893. data->left.resize (96000);
  1894. for (std::size_t i = 0; i < data->left.size(); ++i)
  1895. data->left[i] = 0.5f * (float) std::sin (6.283185307 * 220.0 * (double) i / 48000.0);
  1896. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  1897. inst->prepare (48000.0);
  1898. lynx::ChannelDef c;
  1899. c.sampler.cut = true;
  1900. c.sampler.porta = true;
  1901. c.sampler.portaBeats = 1.0f; // 0.5 s at 120 BPM
  1902. inst->configure (c, 120.0);
  1903. std::vector<float> l (24000), r (24000);
  1904. inst->noteOn (60, 1.0f);
  1905. inst->render (l.data(), r.data(), 2400, 1.0f, 1.0f);
  1906. inst->noteOn (72, 1.0f); // one octave up: starts at 220 Hz and rises
  1907. std::fill (l.begin(), l.end(), 0.0f);
  1908. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  1909. auto crossings = [&] (std::size_t from, std::size_t to) {
  1910. int n = 0;
  1911. for (auto i = from + 1; i < to; ++i)
  1912. n += (l[i - 1] < 0.0f) != (l[i] < 0.0f);
  1913. return n;
  1914. };
  1915. const auto start = crossings (600, 2400); // 37.5 ms still near 220 Hz: ~17 crossings (440 Hz would give 33)
  1916. const auto end = crossings (21600, 24000); // 50 ms at the end of the glide: near 440 Hz (~44; 220 Hz would give 22)
  1917. CHECK (start < 22);
  1918. CHECK (end > 36);
  1919. }
  1920. TEST (zoned_sampler_picks_zone_by_key_and_velocity)
  1921. {
  1922. auto sine = [] (double hz, float amp) {
  1923. auto d = std::make_shared<lynx::SampleData>();
  1924. d->sampleRate = 48000.0;
  1925. d->left.resize (48000);
  1926. for (std::size_t i = 0; i < d->left.size(); ++i)
  1927. d->left[i] = amp * (float) std::sin (6.283185307 * hz * (double) i / 48000.0);
  1928. return d;
  1929. };
  1930. // lows: 220 Hz sine recorded as A3 (57), up to key 69; highs: 880 Hz as A5 (81)
  1931. // hard layer on the highs: same tuning, louder
  1932. std::vector<lynx::LoadedZone> zones {
  1933. { { "graves.wav", 57, 0, 69, 0, 127, 0.0f, 1.0f }, sine (220.0, 0.5f) },
  1934. { { "agudos.wav", 81, 70, 127, 0, 99, 0.0f, 1.0f }, sine (880.0, 0.25f) },
  1935. { { "agudos forte.wav", 81, 70, 127, 100, 127, 0.0f, 1.0f }, sine (880.0, 0.9f) },
  1936. };
  1937. auto inst = lynx::makeZonedSampler (zones);
  1938. inst->prepare (48000.0);
  1939. inst->configure (lynx::ChannelDef {}, 120.0);
  1940. auto play = [&] (int key, float velocity) {
  1941. inst->allNotesOff();
  1942. std::vector<float> l (24000), r (24000);
  1943. inst->render (l.data(), r.data(), 2000, 1.0f, 1.0f); // let the old voices die out
  1944. std::fill (l.begin(), l.end(), 0.0f);
  1945. inst->noteOn (key, velocity);
  1946. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  1947. int crossings = 0;
  1948. float peak = 0.0f;
  1949. for (std::size_t i = 1; i < 24000; ++i)
  1950. {
  1951. crossings += (l[i - 1] < 0.0f) != (l[i] < 0.0f);
  1952. peak = std::max (peak, std::abs (l[i]));
  1953. }
  1954. return std::pair { crossings, peak };
  1955. };
  1956. const auto low = play (69, 0.5f); // A4 from root A3: 440 Hz -> 440 crossings in 0.5 s
  1957. CHECK (std::abs (low.first - 440) < 4);
  1958. const auto soft = play (81, 0.5f); // high zone at the root: 880 Hz
  1959. CHECK (std::abs (soft.first - 880) < 6);
  1960. const auto hard = play (81, 0.95f); // high velocity: hard layer
  1961. CHECK (hard.second > soft.second * 2.0f);
  1962. // overlapping layers round-robin: two identical zones at different levels, notes alternate
  1963. auto rr = lynx::makeZonedSampler ({ { { "a.wav", 60 }, sine (440.0, 0.2f) }, { { "b.wav", 60 }, sine (440.0, 0.8f) } });
  1964. rr->prepare (48000.0);
  1965. rr->configure (lynx::ChannelDef {}, 120.0);
  1966. float peaks[2] {};
  1967. for (int k = 0; k < 2; ++k)
  1968. {
  1969. rr->allNotesOff();
  1970. std::vector<float> l (4800), r (4800);
  1971. rr->render (l.data(), r.data(), 2000, 1.0f, 1.0f);
  1972. std::fill (l.begin(), l.end(), 0.0f);
  1973. rr->noteOn (60, 1.0f);
  1974. rr->render (l.data(), r.data(), 4800, 1.0f, 1.0f);
  1975. for (auto v : l)
  1976. peaks[k] = std::max (peaks[k], std::abs (v));
  1977. }
  1978. CHECK (std::abs (peaks[0] - peaks[1]) > 0.3f);
  1979. }
  1980. TEST (zoned_sampler_loops_while_held)
  1981. {
  1982. // 0.1 s sample with a loop in the middle: holding the note it keeps sounding well past the end of the file;
  1983. // on release, it leaves the loop and ends
  1984. auto data = std::make_shared<lynx::SampleData>();
  1985. data->sampleRate = 48000.0;
  1986. data->left.resize (4800);
  1987. for (std::size_t i = 0; i < data->left.size(); ++i)
  1988. data->left[i] = 0.5f * (float) std::sin (6.283185307 * 480.0 * (double) i / 48000.0); // 100 frames per cycle
  1989. lynx::SampleZone zone { "loop.wav", 60 };
  1990. zone.loopStart = 1000;
  1991. zone.loopEnd = 3000;
  1992. zone.loopMode = 2;
  1993. auto inst = lynx::makeZonedSampler ({ { zone, data } });
  1994. inst->prepare (48000.0);
  1995. lynx::ChannelDef c;
  1996. c.sampler.release = 0.01f;
  1997. inst->configure (c, 120.0);
  1998. inst->noteOn (60, 1.0f);
  1999. std::vector<float> l (48000), r (48000);
  2000. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f); // 0.5 s held
  2001. float held = 0.0f;
  2002. for (std::size_t i = 20000; i < 24000; ++i)
  2003. held = std::max (held, std::abs (l[i]));
  2004. CHECK (held > 0.3f);
  2005. inst->noteOff (60);
  2006. inst->render (l.data() + 24000, r.data() + 24000, 24000, 1.0f, 1.0f);
  2007. float after = 0.0f;
  2008. for (std::size_t i = 40000; i < 48000; ++i)
  2009. after = std::max (after, std::abs (l[i]));
  2010. CHECK (after == 0.0f);
  2011. }
  2012. TEST (global_lfo_follows_song_position)
  2013. {
  2014. // global volume LFO (1-beat period): a note mid-cycle starts mid-wave; the
  2015. // same note with a per-note LFO starts at phase 0
  2016. auto first = [] (bool global, double songTicks) {
  2017. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  2018. inst->prepare (48000.0);
  2019. lynx::ChannelDef c;
  2020. c.synth.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  2021. c.synth.cutoff = 20000.0f;
  2022. c.synth.lfo[lynx::lfoVolume] = { 1.0f, 1.0f, true, 2, 0.0f, 0.0f, global }; // pulse: +1 in the first half
  2023. inst->configure (c, 120.0);
  2024. inst->setSongPosition (songTicks);
  2025. inst->noteOn (69, 1.0f);
  2026. std::vector<float> l (4800), r (4800);
  2027. inst->render (l.data(), r.data(), 4800, 1.0f, 1.0f);
  2028. float peak = 0.0f;
  2029. for (std::size_t i = 2400; i < 4800; ++i)
  2030. peak = std::max (peak, std::abs (l[i]));
  2031. return peak;
  2032. };
  2033. // mid-cycle (phase 0.6) the pulse is at −1: volume ~0; per note (phase 0) it is at +1: ~2x
  2034. const auto globalLate = first (true, 0.6 * lynx::ppq);
  2035. const auto perNote = first (false, 0.6 * lynx::ppq);
  2036. CHECK (globalLate < 0.05f);
  2037. CHECK (perNote > 0.4f);
  2038. }
  2039. TEST (sampler_channel_filter_darkens_and_bypasses_when_open)
  2040. {
  2041. // white noise in the sampler: with a 300 Hz cutoff the energy drops a lot; open passes unchanged
  2042. auto data = std::make_shared<lynx::SampleData>();
  2043. data->sampleRate = 48000.0;
  2044. data->left.resize (48000);
  2045. std::uint32_t seed = 7;
  2046. for (auto& v : data->left)
  2047. {
  2048. seed = seed * 1664525u + 1013904223u;
  2049. v = ((float) (seed >> 8) / 16777216.0f - 0.5f);
  2050. }
  2051. data->right = data->left;
  2052. auto energy = [&] (float cutoff) {
  2053. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  2054. inst->prepare (48000.0);
  2055. lynx::ChannelDef c;
  2056. c.sampler.cutoff = cutoff;
  2057. inst->configure (c, 120.0);
  2058. inst->noteOn (60, 1.0f);
  2059. std::vector<float> l (24000), r (24000);
  2060. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  2061. double e = 0.0;
  2062. for (auto v : l)
  2063. e += (double) v * v;
  2064. return e;
  2065. };
  2066. const auto open = energy (20000.0f), dark = energy (300.0f);
  2067. {
  2068. // high-pass at 10 kHz: also removes most of the noise energy, but from the other side
  2069. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  2070. inst->prepare (48000.0);
  2071. lynx::ChannelDef hp;
  2072. hp.sampler.cutoff = 10000.0f;
  2073. hp.sampler.filterType = 2;
  2074. inst->configure (hp, 120.0);
  2075. inst->noteOn (60, 1.0f);
  2076. std::vector<float> l (24000), r (24000);
  2077. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  2078. double e = 0.0, lowE = 0.0;
  2079. float lp = 0.0f;
  2080. for (auto v : l)
  2081. {
  2082. e += (double) v * v;
  2083. lp += 0.01f * (v - lp); // crude low-pass: almost nothing should remain below
  2084. lowE += (double) lp * lp;
  2085. }
  2086. CHECK (e > 10.0 && e < 0.7 * energy (20000.0f));
  2087. CHECK (lowE < e * 0.01);
  2088. }
  2089. CHECK (open > 100.0);
  2090. CHECK (dark < open * 0.05);
  2091. // +12 st pitch envelope with sustain 1: the sample runs at double speed
  2092. // and ends in half the time (1 s of sample -> 0.5 s)
  2093. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  2094. inst->prepare (48000.0);
  2095. lynx::ChannelDef c;
  2096. c.sampler.pitchEnv = { 12.0f, 0.0f, 0.0f, 0.1f, 1.0f, 0.1f };
  2097. inst->configure (c, 120.0);
  2098. inst->noteOn (60, 1.0f);
  2099. std::vector<float> l (48000), r (48000);
  2100. inst->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  2101. float tail = 0.0f, body = 0.0f;
  2102. for (std::size_t i = 20000; i < 23000; ++i)
  2103. body = std::max (body, std::abs (l[i]));
  2104. for (std::size_t i = 25000; i < 48000; ++i)
  2105. tail = std::max (tail, std::abs (l[i]));
  2106. CHECK (body > 0.1f);
  2107. CHECK (tail == 0.0f);
  2108. }
  2109. TEST (synth_oscillator_pan_and_semitones)
  2110. {
  2111. auto render = [] (lynx::SynthSettings s, std::vector<float>& l, std::vector<float>& r) {
  2112. auto synth = lynx::makeInstrument (lynx::InstrumentKind::synth);
  2113. synth->prepare (48000.0);
  2114. lynx::ChannelDef c;
  2115. c.synth = s;
  2116. synth->configure (c, 120.0);
  2117. synth->noteOn (69, 1.0f);
  2118. l.assign (24000, 0.0f);
  2119. r.assign (24000, 0.0f);
  2120. synth->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  2121. };
  2122. lynx::SynthSettings s;
  2123. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f, 7, 1.0f }; // a fifth up, fully right
  2124. s.cutoff = 20000.0f;
  2125. std::vector<float> l, r;
  2126. render (s, l, r);
  2127. float peakL = 0.0f, peakR = 0.0f;
  2128. int crossings = 0;
  2129. for (std::size_t i = 4800; i < 24000; ++i)
  2130. {
  2131. peakL = std::max (peakL, std::abs (l[i]));
  2132. peakR = std::max (peakR, std::abs (r[i]));
  2133. crossings += (r[i - 1] < 0.0f) != (r[i] < 0.0f);
  2134. }
  2135. CHECK (peakL < 1e-4f && peakR > 0.1f);
  2136. // 440 * 2^(7/12) = 659.3 Hz; 0.4 s = 263.7 cycles = ~527 crossings
  2137. CHECK (std::abs (crossings - 527) < 6);
  2138. }
  2139. TEST (fl_wrapper_state_parses_records_and_vst3_state)
  2140. {
  2141. // Fruity Wrapper blob (version 12): VST3 generator type, class ID, name, path and state
  2142. std::vector<std::uint8_t> blob;
  2143. 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))); };
  2144. auto record = [&] (std::vector<std::uint8_t>& b, std::uint32_t id, const std::vector<std::uint8_t>& payload) {
  2145. u32 (b, id);
  2146. u32 (b, (std::uint32_t) payload.size());
  2147. u32 (b, 0);
  2148. b.insert (b.end(), payload.begin(), payload.end());
  2149. };
  2150. auto bytes = [] (const std::string& s) { return std::vector<std::uint8_t> (s.begin(), s.end()); };
  2151. std::vector<std::uint8_t> vst3State;
  2152. u32 (vst3State, 1);
  2153. record (vst3State, 1, std::vector<std::uint8_t> (64, 0));
  2154. record (vst3State, 3, bytes ("COMPONENTE"));
  2155. record (vst3State, 2, bytes ("CONTROLADOR"));
  2156. // record 4: 3 slots → ParamIDs 700, −1 (empty), 0xFFFFFF01
  2157. std::vector<std::uint8_t> slots;
  2158. for (auto v : { 3u, 700u, 0xFFFFFFFFu, 0xFFFFFF01u })
  2159. u32 (slots, v);
  2160. record (vst3State, 4, slots);
  2161. u32 (blob, 12);
  2162. record (blob, 0x01, std::vector<std::uint8_t> (20, 0xFF));
  2163. record (blob, 0x32, { 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });
  2164. std::vector<std::uint8_t> cid;
  2165. for (int i = 0; i < 16; ++i)
  2166. cid.push_back ((std::uint8_t) (0xA0 + i));
  2167. record (blob, 0x34, cid);
  2168. record (blob, 0x36, bytes ("Surge XT"));
  2169. record (blob, 0x37, bytes ("C:/Program Files/Common Files/VST3/Surge XT.vst3"));
  2170. record (blob, 0x35, vst3State);
  2171. lynx::ForeignPlugin p;
  2172. CHECK (lynx::parseFlWrapper (blob, p));
  2173. CHECK (p.format == lynx::ForeignPlugin::Format::vst3);
  2174. CHECK (p.hasClassId && p.classId[0] == 0xA0 && p.classId[15] == 0xAF);
  2175. CHECK (p.name == "Surge XT" && p.path.find ("Surge XT.vst3") != std::string::npos);
  2176. std::vector<std::uint8_t> component, controller;
  2177. CHECK (lynx::splitFlVst3State (p.state, component, controller));
  2178. CHECK (component == bytes ("COMPONENTE") && controller == bytes ("CONTROLADOR"));
  2179. const auto saved = lynx::flVst3ParamSlots (p.state);
  2180. CHECK (saved == (std::vector<std::int32_t> { 700, -1, (std::int32_t) 0xFFFFFF01u }));
  2181. // FL's slot assignment: saved slots keep their ParamID wherever it now sits; the empty slot stays empty;
  2182. // a vanished ParamID (0xFFFFFF01) leaves its slot dead; parameters without a slot get slots 3, 4… in list order
  2183. const auto positions = lynx::flVst3SlotPositions (saved, { 5u, 700u, 9u });
  2184. CHECK (positions == (std::vector<int> { 1, -1, -1, 0, 2 }));
  2185. CHECK (lynx::flVst3SlotPositions ({}, { 5u, 6u }) == (std::vector<int> { 0, 1 })); // new instance: slot = position
  2186. // version out of range or no type: not a usable wrapper
  2187. blob[0] = 13;
  2188. CHECK (! lynx::parseFlWrapper (blob, p));
  2189. CHECK (! lynx::parseFlWrapper ({ 12, 0, 0, 0 }, p));
  2190. }
  2191. TEST (schedule_index_matches_full_scan)
  2192. {
  2193. // random song (long notes, swing, clips with offset); indexed scheduling must yield
  2194. // exactly the same events as the full scan, including in the block that wraps around
  2195. lynx::Song s = lynx::Song::makeDefault();
  2196. s.swing = 0.6f;
  2197. std::uint32_t seed = 12345;
  2198. auto rnd = [&] (int n) { seed = seed * 1664525u + 1013904223u; return (int) ((seed >> 8) % (std::uint32_t) n); };
  2199. s.patterns.resize (3);
  2200. for (auto& p : s.patterns)
  2201. {
  2202. p.notes.clear();
  2203. for (int i = 0; i < 60; ++i)
  2204. {
  2205. lynx::Note n;
  2206. n.start = rnd (16 * lynx::ppq);
  2207. n.length = rnd (5) == 0 ? rnd (12 * lynx::ppq) + 1 : rnd (lynx::ppq) + 1;
  2208. n.channel = rnd (4);
  2209. n.key = 40 + rnd (40);
  2210. n.slide = rnd (20) == 0;
  2211. p.notes.push_back (n);
  2212. }
  2213. p.sortNotes();
  2214. }
  2215. s.playlist.clear();
  2216. for (int i = 0; i < 12; ++i)
  2217. {
  2218. lynx::Clip c;
  2219. c.pattern = rnd (3);
  2220. c.track = rnd (4);
  2221. c.start = rnd (40) * lynx::ppq;
  2222. c.length = (rnd (12) + 1) * lynx::ppq;
  2223. c.offset = rnd (4) * lynx::ppq;
  2224. s.playlist.push_back (c);
  2225. }
  2226. s.mode = lynx::PlayMode::song;
  2227. const auto index = lynx::makeScheduleIndex (s);
  2228. const auto tps = lynx::ticksPerSample (140.0, 48000.0);
  2229. const auto loop = (double) s.songLength();
  2230. int mismatches = 0, events = 0;
  2231. for (int block = 0; block < 400; ++block)
  2232. {
  2233. const auto start = block == 0 ? loop - 100.0 * tps : (double) rnd ((int) loop * 2);
  2234. const auto samples = 64 + rnd (24000); // up to ~1 beat per block
  2235. lynx::EventBuffer a, b;
  2236. lynx::scheduleSong (s, start, samples, tps, a, false, nullptr);
  2237. lynx::scheduleSong (s, start, samples, tps, b, false, &index);
  2238. events += a.size();
  2239. if (a.size() != b.size())
  2240. {
  2241. ++mismatches;
  2242. continue;
  2243. }
  2244. for (int i = 0; i < a.size(); ++i)
  2245. {
  2246. const auto& x = *(a.begin() + i);
  2247. const auto& y = *(b.begin() + i);
  2248. mismatches += x.sampleOffset != y.sampleOffset || x.type != y.type || x.key != y.key || x.channel != y.channel;
  2249. }
  2250. }
  2251. CHECK (events > 500);
  2252. CHECK (mismatches == 0);
  2253. }
  2254. TEST (mixer_track_eq_defaults_and_boost)
  2255. {
  2256. // FL defaults: 90 Hz, 1.5 kHz and 8 kHz; peak Q 0.632; shelf slope 0.607
  2257. lynx::TrackEq eq;
  2258. CHECK (std::abs (lynx::TrackEq::peakQ (eq.width[1]) - 0.632) < 0.01);
  2259. CHECK (std::abs (lynx::TrackEq::shelfSlope (eq.width[0]) - 0.607) < 0.01);
  2260. CHECK (! eq.active());
  2261. // +12 dB peak at 1.5 kHz on a track: a 1.5 kHz sine rises ~4x
  2262. lynx::Song song = lynx::Song::makeDefault();
  2263. song.mixer[1].eq.gainDb[1] = 12.0f;
  2264. for (auto& c : song.channels)
  2265. c.mixerTrack = 1;
  2266. song.channels[4].instrument = lynx::InstrumentKind::synth;
  2267. song.channels[4].synth = {};
  2268. song.channels[4].synth.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  2269. song.channels[4].synth.cutoff = 20000.0f;
  2270. auto render = [] (const lynx::Song& s) {
  2271. auto state = lynx::RackState::build (s, nullptr, 48000.0);
  2272. lynx::RackRenderer renderer;
  2273. renderer.prepare (48000.0);
  2274. lynx::LiveEventQueue live;
  2275. lynx::NoteEvent on; // 1.5 kHz ~ key 90.6: use 91 (1568 Hz), still within the wide peak
  2276. on.channel = 4;
  2277. on.key = 91;
  2278. on.velocity = 1.0f;
  2279. live.push (on);
  2280. std::vector<float> l (24000), r (24000);
  2281. for (int pos = 0; pos < 24000; pos += 480)
  2282. renderer.process (state.get(), false, 0.0, 480, l.data() + pos, r.data() + pos, pos == 0 ? &live : nullptr);
  2283. float peak = 0.0f;
  2284. for (std::size_t i = 12000; i < 24000; ++i)
  2285. peak = std::max (peak, std::abs (l[i]));
  2286. return peak;
  2287. };
  2288. const auto boosted = render (song);
  2289. song.mixer[1].eq.gainDb[1] = 0.0f;
  2290. const auto flat = render (song);
  2291. CHECK (flat > 0.01f);
  2292. CHECK (boosted / flat > 3.0f && boosted / flat < 4.2f);
  2293. }
  2294. TEST (bars_follow_time_signature_markers)
  2295. {
  2296. lynx::Song song;
  2297. song.beatsPerBar = 4;
  2298. const auto bar4 = (std::int64_t) lynx::ppq * 4;
  2299. auto bars = song.barsBetween (0, bar4 * 3);
  2300. CHECK (bars.size() == 3 && bars[2].tick == bar4 * 2 && bars[2].number == 3);
  2301. // 7/4 from bar 3, and 3/4 in the middle of a 7 bar (cuts and restarts)
  2302. song.addMarker ({ bar4 * 2, "Verso", 7, 4 });
  2303. song.addMarker ({ bar4, "Nome só", 0, 4 });
  2304. const auto seven = (std::int64_t) lynx::ppq * 7;
  2305. song.addMarker ({ bar4 * 2 + seven + lynx::ppq * 2, "", 3, 4 });
  2306. bars = song.barsBetween (0, bar4 * 2 + seven * 2);
  2307. CHECK (bars.size() >= 5);
  2308. CHECK (bars[1].length == bar4 && bars[2].tick == bar4 * 2 && bars[2].length == seven);
  2309. CHECK (bars[3].length == lynx::ppq * 2); // cut short by the change
  2310. CHECK (bars[4].length == lynx::ppq * 3 && bars[4].number == 5);
  2311. CHECK (song.markers()[0].name == "Nome só"); // sorted by tick
  2312. // from far away: starts at the right bar without losing the numbering
  2313. const auto far = song.barsBetween (lynx::ppq * 3000, lynx::ppq * 3001);
  2314. CHECK (far.size() == 1 && far[0].length == lynx::ppq * 3);
  2315. CHECK (song.barAt (lynx::ppq * 3000).number == far[0].number);
  2316. CHECK ((lynx::ppq * 3000 - far[0].tick) < far[0].length);
  2317. }
  2318. TEST (split_drum_channel_moves_notes_to_pads)
  2319. {
  2320. lynx::Song song = lynx::Song::makeDefault();
  2321. const auto channels = (int) song.channels.size();
  2322. song.patterns[0].notes.clear();
  2323. song.patterns[0].notes.push_back ({ 0, 240, 1, 36, 0.9f }); // kit kick (channel 1)
  2324. song.patterns[0].notes.push_back ({ 240, 240, 1, 38, 0.8f }); // snare
  2325. song.patterns[0].notes.push_back ({ 480, 240, 1, 50, 0.8f }); // key without a pad: dropped
  2326. song.patterns[0].notes.push_back ({ 480, 240, 3, 60, 0.8f }); // other channel: shifts by 1 position
  2327. lynx::Automation a;
  2328. a.target = { lynx::AutomationTargetKind::channelVolume, 3, 0, 0 };
  2329. song.automations.push_back (a);
  2330. std::vector<lynx::DrumPad> pads (2);
  2331. pads[0].name = "Kick";
  2332. pads[0].key = 36;
  2333. pads[0].layers = { { "kick.wav" } };
  2334. pads[1].name = "Snare";
  2335. pads[1].key = 38;
  2336. pads[1].layers = { { "snare soft.wav", 60, 0, 127, 0, 90 }, { "snare hard.wav", 60, 0, 127, 91, 127 } };
  2337. pads[1].cutGroup = 2;
  2338. pads[1].cutBy = 2;
  2339. lynx::splitDrumChannel (song, 1, pads);
  2340. CHECK ((int) song.channels.size() == channels + 1);
  2341. CHECK (song.channels[1].samplePath == "kick.wav" && song.channels[1].instrument == lynx::InstrumentKind::sampler);
  2342. CHECK (song.channels[2].zones.size() == 2 && song.channels[2].cutGroup == song.channels[2].cutBy && song.channels[2].cutGroup != 0);
  2343. const auto& notes = song.patterns[0].notes;
  2344. CHECK (notes.size() == 3);
  2345. CHECK (notes[0].channel == 1 && notes[0].key == 60);
  2346. CHECK (notes[1].channel == 2 && notes[1].key == 60);
  2347. CHECK (notes[2].channel == 4); // the old channel 3
  2348. CHECK (song.automations[0].target.index == 4);
  2349. }
  2350. TEST (flp_import_brings_playlist)
  2351. {
  2352. flp::Project p;
  2353. p.header.ppq = 96;
  2354. p.channels = { { 0, flp::ChannelType::sampler, "Kick", "", "", 1 } };
  2355. flp::Pattern empty;
  2356. empty.index = 1;
  2357. flp::Pattern full;
  2358. full.index = 2;
  2359. flp::Note n;
  2360. n.channel = 0;
  2361. full.notes.push_back (n);
  2362. p.patterns = { empty, full };
  2363. flp::Arrangement a;
  2364. flp::PlaylistItem item;
  2365. item.kind = flp::PlaylistItem::Kind::pattern;
  2366. item.index = 2;
  2367. item.position = 384;
  2368. item.length = 192;
  2369. item.track = 3;
  2370. item.patternStartTick = 96;
  2371. a.items.push_back (item);
  2372. item.index = 1; // empty pattern: discarded
  2373. a.items.push_back (item);
  2374. item.kind = flp::PlaylistItem::Kind::channelClip; // audio: not supported yet
  2375. a.items.push_back (item);
  2376. p.arrangements.push_back (a);
  2377. const auto s = lynx::importFlp (p);
  2378. CHECK (s.mode == lynx::PlayMode::song);
  2379. CHECK (s.playlist.size() == 1);
  2380. CHECK (s.playlist[0].pattern == 0 && s.playlist[0].track == 3);
  2381. CHECK (s.playlist[0].start == 4 * lynx::ppq && s.playlist[0].length == 2 * lynx::ppq && s.playlist[0].offset == lynx::ppq);
  2382. }
  2383. TEST (rack_releases_notes_on_position_jump)
  2384. {
  2385. lynx::Song s;
  2386. lynx::ChannelDef c;
  2387. c.instrument = lynx::InstrumentKind::synth;
  2388. s.channels.push_back (c);
  2389. auto& p = s.patterns.emplace_back();
  2390. lynx::Note n;
  2391. n.start = 0;
  2392. n.length = 4 * lynx::ppq; // long note
  2393. p.notes.push_back (n);
  2394. s.bpm = 120.0;
  2395. auto state = lynx::RackState::build (s, nullptr, 48000.0);
  2396. lynx::RackRenderer r;
  2397. r.prepare (48000.0);
  2398. std::vector<float> l (512), rr (512);
  2399. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  2400. double tick = 0.0;
  2401. for (int i = 0; i < 20; ++i, tick += 512 * tps)
  2402. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  2403. // jump to tick 2000 (mid-note, no new "on"): the synth must go silent
  2404. for (int i = 0; i < 40; ++i)
  2405. r.process (state.get(), true, 2000.0 + i * 512 * tps, 512, l.data(), rr.data());
  2406. float tail = 0.0f;
  2407. for (auto v : l)
  2408. tail = std::max (tail, std::abs (v));
  2409. CHECK (tail < 0.001f);
  2410. }
  2411. namespace
  2412. {
  2413. // Two samplers with a constant 0.5 signal on different inserts; returns the output peak.
  2414. float juce_db (float gain)
  2415. {
  2416. return 20.0f * std::log10 (gain);
  2417. }
  2418. float renderMixerCase (const std::function<void (lynx::Song&)>& tweak, lynx::MeterBank* meters = nullptr)
  2419. {
  2420. lynx::Song s;
  2421. s.mixer = lynx::Song::defaultMixer (4);
  2422. for (int i = 0; i < 2; ++i)
  2423. {
  2424. lynx::ChannelDef c;
  2425. c.instrument = lynx::InstrumentKind::sampler;
  2426. c.samplePath = "dc";
  2427. c.volume = 1.0f;
  2428. c.mixerTrack = i + 1;
  2429. s.channels.push_back (c);
  2430. }
  2431. s.patterns.emplace_back();
  2432. tweak (s);
  2433. auto provider = [] (const std::string&) {
  2434. auto d = std::make_shared<lynx::SampleData>();
  2435. d->left.assign (48000, 0.5f);
  2436. return std::shared_ptr<const lynx::SampleData> (d);
  2437. };
  2438. auto state = lynx::RackState::build (s, nullptr, 48000.0, provider);
  2439. lynx::RackRenderer r;
  2440. r.prepare (48000.0, 256);
  2441. lynx::LiveEventQueue live;
  2442. for (int ch = 0; ch < 2; ++ch)
  2443. {
  2444. lynx::NoteEvent on;
  2445. on.channel = ch;
  2446. on.velocity = 1.0f;
  2447. live.push (on);
  2448. }
  2449. std::vector<float> l (1000), rr (1000); // larger than the mixer block: tests the chunking
  2450. r.process (state.get(), false, 0.0, 1000, l.data(), rr.data(), &live, meters);
  2451. return std::max (std::abs (l[999]), std::abs (rr[999]));
  2452. }
  2453. } // namespace
  2454. TEST (mixer_routes_mutes_solos_and_meters)
  2455. {
  2456. // two 0.5 channels summed on the Master at 0 dB
  2457. CHECK (std::abs (renderMixerCase ([] (lynx::Song&) {}) - 1.0f) < 1e-4f);
  2458. // insert 1 muted: only channel 2 remains
  2459. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.mixer[1].muted = true; }) - 0.5f) < 1e-4f);
  2460. // solo on insert 2: same
  2461. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.mixer[2].solo = true; }) - 0.5f) < 1e-4f);
  2462. // FL fader curve: 0.8 = 0 dB, max ≈ +5.6 dB, half travel ≈ -12.7 dB
  2463. CHECK (std::abs (lynx::faderGain (0.8f) - 1.0f) < 1e-5f);
  2464. CHECK (std::abs (juce_db (lynx::faderGain (1.0f)) - 5.59f) < 0.05f);
  2465. CHECK (lynx::faderGain (0.0f) == 0.0f);
  2466. // Master fader at max
  2467. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.mixer[0].volume = 1.0f; }) - lynx::faderGain (1.0f)) < 1e-4f);
  2468. // both channels on the same insert, insert fader at 0.4
  2469. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) {
  2470. s.channels[1].mixerTrack = 1;
  2471. s.mixer[1].volume = 0.4f;
  2472. }) - lynx::faderGain (0.4f)) < 1e-4f);
  2473. // a route outside the mixer falls to the last existing insert, without crashing
  2474. CHECK (renderMixerCase ([] (lynx::Song& s) { s.channels[0].mixerTrack = 100; }) > 0.9f);
  2475. // no mixer: everything straight to the output at 0 dB
  2476. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.mixer.clear(); }) - 1.0f) < 1e-4f);
  2477. lynx::MeterBank meters;
  2478. renderMixerCase ([] (lynx::Song&) {}, &meters);
  2479. CHECK (std::abs (meters.takePeak (1, 0) - 0.5f) < 1e-4f);
  2480. CHECK (std::abs (meters.takePeak (0, 1) - 1.0f) < 1e-4f);
  2481. CHECK (meters.takePeak (1, 0) == 0.0f); // reading resets
  2482. CHECK (meters.takePeak (3, 0) == 0.0f); // insert with no channel
  2483. }
  2484. TEST (next_free_insert_and_flp_mixer_import)
  2485. {
  2486. auto s = lynx::Song::makeDefault();
  2487. CHECK (s.mixer.size() == 17 && s.mixer[0].name == "Master");
  2488. CHECK (s.nextFreeInsert() == 6); // the 5 default channels take 1..5
  2489. flp::Project p;
  2490. p.channels = { { 0, flp::ChannelType::sampler, "Kick", "", "", 30 } };
  2491. p.mixer = { { 0, "" }, { 30, "Drums" } };
  2492. const auto song = lynx::importFlp (p);
  2493. CHECK (song.channels[0].mixerTrack == 30);
  2494. CHECK (song.mixer.size() == 31);
  2495. CHECK (song.mixer[30].name == "Drums" && song.mixer[0].name == "Master");
  2496. }
  2497. namespace
  2498. {
  2499. float runEffectOnSine (lynx::EffectKind kind, const std::function<void (lynx::EffectSlot&)>& tweak, double hz, float amp,
  2500. int frames = 48000)
  2501. {
  2502. auto fx = lynx::makeEffect (kind);
  2503. fx->prepare (48000.0);
  2504. auto slot = lynx::makeEffectSlot (kind);
  2505. tweak (slot);
  2506. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  2507. for (int i = 0; i < frames; ++i)
  2508. l[(std::size_t) i] = r[(std::size_t) i] = amp * (float) std::sin (6.283185307 * hz * i / 48000.0);
  2509. for (int i = 0; i < frames; i += 480)
  2510. fx->process (l.data() + i, r.data() + i, std::min (480, frames - i), slot.params, 120.0);
  2511. float peak = 0.0f;
  2512. for (int i = frames / 2; i < frames; ++i) // second half: already settled
  2513. {
  2514. CHECK (std::isfinite (l[(std::size_t) i]));
  2515. peak = std::max (peak, std::abs (l[(std::size_t) i]));
  2516. }
  2517. return peak;
  2518. }
  2519. } // namespace
  2520. TEST (parametric_eq_bands_and_response)
  2521. {
  2522. // default: transparent
  2523. auto slot = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  2524. CHECK (std::abs (lynx::peq::responseDb (slot.params, 48000.0, 1000.0)) < 0.01);
  2525. CHECK (std::abs (runEffectOnSine (lynx::EffectKind::parametricEq, [] (auto&) {}, 1000.0, 0.5f) - 0.5f) < 0.005f);
  2526. // +12 dB peak at 1 kHz on band 4: the response and the signal agree
  2527. auto boost = [] (lynx::EffectSlot& s) {
  2528. s.params[(std::size_t) lynx::peq::param (3, 1)] = lynx::peq::hzValue (1000.0);
  2529. s.params[(std::size_t) lynx::peq::param (3, 2)] = lynx::peq::gainValue (12.0);
  2530. };
  2531. boost (slot);
  2532. CHECK (std::abs (lynx::peq::responseDb (slot.params, 48000.0, 1000.0) - 12.0) < 0.2);
  2533. CHECK (std::abs (lynx::peq::responseDb (slot.params, 48000.0, 100.0)) < 1.0);
  2534. const auto peak = runEffectOnSine (lynx::EffectKind::parametricEq, boost, 1000.0, 0.1f);
  2535. CHECK (std::abs (peak - 0.1f * std::pow (10.0f, 12.0f / 20.0f)) < 0.01f);
  2536. // low cut at 48 dB/oct at 200 Hz: 50 Hz (2 octaves below) drops ~96 dB; 2 kHz passes
  2537. auto cut = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  2538. cut.params[(std::size_t) lynx::peq::param (0, 0)] = lynx::peq::typeValue (lynx::peq::BandType::lowCut);
  2539. cut.params[(std::size_t) lynx::peq::param (0, 1)] = lynx::peq::hzValue (200.0);
  2540. cut.params[(std::size_t) lynx::peq::param (0, 3)] = lynx::peq::qValue (0.70710678); // Butterworth
  2541. cut.params[(std::size_t) (lynx::peq::slopeParam + 0)] = 1.0f;
  2542. CHECK (lynx::peq::responseDb (cut.params, 48000.0, 50.0) < -80.0);
  2543. CHECK (std::abs (lynx::peq::responseDb (cut.params, 48000.0, 200.0) + 3.0) < 0.5); // -3 dB at the cutoff (Butterworth)
  2544. CHECK (std::abs (lynx::peq::responseDb (cut.params, 48000.0, 2000.0)) < 0.1);
  2545. // round-trip conversions
  2546. CHECK (std::abs (lynx::peq::hz (lynx::peq::hzValue (440.0)) - 440.0) < 0.5);
  2547. CHECK (std::abs (lynx::peq::q (lynx::peq::qValue (2.5)) - 2.5) < 0.01);
  2548. CHECK (lynx::peq::type (lynx::peq::typeValue (lynx::peq::BandType::notch)) == lynx::peq::BandType::notch);
  2549. }
  2550. TEST (fl_parametric_eq2_state_maps_to_bands)
  2551. {
  2552. // v8 blob: band 1 low cut at 100 Hz "Steep 8", band 4 peak +6 dB at 1 kHz, output −3 dB
  2553. std::vector<std::uint8_t> blob (354, 0);
  2554. auto put = [&] (std::size_t off, std::int32_t v) { std::memcpy (blob.data() + off, &v, 4); };
  2555. put (0, 8);
  2556. auto param = [&] (int i, std::int32_t v) { put (4 + 4 * (std::size_t) i, v); };
  2557. auto hzRaw = [] (double hz) { return (std::int32_t) std::lround (std::log (hz / 20.0) / std::log (1000.0) * 65536.0); };
  2558. for (int b = 0; b < 7; ++b)
  2559. param (21 + b, 0); // all off
  2560. param (21 + 0, 3); // high pass (= low cut)
  2561. param (7 + 0, hzRaw (100.0));
  2562. param (14 + 0, 40124); // default width -> Q ~0.68
  2563. param (28 + 0, -3); // Steep 8 -> 4 biquads
  2564. param (21 + 3, 6); // peaking
  2565. param (7 + 3, hzRaw (1000.0));
  2566. param (3, 600); // +6 dB
  2567. param (14 + 3, 25412);
  2568. param (35, -300); // main level −3 dB
  2569. put (0x13E, 0x7F);
  2570. const auto slot = lynx::effectFromFl ("Fruity Parametric EQ 2", blob);
  2571. CHECK (slot.has_value() && slot->kind == lynx::EffectKind::parametricEq);
  2572. const auto& p = slot->params;
  2573. CHECK (lynx::peq::type (p[(std::size_t) lynx::peq::param (0, 0)]) == lynx::peq::BandType::lowCut);
  2574. CHECK (lynx::peq::slopeStages (p[(std::size_t) lynx::peq::slopeParam]) == 4);
  2575. CHECK (lynx::peq::type (p[(std::size_t) lynx::peq::param (3, 0)]) == lynx::peq::BandType::peak);
  2576. CHECK (lynx::peq::type (p[(std::size_t) lynx::peq::param (1, 0)]) == lynx::peq::BandType::off);
  2577. CHECK (std::abs (lynx::peq::responseDb (p, 48000.0, 1000.0) - 3.0) < 0.3); // +6 from the peak −3 from the output
  2578. CHECK (lynx::peq::responseDb (p, 48000.0, 30.0) < -40.0); // 48 dB/oct below 100 Hz
  2579. CHECK (std::abs (lynx::peq::responseDb (p, 48000.0, 8000.0) + 3.0) < 0.3);
  2580. // a band muted by the mask doesn't sound
  2581. put (0x13E, 0x7F & ~(1 << 3));
  2582. const auto muted = lynx::effectFromFl ("Fruity Parametric EQ 2", blob);
  2583. CHECK (lynx::peq::type (muted->params[(std::size_t) lynx::peq::param (3, 0)]) == lynx::peq::BandType::off);
  2584. }
  2585. TEST (reverb_low_cut_and_predelay)
  2586. {
  2587. // impulse: with 100 ms predelay the wet only starts later; with a 3 kHz low cut a
  2588. // 100 Hz sine barely enters the reverb
  2589. auto run = [] (const std::function<void (lynx::EffectSlot&)>& tweak, double hz, bool impulse) {
  2590. auto fx = lynx::makeEffect (lynx::EffectKind::reverb);
  2591. fx->prepare (48000.0);
  2592. auto slot = lynx::makeEffectSlot (lynx::EffectKind::reverb);
  2593. slot.params[4] = 0.0f; // wet only
  2594. slot.params[3] = 1.0f;
  2595. tweak (slot);
  2596. std::vector<float> l (48000), r (48000);
  2597. for (int i = 0; i < 48000; ++i)
  2598. 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);
  2599. for (int i = 0; i < 48000; i += 480)
  2600. fx->process (l.data() + i, r.data() + i, 480, slot.params, 120.0);
  2601. return l;
  2602. };
  2603. const auto delayed = run ([] (auto& s) { s.params[7] = 0.1f; }, 0.0, true);
  2604. float early = 0.0f, later = 0.0f;
  2605. for (std::size_t i = 0; i < 4800; ++i)
  2606. early = std::max (early, std::abs (delayed[i]));
  2607. for (std::size_t i = 4800; i < 24000; ++i)
  2608. later = std::max (later, std::abs (delayed[i]));
  2609. CHECK (early == 0.0f && later > 0.0f);
  2610. 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; };
  2611. const auto open = energy (run ([] (auto&) {}, 100.0, false));
  2612. const auto cut = energy (run ([] (auto& s) { s.params[5] = 1.0f; }, 100.0, false));
  2613. CHECK (cut < open * 0.01);
  2614. }
  2615. TEST (utility_effect_and_fl_stereo_tools)
  2616. {
  2617. // transparent by default; balance fully right silences the left
  2618. CHECK (std::abs (runEffectOnSine (lynx::EffectKind::utility, [] (auto&) {}, 440.0, 0.5f) - 0.5f) < 0.001f);
  2619. CHECK (runEffectOnSine (lynx::EffectKind::utility, [] (auto& s) { s.params[1] = 1.0f; }, 440.0, 0.5f) < 0.001f);
  2620. // Stereo Shaper in "mono": each output = 0.5 L + 0.5 R
  2621. std::vector<std::uint8_t> blob (36, 0);
  2622. auto put = [&] (std::size_t off, std::int32_t v) { std::memcpy (blob.data() + off, &v, 4); };
  2623. put (4, 6400); put (8, 6400); put (12, 6400); put (16, 6400);
  2624. const auto slot = lynx::effectFromFl ("Fruity Stereo Shaper", blob);
  2625. CHECK (slot && slot->kind == lynx::EffectKind::utility);
  2626. auto fx = lynx::makeEffect (lynx::EffectKind::utility);
  2627. float l = 1.0f, r = 0.0f;
  2628. fx->process (&l, &r, 1, slot->params, 120.0);
  2629. CHECK (std::abs (l - 0.5f) < 1e-4f && std::abs (r - 0.5f) < 1e-4f);
  2630. // Balance: volume 256 = 0 dB, pan −128 = fully left
  2631. std::vector<std::uint8_t> bal (8, 0);
  2632. std::int32_t pan = -128, vol = 256;
  2633. std::memcpy (bal.data(), &pan, 4);
  2634. std::memcpy (bal.data() + 4, &vol, 4);
  2635. const auto b = lynx::effectFromFl ("Fruity Balance", bal);
  2636. l = 0.5f; r = 0.5f;
  2637. fx->process (&l, &r, 1, b->params, 120.0);
  2638. CHECK (std::abs (l - 0.5f) < 1e-3f && std::abs (r) < 1e-4f);
  2639. }
  2640. TEST (effects_eq_compressor_behave)
  2641. {
  2642. // EQ at default is transparent
  2643. CHECK (std::abs (runEffectOnSine (lynx::EffectKind::eq, [] (auto&) {}, 1000.0, 0.5f) - 0.5f) < 0.01f);
  2644. // +18 dB on the lows: 60 Hz rises a lot, 5 kHz barely
  2645. CHECK (runEffectOnSine (lynx::EffectKind::eq, [] (auto& s) { s.params[0] = 1.0f; }, 60.0, 0.05f) > 0.3f);
  2646. CHECK (runEffectOnSine (lynx::EffectKind::eq, [] (auto& s) { s.params[0] = 1.0f; }, 5000.0, 0.05f) < 0.06f);
  2647. // compressor: threshold -20 dB, ratio 20:1 flattens a 0 dBFS signal to near the threshold
  2648. const auto squashed = runEffectOnSine (lynx::EffectKind::compressor, [] (auto& s) {
  2649. s.params[0] = 40.0f / 60.0f;
  2650. s.params[1] = 1.0f;
  2651. }, 200.0, 1.0f);
  2652. CHECK (squashed < 0.2f && squashed > 0.05f);
  2653. // a signal below the threshold passes intact
  2654. CHECK (std::abs (runEffectOnSine (lynx::EffectKind::compressor, [] (auto& s) { s.params[0] = 1.0f; }, 200.0, 0.3f) - 0.3f) < 0.01f);
  2655. }
  2656. TEST (effects_delay_echoes_on_tempo_and_reverb_has_tail)
  2657. {
  2658. auto delay = lynx::makeEffect (lynx::EffectKind::delay);
  2659. delay->prepare (48000.0);
  2660. auto slot = lynx::makeEffectSlot (lynx::EffectKind::delay);
  2661. slot.params[0] = 3.5f / 8.0f; // index 3 = 1/4 = 0.5 s at 120 BPM
  2662. slot.params[1] = 0.0f; // no feedback: a single echo
  2663. slot.params[2] = 1.0f;
  2664. slot.params[4] = 0.0f; // no damping
  2665. std::vector<float> l (48000, 0.0f), r (48000, 0.0f);
  2666. l[0] = r[0] = 1.0f;
  2667. delay->process (l.data(), r.data(), 48000, slot.params, 120.0);
  2668. CHECK (std::abs (l[24000] - 1.0f) < 1e-4f);
  2669. CHECK (std::abs (l[12000]) < 1e-6f);
  2670. auto reverb = lynx::makeEffect (lynx::EffectKind::reverb);
  2671. reverb->prepare (48000.0);
  2672. auto rs = lynx::makeEffectSlot (lynx::EffectKind::reverb);
  2673. rs.params[3] = 1.0f;
  2674. std::fill (l.begin(), l.end(), 0.0f);
  2675. std::fill (r.begin(), r.end(), 0.0f);
  2676. l[0] = r[0] = 1.0f;
  2677. reverb->process (l.data(), r.data(), 48000, rs.params, 120.0);
  2678. float tail = 0.0f;
  2679. for (int i = 4800; i < 9600; ++i) // between 100 and 200 ms after the impulse
  2680. tail = std::max (tail, std::abs (l[(std::size_t) i]));
  2681. CHECK (tail > 1e-4f && tail < 1.0f);
  2682. CHECK (lynx::formatEffectParam (lynx::EffectKind::delay, 0, slot.params[0], 120.0) == "1/4 (500 ms)");
  2683. }
  2684. TEST (rack_runs_insert_effects_and_reuses_them)
  2685. {
  2686. // an insert with EQ at -inf doesn't exist; we use the EQ output at -18 dB to see the effect act
  2687. const auto quiet = renderMixerCase ([] (lynx::Song& s) {
  2688. auto eq = lynx::makeEffectSlot (lynx::EffectKind::eq);
  2689. eq.params[4] = 0.0f; // output -18 dB
  2690. s.mixer[1].effects.push_back (eq);
  2691. });
  2692. CHECK (quiet > 0.55f && quiet < 0.6f); // 0.5 from channel 2 + 0.5 * 0.126 from channel 1
  2693. const auto bypassed = renderMixerCase ([] (lynx::Song& s) {
  2694. auto eq = lynx::makeEffectSlot (lynx::EffectKind::eq);
  2695. eq.params[4] = 0.0f;
  2696. eq.enabled = false;
  2697. s.mixer[1].effects.push_back (eq);
  2698. });
  2699. CHECK (std::abs (bypassed - 1.0f) < 1e-4f);
  2700. auto s = lynx::Song::makeDefault();
  2701. s.mixer[2].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::reverb));
  2702. auto a = lynx::RackState::build (s, nullptr, 48000.0);
  2703. s.mixer[2].effects[0].params[0] = 0.9f; // turning a knob doesn't recreate the effect
  2704. auto b = lynx::RackState::build (s, a.get(), 48000.0);
  2705. CHECK (b->effects[2][0] == a->effects[2][0]);
  2706. s.mixer[2].effects[0] = lynx::makeEffectSlot (lynx::EffectKind::delay);
  2707. auto c = lynx::RackState::build (s, b.get(), 48000.0);
  2708. CHECK (c->effects[2][0] != b->effects[2][0]);
  2709. }
  2710. TEST (audio_clips_trigger_cut_and_resume)
  2711. {
  2712. lynx::Song s;
  2713. s.bpm = 120.0; // 1 beat = 0.5 s = 24000 samples at 48 kHz
  2714. lynx::ChannelDef c;
  2715. c.instrument = lynx::InstrumentKind::audioClip;
  2716. c.samplePath = "ramp";
  2717. c.volume = 1.0f;
  2718. s.channels.push_back (c);
  2719. s.patterns.emplace_back();
  2720. lynx::Clip clip;
  2721. clip.kind = lynx::ClipKind::audio;
  2722. clip.channel = 0;
  2723. clip.start = lynx::ppq; // starts at beat 2
  2724. clip.length = 2 * lynx::ppq; // lasts 2 beats
  2725. clip.offset = lynx::ppq; // skips the first beat of the audio
  2726. s.playlist.push_back (clip);
  2727. s.mode = lynx::PlayMode::song;
  2728. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  2729. lynx::EventBuffer ev;
  2730. lynx::scheduleSong (s, 0.0, 4 * 24000, tps, ev);
  2731. CHECK (ev.size() == 2);
  2732. CHECK (ev[0].type == lynx::NoteEvent::Type::on && ev[0].sampleOffset == 24000 && std::abs (ev[0].startSeconds - 0.5) < 1e-9);
  2733. CHECK (ev[1].type == lynx::NoteEvent::Type::off && ev[1].sampleOffset == 3 * 24000);
  2734. // seek to the middle of the clip (beat 2.5): with resume, starts at the block's first sample
  2735. ev.clear();
  2736. lynx::scheduleSong (s, 1.5 * lynx::ppq, 256, tps, ev, true);
  2737. CHECK (ev.size() == 1 && ev[0].sampleOffset == 0 && std::abs (ev[0].startSeconds - 0.75) < 1e-9);
  2738. ev.clear();
  2739. lynx::scheduleSong (s, 1.5 * lynx::ppq, 256, tps, ev, false);
  2740. CHECK (ev.size() == 0);
  2741. // sample whose value = position in seconds: lets us check where playback started
  2742. auto provider = [] (const std::string&) {
  2743. auto d = std::make_shared<lynx::SampleData>();
  2744. d->sampleRate = 48000.0;
  2745. for (int i = 0; i < 48000 * 3; ++i)
  2746. d->left.push_back ((float) i / 48000.0f);
  2747. return std::shared_ptr<const lynx::SampleData> (d);
  2748. };
  2749. auto state = lynx::RackState::build (s, nullptr, 48000.0, provider);
  2750. lynx::RackRenderer r;
  2751. r.prepare (48000.0, 512);
  2752. std::vector<float> l (256), rr (256);
  2753. // first block already playing mid-clip
  2754. r.process (state.get(), true, 1.5 * lynx::ppq, 256, l.data(), rr.data());
  2755. CHECK (std::abs (l[0] - 0.75f) < 0.001f);
  2756. // the clip ends at beat 3: after the short fade, silence (the sample would still have audio)
  2757. double tick = 3.0 * lynx::ppq - 10 * tps;
  2758. r.process (state.get(), false, tick, 256, l.data(), rr.data()); // stops (fade)
  2759. for (int i = 0; i < 4; ++i)
  2760. r.process (state.get(), false, tick, 256, l.data(), rr.data());
  2761. CHECK (std::abs (l[255]) < 1e-6f);
  2762. }
  2763. TEST (remove_channel_fixes_notes_and_audio_clips)
  2764. {
  2765. lynx::Song s;
  2766. s.channels.resize (3);
  2767. s.patterns.resize (1);
  2768. s.patterns[0].notes = { { 0, 240, 0, 60, 1.0f }, { 0, 240, 1, 60, 1.0f }, { 0, 240, 2, 60, 1.0f } };
  2769. lynx::Clip a;
  2770. a.kind = lynx::ClipKind::audio;
  2771. a.channel = 1;
  2772. a.length = 100;
  2773. lynx::Clip b = a;
  2774. b.channel = 2;
  2775. s.playlist = { a, b };
  2776. s.removeChannel (1);
  2777. CHECK (s.channels.size() == 2);
  2778. CHECK (s.patterns[0].notes.size() == 2 && s.patterns[0].notes[1].channel == 1);
  2779. CHECK (s.playlist.size() == 1 && s.playlist[0].channel == 1);
  2780. }
  2781. TEST (flp_import_audio_clips_with_offsets)
  2782. {
  2783. flp::Project p;
  2784. p.header.ppq = 96;
  2785. p.tempo = 120.0;
  2786. p.channels = { { 0, flp::ChannelType::audioClip, "Vocal", "", "%FLStudioData%\\v.wav", 2 },
  2787. { 1, flp::ChannelType::audioClip, "Loop", "", "%FLStudioData%\\l.wav", 3 } };
  2788. flp::Arrangement arr;
  2789. flp::PlaylistItem beats; // offset in beats: end - start = duration in beats
  2790. beats.kind = flp::PlaylistItem::Kind::channelClip;
  2791. beats.index = 0;
  2792. beats.position = 192;
  2793. beats.length = 384; // 4 beats
  2794. beats.startOffset = 2.0f;
  2795. beats.endOffset = 6.0f;
  2796. flp::PlaylistItem ms = beats; // offset in ms: 4 beats at 120 BPM = 2000 ms
  2797. ms.index = 1;
  2798. ms.startOffset = 500.0f;
  2799. ms.endOffset = 2500.0f;
  2800. arr.items = { beats, ms };
  2801. p.arrangements.push_back (arr);
  2802. lynx::FlpImportOptions options;
  2803. options.roots = { "C:\\FL", "C:\\FL\\Data", "" };
  2804. options.fileExists = [] (const std::string&) { return true; };
  2805. const auto s = lynx::importFlp (p, options);
  2806. CHECK (s.channels.size() == 2 && s.channels[0].instrument == lynx::InstrumentKind::audioClip);
  2807. CHECK (s.channels[0].samplePath == "C:\\FL\\Data\\v.wav");
  2808. CHECK (s.playlist.size() == 2);
  2809. CHECK (s.playlist[0].kind == lynx::ClipKind::audio && s.playlist[0].start == 2 * lynx::ppq);
  2810. CHECK (s.playlist[0].offset == 2 * lynx::ppq);
  2811. CHECK (s.playlist[1].offset == lynx::ppq); // 500 ms at 120 BPM = 1 beat
  2812. CHECK (s.mode == lynx::PlayMode::song);
  2813. }
  2814. TEST (plugin_factories_create_reuse_and_fallback)
  2815. {
  2816. lynx::Song s;
  2817. s.mixer = lynx::Song::defaultMixer (2);
  2818. lynx::ChannelDef c;
  2819. c.instrument = lynx::InstrumentKind::plugin;
  2820. c.plugin.id = "VST3-Synth-123";
  2821. c.mixerTrack = 1;
  2822. s.channels.push_back (c);
  2823. lynx::ChannelDef missing = c;
  2824. missing.plugin.id = "VST3-Ausente-0";
  2825. s.channels.push_back (missing);
  2826. lynx::EffectSlot fx;
  2827. fx.kind = lynx::EffectKind::plugin;
  2828. fx.plugin.id = "VST3-Reverb-9";
  2829. s.mixer[1].effects.push_back (fx);
  2830. s.patterns.emplace_back();
  2831. int instrumentsMade = 0, effectsMade = 0;
  2832. lynx::RackState::Factories f;
  2833. f.pluginInstruments = [&] (const lynx::PluginRef& ref, double) -> std::shared_ptr<lynx::Instrument> {
  2834. if (ref.id != "VST3-Synth-123")
  2835. return nullptr;
  2836. ++instrumentsMade;
  2837. auto synth = lynx::makeInstrument (lynx::InstrumentKind::synth);
  2838. synth->prepare (48000.0);
  2839. return synth;
  2840. };
  2841. f.pluginEffects = [&] (const lynx::PluginRef&, double) -> std::shared_ptr<lynx::Effect> {
  2842. ++effectsMade;
  2843. auto eq = lynx::makeEffect (lynx::EffectKind::eq);
  2844. eq->prepare (48000.0);
  2845. return eq;
  2846. };
  2847. auto a = lynx::RackState::build (s, nullptr, 48000.0, f);
  2848. CHECK (instrumentsMade == 1 && effectsMade == 1);
  2849. CHECK (a->instruments.size() == 2 && a->instruments[1] != nullptr); // missing: muted, but it exists
  2850. // changing the saved state doesn't recreate; swapping the plugin does
  2851. s.channels[0].plugin.state = "abc";
  2852. auto b = lynx::RackState::build (s, a.get(), 48000.0, f);
  2853. CHECK (instrumentsMade == 1 && b->instruments[0] == a->instruments[0] && b->effects[1][0] == a->effects[1][0]);
  2854. s.mixer[1].effects[0].plugin.id = "VST3-Outro-1";
  2855. auto c2 = lynx::RackState::build (s, b.get(), 48000.0, f);
  2856. CHECK (effectsMade == 2);
  2857. // rendering with a missing plugin and a plugin slot breaks nothing
  2858. lynx::RackRenderer r;
  2859. r.prepare (48000.0, 256);
  2860. lynx::LiveEventQueue live;
  2861. lynx::NoteEvent on;
  2862. on.channel = 0;
  2863. on.velocity = 1.0f;
  2864. live.push (on);
  2865. on.channel = 1;
  2866. live.push (on);
  2867. std::vector<float> l (256), rr (256);
  2868. r.process (c2.get(), false, 0.0, 256, l.data(), rr.data(), &live);
  2869. float peak = 0.0f;
  2870. for (auto v : l)
  2871. {
  2872. CHECK (std::isfinite (v));
  2873. peak = std::max (peak, std::abs (v));
  2874. }
  2875. CHECK (peak > 0.0f);
  2876. }
  2877. TEST (export_song_adds_silent_tail_and_never_restarts)
  2878. {
  2879. auto s = lynx::Song::makeDefault();
  2880. s.playlist.clear();
  2881. std::int64_t length = 0;
  2882. auto pat = lynx::makeExportSong (s, true, lynx::ppq * 8, length); // empty Playlist: uses the pattern
  2883. CHECK (length == lynx::ppq * 4);
  2884. CHECK (pat.mode == lynx::PlayMode::song && pat.playlist.size() == 2);
  2885. CHECK (pat.songLength() >= length + lynx::ppq * 8);
  2886. // no new notes after the song ends, only silence until the end of the tail
  2887. lynx::EventBuffer events;
  2888. const auto tps = lynx::ticksPerSample (pat.bpm, 48000.0);
  2889. int onsAfterEnd = 0, onsBefore = 0;
  2890. for (double tick = 0.0; tick < (double) (length + lynx::ppq * 8); tick += 512 * tps)
  2891. {
  2892. events.clear();
  2893. lynx::scheduleSong (pat, tick, 512, tps, events);
  2894. for (const auto& e : events)
  2895. if (e.type == lynx::NoteEvent::Type::on)
  2896. (tick + e.sampleOffset * tps >= (double) length ? onsAfterEnd : onsBefore)++;
  2897. }
  2898. CHECK (onsBefore == (int) s.patterns[0].notes.size());
  2899. CHECK (onsAfterEnd == 0);
  2900. // with Playlist: the end is the last clip's, without rounding
  2901. s.playlist.push_back ({ 0, 0, lynx::ppq * 2, lynx::ppq * 3, 0 });
  2902. auto song = lynx::makeExportSong (s, true, 0, length);
  2903. CHECK (length == lynx::ppq * 5 && song.playlist.size() == 1);
  2904. song = lynx::makeExportSong (s, false, 0, length);
  2905. CHECK (length == lynx::ppq * 4 && song.playlist[0].start == 0);
  2906. }
  2907. TEST (note_edit_selection_operations)
  2908. {
  2909. namespace ne = lynx::noteedit;
  2910. lynx::Pattern p;
  2911. p.notes = { { 0, 240, 0, 60 }, { 480, 240, 0, 64 }, { 960, 480, 1, 67 } };
  2912. // sorting keeps the indices in step
  2913. p.notes[0].start = 1200;
  2914. std::vector<int> tracked { 0, 2 };
  2915. ne::sortTracking (p, tracked);
  2916. CHECK (p.notes[2].start == 1200 && p.notes[(std::size_t) tracked[0]].start == 1200);
  2917. CHECK (p.notes[(std::size_t) tracked[1]].key == 67);
  2918. // group move respects the limits
  2919. std::int64_t dt = -5000;
  2920. int dk = 100;
  2921. ne::move (p, { 0, 1 }, dt, dk);
  2922. CHECK (dt == -480 && dk == 127 - 67 && p.notes[0].start == 0 && p.notes[1].key == 127);
  2923. // duplicate: right after the selection, rounded to the grid
  2924. lynx::Pattern q;
  2925. q.notes = { { 0, 240, 0, 60 }, { 240, 300, 0, 62 } }; // 540-tick selection
  2926. const auto added = ne::duplicate (q, { 0, 1 }, 960);
  2927. CHECK (added.size() == 2 && q.notes[(std::size_t) added[0]].start == 960 && q.notes[(std::size_t) added[1]].start == 1200);
  2928. // paste onto another channel with an offset
  2929. const auto pasted = ne::paste (q, ne::copy (q, { 1 }), 100, 3);
  2930. CHECK (pasted.size() == 1 && q.notes.back().channel == 3 && q.notes.back().start == 340);
  2931. // quantize rounds to the nearest
  2932. q.notes[0].start = 130;
  2933. q.notes[1].start = 100;
  2934. ne::quantize (q, { 0, 1 }, 240);
  2935. CHECK (q.notes[0].start == 240 && q.notes[1].start == 0);
  2936. // remove several (order and duplicates don't matter)
  2937. const auto before = q.notes.size();
  2938. ne::remove (q, { 1, 0, 1 });
  2939. CHECK (q.notes.size() == before - 2);
  2940. }
  2941. TEST (recorder_builds_notes_in_pattern_and_song_mode)
  2942. {
  2943. auto song = lynx::Song::makeDefault();
  2944. const auto loop = song.patterns[0].effectiveLength (4); // 1 bar = 3840
  2945. lynx::NoteRecorder r;
  2946. r.add (song, { 100.0, 4, 60, 0.5f, true }); // no take: ignored
  2947. CHECK (r.takeFinished().empty());
  2948. r.begin (loop);
  2949. r.add (song, { 4000.0, 4, 60, 0.5f, true }); // second loop pass
  2950. r.add (song, { 4480.0, 4, 60, 0.0f, false });
  2951. r.add (song, { 5000.0, 4, 64, 0.9f, true }); // held until stop
  2952. r.end (song, 5240.0);
  2953. const auto notes = r.takeFinished();
  2954. CHECK (notes.size() == 2);
  2955. CHECK (notes[0].start == 4000 - 3840 && notes[0].length == 480 && notes[0].velocity == 0.5f && notes[0].channel == 4);
  2956. CHECK (notes[1].key == 64 && notes[1].start == 5000 - 3840 && notes[1].length == 240);
  2957. // song mode: position inside the current pattern's clip (with offset)
  2958. song.mode = lynx::PlayMode::song;
  2959. song.playlist = { { 0, 0, 7680, 3840, 960 } };
  2960. CHECK (lynx::patternPositionForTick (song, 7680.0 + 100.0, loop) == 1060);
  2961. CHECK (lynx::patternPositionForTick (song, 100.0, loop) == 100); // outside the clip: like loop
  2962. }
  2963. TEST (automation_curve_and_playback)
  2964. {
  2965. lynx::Automation a;
  2966. a.points = { { 0, 0.0f }, { 960, 1.0f }, { 1920, 0.5f, 0.0f } };
  2967. CHECK (a.valueAt (-10.0) == 0.0f && a.valueAt (480.0) == 0.5f && a.valueAt (5000.0) == 0.5f);
  2968. CHECK (a.length() == 1920);
  2969. a.points[0].tension = 1.0f; // curve: starts slow
  2970. CHECK (a.valueAt (480.0) < 0.2f && a.valueAt (480.0) > 0.0f);
  2971. // automated Master: silence in the first bar, sound in the second, and the last value
  2972. // keeps applying after the automation clip ends
  2973. auto song = lynx::Song::makeDefault();
  2974. song.bpm = 120.0;
  2975. song.mode = lynx::PlayMode::song;
  2976. const auto bar = (std::int64_t) lynx::ppq * 4;
  2977. for (int b = 0; b < 3; ++b)
  2978. song.playlist.push_back ({ 0, 0, bar * b, bar, 0 });
  2979. lynx::Automation master;
  2980. master.target = { lynx::AutomationTargetKind::mixerVolume, 0 };
  2981. master.points = { { 0, 0.0f }, { bar - 1, 0.0f }, { bar, 0.8f } };
  2982. song.automations.push_back (master);
  2983. lynx::Clip ac;
  2984. ac.kind = lynx::ClipKind::automation;
  2985. ac.automation = 0;
  2986. ac.track = 1;
  2987. ac.length = bar + bar / 2;
  2988. song.playlist.push_back (ac);
  2989. const double sr = 48000.0;
  2990. auto state = lynx::RackState::build (song, nullptr, sr);
  2991. CHECK (state->hasAutomation && state->mixerVolumeAuto[0] == 0 && state->automationClips[0].size() == 1);
  2992. lynx::RackRenderer r;
  2993. r.prepare (sr, 512);
  2994. std::vector<float> l (512), rr (512);
  2995. const auto tps = lynx::ticksPerSample (song.bpm, sr);
  2996. float peakBar1 = 0.0f, peakBar2 = 0.0f, peakBar3 = 0.0f;
  2997. for (double tick = 0.0; tick < (double) (bar * 3); tick += 512 * tps)
  2998. {
  2999. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  3000. auto& peak = tick < (double) bar - 512 * tps ? peakBar1 : tick < (double) bar * 2 ? peakBar2 : peakBar3;
  3001. for (auto v : l)
  3002. peak = std::max (peak, std::abs (v));
  3003. }
  3004. CHECK (peakBar1 < 1.0e-6f);
  3005. CHECK (peakBar2 > 0.05f);
  3006. CHECK (peakBar3 > 0.05f); // after the clip: keeps the last value
  3007. // target removed: automation disappears from the tables
  3008. song.removeChannel (0);
  3009. song.automations[0].target = { lynx::AutomationTargetKind::channelVolume, 0 };
  3010. song.removeChannel (0);
  3011. CHECK (song.automations[0].target.kind == lynx::AutomationTargetKind::none);
  3012. song.removeAutomation (0);
  3013. CHECK (song.automations.empty() && song.playlist.size() == 3);
  3014. }
  3015. TEST (mixer_sends_between_inserts)
  3016. {
  3017. // insert 1 goes only to 3; 3 goes to the Master: same sum (0.5 + 0.5)
  3018. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.setRoute (1, 3, true); s.setRoute (1, 0, false); }) - 1.0f) < 1e-4f);
  3019. // send at 50% and muted destination
  3020. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.setRoute (1, 3, true, 0.5f); s.setRoute (1, 0, false); }) - 0.75f) < 1e-4f);
  3021. 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);
  3022. // going to the Master and to 3: the signal doubles
  3023. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.setRoute (1, 3, true); }) - 1.5f) < 1e-4f);
  3024. // solo on 3 lets what reaches it sound (insert 1), but not 2
  3025. 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);
  3026. // solo on 1 lets the path to the Master (3) sound
  3027. 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);
  3028. // order and cycles
  3029. auto song = lynx::Song::makeDefault();
  3030. song.setRoute (4, 2, true);
  3031. song.setRoute (2, 1, true);
  3032. CHECK (! song.canRoute (1, 4) && ! song.canRoute (1, 2) && song.canRoute (1, 5));
  3033. song.setRoute (1, 4, true); // ignored: would create a cycle
  3034. CHECK (! song.routes (1, 4));
  3035. const auto order = song.mixerOrder();
  3036. const auto pos = [&] (int t) { return std::find (order.begin(), order.end(), t) - order.begin(); };
  3037. CHECK ((int) order.size() == (int) song.mixer.size() - 1);
  3038. CHECK (pos (4) < pos (2) && pos (2) < pos (1));
  3039. song.setRoute (4, 2, false);
  3040. CHECK (! song.routes (4, 2) && song.routes (4, 0));
  3041. }
  3042. namespace
  3043. {
  3044. // Test effect: delays the signal by `latency` samples and reports that latency (like a lookahead plugin).
  3045. class LatentEffect final : public lynx::Effect
  3046. {
  3047. public:
  3048. explicit LatentEffect (int samples) : latency (samples), line (samples) {}
  3049. void prepare (double) noexcept override {}
  3050. void reset() noexcept override {}
  3051. void process (float* l, float* r, int n, const lynx::EffectParams&, double) noexcept override { line.process (l, r, n); }
  3052. int latencySamples() const noexcept override { return latency; }
  3053. private:
  3054. int latency;
  3055. lynx::DelayLine line;
  3056. };
  3057. } // namespace
  3058. TEST (delay_line_mix_into_matches_process_and_drains_tail)
  3059. {
  3060. // mixInto = process over source*level, added to the destination; in stretches that cross the ring
  3061. lynx::DelayLine a (37), b (37);
  3062. std::vector<float> sl (300), sr (300), dl (300, 0.5f), dr (300, -0.5f), xl (300), xr (300);
  3063. for (int i = 0; i < 300; ++i)
  3064. {
  3065. sl[(std::size_t) i] = (float) std::sin (i * 0.1);
  3066. sr[(std::size_t) i] = (float) std::cos (i * 0.07);
  3067. }
  3068. for (int start = 0; start < 300; start += 100)
  3069. {
  3070. b.mixInto (sl.data() + start, sr.data() + start, 0.25f, dl.data() + start, dr.data() + start, 100);
  3071. for (int i = start; i < start + 100; ++i)
  3072. {
  3073. xl[(std::size_t) i] = sl[(std::size_t) i] * 0.25f;
  3074. xr[(std::size_t) i] = sr[(std::size_t) i] * 0.25f;
  3075. }
  3076. a.process (xl.data() + start, xr.data() + start, 100);
  3077. }
  3078. float worst = 0.0f;
  3079. for (int i = 0; i < 300; ++i)
  3080. worst = std::max ({ worst, std::abs (dl[(std::size_t) i] - 0.5f - xl[(std::size_t) i]),
  3081. std::abs (dr[(std::size_t) i] + 0.5f - xr[(std::size_t) i]) });
  3082. CHECK (worst < 1e-6f);
  3083. // silenced source: the tail still in the line comes out, then nothing remains
  3084. std::vector<float> tl (64, 0.0f), tr (64, 0.0f);
  3085. b.mixInto (nullptr, nullptr, 1.0f, tl.data(), tr.data(), 64);
  3086. CHECK (std::abs (tl[0] - sl[263] * 0.25f) < 1e-6f);
  3087. std::vector<float> zl (64, 0.0f), zr (64, 0.0f);
  3088. b.mixInto (nullptr, nullptr, 1.0f, zl.data(), zr.data(), 64);
  3089. CHECK (*std::max_element (zl.begin(), zl.end()) == 0.0f && *std::min_element (zl.begin(), zl.end()) == 0.0f);
  3090. }
  3091. TEST (limiter_lookahead_holds_ceiling_on_bursts)
  3092. {
  3093. // short bursts over a low floor: the sliding maximum must see each peak before it leaves
  3094. auto fx = lynx::makeEffect (lynx::EffectKind::limiter);
  3095. fx->prepare (48000.0);
  3096. auto slot = lynx::makeEffectSlot (lynx::EffectKind::limiter);
  3097. slot.params[2] = 0.0f; // 10 ms release
  3098. std::vector<float> l (48000), r (48000);
  3099. std::uint32_t seed = 1;
  3100. for (int i = 0; i < 48000; ++i)
  3101. {
  3102. seed = seed * 1664525u + 1013904223u;
  3103. const auto noise = ((float) (seed >> 8) / 16777216.0f - 0.5f) * 0.1f;
  3104. l[(std::size_t) i] = noise + ((i % 9973) < 3 ? 3.0f : 0.0f);
  3105. r[(std::size_t) i] = -noise;
  3106. }
  3107. for (int i = 0; i < 48000; i += 333)
  3108. fx->process (l.data() + i, r.data() + i, std::min (333, 48000 - i), slot.params, 120.0);
  3109. float peak = 0.0f, quiet = 0.0f;
  3110. for (int i = 0; i < 48000; ++i)
  3111. peak = std::max (peak, std::abs (l[(std::size_t) i]));
  3112. for (int i = 9973 * 2 + 2000; i < 9973 * 2 + 2400; ++i) // 40 ms after the burst the gain has already recovered
  3113. quiet = std::max (quiet, std::abs (r[(std::size_t) i]));
  3114. const auto ceiling = 1.0f; // the default ceiling is at 0 dBFS or below
  3115. CHECK (peak <= ceiling + 1e-5f);
  3116. CHECK (quiet > 0.03f);
  3117. }
  3118. TEST (pdc_aligns_paths_through_latent_effects)
  3119. {
  3120. // plan: channel 0 -> insert 1 (effect of 100) -> insert 3; channel 1 -> insert 2 -> Master
  3121. lynx::Song s;
  3122. s.mixer = lynx::Song::defaultMixer (4);
  3123. s.channels.resize (3);
  3124. s.channels[0].mixerTrack = 1;
  3125. s.channels[1].mixerTrack = 2;
  3126. s.channels[2].mixerTrack = 3;
  3127. s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::eq));
  3128. s.setRoute (1, 3, true);
  3129. s.setRoute (1, 0, false);
  3130. auto plan = lynx::computePdc (s, { 0, 0, 30 }, { {}, { 100 } });
  3131. CHECK (plan.inAlign[1] == 0 && plan.outLat[1] == 100);
  3132. CHECK (plan.inAlign[3] == 100 && plan.channelDelay[2] == 70); // instrument of 30 on insert 3
  3133. CHECK (plan.sendDelay[1][1] == 0); // the slowest path isn't delayed
  3134. CHECK (plan.sendDelay[2][0] == 100 && plan.sendDelay[3][0] == 0 && plan.total == 100);
  3135. // bypass zeroes the slot's latency
  3136. s.mixer[1].effects[0].enabled = false;
  3137. CHECK (lynx::computePdc (s, { 0, 0, 30 }, { {}, { 100 } }).total == 30);
  3138. // rendered: two impulses played together come out together
  3139. lynx::Song r;
  3140. r.mixer = lynx::Song::defaultMixer (2);
  3141. for (int i = 0; i < 2; ++i)
  3142. {
  3143. lynx::ChannelDef c;
  3144. c.instrument = lynx::InstrumentKind::sampler;
  3145. c.samplePath = "impulso";
  3146. c.volume = 1.0f;
  3147. c.mixerTrack = i + 1;
  3148. r.channels.push_back (c);
  3149. }
  3150. r.patterns.emplace_back();
  3151. lynx::EffectSlot fx;
  3152. fx.kind = lynx::EffectKind::plugin;
  3153. fx.plugin.id = "latente";
  3154. r.mixer[1].effects.push_back (fx);
  3155. lynx::RackState::Factories f;
  3156. f.samples = [] (const std::string&) {
  3157. auto d = std::make_shared<lynx::SampleData>();
  3158. d->left.assign (64, 0.0f);
  3159. d->left[0] = 1.0f;
  3160. return std::shared_ptr<const lynx::SampleData> (d);
  3161. };
  3162. f.pluginEffects = [] (const lynx::PluginRef&, double) -> std::shared_ptr<lynx::Effect> { return std::make_shared<LatentEffect> (100); };
  3163. auto state = lynx::RackState::build (r, nullptr, 48000.0, f);
  3164. CHECK (state->pdc.total == 100 && state->sendDelays[2][0] != nullptr && state->sendDelays[2][0]->length() == 100);
  3165. lynx::RackRenderer renderer;
  3166. renderer.prepare (48000.0, 256);
  3167. lynx::LiveEventQueue live;
  3168. for (int ch = 0; ch < 2; ++ch)
  3169. {
  3170. lynx::NoteEvent on;
  3171. on.channel = ch;
  3172. on.key = 60;
  3173. on.velocity = 1.0f;
  3174. live.push (on);
  3175. }
  3176. std::vector<float> l (256), rr (256);
  3177. renderer.process (state.get(), false, 0.0, 256, l.data(), rr.data(), &live);
  3178. int first = -1;
  3179. for (int i = 0; i < 256 && first < 0; ++i)
  3180. if (std::abs (l[(std::size_t) i]) > 0.01f)
  3181. first = i;
  3182. CHECK (first == 100 && std::abs (l[100] - 2.0f) < 1e-3f); // both impulses arrive together, summed
  3183. // editing without changing latencies reuses the lines
  3184. r.channels[0].volume = 0.5f;
  3185. auto next = lynx::RackState::build (r, state.get(), 48000.0, f);
  3186. CHECK (next->sendDelays[2][0] == state->sendDelays[2][0]);
  3187. }
  3188. TEST (mixer_mute_fades_instead_of_clicking)
  3189. {
  3190. lynx::Song s;
  3191. s.mixer = lynx::Song::defaultMixer (2);
  3192. lynx::ChannelDef c;
  3193. c.instrument = lynx::InstrumentKind::sampler;
  3194. c.samplePath = "dc";
  3195. c.volume = 1.0f;
  3196. c.mixerTrack = 1;
  3197. s.channels.push_back (c);
  3198. s.patterns.emplace_back();
  3199. auto provider = [] (const std::string&) {
  3200. auto d = std::make_shared<lynx::SampleData>();
  3201. d->left.assign (48000, 0.5f);
  3202. return std::shared_ptr<const lynx::SampleData> (d);
  3203. };
  3204. auto on = lynx::RackState::build (s, nullptr, 48000.0, provider);
  3205. s.mixer[1].muted = true;
  3206. auto off = lynx::RackState::build (s, on.get(), 48000.0, provider);
  3207. lynx::RackRenderer r;
  3208. r.prepare (48000.0, 256);
  3209. lynx::LiveEventQueue live;
  3210. lynx::NoteEvent note;
  3211. note.velocity = 1.0f;
  3212. live.push (note);
  3213. std::vector<float> l (256), rr (256);
  3214. r.process (on.get(), false, 0.0, 256, l.data(), rr.data(), &live);
  3215. CHECK (std::abs (l[255] - 0.5f) < 1e-3f);
  3216. r.process (off.get(), false, 0.0, 256, l.data(), rr.data());
  3217. CHECK (l[0] > 0.45f && l[128] > 0.2f && l[128] < 0.3f && std::abs (l[255]) < 1e-6f); // ramp down to zero
  3218. r.process (off.get(), false, 0.0, 256, l.data(), rr.data());
  3219. CHECK (std::abs (l[0]) < 1e-9f);
  3220. }
  3221. TEST (dither_quantizes_to_lsb_grid_with_small_error)
  3222. {
  3223. lynx::Dither d (16);
  3224. std::vector<float> x (4800);
  3225. for (std::size_t i = 0; i < x.size(); ++i)
  3226. x[i] = 0.25f * std::sin ((float) i * 0.05f);
  3227. auto y = x;
  3228. d.process (y.data(), (int) y.size(), 0);
  3229. double errorSum = 0.0;
  3230. bool onGrid = true;
  3231. for (std::size_t i = 0; i < x.size(); ++i)
  3232. {
  3233. const auto steps = y[i] * 32768.0f;
  3234. onGrid = onGrid && std::abs (steps - std::round (steps)) < 1e-3f;
  3235. errorSum += std::abs (y[i] - x[i]);
  3236. }
  3237. CHECK (onGrid);
  3238. CHECK (errorSum / (double) x.size() < 4.0 / 32768.0); // a few LSBs of noise on average
  3239. }
  3240. TEST (parallel_rendering_matches_sequential)
  3241. {
  3242. // 32 channels (worth parallelizing), inserts with chained sends
  3243. auto song = lynx::Song::makeDefault();
  3244. song.mixer = lynx::Song::defaultMixer (16);
  3245. for (int i = 5; i < 32; ++i)
  3246. {
  3247. lynx::ChannelDef c;
  3248. c.instrument = i % 2 ? lynx::InstrumentKind::synth : lynx::InstrumentKind::hat;
  3249. c.mixerTrack = 1 + i % 12;
  3250. c.volume = 0.3f;
  3251. song.channels.push_back (c);
  3252. for (int step = i % 4; step < 16; step += 3)
  3253. song.patterns[0].notes.push_back ({ (std::int64_t) step * lynx::ticksPerStep, 200, i, 48 + i, 0.7f });
  3254. }
  3255. song.patterns[0].sortNotes();
  3256. song.setRoute (3, 7, true, 0.6f);
  3257. song.setRoute (7, 9, true, 0.5f);
  3258. song.setRoute (2, 9, true);
  3259. song.mixer[9].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::reverb));
  3260. auto seqState = lynx::RackState::build (song, nullptr, 48000.0);
  3261. auto parState = lynx::RackState::build (song, nullptr, 48000.0);
  3262. CHECK (parState->parallel && parState->mixerLayers.size() == 3);
  3263. lynx::WorkerPool pool (3);
  3264. lynx::RackRenderer seq, par;
  3265. seq.prepare (48000.0, 512);
  3266. par.prepare (48000.0, 512);
  3267. par.setWorkerPool (&pool);
  3268. std::vector<float> l1 (512), r1 (512), l2 (512), r2 (512);
  3269. const auto tps = lynx::ticksPerSample (song.bpm, 48000.0);
  3270. bool same = true;
  3271. float peak = 0.0f;
  3272. for (int block = 0; block < 200; ++block)
  3273. {
  3274. seq.process (seqState.get(), true, block * 512 * tps, 512, l1.data(), r1.data());
  3275. par.process (parState.get(), true, block * 512 * tps, 512, l2.data(), r2.data());
  3276. same = same && l1 == l2 && r1 == r2;
  3277. for (auto v : l1)
  3278. peak = std::max (peak, std::abs (v));
  3279. }
  3280. CHECK (same);
  3281. CHECK (peak > 0.05f);
  3282. // the pool handles many small rounds in a row
  3283. std::atomic<int> sum { 0 };
  3284. auto add = [&sum] (int i) { sum.fetch_add (i + 1); };
  3285. for (int round = 0; round < 2000; ++round)
  3286. pool.parallelFor (5, add);
  3287. CHECK (sum.load() == 2000 * 15);
  3288. }
  3289. TEST (arrangements_switch_and_keep_clip_indices)
  3290. {
  3291. auto s = lynx::Song::makeDefault();
  3292. s.patterns.emplace_back().name = "B";
  3293. s.playlist = { { 1, 0, 0, 960, 0 } };
  3294. s.loopEnd = 960;
  3295. CHECK (s.arrangements.size() == 1 && s.currentArrangement == 0);
  3296. const auto second = s.addArrangement ("Versão curta", true);
  3297. CHECK (second == 1 && s.currentArrangement == 1 && s.playlist.size() == 1 && s.loopEnd == 960);
  3298. s.playlist.push_back ({ 0, 1, 960, 960, 0 });
  3299. s.loopEnd = 0;
  3300. s.selectArrangement (0);
  3301. CHECK (s.playlist.size() == 1 && s.loopEnd == 960 && s.arrangements[1].clips.size() == 2);
  3302. // removing pattern 0 fixes the clips stored in the other arrangement
  3303. s.removePattern (0);
  3304. CHECK (s.playlist.size() == 1 && s.playlist[0].pattern == 0);
  3305. CHECK (s.arrangements[1].clips.size() == 1 && s.arrangements[1].clips[0].pattern == 0);
  3306. s.removeArrangement (0);
  3307. CHECK (s.arrangements.size() == 1 && s.currentArrangement == 0 && s.playlist.size() == 1 && s.loopEnd == 0);
  3308. }
  3309. namespace
  3310. {
  3311. // Test effect that inverts the signal and counts how many times it processed.
  3312. class CountingInverter final : public lynx::Effect
  3313. {
  3314. public:
  3315. void prepare (double) noexcept override {}
  3316. void reset() noexcept override {}
  3317. void process (float* l, float* r, int n, const lynx::EffectParams&, double) noexcept override
  3318. {
  3319. ++calls;
  3320. for (int i = 0; i < n; ++i)
  3321. {
  3322. l[i] = -l[i];
  3323. r[i] = -r[i];
  3324. }
  3325. }
  3326. int calls = 0;
  3327. };
  3328. } // namespace
  3329. TEST (keyboard_controller_outputs_key_value)
  3330. {
  3331. std::vector<std::uint8_t> blob (554, 0);
  3332. const std::uint32_t version = 3;
  3333. std::memcpy (blob.data(), &version, 4);
  3334. const float key60 = 0.7f, off = 0.2f;
  3335. std::memcpy (blob.data() + 12 + 60 * 4, &key60, 4);
  3336. std::memcpy (blob.data() + 548, &off, 4);
  3337. blob[552] = 1; // auto release
  3338. lynx::ChannelDef c;
  3339. c.instrument = lynx::InstrumentKind::controller;
  3340. c.controllerState = blob;
  3341. auto inst = lynx::makeInstrument (lynx::InstrumentKind::controller);
  3342. inst->prepare (48000.0);
  3343. inst->configure (c, 120.0);
  3344. std::vector<float> l (64), r (64);
  3345. inst->noteOn (60, 1.0f);
  3346. inst->render (l.data(), r.data(), 64, 1.0f, 1.0f);
  3347. CHECK (std::abs (inst->controlOutput (0) - 0.7f) < 1e-6f);
  3348. inst->noteOff (60);
  3349. CHECK (std::abs (inst->controlOutput (0) - 0.2f) < 1e-6f);
  3350. }
  3351. TEST (envelope_controller_ducks_on_each_note)
  3352. {
  3353. // a unipolar articulator like "Basic Sidechain": base 0.05, drops to 0 on the note and rises to 1 in 0.3 s
  3354. lynx::ControllerArticulator a;
  3355. a.envOn = true;
  3356. a.base = 0.05f;
  3357. a.envLevel = 1.0f;
  3358. a.count = 3;
  3359. a.time = { 0.0f, 0.2f, 0.3f };
  3360. a.level = { 0.0f, 0.75f, 1.0f };
  3361. CHECK (std::abs (lynx::controllerValue (a, 0.0, -1.0) - 0.05f) < 1e-4f);
  3362. CHECK (std::abs (lynx::controllerValue (a, 0.1, -1.0) - 0.425f) < 1e-3f);
  3363. CHECK (lynx::controllerValue (a, 1.0, -1.0) > 0.99f); // no sustain: runs to the end and stays
  3364. a.sustain = 1;
  3365. CHECK (std::abs (lynx::controllerValue (a, 1.0, -1.0) - 0.8f) < 1e-3f); // held at sustain
  3366. CHECK (lynx::controllerValue (a, 1.0, 0.5) > 0.99f); // released: continues to the end
  3367. a.bipolar = true;
  3368. a.base = 0.5f;
  3369. a.sustain = -1;
  3370. CHECK (std::abs (lynx::controllerValue (a, 0.0, -1.0) - 0.0f) < 1e-4f); // bipolar: 0.5 + (0 − 0.5)
  3371. }
  3372. TEST (peak_controller_drives_live_automation)
  3373. {
  3374. // track 1: source (DC 0.5) with Peak Controller; track 2: DC 0.5 with volume linked to the controller
  3375. auto render = [] (bool linked) {
  3376. lynx::Song s;
  3377. s.mixer = lynx::Song::defaultMixer (2);
  3378. for (int t = 1; t <= 2; ++t)
  3379. {
  3380. lynx::ChannelDef c;
  3381. c.instrument = lynx::InstrumentKind::sampler;
  3382. c.samplePath = "dc";
  3383. c.volume = 1.0f;
  3384. c.mixerTrack = t;
  3385. s.channels.push_back (c);
  3386. }
  3387. s.patterns.emplace_back();
  3388. auto peak = lynx::makeEffectSlot (lynx::EffectKind::peakController);
  3389. peak.params[0] = 1.0f; // base 1
  3390. peak.params[1] = 0.0f; // amount −1: 1 − peak
  3391. peak.params[2] = 0.5f; // no tension
  3392. s.mixer[1].effects.push_back (peak);
  3393. if (linked)
  3394. {
  3395. lynx::Automation a;
  3396. a.name = "Peak";
  3397. a.target = { lynx::AutomationTargetKind::mixerVolume, 2 };
  3398. a.source = { 1, 0, 0 };
  3399. s.automations.push_back (a);
  3400. }
  3401. lynx::RackState::Factories f;
  3402. f.samples = [] (const std::string&) {
  3403. auto d = std::make_shared<lynx::SampleData>();
  3404. d->left.assign (48000, 0.5f);
  3405. return std::shared_ptr<const lynx::SampleData> (d);
  3406. };
  3407. auto state = lynx::RackState::build (s, nullptr, 48000.0, f);
  3408. lynx::RackRenderer r;
  3409. r.prepare (48000.0, 512);
  3410. lynx::LiveEventQueue live;
  3411. for (int ch = 0; ch < 2; ++ch)
  3412. {
  3413. lynx::NoteEvent on;
  3414. on.channel = ch;
  3415. on.velocity = 1.0f;
  3416. live.push (on);
  3417. }
  3418. std::vector<float> l (4800), rr (4800);
  3419. r.process (state.get(), false, 0.0, 4800, l.data(), rr.data(), &live);
  3420. return l[4000];
  3421. };
  3422. const auto free = render (false), ducked = render (true);
  3423. CHECK (std::isfinite (ducked) && ducked > 0.0f);
  3424. CHECK (ducked < free - 0.05f); // the 0.5 peak on track 1 lowers track 2's volume
  3425. }
  3426. TEST (effect_slot_dry_wet_and_smart_disable)
  3427. {
  3428. lynx::Song s;
  3429. s.mixer = lynx::Song::defaultMixer (1);
  3430. lynx::ChannelDef c;
  3431. c.instrument = lynx::InstrumentKind::sampler;
  3432. c.samplePath = "dc";
  3433. c.volume = 1.0f;
  3434. c.mixerTrack = 1;
  3435. s.channels.push_back (c);
  3436. s.patterns.emplace_back();
  3437. lynx::EffectSlot fx;
  3438. fx.kind = lynx::EffectKind::plugin;
  3439. fx.plugin.id = "inversor";
  3440. fx.mix = 0.25f; // 75% dry (+0.5) and 25% wet (-0.5) = +0.25
  3441. s.mixer[1].effects.push_back (fx);
  3442. auto inverter = std::make_shared<CountingInverter>();
  3443. lynx::RackState::Factories f;
  3444. f.samples = [] (const std::string&) {
  3445. auto d = std::make_shared<lynx::SampleData>();
  3446. d->left.assign (4800, 0.5f);
  3447. return std::shared_ptr<const lynx::SampleData> (d);
  3448. };
  3449. f.pluginEffects = [inverter] (const lynx::PluginRef&, double) -> std::shared_ptr<lynx::Effect> { return inverter; };
  3450. auto state = lynx::RackState::build (s, nullptr, 48000.0, f);
  3451. lynx::RackRenderer r;
  3452. r.prepare (48000.0, 512);
  3453. lynx::LiveEventQueue live;
  3454. lynx::NoteEvent on;
  3455. on.velocity = 1.0f;
  3456. live.push (on);
  3457. std::vector<float> l (480), rr (480);
  3458. r.process (state.get(), false, 0.0, 480, l.data(), rr.data(), &live);
  3459. CHECK (std::abs (l[100] - 0.25f) < 1e-4f);
  3460. // after the sample ends: 4 s of silence and the plugin stops being called
  3461. for (int i = 0; i < 100 * 6; ++i) // 6 s
  3462. r.process (state.get(), false, 0.0, 480, l.data(), rr.data());
  3463. const auto callsAfterSilence = inverter->calls;
  3464. for (int i = 0; i < 100; ++i)
  3465. r.process (state.get(), false, 0.0, 480, l.data(), rr.data());
  3466. CHECK (inverter->calls == callsAfterSilence);
  3467. CHECK (callsAfterSilence < 100 * 6);
  3468. // sound again: processing resumes in the same block
  3469. live.push (on);
  3470. r.process (state.get(), false, 0.0, 480, l.data(), rr.data(), &live);
  3471. CHECK (inverter->calls == callsAfterSilence + 1 && std::abs (l[100] - 0.25f) < 1e-4f);
  3472. }
  3473. TEST (swing_delays_offbeat_sixteenths)
  3474. {
  3475. CHECK (lynx::swingDelay (0, 1.0f) == 0);
  3476. CHECK (lynx::swingDelay (lynx::ticksPerStep, 1.0f) == lynx::ticksPerStep / 2);
  3477. CHECK (lynx::swingDelay (lynx::ticksPerStep * 2, 1.0f) == 0);
  3478. CHECK (lynx::swingDelay (lynx::ticksPerStep + 10, 1.0f) == (lynx::ticksPerStep - 20) / 2); // off the grid: triangular weight (FL)
  3479. CHECK (lynx::swingDelay (lynx::ticksPerStep, 1.0f, 0.5f) == lynx::ticksPerStep / 4); // channel mix
  3480. CHECK (lynx::swingDelay (lynx::ticksPerStep * 3, 0.5f) == lynx::ticksPerStep / 4);
  3481. lynx::Pattern p;
  3482. p.notes = { { 0, 100, 0, 60 }, { lynx::ticksPerStep, 100, 0, 62 } };
  3483. lynx::EventBuffer ev;
  3484. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  3485. lynx::schedulePatternLoop (p, p.effectiveLength (4), 0.0, 12000, tps, ev, 1.0f);
  3486. int onOffset = -1;
  3487. for (auto& e : ev)
  3488. if (e.type == lynx::NoteEvent::Type::on && e.key == 62)
  3489. onOffset = e.sampleOffset;
  3490. CHECK (onOffset == (int) std::floor ((lynx::ticksPerStep * 1.5) / tps));
  3491. }
  3492. TEST (sampler_settings_pitch_reverse_envelope_cut)
  3493. {
  3494. auto ramp = std::make_shared<lynx::SampleData>();
  3495. for (int i = 0; i < 48000; ++i)
  3496. ramp->left.push_back ((float) i / 48000.0f); // ramp: the value tells where the read position is
  3497. ramp->sampleRate = 48000.0;
  3498. auto play = [&] (const lynx::SamplerSettings& s, int key, int frames, bool releaseAfterHalf) {
  3499. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  3500. inst->prepare (48000.0);
  3501. lynx::ChannelDef c;
  3502. c.sampler = s;
  3503. inst->configure (c, 120.0);
  3504. inst->noteOn (key, 1.0f);
  3505. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  3506. inst->render (l.data(), r.data(), frames / 2, 1.0f, 1.0f);
  3507. if (releaseAfterHalf)
  3508. inst->noteOff (key);
  3509. inst->render (l.data() + frames / 2, r.data() + frames / 2, frames - frames / 2, 1.0f, 1.0f);
  3510. return l;
  3511. };
  3512. // +12 semitones: reads twice as fast
  3513. lynx::SamplerSettings up;
  3514. up.pitch = 12.0f;
  3515. CHECK (std::abs (play (up, 60, 1000, false)[999] - 2.0f * 999.0f / 48000.0f) < 1e-3f);
  3516. // reversed: starts from the end
  3517. lynx::SamplerSettings back;
  3518. back.reverse = true;
  3519. CHECK (play (back, 60, 100, false)[10] > 0.99f);
  3520. // 10 ms attack: starts silent and reaches full level
  3521. lynx::SamplerSettings slow;
  3522. slow.attack = 0.01f;
  3523. const auto a = play (slow, 60, 2000, false);
  3524. CHECK (a[10] < 0.2f * (10.0f / 48000.0f) + 1e-6f && std::abs (a[1500] - 1500.0f / 48000.0f) < 1e-4f);
  3525. // 5 ms release: gone right after release; without release it plays in full
  3526. lynx::SamplerSettings rel;
  3527. rel.release = 0.005f;
  3528. CHECK (play (rel, 60, 2000, true)[1999] == 0.0f);
  3529. CHECK (play (lynx::SamplerSettings {}, 60, 2000, true)[1999] > 0.0f);
  3530. // cut itself: the second note cuts the first (one voice remains)
  3531. lynx::SamplerSettings cut;
  3532. cut.cut = true;
  3533. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  3534. inst->prepare (48000.0);
  3535. lynx::ChannelDef cutChannel;
  3536. cutChannel.sampler = cut;
  3537. inst->configure (cutChannel, 120.0);
  3538. inst->noteOn (60, 1.0f);
  3539. std::vector<float> l (2000), r (2000);
  3540. inst->render (l.data(), r.data(), 1000, 1.0f, 1.0f);
  3541. inst->noteOn (60, 1.0f);
  3542. std::fill (l.begin(), l.end(), 0.0f);
  3543. inst->render (l.data(), r.data(), 2000, 1.0f, 1.0f);
  3544. CHECK (std::abs (l[1999] - 1999.0f / 48000.0f) < 1e-4f); // only the new note
  3545. }
  3546. TEST (playlist_split_and_track_mute)
  3547. {
  3548. lynx::Clip c { 0, 3, 960, 3840, 480 };
  3549. const auto rest = lynx::splitClip (c, 2000);
  3550. CHECK (c.start == 960 && c.length == 1040 && c.offset == 480);
  3551. CHECK (rest.start == 2000 && rest.length == 2800 && rest.offset == 480 + 1040 && rest.track == 3);
  3552. auto s = lynx::Song::makeDefault();
  3553. s.mode = lynx::PlayMode::song;
  3554. s.playlist = { { 0, 0, 0, 3840, 0 } };
  3555. lynx::EventBuffer ev;
  3556. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  3557. lynx::scheduleSong (s, 0.0, 48000, tps, ev);
  3558. CHECK (ev.size() > 0);
  3559. s.playlistTracks.resize (1);
  3560. s.playlistTracks[0].muted = true;
  3561. ev.clear();
  3562. lynx::scheduleSong (s, 0.0, 48000, tps, ev);
  3563. CHECK (ev.size() == 0);
  3564. }
  3565. TEST (note_pan_pitch_and_mute)
  3566. {
  3567. lynx::Pattern p;
  3568. lynx::Note a { 0, 240, 0, 60 };
  3569. a.pan = -1.0f;
  3570. a.finePitch = 50.0f;
  3571. lynx::Note b { 240, 240, 0, 62 };
  3572. b.muted = true;
  3573. p.notes = { a, b };
  3574. lynx::EventBuffer ev;
  3575. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  3576. lynx::schedulePatternLoop (p, p.effectiveLength (4), 0.0, 48000, tps, ev);
  3577. int ons = 0;
  3578. for (auto& e : ev)
  3579. if (e.type == lynx::NoteEvent::Type::on)
  3580. {
  3581. ++ons;
  3582. CHECK (e.key == 60 && e.pan == -1.0f && e.cents == 50.0f);
  3583. }
  3584. CHECK (ons == 1); // the muted one doesn't play
  3585. // note pan in the sampler: fully left
  3586. auto dc = std::make_shared<lynx::SampleData>();
  3587. dc->left.assign (4800, 0.5f);
  3588. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, dc);
  3589. inst->prepare (48000.0);
  3590. inst->setNextNoteExpression (-1.0f, 0.0f);
  3591. inst->noteOn (60, 1.0f);
  3592. std::vector<float> l (100), r (100);
  3593. inst->render (l.data(), r.data(), 100, 1.0f, 1.0f);
  3594. CHECK (l[50] > 0.6f && std::abs (r[50]) < 1e-6f);
  3595. }
  3596. TEST (tempo_automation_changes_speed_and_duration)
  3597. {
  3598. auto song = lynx::Song::makeDefault();
  3599. song.bpm = 120.0;
  3600. song.mode = lynx::PlayMode::song;
  3601. const auto bar = (std::int64_t) lynx::ppq * 4;
  3602. song.playlist = { { 0, 0, 0, bar, 0 }, { 0, 0, bar, bar, 0 } };
  3603. lynx::Automation tempo;
  3604. tempo.target = { lynx::AutomationTargetKind::tempo, 0 };
  3605. const auto v120 = lynx::valueFromTempo (120.0), v240 = lynx::valueFromTempo (240.0);
  3606. tempo.points = { { 0, v120 }, { bar - 1, v120 }, { bar, v240 } }; // step: 120 -> 240 at bar 2
  3607. song.automations.push_back (tempo);
  3608. lynx::Clip clip;
  3609. clip.kind = lynx::ClipKind::automation;
  3610. clip.automation = 0;
  3611. clip.track = 1;
  3612. clip.length = bar * 2;
  3613. song.playlist.push_back (clip);
  3614. CHECK (std::abs (song.tempoAt (100.0) - 120.0) < 0.01 && std::abs (song.tempoAt ((double) bar + 100.0) - 240.0) < 0.01);
  3615. // 1 bar at 120 (2 s) + 1 at 240 (1 s)
  3616. CHECK (std::abs (song.secondsForTicks (bar * 2) - 3.0) < 0.01);
  3617. auto state = lynx::RackState::build (song, nullptr, 48000.0);
  3618. CHECK (state->tempoAutomation == 0);
  3619. lynx::RackRenderer r;
  3620. r.prepare (48000.0, 512);
  3621. std::vector<float> l (512), rr (512);
  3622. r.process (state.get(), true, 10.0, 512, l.data(), rr.data());
  3623. CHECK (std::abs (r.currentBpm() - 120.0) < 0.01);
  3624. r.process (state.get(), true, (double) bar + 10.0, 512, l.data(), rr.data());
  3625. CHECK (std::abs (r.currentBpm() - 240.0) < 0.01);
  3626. }
  3627. TEST (bounce_insert_song_and_apply)
  3628. {
  3629. auto s = lynx::Song::makeDefault();
  3630. s.setRoute (3, 7, true, 0.5f);
  3631. s.mixer[0].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::reverb));
  3632. s.mixer[2].solo = true;
  3633. const auto b = lynx::makeBounceSong (s, 3);
  3634. CHECK (b.mixer[3].solo && ! b.mixer[2].solo && b.mixer[3].toMaster && b.mixer[3].sends.empty());
  3635. CHECK (b.mixer[0].effects.empty() && b.mode == lynx::PlayMode::song);
  3636. const auto audible = b.soloAudible();
  3637. CHECK (audible[3] && ! audible[1] && ! audible[7]);
  3638. const auto channels = s.channels.size();
  3639. const auto inserts = s.mixer.size();
  3640. const auto created = lynx::applyBounce (s, 3, "C:/x.wav", 3840);
  3641. CHECK (created == (int) inserts && s.mixer.size() == inserts + 1 && s.mixer[3].muted);
  3642. CHECK (s.mixer[(std::size_t) created].sends.size() == 1 && s.mixer[(std::size_t) created].sends[0].target == 7);
  3643. CHECK (s.channels.size() == channels + 1 && s.channels.back().mixerTrack == created);
  3644. CHECK (s.playlist.back().kind == lynx::ClipKind::audio && s.playlist.back().length == 3840);
  3645. }
  3646. TEST (mixer_stereo_separation_phase_swap)
  3647. {
  3648. lynx::MixerTrack t;
  3649. std::vector<float> l { 1.0f }, r { 0.0f };
  3650. t.stereo = 1.0f; // mono
  3651. lynx::RackRenderer::applyStereoForTest (t, l.data(), r.data(), 1);
  3652. CHECK (std::abs (l[0] - 0.5f) < 1e-6f && std::abs (r[0] - 0.5f) < 1e-6f);
  3653. l = { 1.0f };
  3654. r = { 0.0f };
  3655. t.stereo = -1.0f; // doubled side: 1.5 L - 0.5 R
  3656. lynx::RackRenderer::applyStereoForTest (t, l.data(), r.data(), 1);
  3657. CHECK (std::abs (l[0] - 1.5f) < 1e-6f && std::abs (r[0] + 0.5f) < 1e-6f);
  3658. l = { 1.0f };
  3659. r = { 0.25f };
  3660. t.stereo = 0.0f;
  3661. t.swapChannels = true;
  3662. t.invertPhase = true;
  3663. lynx::RackRenderer::applyStereoForTest (t, l.data(), r.data(), 1);
  3664. CHECK (l[0] == -0.25f && r[0] == -1.0f);
  3665. }
  3666. TEST (effects_limiter_filter_distortion_chorus)
  3667. {
  3668. const double sr = 48000.0;
  3669. auto sine = [] (float hz, float amp, int n) {
  3670. std::vector<float> v ((std::size_t) n);
  3671. for (int i = 0; i < n; ++i)
  3672. v[(std::size_t) i] = amp * std::sin (2.0f * 3.14159265f * hz * (float) i / 48000.0f);
  3673. return v;
  3674. };
  3675. auto peak = [] (const std::vector<float>& v, int from) {
  3676. float p = 0.0f;
  3677. for (std::size_t i = (std::size_t) from; i < v.size(); ++i)
  3678. p = std::max (p, std::abs (v[i]));
  3679. return p;
  3680. };
  3681. // limiter: +12 dB on a 0.9 sine never exceeds the ceiling (-1 dB) and reports the latency
  3682. auto lim = lynx::makeEffect (lynx::EffectKind::limiter);
  3683. lim->prepare (sr);
  3684. auto slot = lynx::makeEffectSlot (lynx::EffectKind::limiter);
  3685. slot.params[0] = 11.0f / 12.0f; // -1 dB
  3686. slot.params[1] = 0.5f; // +12 dB
  3687. auto l = sine (100.0f, 0.9f, 48000), r = l;
  3688. lim->process (l.data(), r.data(), 48000, slot.params, 120.0);
  3689. CHECK (peak (l, 0) <= std::pow (10.0f, -1.0f / 20.0f) + 1e-4f);
  3690. CHECK (peak (l, 4800) > 0.8f);
  3691. CHECK (lim->latencySamples() == 72);
  3692. // low-pass filter at 500 Hz knocks down an 8 kHz sine
  3693. auto lp = lynx::makeEffect (lynx::EffectKind::filter);
  3694. lp->prepare (sr);
  3695. auto fs = lynx::makeEffectSlot (lynx::EffectKind::filter);
  3696. fs.params[1] = std::log (500.0f / 20.0f) / std::log (1000.0f);
  3697. l = sine (8000.0f, 1.0f, 9600);
  3698. r = l;
  3699. lp->process (l.data(), r.data(), 9600, fs.params, 120.0);
  3700. CHECK (peak (l, 4800) < 0.05f);
  3701. // distortion and chorus: finite, audible output
  3702. for (auto kind : { lynx::EffectKind::distortion, lynx::EffectKind::chorus })
  3703. {
  3704. auto fx = lynx::makeEffect (kind);
  3705. fx->prepare (sr);
  3706. auto ps = lynx::makeEffectSlot (kind);
  3707. l = sine (220.0f, 0.5f, 9600);
  3708. r = l;
  3709. fx->process (l.data(), r.data(), 9600, ps.params, 120.0);
  3710. bool finite = true;
  3711. for (auto v : l)
  3712. finite = finite && std::isfinite (v);
  3713. CHECK (finite && peak (l, 2400) > 0.1f && peak (l, 0) < 2.0f);
  3714. }
  3715. }
  3716. TEST (slide_notes_glide_without_retrigger)
  3717. {
  3718. // sampler with a ramp: the read speed doubles after a one-octave slide
  3719. auto ramp = std::make_shared<lynx::SampleData>();
  3720. for (int i = 0; i < 96000; ++i)
  3721. ramp->left.push_back ((float) i / 96000.0f);
  3722. ramp->sampleRate = 48000.0;
  3723. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  3724. inst->prepare (48000.0);
  3725. inst->noteOn (60, 1.0f);
  3726. std::vector<float> l (2000), r (2000);
  3727. inst->render (l.data(), r.data(), 1000, 1.0f, 1.0f);
  3728. const auto stepBefore = l[999] - l[998];
  3729. inst->slideTo (72, 0.0f, 100.0f);
  3730. std::fill (l.begin(), l.end(), 0.0f);
  3731. inst->render (l.data(), r.data(), 1000, 1.0f, 1.0f);
  3732. const auto stepAfter = l[999] - l[998];
  3733. CHECK (std::abs (stepAfter / stepBefore - 2.0f) < 0.01f);
  3734. // the sequencer sends "slide" (no off) for the slide note
  3735. lynx::Pattern p;
  3736. lynx::Note base { 0, 960, 0, 48 };
  3737. lynx::Note glide { 480, 240, 0, 55 };
  3738. glide.slide = true;
  3739. p.notes = { base, glide };
  3740. lynx::EventBuffer ev;
  3741. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  3742. lynx::schedulePatternLoop (p, p.effectiveLength (4), 0.0, 30000, tps, ev);
  3743. int ons = 0, offs = 0, slides = 0;
  3744. for (auto& e : ev)
  3745. {
  3746. ons += e.type == lynx::NoteEvent::Type::on;
  3747. offs += e.type == lynx::NoteEvent::Type::off;
  3748. if (e.type == lynx::NoteEvent::Type::slide)
  3749. {
  3750. ++slides;
  3751. CHECK (e.key == 55 && std::abs (e.slideSamples - 240.0f / (float) tps) < 1.0f);
  3752. }
  3753. }
  3754. CHECK (ons == 1 && offs == 1 && slides == 1);
  3755. }
  3756. TEST (synth_fm_phase_modulation)
  3757. {
  3758. auto render = [] (const lynx::SynthSettings& s) {
  3759. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  3760. inst->prepare (48000.0);
  3761. lynx::ChannelDef c;
  3762. c.synth = s;
  3763. inst->configure (c, 120.0);
  3764. inst->noteOn (69, 1.0f); // 440 Hz
  3765. std::vector<float> l (48000), r (48000);
  3766. inst->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  3767. return l;
  3768. };
  3769. // energy (Goertzel) at frequency f over frames [from, to)
  3770. auto energy = [] (const std::vector<float>& x, double f, int from, int to) {
  3771. const auto w = 2.0 * 3.141592653589793 * f / 48000.0, k = 2.0 * std::cos (w);
  3772. double s1 = 0.0, s2 = 0.0;
  3773. for (int i = from; i < to; ++i)
  3774. {
  3775. const auto s0 = x[(std::size_t) i] + k * s1 - s2;
  3776. s2 = s1;
  3777. s1 = s0;
  3778. }
  3779. return s1 * s1 + s2 * s2 - k * s1 * s2;
  3780. };
  3781. lynx::SynthSettings plain;
  3782. plain.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  3783. plain.osc[2] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  3784. plain.cutoff = 20000.0f;
  3785. auto fm = plain;
  3786. fm.fm = 1.0f;
  3787. const auto a = render (plain), b = render (fm);
  3788. // no FM: osc 3 adds (same pitch) and there's no 2nd harmonic; with FM the sidebands appear
  3789. CHECK (energy (a, 880.0, 4800, 24000) < 1e-3 * energy (a, 440.0, 4800, 24000));
  3790. CHECK (energy (b, 880.0, 4800, 24000) > 0.1 * energy (b, 440.0, 4800, 24000));
  3791. CHECK (energy (b, 1320.0, 4800, 24000) > 0.01 * energy (b, 440.0, 4800, 24000));
  3792. for (auto v : b)
  3793. CHECK (std::isfinite (v) && std::abs (v) < 1.0f);
  3794. // index decaying to 0: the start is bright, the end is nearly a sine again
  3795. auto decaying = fm;
  3796. decaying.fmDecay = 0.1f;
  3797. decaying.fmSustain = 0.0f;
  3798. const auto c = render (decaying);
  3799. const auto early = energy (c, 880.0, 0, 2400) / energy (c, 440.0, 0, 2400);
  3800. const auto late = energy (c, 880.0, 36000, 48000) / energy (c, 440.0, 36000, 48000);
  3801. CHECK (early > 0.05 && late < 1e-3);
  3802. }
  3803. TEST (synth_three_oscillators_adsr_filter)
  3804. {
  3805. auto render = [] (const lynx::SynthSettings& s, int frames, int releaseAt) {
  3806. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  3807. inst->prepare (48000.0);
  3808. lynx::ChannelDef c;
  3809. c.synth = s;
  3810. inst->configure (c, 120.0);
  3811. inst->noteOn (69, 1.0f); // A4 = 440 Hz
  3812. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  3813. inst->render (l.data(), r.data(), releaseAt, 1.0f, 1.0f);
  3814. inst->noteOff (69);
  3815. inst->render (l.data() + releaseAt, r.data() + releaseAt, frames - releaseAt, 1.0f, 1.0f);
  3816. return l;
  3817. };
  3818. auto peakIn = [] (const std::vector<float>& v, int from, int to) {
  3819. float p = 0.0f;
  3820. for (int i = from; i < to; ++i)
  3821. p = std::max (p, std::abs (v[(std::size_t) i]));
  3822. return p;
  3823. };
  3824. // default: sounds and fades after the release
  3825. const lynx::SynthSettings standard;
  3826. const auto a = render (standard, 48000, 24000);
  3827. CHECK (peakIn (a, 1000, 20000) > 0.05f && peakIn (a, 40000, 48000) < 1e-3f);
  3828. // pure sine with an open filter: zero-crossing count gives ~440 Hz
  3829. lynx::SynthSettings sine;
  3830. sine.osc[0].wave = lynx::Waveform::sine;
  3831. sine.cutoff = 20000.0f;
  3832. const auto b = render (sine, 48000, 47000);
  3833. int crossings = 0;
  3834. for (int i = 4800; i < 4800 + 48000 / 2; ++i)
  3835. crossings += (b[(std::size_t) i - 1] < 0.0f) != (b[(std::size_t) i] < 0.0f);
  3836. CHECK (std::abs (crossings - 440) < 6); // half a second = 220 cycles = 440 crossings
  3837. float sinePeak = 0.0f;
  3838. for (int i = 4800; i < 9600; ++i)
  3839. sinePeak = std::max (sinePeak, std::abs (b[(std::size_t) i]));
  3840. CHECK (sinePeak > 0.2f && sinePeak < 0.35f); // 0.3 level, approximated sine without clipping
  3841. // second oscillator an octave up adds energy; sustain 0 makes the note decay on its own
  3842. lynx::SynthSettings two = sine;
  3843. two.osc[1] = { lynx::Waveform::sine, 1, 0.0f, 1.0f };
  3844. two.sustain = 0.0f;
  3845. two.decay = 0.1f;
  3846. const auto c = render (two, 48000, 47000);
  3847. CHECK (peakIn (c, 100, 2000) > peakIn (b, 100, 2000) && peakIn (c, 30000, 40000) < 1e-3f);
  3848. }
  3849. TEST (set_target_value_round_trips)
  3850. {
  3851. auto s = lynx::Song::makeDefault();
  3852. s.mixer[2].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay));
  3853. const lynx::AutomationTarget targets[] = {
  3854. { lynx::AutomationTargetKind::channelVolume, 1 }, { lynx::AutomationTargetKind::channelPan, 2 },
  3855. { lynx::AutomationTargetKind::mixerVolume, 3 }, { lynx::AutomationTargetKind::mixerPan, 0 },
  3856. { lynx::AutomationTargetKind::effectParam, 2, 0, 1 }, { lynx::AutomationTargetKind::tempo, 0 },
  3857. };
  3858. for (const auto& t : targets)
  3859. {
  3860. CHECK (s.setTargetValue (t, 0.25f));
  3861. CHECK (std::abs (s.targetValue (t) - 0.25f) < 1e-5f);
  3862. }
  3863. CHECK (! s.setTargetValue ({ lynx::AutomationTargetKind::channelParam, 0, 0, 3 }, 0.5f)); // lives in the plugin
  3864. }
  3865. TEST (cut_groups_stretch_and_envelope_import)
  3866. {
  3867. // open hat (cut by 1) is cut when the closed one (group 1) plays
  3868. lynx::Song s;
  3869. s.mixer = lynx::Song::defaultMixer (2);
  3870. for (int i = 0; i < 2; ++i)
  3871. {
  3872. lynx::ChannelDef c;
  3873. c.instrument = lynx::InstrumentKind::sampler;
  3874. c.samplePath = "dc";
  3875. c.volume = 1.0f;
  3876. c.mixerTrack = i + 1;
  3877. s.channels.push_back (c);
  3878. }
  3879. s.channels[0].cutBy = 1; // open
  3880. s.channels[1].cutGroup = 1; // closed
  3881. auto& p = s.patterns.emplace_back();
  3882. p.notes = { { 0, 100, 0, 60 }, { 960, 100, 1, 60 } };
  3883. auto provider = [] (const std::string&) {
  3884. auto d = std::make_shared<lynx::SampleData>();
  3885. d->left.assign (96000, 0.5f);
  3886. return std::shared_ptr<const lynx::SampleData> (d);
  3887. };
  3888. auto state = lynx::RackState::build (s, nullptr, 48000.0, provider);
  3889. CHECK (state->hasCutGroups && state->cutTargets[1].size() == 1 && state->cutTargets[1][0] == 0);
  3890. lynx::RackRenderer r;
  3891. r.prepare (48000.0, 512);
  3892. std::vector<float> l (512), rr (512);
  3893. const auto tps = lynx::ticksPerSample (s.bpm, 48000.0);
  3894. float afterCut = 0.0f;
  3895. for (double tick = 0.0; tick < 960.0 * 3; tick += 512 * tps)
  3896. {
  3897. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  3898. if (tick > 960.0 * 2) // the closed one continues; the open one has stopped
  3899. afterCut = std::max (afterCut, std::abs (l[256]));
  3900. }
  3901. CHECK (std::abs (afterCut - 0.5f * 0.78f) < 0.01f); // only the closed one (default velocity 0.78)
  3902. // resampling stretch: 1 s of sample stretched to 4 beats at 120 BPM = 2 s
  3903. auto ramp = std::make_shared<lynx::SampleData>();
  3904. for (int i = 0; i < 48000; ++i)
  3905. ramp->left.push_back ((float) i / 48000.0f);
  3906. ramp->sampleRate = 48000.0;
  3907. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  3908. inst->prepare (48000.0);
  3909. lynx::ChannelDef c;
  3910. c.sampler.stretchBeats = 4.0f;
  3911. inst->configure (c, 120.0);
  3912. inst->noteOn (72, 1.0f); // the note pitch doesn't change the speed
  3913. std::vector<float> a (48000), b (48000);
  3914. inst->render (a.data(), b.data(), 48000, 1.0f, 1.0f);
  3915. CHECK (std::abs (a[47999] - 0.5f) < 0.01f); // after 1 s it has read half
  3916. // FL envelope time: 32950 = 2 s; < 101 = 0
  3917. CHECK (std::abs (flp::Channel::envelopeTime (32950) - 2.0) < 0.01 && flp::Channel::envelopeTime (50) == 0.0);
  3918. }
  3919. TEST (time_stretch_keeps_pitch)
  3920. {
  3921. lynx::SampleData sine;
  3922. sine.sampleRate = 48000.0;
  3923. for (int i = 0; i < 48000; ++i)
  3924. sine.left.push_back (0.5f * std::sin (2.0f * 3.14159265f * 440.0f * (float) i / 48000.0f));
  3925. auto crossingsPerSecond = [] (const lynx::SampleData& d) {
  3926. int c = 0;
  3927. const auto n = (int) d.frames();
  3928. for (int i = 4800; i < n - 4800; ++i)
  3929. c += (d.left[(std::size_t) i - 1] < 0.0f) != (d.left[(std::size_t) i] < 0.0f);
  3930. return (double) c / ((double) (n - 9600) / d.sampleRate);
  3931. };
  3932. for (double ratio : { 2.0, 0.5, 1.37 })
  3933. {
  3934. const auto out = lynx::timeStretch (sine, ratio);
  3935. CHECK (std::abs ((double) out->frames() - 48000.0 * ratio) < 2.0);
  3936. CHECK (std::abs (crossingsPerSecond (*out) - 880.0) < 15.0); // 440 Hz stays 440 Hz
  3937. float peak = 0.0f;
  3938. for (std::size_t i = 4800; i + 4800 < out->frames(); ++i)
  3939. peak = std::max (peak, std::abs (out->left[i]));
  3940. CHECK (peak > 0.4f && peak < 0.6f); // no gaps or clipping in the overlap
  3941. }
  3942. }
  3943. TEST (sampler_region_start_and_end)
  3944. {
  3945. auto ramp = std::make_shared<lynx::SampleData>();
  3946. for (int i = 0; i < 10000; ++i)
  3947. ramp->left.push_back ((float) i / 10000.0f);
  3948. ramp->sampleRate = 48000.0;
  3949. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  3950. inst->prepare (48000.0);
  3951. lynx::ChannelDef c;
  3952. c.sampler.regionStart = 0.25f;
  3953. c.sampler.regionEnd = 0.5f;
  3954. inst->configure (c, 120.0);
  3955. inst->noteOn (60, 1.0f);
  3956. std::vector<float> l (6000), r (6000);
  3957. inst->render (l.data(), r.data(), 6000, 1.0f, 1.0f);
  3958. CHECK (std::abs (l[0] - 0.25f) < 0.001f); // starts at the beginning of the slice
  3959. CHECK (l[2400] > 0.48f && l[2600] == 0.0f); // and stops at its end
  3960. }
  3961. TEST (arpeggiator_plays_held_chord_in_steps)
  3962. {
  3963. auto song = lynx::Song::makeDefault();
  3964. song.bpm = 120.0;
  3965. song.patterns[0].notes.clear();
  3966. for (int key : { 60, 64, 67 })
  3967. song.patterns[0].notes.push_back ({ 0, lynx::ppq * 4, 4, key, 0.8f }); // chord held for 1 bar
  3968. song.channels[4].arp.direction = 1; // up
  3969. song.channels[4].arp.stepBeats = 0.25f;
  3970. auto state = lynx::RackState::build (song, nullptr, 48000.0);
  3971. CHECK (state->arpeggiators[4] != nullptr && state->arpeggiators[0] == nullptr);
  3972. // the arpeggiator generates the notes; we count what it hands to the instrument
  3973. auto& arp = *state->arpeggiators[4];
  3974. const auto tps = lynx::ticksPerSample (song.bpm, 48000.0);
  3975. std::vector<int> keys;
  3976. lynx::EventBuffer ev;
  3977. for (double tick = 0.0; tick < lynx::ppq * 2.0; tick += 512 * tps)
  3978. {
  3979. ev.clear();
  3980. lynx::schedulePatternLoop (song.patterns[0], song.patterns[0].effectiveLength (4), tick, 512, tps, ev);
  3981. int in = 0, out = 0;
  3982. for (auto& e : ev)
  3983. if (e.channel == 4)
  3984. arp.input[(std::size_t) in++] = e;
  3985. arp.process (4, arp.input.data(), in, tick, tps, 512, song.channels[4].arp, arp.output.data(), out);
  3986. for (int i = 0; i < out; ++i)
  3987. if (arp.output[(std::size_t) i].type == lynx::NoteEvent::Type::on)
  3988. keys.push_back (arp.output[(std::size_t) i].key);
  3989. }
  3990. // 2 beats = 8 sixteenth steps: 60 64 67 60 64 67 60 64
  3991. CHECK (keys.size() >= 8); // the last block goes slightly past 2 beats
  3992. const int expected[] = { 60, 64, 67, 60, 64, 67, 60, 64 };
  3993. for (std::size_t i = 0; i < keys.size() && i < 8; ++i)
  3994. CHECK (keys[i] == expected[i]);
  3995. // actually rendering also makes sound
  3996. lynx::RackRenderer r;
  3997. r.prepare (48000.0, 512);
  3998. std::vector<float> l (512), rr (512);
  3999. float peak = 0.0f;
  4000. for (double tick = 0.0; tick < lynx::ppq; tick += 512 * tps)
  4001. {
  4002. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  4003. for (auto v : l)
  4004. peak = std::max (peak, std::abs (v));
  4005. }
  4006. CHECK (peak > 0.01f);
  4007. }
  4008. TEST (audio_clip_fades_and_gain)
  4009. {
  4010. lynx::Song s;
  4011. s.bpm = 120.0;
  4012. s.mode = lynx::PlayMode::song;
  4013. s.mixer = lynx::Song::defaultMixer (1);
  4014. lynx::ChannelDef c;
  4015. c.instrument = lynx::InstrumentKind::audioClip;
  4016. c.samplePath = "dc";
  4017. c.volume = 1.0f;
  4018. c.mixerTrack = 1;
  4019. s.channels.push_back (c);
  4020. s.patterns.emplace_back();
  4021. lynx::Clip clip;
  4022. clip.kind = lynx::ClipKind::audio;
  4023. clip.channel = 0;
  4024. clip.length = lynx::ppq * 4; // 2 s at 120 BPM
  4025. clip.fadeIn = lynx::ppq; // 0.5 s
  4026. clip.fadeOut = lynx::ppq;
  4027. clip.gain = 0.5f;
  4028. s.playlist.push_back (clip);
  4029. auto provider = [] (const std::string&) {
  4030. auto d = std::make_shared<lynx::SampleData>();
  4031. d->left.assign (48000 * 4, 1.0f);
  4032. return std::shared_ptr<const lynx::SampleData> (d);
  4033. };
  4034. auto state = lynx::RackState::build (s, nullptr, 48000.0, provider);
  4035. lynx::RackRenderer r;
  4036. r.prepare (48000.0, 512);
  4037. std::vector<float> all;
  4038. std::vector<float> l (512), rr (512);
  4039. const auto tps = lynx::ticksPerSample (s.bpm, 48000.0);
  4040. for (double tick = 0.0; tick < lynx::ppq * 4.0; tick += 512 * tps)
  4041. {
  4042. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  4043. all.insert (all.end(), l.begin(), l.end());
  4044. }
  4045. CHECK (all[100] < 0.01f); // fade-in start
  4046. CHECK (std::abs (all[12000] - 0.25f) < 0.02f); // fade-in midpoint: half of 0.5
  4047. CHECK (std::abs (all[48000] - 0.5f) < 0.01f); // body: the clip gain
  4048. CHECK (std::abs (all[96000 - 12000] - 0.25f) < 0.02f); // fade-out midpoint
  4049. }
  4050. TEST (slicer_detects_hits_and_plays_slices_by_key)
  4051. {
  4052. // 4 hits (decaying noise) every 0.25 s
  4053. lynx::SampleData loop;
  4054. loop.sampleRate = 48000.0;
  4055. loop.left.assign (48000, 0.0f);
  4056. lynx::Noise noise;
  4057. for (int hit = 0; hit < 4; ++hit)
  4058. for (int i = 0; i < 6000; ++i)
  4059. loop.left[(std::size_t) (hit * 12000 + i)] = noise.next() * 0.8f * std::exp (-(float) i / 1500.0f);
  4060. const auto slices = lynx::detectSlices (loop, 0.5f);
  4061. CHECK (slices.size() == 4);
  4062. for (std::size_t i = 0; i < slices.size(); ++i)
  4063. CHECK (std::abs (slices[i] - 0.25f * (float) i) < 0.01f);
  4064. // key 61 plays the second slice, which starts at 0.25 and ends before 0.5
  4065. auto ramp = std::make_shared<lynx::SampleData>();
  4066. for (int i = 0; i < 48000; ++i)
  4067. ramp->left.push_back ((float) i / 48000.0f);
  4068. ramp->sampleRate = 48000.0;
  4069. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  4070. inst->prepare (48000.0);
  4071. lynx::ChannelDef c;
  4072. c.sampler.slices = slices;
  4073. inst->configure (c, 120.0);
  4074. inst->noteOn (61, 1.0f);
  4075. std::vector<float> l (20000), r (20000);
  4076. inst->render (l.data(), r.data(), 20000, 1.0f, 1.0f);
  4077. CHECK (std::abs (l[0] - 0.25f) < 0.01f && l[11000] > 0.45f && l[13000] == 0.0f);
  4078. }
  4079. TEST (project_templates_render_sound)
  4080. {
  4081. const auto names = lynx::templateNames();
  4082. CHECK (names.size() == 4);
  4083. for (int t = 1; t < (int) names.size(); ++t)
  4084. {
  4085. auto song = lynx::makeTemplate (t);
  4086. auto state = lynx::RackState::build (song, nullptr, 48000.0);
  4087. lynx::RackRenderer r;
  4088. r.prepare (48000.0, 512);
  4089. std::vector<float> l (512), rr (512);
  4090. const auto tps = lynx::ticksPerSample (song.bpm, 48000.0);
  4091. float peak = 0.0f;
  4092. for (double tick = 0.0; tick < lynx::ppq * 4.0; tick += 512 * tps)
  4093. {
  4094. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  4095. for (auto v : l)
  4096. peak = std::max (peak, std::abs (v));
  4097. }
  4098. CHECK (peak > 0.05f && peak < 4.0f);
  4099. }
  4100. CHECK (lynx::makeTemplate (0).patterns[0].notes.empty());
  4101. }
  4102. // --- interface translations (resources/i18n) -------------------------------------------------------
  4103. namespace i18ntest
  4104. {
  4105. std::string readFile (const std::filesystem::path& path)
  4106. {
  4107. std::ifstream in (path, std::ios::binary);
  4108. return { std::istreambuf_iterator<char> (in), std::istreambuf_iterator<char>() };
  4109. }
  4110. std::string unescape (const std::string& s)
  4111. {
  4112. std::string out;
  4113. for (std::size_t i = 0; i < s.size(); ++i)
  4114. {
  4115. if (s[i] == '\\' && i + 1 < s.size())
  4116. {
  4117. const auto n = s[++i];
  4118. out += n == 'n' ? '\n' : n == 't' ? '\t' : n;
  4119. }
  4120. else
  4121. out += s[i];
  4122. }
  4123. return out;
  4124. }
  4125. // reads a quoted string starting at s[pos] == '"'; returns the raw (escaped) contents and moves pos past the closing quote
  4126. bool quoted (const std::string& s, std::size_t& pos, std::string& raw)
  4127. {
  4128. if (pos >= s.size() || s[pos] != '"')
  4129. return false;
  4130. raw.clear();
  4131. for (++pos; pos < s.size() && s[pos] != '"' && s[pos] != '\n'; ++pos)
  4132. {
  4133. if (s[pos] == '\\' && pos + 1 < s.size())
  4134. raw += s[pos++];
  4135. raw += s[pos];
  4136. }
  4137. if (pos >= s.size() || s[pos] != '"')
  4138. return false;
  4139. ++pos;
  4140. return true;
  4141. }
  4142. // JUCE LocalisedStrings format: "english" = "translation"; duplicates are reported in `duplicates`
  4143. std::map<std::string, std::string> parseTable (const std::string& text, std::vector<std::string>& duplicates)
  4144. {
  4145. std::map<std::string, std::string> table;
  4146. std::istringstream lines (text);
  4147. std::string line;
  4148. while (std::getline (lines, line))
  4149. {
  4150. std::size_t pos = line.find_first_not_of (" \t");
  4151. std::string key, value;
  4152. if (pos == std::string::npos || ! quoted (line, pos, key))
  4153. continue;
  4154. pos = line.find ('"', pos);
  4155. if (pos == std::string::npos || ! quoted (line, pos, value))
  4156. value.clear();
  4157. const auto k = unescape (key);
  4158. if (table.count (k) != 0)
  4159. duplicates.push_back (k);
  4160. table[k] = unescape (value);
  4161. }
  4162. return table;
  4163. }
  4164. // string literals passed to tr() / TR_NOOP() in the sources (adjacent literals are concatenated)
  4165. std::map<std::string, std::string> sourceKeys (const std::filesystem::path& srcDir)
  4166. {
  4167. std::map<std::string, std::string> keys;
  4168. for (const auto& entry : std::filesystem::recursive_directory_iterator (srcDir))
  4169. {
  4170. const auto ext = entry.path().extension().string();
  4171. if (! entry.is_regular_file() || (ext != ".cpp" && ext != ".h"))
  4172. continue;
  4173. // drop // comment lines (they may quote tr ("...") as an example)
  4174. std::string text, line;
  4175. std::istringstream in (readFile (entry.path()));
  4176. while (std::getline (in, line))
  4177. {
  4178. const auto first = line.find_first_not_of (" \t");
  4179. text += (first != std::string::npos && line.compare (first, 2, "//") == 0) ? std::string() : line;
  4180. text += '\n';
  4181. }
  4182. auto isIdent = [] (char c) { return std::isalnum ((unsigned char) c) || c == '_'; };
  4183. for (const std::string name : { "tr", "TR_NOOP" })
  4184. for (auto at = text.find (name); at != std::string::npos; at = text.find (name, at + 1))
  4185. {
  4186. if ((at > 0 && isIdent (text[at - 1])) || isIdent (text[at + name.size()]))
  4187. continue;
  4188. auto pos = text.find_first_not_of (" \t\n", at + name.size());
  4189. if (pos == std::string::npos || text[pos] != '(')
  4190. continue;
  4191. pos = text.find_first_not_of (" \t\n", pos + 1);
  4192. std::string key, raw;
  4193. bool any = false;
  4194. while (pos != std::string::npos && quoted (text, pos, raw))
  4195. {
  4196. key += raw;
  4197. any = true;
  4198. pos = text.find_first_not_of (" \t\n", pos);
  4199. }
  4200. if (any)
  4201. keys.emplace (unescape (key), entry.path().filename().string());
  4202. }
  4203. }
  4204. return keys;
  4205. }
  4206. std::set<std::string> placeholders (const std::string& s)
  4207. {
  4208. std::set<std::string> found;
  4209. for (auto open = s.find ('{'); open != std::string::npos; open = s.find ('{', open + 1))
  4210. if (const auto close = s.find ('}', open); close != std::string::npos && close - open <= 3)
  4211. found.insert (s.substr (open, close - open + 1));
  4212. return found;
  4213. }
  4214. } // namespace i18ntest
  4215. TEST (translations_cover_every_ui_string)
  4216. {
  4217. using namespace i18ntest;
  4218. const auto text = readFile ("resources/i18n/pt-BR.txt");
  4219. CHECK (! text.empty());
  4220. std::vector<std::string> duplicates;
  4221. const auto table = parseTable (text, duplicates);
  4222. CHECK (table.size() > 300);
  4223. CHECK (duplicates.empty());
  4224. for (const auto& d : duplicates)
  4225. std::printf (" duplicate pt-BR entry: \"%s\"\n", d.c_str());
  4226. const auto keys = sourceKeys ("src");
  4227. CHECK (keys.size() > 300);
  4228. int missing = 0;
  4229. for (const auto& [key, file] : keys)
  4230. if (auto it = table.find (key); it == table.end() || it->second.empty())
  4231. {
  4232. ++missing;
  4233. std::printf (" no pt-BR translation for \"%s\" (%s)\n", key.c_str(), file.c_str());
  4234. }
  4235. CHECK (missing == 0);
  4236. // no empty values, and every {n} placeholder survives the translation
  4237. int empty = 0, badPlaceholders = 0;
  4238. for (const auto& [english, portuguese] : table)
  4239. {
  4240. empty += portuguese.empty() ? 1 : 0;
  4241. if (placeholders (english) != placeholders (portuguese))
  4242. {
  4243. ++badPlaceholders;
  4244. std::printf (" placeholders differ: \"%s\"\n", english.c_str());
  4245. }
  4246. }
  4247. CHECK (empty == 0);
  4248. CHECK (badPlaceholders == 0);
  4249. }
  4250. TEST (translations_embedded_table_is_up_to_date)
  4251. {
  4252. // src/ui/I18nData.h must be regenerated (tools/make_i18n.py) whenever the .txt changes
  4253. const auto text = i18ntest::readFile ("resources/i18n/pt-BR.txt");
  4254. CHECK (text.size() == sizeof (lynx::i18n::data::ptBR));
  4255. CHECK (std::memcmp (text.data(), lynx::i18n::data::ptBR, std::min (text.size(), sizeof (lynx::i18n::data::ptBR))) == 0);
  4256. }
  4257. // --- workflow shell: pattern/channel operations, key map, workspace layout, control math -------------
  4258. TEST (workflow_pattern_navigation_and_insert)
  4259. {
  4260. auto song = lynx::Song::makeDefault();
  4261. song.patterns.resize (3);
  4262. song.patterns[1].name = "B";
  4263. song.patterns[2].name = "C";
  4264. song.patterns[2].notes.push_back ({});
  4265. song.currentPattern = 0;
  4266. CHECK (lynx::stepPattern (song, 1) == 1 && lynx::stepPattern (song, -1) == 0 && lynx::stepPattern (song, 10) == 2);
  4267. // pattern 0 has the default notes, 1 is empty, 2 has a note
  4268. CHECK (! lynx::isPatternEmpty (song.patterns[0]) && lynx::isPatternEmpty (song.patterns[1]));
  4269. CHECK (lynx::findNextEmptyPattern (song, 0) == 1 && lynx::findNextEmptyPattern (song, 1) == -1);
  4270. CHECK (lynx::gotoNextEmptyPattern (song) == 1 && song.currentPattern == 1);
  4271. song.patterns[1].notes.push_back ({});
  4272. const auto before = song.patterns.size();
  4273. CHECK (lynx::gotoNextEmptyPattern (song) == (int) before && song.patterns.size() == before + 1);
  4274. CHECK (song.patterns.back().name == "Pattern 1" || song.patterns.back().name.rfind ("Pattern ", 0) == 0);
  4275. // insert keeps Playlist clips on their patterns
  4276. lynx::Clip clip;
  4277. clip.pattern = 2;
  4278. song.playlist = { clip };
  4279. song.arrangements.push_back ({ "Other", { clip }, 0, 0, {} });
  4280. CHECK (lynx::insertPattern (song, 1, "New") == 1 && song.currentPattern == 1);
  4281. CHECK (song.patterns[1].name == "New" && song.patterns[1].notes.empty() && song.patterns[3].name == "C");
  4282. CHECK (song.playlist[0].pattern == 3 && song.arrangements[1].clips[0].pattern == 3);
  4283. }
  4284. TEST (workflow_split_pattern_by_channel)
  4285. {
  4286. auto song = lynx::Song::makeDefault();
  4287. song.patterns.resize (1);
  4288. auto& p = song.patterns[0];
  4289. p.name = "Beat";
  4290. p.notes.clear();
  4291. for (int i = 0; i < 4; ++i)
  4292. p.notes.push_back ({ (std::int64_t) i * lynx::ticksPerStep, lynx::ticksPerStep, i % 2 == 0 ? 0 : 2, 60 });
  4293. song.channels[2].colour = 0xff112233;
  4294. lynx::Clip clip;
  4295. clip.pattern = 0;
  4296. song.playlist = { clip };
  4297. const auto created = lynx::splitPatternByChannel (song, 0);
  4298. CHECK (created == 2 && song.patterns.size() == 3);
  4299. CHECK (song.patterns[0].notes.size() == 4); // the original is unchanged
  4300. CHECK (song.patterns[1].name == "Beat - " + song.channels[0].name && song.patterns[1].notes.size() == 2);
  4301. CHECK (song.patterns[2].colour == 0xff112233u && song.patterns[2].notes.size() == 2 && song.patterns[2].notes[0].channel == 2);
  4302. CHECK (song.playlist[0].pattern == 0);
  4303. CHECK (lynx::splitPatternByChannel (song, 99) == 0);
  4304. }
  4305. TEST (workflow_channel_selection)
  4306. {
  4307. lynx::ChannelSelection s;
  4308. s.selectOnly (2);
  4309. s.toggle (5);
  4310. s.toggle (0);
  4311. CHECK ((s.rows == std::vector<int> { 0, 2, 5 }) && s.contains (5) && ! s.contains (3));
  4312. s.toggle (2);
  4313. CHECK ((s.rows == std::vector<int> { 0, 5 }));
  4314. s.selectOnly (3);
  4315. s.extendTo (6);
  4316. CHECK ((s.rows == std::vector<int> { 3, 4, 5, 6 }));
  4317. s.extendTo (1);
  4318. CHECK ((s.rows == std::vector<int> { 1, 2, 3 }));
  4319. s.selectOnly (4);
  4320. s.toggle (4); // the last one stays
  4321. CHECK ((s.rows == std::vector<int> { 4 }));
  4322. s.selectAll (3);
  4323. CHECK ((s.rows == std::vector<int> { 0, 1, 2 }));
  4324. s.rows = { 7, 9 };
  4325. s.clamp (5);
  4326. CHECK (s.rows.size() == 1 && s.rows[0] < 5);
  4327. }
  4328. TEST (workflow_move_clone_insert_channels)
  4329. {
  4330. auto song = lynx::Song::makeDefault();
  4331. const auto names = [&] {
  4332. std::vector<std::string> n;
  4333. for (const auto& c : song.channels)
  4334. n.push_back (c.name);
  4335. return n;
  4336. };
  4337. const auto original = names();
  4338. const auto count = (int) song.channels.size();
  4339. CHECK (count >= 4);
  4340. // references that must follow their channel
  4341. song.patterns[0].notes.push_back ({ 0, 240, 1, 64 });
  4342. lynx::Automation a;
  4343. a.target = { lynx::AutomationTargetKind::channelVolume, 1 };
  4344. song.automations.push_back (a);
  4345. song.midiLinks.push_back ({ 7, -1, { lynx::AutomationTargetKind::channelPan, 3 } });
  4346. lynx::Clip audio;
  4347. audio.kind = lynx::ClipKind::audio;
  4348. audio.channel = 3;
  4349. song.playlist.push_back (audio);
  4350. std::vector<int> selection { 1, 3 };
  4351. CHECK (lynx::moveChannels (song, selection, -1));
  4352. CHECK ((selection == std::vector<int> { 0, 2 }));
  4353. CHECK (song.channels[0].name == original[1] && song.channels[1].name == original[0] && song.channels[2].name == original[3]
  4354. && song.channels[3].name == original[2]);
  4355. CHECK (song.automations[0].target.index == 0 && song.midiLinks[0].target.index == 2 && song.playlist.back().channel == 2);
  4356. CHECK (std::any_of (song.patterns[0].notes.begin(), song.patterns[0].notes.end(),
  4357. [] (const lynx::Note& n) { return n.channel == 0 && n.key == 64; }));
  4358. CHECK (! lynx::moveChannels (song, selection, -1)); // the block is at the top
  4359. CHECK (lynx::moveChannels (song, selection, 1) && (selection == std::vector<int> { 1, 3 }) && names() == original);
  4360. // clone: settings, not notes, right below, with a new name
  4361. song.channels[1].volume = 0.33f;
  4362. const auto notesBefore = song.patterns[0].notes.size();
  4363. const auto clone = lynx::cloneChannel (song, 1);
  4364. CHECK (clone == 2 && (int) song.channels.size() == count + 1);
  4365. CHECK (song.channels[2].name == original[1] + " #2" && song.channels[2].volume == 0.33f);
  4366. CHECK (song.patterns[0].notes.size() == notesBefore);
  4367. CHECK (song.channels[3].name == original[2] && song.automations[0].target.index == 1);
  4368. CHECK (lynx::cloneChannel (song, 1) == 2 && song.channels[2].name == original[1] + " #3");
  4369. // remove several
  4370. CHECK (lynx::removeChannels (song, { 2, 3, 2 }) == 2 && (int) song.channels.size() == count);
  4371. CHECK (names() == original);
  4372. }
  4373. TEST (workflow_send_channels_to_free_inserts)
  4374. {
  4375. auto song = lynx::Song::makeDefault();
  4376. for (auto& c : song.channels)
  4377. c.mixerTrack = 0;
  4378. song.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay)); // not free: has effects
  4379. song.channels[0].mixerTrack = 2; // not free: used
  4380. song.setRoute (5, 3, true); // 3 is not free: receives a send
  4381. CHECK (! lynx::isInsertFree (song, 1) && ! lynx::isInsertFree (song, 2) && ! lynx::isInsertFree (song, 3) && lynx::isInsertFree (song, 4));
  4382. song.channels[1].colour = 0xff445566;
  4383. const auto tracks = lynx::sendChannelsToFreeInserts (song, { 1, 2 });
  4384. CHECK ((tracks == std::vector<int> { 4, 5 }) || (tracks == std::vector<int> { 4, 6 }));
  4385. CHECK (song.channels[1].mixerTrack == 4 && song.mixer[4].name == song.channels[1].name && song.mixer[4].colour == 0xff445566u);
  4386. CHECK (song.mixer[(std::size_t) tracks[1]].name == song.channels[2].name);
  4387. // with no free insert left, a new one is added at the end
  4388. auto full = lynx::Song::makeDefault();
  4389. full.mixer = lynx::Song::defaultMixer (1);
  4390. full.channels[0].mixerTrack = 1;
  4391. const auto added = lynx::sendChannelsToFreeInserts (full, { 1 });
  4392. CHECK (added.size() == 1 && added[0] == 2 && full.mixer.size() == 3 && full.channels[1].mixerTrack == 2);
  4393. }
  4394. TEST (workflow_palette_random_colour)
  4395. {
  4396. const auto& palette = lynx::lynxPalette();
  4397. for (std::uint32_t seed = 0; seed < 50; ++seed)
  4398. {
  4399. const auto current = palette[seed % palette.size()];
  4400. const auto c = lynx::randomPaletteColour (current, seed);
  4401. CHECK (c != current && std::find (palette.begin(), palette.end(), c) != palette.end());
  4402. }
  4403. }
  4404. TEST (workflow_key_map)
  4405. {
  4406. using namespace lynx::keys;
  4407. KeyMap map;
  4408. const auto global = Context::global, rack = Context::channelRack;
  4409. CHECK (map.find ({ space, none }, global, true) == "transport.playStop");
  4410. CHECK (map.find ({ space, ctrl }, global, true) == "transport.pause");
  4411. CHECK (map.find ({ f6, none }, global, true) == "panel.channelRack");
  4412. CHECK (map.find ({ f8, alt }, global, false) == "panel.browser");
  4413. CHECK (map.find ({ insert, ctrl | shift }, global, false) == "pattern.insert");
  4414. CHECK (map.find ({ numpadPlus, none }, rack, true) == "pattern.next");
  4415. // panel context: only while focused
  4416. CHECK (map.find ({ 'L', ctrl }, rack, true) == "rack.sendToInserts");
  4417. CHECK (map.find ({ 'L', ctrl }, global, true).empty());
  4418. CHECK (map.find ({ up, alt }, rack, false) == "rack.moveUp");
  4419. // typing piano: note keys play, other plain keys only for whilePiano actions; chords always work
  4420. CHECK (KeyMap::playsNote ({ 'Z', none }, true) && ! KeyMap::playsNote ({ 'Z', none }, false) && ! KeyMap::playsNote ({ 'Z', ctrl }, true));
  4421. CHECK (map.find ({ 'L', none }, global, true) == "transport.toggleMode");
  4422. CHECK (map.find ({ '1', none }, rack, false) == "rack.mute1" && map.find ({ '0', none }, rack, false) == "rack.mute10");
  4423. CHECK (map.find ({ '1', none }, rack, true).empty()); // a plain digit is not a shortcut while the piano is on
  4424. CHECK (map.find ({ '2', ctrl }, rack, true) == "rack.solo2");
  4425. CHECK (typingPianoNote ('Z') == 60 && typingPianoNote ('q') == 72 && typingPianoNote ('P') == 88 && typingPianoNote ('L') == -1);
  4426. CHECK (map.conflicts().empty());
  4427. // chord text
  4428. CHECK (toString ({ f4, ctrl | shift }) == "Ctrl+Shift+F4" && toString ({ numpadMinus, none }) == "Numpad -");
  4429. CHECK (parseChord ("Shift+Ctrl+Ins") == (Chord { insert, ctrl | shift }));
  4430. CHECK (parseChord ("alt+up") == (Chord { up, alt }) && parseChord ("k") == (Chord { 'K', none }));
  4431. CHECK (parseChord ("Numpad +") == (Chord { numpadPlus, none }) && ! parseChord ("F13") && ! parseChord ("Ctrl+"));
  4432. for (const auto& a : actions())
  4433. for (const auto& c : a.defaults)
  4434. CHECK (parseChord (toString (c)) == c);
  4435. // JSON overrides
  4436. std::vector<std::string> errors;
  4437. CHECK (map.loadJson (R"({ "pattern.next": "Ctrl+Right", "rack.clone": ["Alt+D", "Ctrl+D"], "help.shortcuts": "", "nope": "F1", "file.open": "Hyper+Q" })", &errors));
  4438. CHECK (errors.size() == 2);
  4439. CHECK (map.find ({ right, ctrl }, global, false) == "pattern.next" && map.find ({ numpadPlus, none }, global, false).empty());
  4440. CHECK (map.find ({ 'D', ctrl }, rack, false) == "rack.clone" && map.find ({ f1, none }, global, false).empty());
  4441. map.setChords ("pattern.previous", { { right, ctrl } });
  4442. CHECK (map.conflicts().size() == 1);
  4443. KeyMap reloaded;
  4444. CHECK (reloaded.loadJson (map.toJson()) && reloaded.chordsFor ("rack.clone") == map.chordsFor ("rack.clone"));
  4445. CHECK (! map.loadJson ("[1, 2]") && ! map.loadJson ("{\"a\": }"));
  4446. map.resetToDefaults();
  4447. CHECK (map.find ({ numpadPlus, none }, global, false) == "pattern.next");
  4448. }
  4449. TEST (workflow_workspace_layout)
  4450. {
  4451. using namespace lynx::workspace;
  4452. auto l = Layout::makeDefault (1280, 620);
  4453. // every visible panel is inside the desktop; the default shows Browser, Playlist and Channel Rack
  4454. for (const auto& p : l.panels)
  4455. CHECK (p.bounds.x >= 0 && p.bounds.y >= 0 && p.bounds.right() <= 1280 && p.bounds.bottom() <= 620 && p.bounds.w >= minWidth);
  4456. CHECK (l[Panel::browser].visible && l[Panel::playlist].visible && l[Panel::channelRack].visible);
  4457. CHECK (! l[Panel::pianoRoll].visible && ! l[Panel::mixer].visible);
  4458. CHECK (l[Panel::playlist].bounds.x == l[Panel::browser].bounds.right() && l[Panel::playlist].bounds.right() == 1280);
  4459. CHECK (l.isFrontmost (Panel::channelRack) && l.focused == Panel::channelRack);
  4460. // toggle: show+focus, focus, hide
  4461. CHECK (l.toggle (Panel::mixer) && l.focused == Panel::mixer && l.isFrontmost (Panel::mixer));
  4462. CHECK (l.toggle (Panel::channelRack) && l.focused == Panel::channelRack && l.isFrontmost (Panel::channelRack));
  4463. CHECK (! l.toggle (Panel::channelRack) && ! l[Panel::channelRack].visible && l.focused == Panel::mixer);
  4464. l.toggleMaximised (Panel::playlist);
  4465. CHECK (l[Panel::playlist].maximised && l.focused == Panel::playlist);
  4466. // save and load at another size: positions scale
  4467. l[Panel::mixer].detached = true;
  4468. l[Panel::mixer].windowBounds = { 100, 50, 900, 500 };
  4469. const auto text = l.serialise();
  4470. const auto big = Layout::parse (text, 2560, 1240);
  4471. CHECK (big.has_value());
  4472. if (big)
  4473. {
  4474. CHECK ((*big)[Panel::playlist].maximised && (*big)[Panel::mixer].detached && (*big)[Panel::mixer].windowBounds.w == 900);
  4475. CHECK (std::abs ((*big)[Panel::playlist].bounds.x - 2 * l[Panel::playlist].bounds.x) <= 1);
  4476. CHECK (big->order == l.order && big->focused == l.focused);
  4477. }
  4478. CHECK (! Layout::parse ("garbage", 100, 100) && ! Layout::parse ("lynx-layout 1\npanel nowhere 1 0 0 0 0 1 1 0 0 0 0\n", 100, 100));
  4479. // resize keeps panels inside and edges glued to the border
  4480. l.resize (1000, 500);
  4481. CHECK (l[Panel::playlist].bounds.right() == 1000 && l[Panel::browser].bounds.bottom() == 500);
  4482. for (const auto& p : l.panels)
  4483. CHECK (p.bounds.right() <= 1000 && p.bounds.bottom() <= 500);
  4484. // off-screen panels come back
  4485. l[Panel::pianoRoll].bounds = { 5000, -300, 400, 300 };
  4486. CHECK (l.bringBackOffscreen() == 1 && l[Panel::pianoRoll].bounds.x + 400 <= 1000 && l[Panel::pianoRoll].bounds.y == 0);
  4487. // snapping: to the desktop, to another panel, and resizing one edge
  4488. CHECK ((snap ({ 5, 6, 200, 100 }, {}, 1000, 500) == Rect { 0, 0, 200, 100 }));
  4489. CHECK ((snap ({ 304, 50, 200, 100 }, { { 0, 0, 300, 400 } }, 1000, 500) == Rect { 300, 50, 200, 100 }));
  4490. CHECK ((snap ({ 304, 50, 200, 100 }, { { 0, 0, 300, 400 } }, 1000, 500, 2) == Rect { 304, 50, 200, 100 })); // out of range
  4491. CHECK ((snap ({ 100, 100, 195, 100 }, { { 300, 0, 300, 400 } }, 1000, 500, 8, right) == Rect { 100, 100, 200, 100 }));
  4492. CHECK ((snap ({ 100, 100, 195, 100 }, { { 300, 1000, 300, 400 } }, 2000, 2000, 8, right) == Rect { 100, 100, 195, 100 })); // not facing
  4493. }
  4494. TEST (workflow_control_math)
  4495. {
  4496. using namespace lynx::controls;
  4497. CHECK (std::abs (dragValue (0.5, 75, 0, 1, 150, false) - 1.0) < 1e-9);
  4498. CHECK (std::abs (dragValue (0.5, 75, 0, 1, 150, true) - 0.55) < 1e-9);
  4499. CHECK (dragValue (0.5, -1000, -1, 1, 150, false) == -1.0);
  4500. CHECK (std::abs (wheelValue (0.5, 1, 0, 1, false) - 0.52) < 1e-9 && std::abs (wheelValue (0.5, -1, 0, 1, true) - 0.498) < 1e-9);
  4501. CHECK (wheelValue (3, 1, 0, 10, true, 1) == 4.0); // integer controls move at least one step
  4502. CHECK (std::abs (snapToInterval (0.234, 0, 0.1) - 0.2) < 1e-9);
  4503. CHECK (tempoDrag (130.0, 8, false, false) == 132.0 && tempoDrag (130.0, -3, false, false) == 130.0);
  4504. CHECK (std::abs (tempoDrag (130.0, 25, true, false) - 130.25) < 1e-9);
  4505. CHECK (std::abs (tempoDrag (130.0, 8, false, true) - 130.2) < 1e-9);
  4506. CHECK (tempoDrag (520.0, 400, false, false) == lynx::maxTempo && halfTempo (15.0) == lynx::minTempo && doubleTempo (130.0) == 260.0);
  4507. TapTempo tap;
  4508. CHECK (! tap.tap (1000.0));
  4509. CHECK (tap.tap (1500.0) == 120.0);
  4510. CHECK (tap.tap (2000.0) == 120.0 && tap.count() == 3);
  4511. CHECK (std::abs (*tap.tap (2400.0) - 128.57) < 0.01); // average of 500, 500, 400 ms
  4512. CHECK (! tap.tap (9000.0) && tap.count() == 1); // a long pause starts over
  4513. }
  4514. int main (int argc, char** argv)
  4515. {
  4516. if (argc > 1)
  4517. realFlpDir = argv[1];
  4518. for (auto& [name, fn] : registry())
  4519. {
  4520. std::printf ("%s\n", name);
  4521. fn();
  4522. }
  4523. std::printf ("\n%d checks, %d failures\n", checks, failures);
  4524. return failures == 0 ? 0 : 1;
  4525. }
  4526. TEST (synth_cutoff_keytrack)
  4527. {
  4528. // the cutoff follows the note from key 48 (130.81 Hz), like Harmor's "Key to filter frequency"
  4529. auto rms = [] (float keyTrack, int key) {
  4530. lynx::SynthSettings s;
  4531. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  4532. s.cutoff = 130.81f;
  4533. s.keyTrack = keyTrack;
  4534. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  4535. inst->prepare (48000.0);
  4536. lynx::ChannelDef c;
  4537. c.synth = s;
  4538. inst->configure (c, 120.0);
  4539. inst->noteOn (key, 1.0f);
  4540. std::vector<float> l (24000), r (24000);
  4541. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  4542. double e = 0.0;
  4543. for (int i = 4800; i < 24000; ++i)
  4544. e += (double) l[(std::size_t) i] * l[(std::size_t) i];
  4545. return std::sqrt (e / 19200.0);
  4546. };
  4547. const auto fixed = rms (0.0f, 72), tracked = rms (1.0f, 72);
  4548. CHECK (tracked > 4.0 * fixed); // 2 octaves up: without keytrack the low-pass cuts
  4549. CHECK (std::abs (rms (1.0f, 48) - rms (0.0f, 48)) < 0.05 * rms (0.0f, 48)); // unchanged at the reference key
  4550. }
  4551. namespace
  4552. {
  4553. std::vector<float> renderSynthNote (const lynx::SynthSettings& s, int key, int frames)
  4554. {
  4555. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  4556. inst->prepare (48000.0);
  4557. lynx::ChannelDef c;
  4558. c.synth = s;
  4559. inst->configure (c, 120.0);
  4560. inst->noteOn (key, 1.0f);
  4561. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  4562. inst->render (l.data(), r.data(), frames, 1.0f, 1.0f);
  4563. return l;
  4564. }
  4565. double goertzel (const std::vector<float>& x, double f, int from, int to)
  4566. {
  4567. const auto w = 2.0 * 3.141592653589793 * f / 48000.0, k = 2.0 * std::cos (w);
  4568. double s1 = 0.0, s2 = 0.0;
  4569. for (int i = from; i < to; ++i)
  4570. {
  4571. const auto s0 = x[(std::size_t) i] + k * s1 - s2;
  4572. s2 = s1;
  4573. s1 = s0;
  4574. }
  4575. return s1 * s1 + s2 * s2 - k * s1 * s2;
  4576. }
  4577. } // namespace
  4578. TEST (synth_pitch_sweep_ring_and_bands)
  4579. {
  4580. lynx::SynthSettings sine;
  4581. sine.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  4582. sine.cutoff = 20000.0f;
  4583. // sweep: starts at f·(1 + sweep) and returns to f (time constant s = 10 ms; s⁴ falls 4× faster)
  4584. auto sweep = sine;
  4585. sweep.sweep = 1.0f;
  4586. sweep.sweepTime = 0.01f;
  4587. const auto a = renderSynthNote (sweep, 69, 24000);
  4588. auto crossings = [] (const std::vector<float>& x, int to) {
  4589. int n = 0;
  4590. for (int i = 1; i < to; ++i)
  4591. n += (x[(std::size_t) i - 1] < 0.0f) != (x[(std::size_t) i] < 0.0f);
  4592. return n;
  4593. };
  4594. CHECK (crossings (a, 480) > 1.3 * crossings (renderSynthNote (sine, 69, 480), 480)); // 10 ms: much higher
  4595. CHECK (goertzel (a, 440.0, 12000, 24000) > 100.0 * goertzel (a, 880.0, 12000, 24000));
  4596. // ring with |a| = 1: carrier 440 × modulator 110 -> only 330 and 550, no 440
  4597. auto ring = sine;
  4598. ring.am = ring.ring = true;
  4599. ring.osc[2] = { lynx::Waveform::sine, -2, 0.0f, 1.0f };
  4600. const auto b = renderSynthNote (ring, 69, 24000);
  4601. CHECK (goertzel (b, 330.0, 4800, 24000) > 100.0 * goertzel (b, 440.0, 4800, 24000));
  4602. CHECK (goertzel (b, 550.0, 4800, 24000) > 100.0 * goertzel (b, 440.0, 4800, 24000));
  4603. // 3 bands: muting the high knocks down a 4 kHz note and barely touches an 80 Hz one
  4604. auto bands = sine;
  4605. bands.bandGain = { 1.0f, 1.0f, 0.0f };
  4606. auto rms = [] (const std::vector<float>& x) {
  4607. double e = 0.0;
  4608. for (std::size_t i = 4800; i < x.size(); ++i)
  4609. e += (double) x[i] * x[i];
  4610. return std::sqrt (e / (double) (x.size() - 4800));
  4611. };
  4612. CHECK (rms (renderSynthNote (bands, 107, 24000)) < 0.3 * rms (renderSynthNote (sine, 107, 24000)));
  4613. CHECK (rms (renderSynthNote (bands, 28, 24000)) > 0.85 * rms (renderSynthNote (sine, 28, 24000)));
  4614. }
  4615. TEST (love_philter_map_evaluation)
  4616. {
  4617. lynx::LovePhilterMap line { { { 0.0, 0.0 }, { 1.0, 1.0 } } };
  4618. CHECK (std::abs (lynx::lovePhilterMapAt (line, 0.5) - 0.5) < 1e-9);
  4619. CHECK (std::abs (lynx::lovePhilterMapAt (line, 1.0) - 1.0) < 1e-9);
  4620. // steps (Δx = 0): 1 until 0.4375, ramp to 0 at 0.5, then 0
  4621. lynx::LovePhilterMap steps { { { 0.0, 1.0 }, { 0.4375, 1.0 }, { 0.0625, 0.0 }, { 0.5, 0.0 } } };
  4622. CHECK (lynx::lovePhilterMapAt (steps, 0.27) == 1.0);
  4623. CHECK (lynx::lovePhilterMapAt (steps, 0.75) == 0.0);
  4624. CHECK (std::abs (lynx::lovePhilterMapAt (steps, 0.46875) - 0.5) < 1e-9);
  4625. CHECK (lynx::lovePhilterMapAt ({}, 0.3) == 1.0);
  4626. }
  4627. TEST (lofi_holds_and_quantizes)
  4628. {
  4629. auto fx = lynx::makeEffect (lynx::EffectKind::lofi);
  4630. fx->prepare (48000.0);
  4631. auto slot = lynx::makeEffectSlot (lynx::EffectKind::lofi);
  4632. slot.params[0] = 0.5f; // 128·0.125 + 1 = 17 samples
  4633. slot.params[1] = 1.0f; // 65536/2049 ≈ 32 levels
  4634. std::vector<float> l (170), r (170);
  4635. for (std::size_t i = 0; i < l.size(); ++i)
  4636. l[i] = r[i] = 0.9f * (float) std::sin (0.05 * (double) i);
  4637. const auto original = l;
  4638. fx->process (l.data(), r.data(), 170, slot.params, 120.0);
  4639. for (int i = 0; i < 17; ++i)
  4640. CHECK (l[(std::size_t) i] == l[0]);
  4641. CHECK (l[17] != l[16]);
  4642. const auto step = 2.0f * 2049.0f / 65536.0f;
  4643. for (auto v : l)
  4644. CHECK (std::abs (v / step - std::round (v / step)) < 1e-3f);
  4645. CHECK (std::abs (l[0] - original[0]) <= step);
  4646. CHECK (lynx::formatEffectParam (lynx::EffectKind::lofi, 1, 0.0f, 120.0) == "16.0 bits");
  4647. }
  4648. namespace
  4649. {
  4650. lynx::EffectParams effectorParams (int type, float x, float y)
  4651. {
  4652. auto slot = lynx::makeEffectSlot (lynx::EffectKind::effector);
  4653. slot.params[0] = (float) type / 11.0f;
  4654. slot.params[3] = x;
  4655. slot.params[4] = y;
  4656. return slot.params;
  4657. }
  4658. } // namespace
  4659. TEST (effector_algorithms)
  4660. {
  4661. CHECK (lynx::effector::typeOf (8.0f / 11.0f) == 8);
  4662. CHECK (std::string (lynx::effector::typeName (11)) == "Ring");
  4663. CHECK (std::abs (lynx::effector::rateBeats (0.5f, 0.0f) - 0.75) < 1e-9); // trunc(8·0.5 + 0.5) = 4 -> 3/4
  4664. CHECK (std::abs (lynx::effector::rateBeats (1.0f, 0.5f) - 2.0) < 1e-9); // 8 × (1 − 0.5)²
  4665. auto run = [] (const lynx::EffectParams& p, std::vector<float> in, double bpm = 120.0) {
  4666. auto fx = lynx::makeEffect (lynx::EffectKind::effector);
  4667. fx->prepare (48000.0);
  4668. fx->setSongPosition (0.0);
  4669. auto r = in;
  4670. fx->process (in.data(), r.data(), (int) in.size(), p, bpm);
  4671. return in;
  4672. };
  4673. // Distort with Y = 1 (everything goes to the cascade): 0.5 comes out 0.5 (compensation G = 0.5/F(0.5))
  4674. {
  4675. auto p = effectorParams (0, 0.5f, 1.0f);
  4676. const auto out = run (p, std::vector<float> (4800, 0.5f));
  4677. CHECK (std::abs (out.back() - 0.5f) < 1e-3f);
  4678. const auto small = run (p, std::vector<float> (4800, 0.05f));
  4679. CHECK (small.back() > 0.45f && small.back() < 0.5f); // saturates near ±0.5
  4680. }
  4681. // Ring: DC 1 becomes the carrier sine, 2^(8.7·0 + 5) = 32 Hz -> 32 cycles per second
  4682. {
  4683. auto p = effectorParams (11, 0.0f, 0.0f);
  4684. const auto out = run (p, std::vector<float> (48000, 1.0f));
  4685. int crossings = 0;
  4686. for (std::size_t i = 4800; i < out.size(); ++i)
  4687. crossings += (out[i - 1] < 0.0f) != (out[i] < 0.0f);
  4688. CHECK (crossings >= 56 && crossings <= 60); // 0.9 s × 32 Hz × 2
  4689. }
  4690. // Trancer, Y = 0: at the start of the period the gain drops to zero; X = 1 returns only at the end of the period
  4691. {
  4692. auto p = effectorParams (8, 1.0f, 0.0f);
  4693. p[5] = 1.0f; // 8/1 = 8 beats = 4 s at 120 BPM
  4694. const auto out = run (p, std::vector<float> (48000, 1.0f));
  4695. CHECK (out[100] > 0.3f); // still rising on the "and" (1% of the period = 40 ms)
  4696. CHECK (out[24000] < 0.05f); // 0.5 s: trough
  4697. }
  4698. // Reverb with Wet = 0: the dry passes intact
  4699. {
  4700. auto p = effectorParams (6, 0.5f, 0.5f);
  4701. p[2] = 0.0f;
  4702. std::vector<float> in (4800);
  4703. for (std::size_t i = 0; i < in.size(); ++i)
  4704. in[i] = (float) std::sin (0.01 * (double) i);
  4705. const auto out = run (p, in);
  4706. for (std::size_t i = 0; i < in.size(); ++i)
  4707. CHECK (std::abs (out[i] - in[i]) < 1e-6f);
  4708. }
  4709. // Delay: the echo arrives after the Mod Rate period (1/4 beat at 120 BPM = 125 ms), at level X²
  4710. {
  4711. auto p = effectorParams (5, 0.7f, 0.5f);
  4712. p[5] = 1.0f / 8.0f; // index 1 = 1/4
  4713. std::vector<float> in (12000, 0.0f);
  4714. in[0] = 1.0f;
  4715. const auto out = run (p, in);
  4716. CHECK (std::abs (out[6000] - 0.49f) < 0.02f);
  4717. CHECK (std::abs (out[3000]) < 1e-6f);
  4718. }
  4719. // Stutter: repeats the recorded start every period
  4720. {
  4721. auto p = effectorParams (9, 0.0f, 0.0f);
  4722. p[5] = 0.0f; // 1/8 beat = 62.5 ms = 3000 samples
  4723. std::vector<float> in (9000);
  4724. for (std::size_t i = 0; i < in.size(); ++i)
  4725. in[i] = (float) i / 9000.0f;
  4726. const auto out = run (p, in);
  4727. CHECK (std::abs (out[3000 + 500] - in[500]) < 0.01f); // after the crossfade, it's the start again
  4728. CHECK (std::abs (out[1000] - in[1000]) < 1e-6f);
  4729. }
  4730. }
  4731. TEST (crossover_linkwitz_riley_sums_flat)
  4732. {
  4733. // low band + high band of the same crossover: sum with magnitude 1 (Linkwitz-Riley; for 12 and 36 dB the HP is inverted)
  4734. for (const auto combo : { 1, 3, 4, 5, 6, 7 })
  4735. for (const auto testHz : { 200.0, 1000.0, 5000.0 })
  4736. {
  4737. auto run = [&] (bool high) {
  4738. auto fx = lynx::makeEffect (lynx::EffectKind::crossover);
  4739. fx->prepare (48000.0);
  4740. auto slot = lynx::makeEffectSlot (lynx::EffectKind::crossover);
  4741. const auto value = (float) (std::log2 (1000.0 / 30.0) / 9.0589);
  4742. slot.params[high ? 0 : 3] = 1.0f;
  4743. slot.params[high ? 1 : 4] = value;
  4744. slot.params[high ? 2 : 5] = (float) combo / 7.0f;
  4745. std::vector<float> l (24000), r (24000);
  4746. for (std::size_t i = 0; i < l.size(); ++i)
  4747. l[i] = r[i] = (float) std::sin (2.0 * 3.141592653589793 * testHz * (double) i / 48000.0);
  4748. fx->process (l.data(), r.data(), 24000, slot.params, 120.0);
  4749. return l;
  4750. };
  4751. const auto low = run (false), high = run (true);
  4752. double peak = 0.0;
  4753. for (std::size_t i = 12000; i < low.size(); ++i)
  4754. peak = std::max (peak, (double) std::abs (low[i] + high[i]));
  4755. CHECK (std::abs (peak - 1.0) < 0.02);
  4756. }
  4757. // 96 dB/oct: two octaves above the cutoff the low-pass is already below −150 dB... in practice, very low
  4758. auto fx = lynx::makeEffect (lynx::EffectKind::crossover);
  4759. fx->prepare (48000.0);
  4760. auto slot = lynx::makeEffectSlot (lynx::EffectKind::crossover);
  4761. slot.params[3] = 1.0f;
  4762. slot.params[4] = (float) (std::log2 (500.0 / 30.0) / 9.0589);
  4763. slot.params[5] = 1.0f;
  4764. std::vector<float> l (24000), r (24000);
  4765. for (std::size_t i = 0; i < l.size(); ++i)
  4766. l[i] = r[i] = (float) std::sin (2.0 * 3.141592653589793 * 2000.0 * (double) i / 48000.0);
  4767. fx->process (l.data(), r.data(), 24000, slot.params, 120.0);
  4768. float peak = 0.0f;
  4769. for (std::size_t i = 12000; i < l.size(); ++i)
  4770. peak = std::max (peak, std::abs (l[i]));
  4771. CHECK (peak < 1e-4f);
  4772. }
  4773. TEST (rhythm_gain_and_autopan)
  4774. {
  4775. // 1-beat gate: 1 → 0 at 0.5 beat (linear) → 1 at the end; at 120 BPM 1 beat = 24000 samples at 48 kHz
  4776. auto slot = lynx::makeEffectSlot (lynx::EffectKind::rhythmGain);
  4777. slot.params[0] = 1.0f / 64.0f;
  4778. slot.params[1] = 3.0f / 12.0f;
  4779. const float pts[3][3] = { { 0.0f, 1.0f, 0.5f }, { 0.5f, 0.0f, 0.5f }, { 1.0f, 1.0f, 0.5f } };
  4780. for (int k = 0; k < 3; ++k)
  4781. for (int j = 0; j < 3; ++j)
  4782. slot.params[(std::size_t) (2 + 3 * k + j)] = pts[k][j];
  4783. auto fx = lynx::makeEffect (lynx::EffectKind::rhythmGain);
  4784. fx->prepare (48000.0);
  4785. fx->setSongPosition (960.0 * 2.0); // beat 2: phase 0
  4786. std::vector<float> l (24000, 1.0f), r (24000, 1.0f);
  4787. fx->process (l.data(), r.data(), 24000, slot.params, 120.0);
  4788. CHECK (std::abs (l[0] - 1.0f) < 1e-3f);
  4789. CHECK (std::abs (l[6000] - 0.5f) < 1e-3f);
  4790. CHECK (l[12000] < 1e-3f);
  4791. CHECK (std::abs (l[18000] - 0.5f) < 1e-3f);
  4792. // positive tension: changes quickly at the start of the segment
  4793. CHECK (lynx::effectInfo (lynx::EffectKind::rhythmGain).params.size() == 39);
  4794. // auto-pan: 1-beat period, full depth; start phase 0.75 -> W = 0 rising (pan centered)
  4795. auto pan = lynx::makeEffectSlot (lynx::EffectKind::autoPan);
  4796. pan.params[0] = 1.0f / 64.0f;
  4797. pan.params[1] = 1.0f;
  4798. auto ap = lynx::makeEffect (lynx::EffectKind::autoPan);
  4799. ap->prepare (48000.0);
  4800. ap->setSongPosition (0.0);
  4801. std::vector<float> a (24000, 1.0f), b (24000, 1.0f);
  4802. ap->process (a.data(), b.data(), 24000, pan.params, 120.0);
  4803. CHECK (std::abs (a[0] - 1.0f) < 1e-3f && std::abs (b[0] - 1.0f) < 1e-3f);
  4804. CHECK (a[6000] < 0.01f && std::abs (b[6000] - 1.0f) < 1e-3f); // ¼ cycle later: fully right
  4805. }
  4806. TEST (vocoder_side_inputs_split_modulator_and_carrier)
  4807. {
  4808. // "Side inputs" mode (Vocodex): modulator from side input 1 (noise in the first half), carrier from side input 2
  4809. // (saw), own input silent → the output follows the side modulator; with input 1 silent, the output is silent
  4810. auto slot = lynx::makeEffectSlot (lynx::EffectKind::vocoder);
  4811. slot.params[16] = 1.0f;
  4812. auto fx = lynx::makeEffect (lynx::EffectKind::vocoder);
  4813. fx->prepare (48000.0);
  4814. std::vector<float> modL (48000), car (48000), l (48000, 0.0f), r (48000, 0.0f);
  4815. std::uint32_t seed = 1;
  4816. for (std::size_t i = 0; i < modL.size(); ++i)
  4817. {
  4818. seed = seed * 1664525u + 1013904223u;
  4819. modL[i] = i < 24000 ? ((float) (seed >> 8) / 16777216.0f - 0.5f) : 0.0f;
  4820. car[i] = (float) (2.0 * std::fmod ((double) i * 220.0 / 48000.0, 1.0) - 1.0) * 0.5f;
  4821. }
  4822. for (int done = 0; done < 48000; done += 480)
  4823. {
  4824. fx->setSidechain (modL.data() + done, modL.data() + done);
  4825. fx->setSidechain2 (car.data() + done, car.data() + done);
  4826. fx->process (l.data() + done, r.data() + done, 480, slot.params, 120.0);
  4827. }
  4828. auto rms = [&] (int from, int to) {
  4829. double e = 0.0;
  4830. for (int i = from; i < to; ++i)
  4831. e += (double) l[(std::size_t) i] * l[(std::size_t) i];
  4832. return std::sqrt (e / (to - from));
  4833. };
  4834. CHECK (rms (6000, 20000) > 0.01);
  4835. CHECK (rms (40000, 48000) < 0.1 * rms (6000, 20000));
  4836. // the side modulator configured but silent: nothing comes out (the own input is not used instead)
  4837. std::vector<float> a (4800, 0.3f), b (4800, 0.3f);
  4838. for (int done = 0; done < 4800; done += 480)
  4839. {
  4840. fx->setSidechain (nullptr, nullptr);
  4841. fx->setSidechain2 (car.data() + done, car.data() + done);
  4842. fx->process (a.data() + done, b.data() + done, 480, slot.params, 120.0);
  4843. }
  4844. CHECK (std::abs (a[4700]) < 0.05f);
  4845. }
  4846. TEST (vocoder_follows_modulator)
  4847. {
  4848. // modulator (L) plays only in the first half; carrier (R) is a continuous saw: the wet follows the modulator
  4849. auto slot = lynx::makeEffectSlot (lynx::EffectKind::vocoder);
  4850. auto fx = lynx::makeEffect (lynx::EffectKind::vocoder);
  4851. fx->prepare (48000.0);
  4852. std::vector<float> l (48000), r (48000);
  4853. std::uint32_t seed = 1;
  4854. for (std::size_t i = 0; i < l.size(); ++i)
  4855. {
  4856. seed = seed * 1664525u + 1013904223u;
  4857. l[i] = i < 24000 ? ((float) (seed >> 8) / 16777216.0f - 0.5f) : 0.0f;
  4858. r[i] = (float) (2.0 * std::fmod ((double) i * 220.0 / 48000.0, 1.0) - 1.0) * 0.5f;
  4859. }
  4860. fx->process (l.data(), r.data(), 48000, slot.params, 120.0);
  4861. auto rms = [&] (int from, int to) {
  4862. double e = 0.0;
  4863. for (int i = from; i < to; ++i)
  4864. e += (double) l[(std::size_t) i] * l[(std::size_t) i];
  4865. return std::sqrt (e / (to - from));
  4866. };
  4867. CHECK (rms (6000, 20000) > 0.01);
  4868. CHECK (rms (40000, 48000) < 0.1 * rms (6000, 20000)); // modulator silent: the vocoder fades out (100 ms release)
  4869. for (std::size_t i = 0; i < l.size(); ++i)
  4870. CHECK (l[i] == r[i] && std::isfinite (l[i])); // mono output
  4871. }
  4872. // Vocodex (REA_rodada35): a synthetic state in FL's layout (version 8, 13 maps, 20 parameters, the 0x24 block,
  4873. // 13 map-axis bytes, tone, notes)
  4874. struct VocodexSpec
  4875. {
  4876. // Wet, SG, ModVol, ModHP, CarVol, CarLP, CarNoise, CarNoiseHP, Hold, Att, AttCurve, Rel, RelCurve, Freeze, BW,
  4877. // Flatness, ModBW, ModPitch, FatPitch, FatPan
  4878. std::array<std::int32_t, 20> params { 1000, 0, 0, 0, 0, 65536, 0, 0, 0, 2000, 0, 3000, 0, 0, 1000, 0, 2000, 0, 0, 0 };
  4879. std::array<std::int32_t, 7> block { 0, 2, 0, 24, 1, 1, 2 }; // hold mode, order, unison, bands, draft field, ModIn, CarIn
  4880. std::array<std::uint8_t, 8> flags { 0, 1, 0, 1, 1, 0, 0, 0 }; // L-R, MIN TIMES, TO MOD, THREADED, subtractive, TO NOISE, FROM CAR, FROM CONS
  4881. std::vector<std::uint8_t> bytes() const
  4882. {
  4883. std::vector<std::uint8_t> d;
  4884. auto put = [&d] (const void* p, std::size_t n) { d.insert (d.end(), (const std::uint8_t*) p, (const std::uint8_t*) p + n); };
  4885. auto i32 = [&] (std::int32_t v) { put (&v, 4); };
  4886. i32 (8 << 16);
  4887. for (int m = 0; m < 13; ++m)
  4888. {
  4889. const double y0 = m == 8 ? 0.1429 : (m == 3 || m == 4 || m == 11) ? 0.0 : 0.5;
  4890. const double y1 = m == 8 ? 0.9918 : y0;
  4891. i32 (1), i32 (0), i32 (2);
  4892. for (const auto& [dx, y] : { std::pair { 0.0, y0 }, std::pair { 1.0, y1 } })
  4893. {
  4894. put (&dx, 8), put (&y, 8);
  4895. i32 (0), i32 (0); // tension (f32 0), flags
  4896. }
  4897. const std::array<std::uint8_t, 20> tail {};
  4898. put (tail.data(), tail.size());
  4899. }
  4900. for (auto v : params)
  4901. i32 (v);
  4902. for (auto v : block)
  4903. i32 (v);
  4904. put (flags.data(), flags.size());
  4905. const std::array<std::uint8_t, 13> axis {};
  4906. put (axis.data(), axis.size());
  4907. d.push_back (3), put ("PWM", 3);
  4908. i32 (1), i32 (60);
  4909. return d;
  4910. }
  4911. };
  4912. std::vector<float> vocodexSaw (int n, double hz, double fs)
  4913. {
  4914. std::vector<float> out ((std::size_t) n);
  4915. for (int i = 0; i < n; ++i)
  4916. out[(std::size_t) i] = (float) (2.0 * std::fmod (i * hz / fs, 1.0) - 1.0) * 0.4f;
  4917. return out;
  4918. }
  4919. TEST (vocodex_state_parse_and_conversion)
  4920. {
  4921. VocodexSpec spec;
  4922. spec.block = { 1, 3, 2, 40, 0, 2, 1 };
  4923. spec.params[17] = -1200;
  4924. const auto raw = spec.bytes();
  4925. const auto s = lynx::vocodex::parseState (raw);
  4926. CHECK (s.has_value());
  4927. if (! s)
  4928. return;
  4929. CHECK (s->version == 8 && s->holdMode == 1 && s->order == 3 && s->unison == 2 && s->bands == 40);
  4930. CHECK (s->draft() && s->modIn == 2 && s->carIn == 1 && s->minTimes && s->subtractiveGate && ! s->lrEncoding);
  4931. CHECK (s->params[lynx::vocodex::modPitch] == -1200 && s->params[lynx::vocodex::carLp] == 65536);
  4932. CHECK (s->maps[8].x.size() == 2 && std::abs (s->maps[8].y[1] - 0.9918) < 1e-12 && s->maps[8].x[1] == 1.0);
  4933. CHECK (s->tone == "PWM" && s->notes.size() == 1 && s->notes[0] == 60);
  4934. const auto v = lynx::vocodexEffect (raw);
  4935. CHECK (v && v->slot.kind == lynx::EffectKind::vocodex && v->slot.state == raw && v->modIn == 2 && v->carIn == 1 && v->notes.empty());
  4936. spec.block[6] = -1; // internal synth carrier: not available yet → reported
  4937. spec.params[1] = 150; // Soundgoodizer stage
  4938. const auto w = lynx::vocodexEffect (spec.bytes());
  4939. CHECK (w && w->carIn == -1 && w->notes.size() == 2);
  4940. CHECK (! lynx::vocodex::parseState ({ 1, 2, 3 }).has_value());
  4941. }
  4942. TEST (vocodex_vocodes_side_inputs)
  4943. {
  4944. // modulator on side input 1 (noise in the first half), carrier on side input 2 (saw), own input silent: the
  4945. // output follows the modulator's envelope and fades after it stops
  4946. VocodexSpec spec;
  4947. lynx::EffectSlot slot = lynx::makeEffectSlot (lynx::EffectKind::vocodex);
  4948. slot.state = spec.bytes();
  4949. auto fx = lynx::makeEffect (slot);
  4950. fx->prepare (48000.0);
  4951. CHECK (fx->latencySamples() == 0);
  4952. const auto car = vocodexSaw (48000, 110.0, 48000.0);
  4953. std::vector<float> mod (48000), l (48000, 0.0f), r (48000, 0.0f);
  4954. std::uint32_t seed = 7;
  4955. for (std::size_t i = 0; i < mod.size(); ++i)
  4956. {
  4957. seed = seed * 1664525u + 1013904223u;
  4958. mod[i] = i < 24000 ? ((float) (seed >> 8) / 16777216.0f - 0.5f) : 0.0f;
  4959. }
  4960. for (int done = 0; done < 48000; done += 512)
  4961. {
  4962. const int n = std::min (512, 48000 - done);
  4963. fx->setSidechain (mod.data() + done, mod.data() + done);
  4964. fx->setSidechain2 (car.data() + done, car.data() + done);
  4965. fx->process (l.data() + done, r.data() + done, n, slot.params, 120.0);
  4966. }
  4967. auto rms = [&] (int from, int to) {
  4968. double e = 0.0;
  4969. for (int i = from; i < to; ++i)
  4970. e += (double) l[(std::size_t) i] * l[(std::size_t) i] + (double) r[(std::size_t) i] * r[(std::size_t) i];
  4971. return std::sqrt (e / (2.0 * (to - from)));
  4972. };
  4973. CHECK (rms (6000, 20000) > 0.02);
  4974. CHECK (rms (40000, 48000) < 0.01 * rms (6000, 20000));
  4975. CHECK (std::abs (l[0]) < 1e-6f); // the gains ramp up from 0 when the plugin is created
  4976. }
  4977. TEST (vocodex_draft_latency_and_pass_through)
  4978. {
  4979. // carrier pass-through at unit gain only (Wet 0): after a Flush the gains snap, so the output is the carrier,
  4980. // 16 samples late in Draft
  4981. VocodexSpec spec;
  4982. spec.params[0] = 0; // Wet
  4983. spec.params[4] = 12800; // CarVol = 1
  4984. for (const int draftField : { 1, 0 })
  4985. {
  4986. spec.block[4] = draftField;
  4987. const auto s = lynx::vocodex::parseState (spec.bytes());
  4988. CHECK (s.has_value());
  4989. lynx::vocodex::Engine engine;
  4990. engine.prepare (*s, 44100.0, 300, s->draft());
  4991. CHECK (engine.latencySamples() == (draftField == 0 ? 16 : 0));
  4992. engine.flush();
  4993. const auto saw = vocodexSaw (3000, 220.0, 44100.0);
  4994. std::vector<float> car (6000), mod (6000, 0.0f), out (6000);
  4995. for (int i = 0; i < 3000; ++i)
  4996. car[(std::size_t) (2 * i)] = car[(std::size_t) (2 * i + 1)] = saw[(std::size_t) i];
  4997. static constexpr int sizes[] { 300, 37, 128, 1, 255, 16, 299 }; // uneven blocks exercise the FIFOs
  4998. for (int done = 0, k = 0, n = 0; done < 3000; done += n, ++k)
  4999. {
  5000. n = std::min (sizes[k % 7], 3000 - done);
  5001. engine.process (mod.data() + 2 * done, mod.data() + 2 * done, car.data() + 2 * done, out.data() + 2 * done, n);
  5002. }
  5003. const int lag = engine.latencySamples();
  5004. auto maxError = 0.0f;
  5005. for (int i = lag; i < 3000; ++i)
  5006. maxError = std::max (maxError, std::abs (out[(std::size_t) (2 * i)] - saw[(std::size_t) (i - lag)]));
  5007. CHECK (maxError == 0.0f);
  5008. }
  5009. }
  5010. TEST (vocodex_soundgoodizer_stage_limits_the_output)
  5011. {
  5012. // SG > 0: the vocoder's output (loud here: Wet 2000) goes through the Soundgoodizer approximation, whose
  5013. // master limiter keeps the peaks under −0.2 dBFS; its look-ahead is reported as latency
  5014. VocodexSpec spec;
  5015. spec.params[0] = 2000;
  5016. spec.params[1] = 250;
  5017. lynx::EffectSlot slot = lynx::makeEffectSlot (lynx::EffectKind::vocodex);
  5018. slot.state = spec.bytes();
  5019. auto fx = lynx::makeEffect (slot);
  5020. fx->prepare (48000.0);
  5021. CHECK (fx->latencySamples() == 72); // 1.5 ms at 48 kHz
  5022. const auto car = vocodexSaw (48000, 110.0, 48000.0);
  5023. std::vector<float> mod (48000), l (48000, 0.0f), r (48000, 0.0f);
  5024. for (std::size_t i = 0; i < mod.size(); ++i)
  5025. mod[i] = 0.9f * (float) std::sin (0.07 * (double) i) * (float) std::sin (0.0003 * (double) i);
  5026. auto peak = 0.0f;
  5027. for (int done = 0; done < 48000; done += 512)
  5028. {
  5029. const int n = std::min (512, 48000 - done);
  5030. fx->setSidechain (mod.data() + done, mod.data() + done);
  5031. fx->setSidechain2 (car.data() + done, car.data() + done);
  5032. fx->process (l.data() + done, r.data() + done, n, slot.params, 120.0);
  5033. }
  5034. for (std::size_t i = 0; i < l.size(); ++i)
  5035. peak = std::max ({ peak, std::abs (l[i]), std::abs (r[i]) });
  5036. CHECK (peak > 0.5f && peak <= 0.9775f);
  5037. }
  5038. TEST (vocodex_tail_bypass_and_noise)
  5039. {
  5040. // both inputs silent for longer than 0.5 s + hold + release: the own input passes unchanged
  5041. VocodexSpec spec;
  5042. const auto s = lynx::vocodex::parseState (spec.bytes());
  5043. CHECK (s.has_value());
  5044. lynx::vocodex::Engine engine;
  5045. engine.prepare (*s, 44100.0, 512, false);
  5046. std::vector<float> zero (1024, 0.0f), own (1024), out (1024);
  5047. for (std::size_t i = 0; i < own.size(); ++i)
  5048. own[i] = 0.25f * (float) std::sin (0.01 * (double) i);
  5049. for (int b = 0; b < 80; ++b)
  5050. engine.process (own.data(), zero.data(), zero.data(), out.data(), 512);
  5051. CHECK (out == own);
  5052. // carrier noise: the IPP-compatible generator restarts from the same seed after a Flush
  5053. spec.params[6] = 9000;
  5054. const auto noisy = lynx::vocodex::parseState (spec.bytes());
  5055. lynx::vocodex::Engine a;
  5056. a.prepare (*noisy, 44100.0, 512, false);
  5057. std::vector<float> mod (1024), first (1024), second (1024);
  5058. for (std::size_t i = 0; i < mod.size(); ++i)
  5059. mod[i] = 0.3f * (float) std::sin (0.05 * (double) i);
  5060. a.flush();
  5061. a.process (own.data(), mod.data(), zero.data(), first.data(), 512);
  5062. a.flush();
  5063. a.process (own.data(), mod.data(), zero.data(), second.data(), 512);
  5064. CHECK (first == second);
  5065. auto energy = 0.0;
  5066. for (auto v : first)
  5067. energy += (double) v * v;
  5068. CHECK (energy > 1e-6 && std::isfinite (energy));
  5069. }
  5070. TEST (synth_spectral_oscillator)
  5071. {
  5072. // 1/n spectrum = saw: same harmonic proportions and same level as LYNX's saw
  5073. lynx::SynthSettings saw;
  5074. saw.osc[0] = { lynx::Waveform::saw, 0, 0.0f, 1.0f };
  5075. saw.cutoff = 20000.0f;
  5076. auto spectral = saw;
  5077. spectral.osc[0].wave = lynx::Waveform::spectral;
  5078. for (int n = 1; n <= lynx::SynthSettings::spectrumSize; ++n)
  5079. spectral.spectrum[(std::size_t) n - 1] = 1.0f / (float) n;
  5080. const auto a = renderSynthNote (saw, 57, 24000), b = renderSynthNote (spectral, 57, 24000); // 220 Hz
  5081. for (const auto h : { 1, 2, 3, 5 })
  5082. {
  5083. const auto ea = goertzel (a, 220.0 * h, 4800, 24000), eb = goertzel (b, 220.0 * h, 4800, 24000);
  5084. CHECK (std::abs (10.0 * std::log10 (eb / ea)) < 0.5); // within 0.5 dB
  5085. }
  5086. // odd only: no 2nd harmonic
  5087. auto odd = spectral;
  5088. for (int n = 2; n <= lynx::SynthSettings::spectrumSize; n += 2)
  5089. odd.spectrum[(std::size_t) n - 1] = 0.0f;
  5090. const auto c = renderSynthNote (odd, 57, 24000);
  5091. CHECK (goertzel (c, 440.0, 4800, 24000) < 1e-4 * goertzel (c, 220.0, 4800, 24000));
  5092. // high note: the band-limited tables don't pass Nyquist (no aliasing below the fundamental)
  5093. const auto d = renderSynthNote (spectral, 105, 24000); // 3520 Hz
  5094. CHECK (goertzel (d, 1000.0, 4800, 24000) < 1e-3 * goertzel (d, 3520.0, 4800, 24000));
  5095. }
  5096. TEST (compressor_sidechain_ducks_and_orders_mixer)
  5097. {
  5098. // the detector listens to the side input: quiet signal on the track, loud kick on the sidechain -> reduction
  5099. auto slot = lynx::makeEffectSlot (lynx::EffectKind::compressor);
  5100. slot.params[0] = 0.5f; // threshold
  5101. slot.params[1] = 1.0f; // high ratio
  5102. slot.params[4] = 0.0f;
  5103. auto run = [&] (bool withSidechain) {
  5104. auto fx = lynx::makeEffect (lynx::EffectKind::compressor);
  5105. fx->prepare (48000.0);
  5106. std::vector<float> l (4800, 0.1f), r (4800, 0.1f), kick (4800, 1.0f);
  5107. if (withSidechain)
  5108. fx->setSidechain (kick.data(), kick.data());
  5109. fx->process (l.data(), r.data(), 4800, slot.params, 120.0);
  5110. return l.back();
  5111. };
  5112. const auto alone = run (false), ducked = run (true);
  5113. CHECK (ducked < 0.5f * alone);
  5114. // order: track 5 listens to 7 via sidechain -> 7 comes before 5
  5115. auto song = lynx::Song::makeDefault();
  5116. while (song.mixer.size() < 8)
  5117. song.mixer.push_back ({});
  5118. auto comp = lynx::makeEffectSlot (lynx::EffectKind::compressor);
  5119. comp.sidechain = 7;
  5120. song.mixer[5].effects.push_back (comp);
  5121. const auto order = song.mixerOrder();
  5122. const auto at = [&] (int t) { return std::find (order.begin(), order.end(), t) - order.begin(); };
  5123. CHECK (at (7) < at (5));
  5124. }
  5125. TEST (pitch_correction_pulls_to_allowed_note)
  5126. {
  5127. auto run = [] (const lynx::EffectParams& p, double hz) {
  5128. auto fx = lynx::makeEffect (lynx::EffectKind::pitchCorrect);
  5129. fx->prepare (48000.0);
  5130. std::vector<float> l (48000 * 2), r;
  5131. for (std::size_t i = 0; i < l.size(); ++i)
  5132. l[i] = 0.5f * (float) std::sin (2.0 * 3.141592653589793 * hz * (double) i / 48000.0);
  5133. r = l;
  5134. fx->process (l.data(), r.data(), (int) l.size(), p, 120.0);
  5135. // frequency from zero crossings in the last second
  5136. int crossings = 0;
  5137. for (std::size_t i = 48000 + 1; i < l.size(); ++i)
  5138. crossings += (l[i - 1] < 0.0f) != (l[i] < 0.0f);
  5139. return crossings / 2.0;
  5140. };
  5141. auto slot = lynx::makeEffectSlot (lynx::EffectKind::pitchCorrect); // chromatic, instant, A 440
  5142. CHECK (std::abs (run (slot.params, 452.0) - 440.0) < 4.0);
  5143. for (int k = 0; k < 12; ++k)
  5144. slot.params[(std::size_t) (5 + k)] = k == 0 ? 1.0f : 0.0f; // only C
  5145. CHECK (std::abs (run (slot.params, 452.0) - 523.25) < 5.0); // C5 (523 Hz) is closer than C4 (262)
  5146. slot.params[2] = 1.0f; // turn everything off: passes unchanged
  5147. CHECK (std::abs (run (slot.params, 452.0) - 452.0) < 4.0);
  5148. }
  5149. TEST (pitch_correction_bypass_is_a_pure_delay)
  5150. {
  5151. // FL's Pitcher with Bypass All still runs its shifter: the plain path is an exact 9-sample delay, the formant
  5152. // path (256-Hann overlap-add) an exact 257-sample delay, and Gender changes nothing without a shift
  5153. // (REA_rodada30 §2.4/2.5); both are reported as latency
  5154. std::vector<float> in (48000);
  5155. for (std::size_t i = 0; i < in.size(); ++i)
  5156. in[i] = 0.5f * (float) std::sin (2.0 * 3.141592653589793 * 440.0 * (double) i / 48000.0)
  5157. + 0.2f * (float) std::sin (2.0 * 3.141592653589793 * 1234.5 * (double) i / 48000.0);
  5158. auto run = [&] (bool formant, float gender, int& latency) {
  5159. auto fx = lynx::makeEffect (lynx::EffectKind::pitchCorrect);
  5160. fx->prepare (48000.0);
  5161. auto slot = lynx::makeEffectSlot (lynx::EffectKind::pitchCorrect);
  5162. slot.params[2] = 1.0f;
  5163. slot.params[29] = formant ? 1.0f : 0.0f;
  5164. slot.params[30] = gender;
  5165. auto l = in, r = in;
  5166. for (std::size_t i = 0; i < l.size(); i += 480)
  5167. fx->process (l.data() + i, r.data() + i, 480, slot.params, 120.0);
  5168. latency = fx->latencySamples();
  5169. return l;
  5170. };
  5171. int latency = 0;
  5172. auto plain = run (false, 0.5f, latency);
  5173. CHECK (latency == 9);
  5174. auto worst = 0.0f;
  5175. for (std::size_t i = 4000; i < in.size(); ++i)
  5176. worst = std::max (worst, std::abs (plain[i] - in[i - 9]));
  5177. CHECK (worst < 1e-5f);
  5178. auto formant = run (true, 0.8f, latency);
  5179. CHECK (latency == 257);
  5180. worst = 0.0f;
  5181. for (std::size_t i = 4000; i < in.size(); ++i)
  5182. worst = std::max (worst, std::abs (formant[i] - in[i - 257]));
  5183. CHECK (worst < 1e-5f);
  5184. }
  5185. TEST (pitch_correction_formant_path)
  5186. {
  5187. // Formant on: PSOLA keeps the correction (output pitch = grain spacing) while Gender resamples the grains:
  5188. // the spectrum of a saw moves up with Gender > 0.5 and down with Gender < 0.5
  5189. auto run = [] (float gender) {
  5190. auto fx = lynx::makeEffect (lynx::EffectKind::pitchCorrect);
  5191. fx->prepare (48000.0);
  5192. auto slot = lynx::makeEffectSlot (lynx::EffectKind::pitchCorrect); // chromatic, instant, A 440
  5193. slot.params[29] = 1.0f;
  5194. slot.params[30] = gender;
  5195. std::vector<float> l (48000 * 2), r;
  5196. for (std::size_t i = 0; i < l.size(); ++i)
  5197. l[i] = 0.5f * (float) (2.0 * std::fmod (452.0 * (double) i / 48000.0, 1.0) - 1.0); // saw
  5198. r = l;
  5199. fx->process (l.data(), r.data(), (int) l.size(), slot.params, 120.0);
  5200. l.erase (l.begin(), l.begin() + 48000);
  5201. return l;
  5202. };
  5203. // period by autocorrelation (lags 60…160 = 300…800 Hz)
  5204. auto pitch = [] (const std::vector<float>& x) {
  5205. auto best = 0.0, bestLag = 0.0;
  5206. for (int lag = 60; lag <= 160; ++lag)
  5207. {
  5208. auto sum = 0.0;
  5209. for (std::size_t i = 0; i + (std::size_t) lag < x.size(); ++i)
  5210. sum += (double) x[i] * x[i + (std::size_t) lag];
  5211. if (sum > best)
  5212. {
  5213. best = sum;
  5214. bestLag = lag;
  5215. }
  5216. }
  5217. return 48000.0 / bestLag;
  5218. };
  5219. // brightness: energy of the first difference relative to the energy
  5220. auto brightness = [] (const std::vector<float>& x) {
  5221. auto e = 0.0, d = 0.0;
  5222. for (std::size_t i = 1; i < x.size(); ++i)
  5223. {
  5224. e += (double) x[i] * x[i];
  5225. d += (double) (x[i] - x[i - 1]) * (x[i] - x[i - 1]);
  5226. }
  5227. return d / e;
  5228. };
  5229. const auto neutral = run (0.5f), up = run (0.8f), down = run (0.3f);
  5230. CHECK (std::abs (pitch (neutral) - 440.0) < 5.0); // 452 Hz pulled to A
  5231. CHECK (std::abs (pitch (up) - 440.0) < 5.0); // Gender does not move the pitch
  5232. CHECK (brightness (up) > 1.5 * brightness (neutral));
  5233. CHECK (brightness (down) < 0.7 * brightness (neutral));
  5234. }
  5235. TEST (parallel_container_inner_links_modulate)
  5236. {
  5237. // one branch: utility (gain) + a control-only auto-pan LFO (1 beat); the link maps the LFO 0..1 onto the
  5238. // utility gain −24 dB..0 dB, so the level must swing; without the link it stays put
  5239. auto container = lynx::makeEffectSlot (lynx::EffectKind::parallel);
  5240. auto gain = lynx::makeEffectSlot (lynx::EffectKind::utility);
  5241. auto lfo = lynx::makeEffectSlot (lynx::EffectKind::autoPan);
  5242. lfo.params[0] = 1.0f / 64.0f;
  5243. lfo.params[4] = 1.0f; // control only: audio passes unchanged
  5244. container.branches.push_back ({ { gain, lfo }, 1.0f });
  5245. lynx::EffectLink link;
  5246. link.source = 1;
  5247. link.param = 0;
  5248. for (int i = 0; i <= 32; ++i)
  5249. link.curve.push_back (0.5f * (float) i / 32.0f);
  5250. auto levels = [&] (bool linked) {
  5251. auto slot = container;
  5252. if (linked)
  5253. slot.links.push_back (link);
  5254. auto fx = lynx::makeParallelEffect (slot);
  5255. fx->prepare (48000.0);
  5256. float lo = 1e9f, hi = 0.0f;
  5257. for (int block = 0; block < 94; ++block) // ~1 beat at 120 BPM in 256-sample blocks
  5258. {
  5259. std::vector<float> l (256, 1.0f), r (256, 1.0f);
  5260. fx->setSongPosition (block * 256.0 / 48000.0 * 2.0 * 960.0); // the engine positions every block
  5261. fx->process (l.data(), r.data(), 256, slot.params, 120.0);
  5262. lo = std::min (lo, std::abs (l[128]));
  5263. hi = std::max (hi, std::abs (l[128]));
  5264. }
  5265. return std::pair { lo, hi };
  5266. };
  5267. const auto [lo, hi] = levels (true);
  5268. CHECK (hi > 0.8f && lo < 0.12f);
  5269. const auto [lo0, hi0] = levels (false);
  5270. CHECK (std::abs (hi0 - lo0) < 1e-4f);
  5271. }
  5272. TEST (synth_spectrum_decays_per_harmonic)
  5273. {
  5274. // 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
  5275. lynx::SynthSettings s;
  5276. s.osc[0] = { lynx::Waveform::spectral, 0, 0.0f, 1.0f };
  5277. s.cutoff = 20000.0f;
  5278. s.decay = 0.0f;
  5279. s.sustain = 1.0f;
  5280. s.spectrum[0] = 1.0f;
  5281. s.spectrum[2] = 1.0f;
  5282. s.spectrumDecay[2] = 0.2f;
  5283. const auto x = renderSynthNote (s, 57, 48000); // 220 Hz, 48 kHz, 1 s
  5284. // equal 2400-sample windows (Goertzel power grows with the window): 10…60 ms and 500…550 ms
  5285. const auto early1 = goertzel (x, 220.0, 480, 2880), early3 = goertzel (x, 660.0, 480, 2880);
  5286. const auto late1 = goertzel (x, 220.0, 24000, 26400), late3 = goertzel (x, 660.0, 24000, 26400);
  5287. CHECK (early3 > 0.05 * early1); // ≈ −9 dB on average over 10…60 ms
  5288. CHECK (late3 < 1e-4 * late1);
  5289. CHECK (std::abs (10.0 * std::log10 (late1 / early1)) < 1.0); // the 1st holds
  5290. // without per-harmonic decay the spectrum stays as it is
  5291. s.spectrumDecay[2] = 0.0f;
  5292. const auto y = renderSynthNote (s, 57, 48000);
  5293. CHECK (std::abs (10.0 * std::log10 (goertzel (y, 660.0, 24000, 26400) / goertzel (y, 660.0, 480, 2880))) < 1.0);
  5294. }
  5295. TEST (worker_pool_runs_each_index_once_per_round)
  5296. {
  5297. // rounds of alternating sizes (a stalled worker must never run an index of a later round), each index
  5298. // exactly once, and nothing running after parallelFor returns
  5299. lynx::WorkerPool pool (3);
  5300. std::vector<std::atomic<int>> hits (64);
  5301. std::atomic<int> round { 0 }, outside { 0 }, wrongRound { 0 };
  5302. std::atomic<bool> open { false };
  5303. int failures = 0;
  5304. for (int r = 1; r <= 20000; ++r)
  5305. {
  5306. const auto n = (r % 3 == 0) ? 64 : (r % 3 == 1 ? 2 : 9);
  5307. for (int i = 0; i < n; ++i)
  5308. hits[(std::size_t) i].store (0);
  5309. round.store (r);
  5310. open.store (true);
  5311. auto fn = [&, r] (int i) {
  5312. if (! open.load())
  5313. outside.fetch_add (1);
  5314. if (round.load() != r)
  5315. wrongRound.fetch_add (1);
  5316. hits[(std::size_t) i].fetch_add (1);
  5317. };
  5318. pool.parallelFor (n, fn);
  5319. open.store (false);
  5320. for (int i = 0; i < n; ++i)
  5321. failures += hits[(std::size_t) i].load() != 1;
  5322. }
  5323. CHECK (failures == 0);
  5324. CHECK (outside.load() == 0);
  5325. CHECK (wrongRound.load() == 0);
  5326. }
  5327. TEST (ladder_filter_follows_toxic_law)
  5328. {
  5329. // the 4-pole ladder: −24 dB/oct far above the cutoff (vs −12 for the SVF), resonance raises the corner, and
  5330. // the input saturation keeps it bounded even at full resonance
  5331. auto level = [] (bool ladder, float res, double hz) {
  5332. lynx::SynthSettings s;
  5333. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  5334. s.cutoff = 500.0f;
  5335. s.resonance = res;
  5336. s.ladder = ladder;
  5337. const auto key = (int) std::lround (69.0 + 12.0 * std::log2 (hz / 440.0));
  5338. const auto x = renderSynthNote (s, key, 48000);
  5339. double e = 0.0, peak = 0.0;
  5340. for (std::size_t i = 24000; i < 48000; ++i)
  5341. e += (double) x[i] * x[i], peak = std::max (peak, (double) std::abs (x[i]));
  5342. return std::pair { std::sqrt (e / 24000.0), peak };
  5343. };
  5344. 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
  5345. const auto svfHigh = level (false, 0.0f, 3520.0).first / level (false, 0.0f, 110.0).first;
  5346. CHECK (20.0 * std::log10 (high / low) < -55.0); // ≈ 24 dB/oct over ~2.8 octaves
  5347. CHECK (20.0 * std::log10 (svfHigh) > -45.0); // the 2-pole SVF falls much less
  5348. const auto corner0 = level (true, 0.0f, 523.25).first, corner1 = level (true, 0.6f, 523.25).first;
  5349. CHECK (corner1 > 1.5 * corner0); // resonance boosts near the cutoff
  5350. const auto loud = level (true, 1.0f, 523.25);
  5351. CHECK (std::isfinite (loud.first) && loud.second < 20.0); // self-oscillation stays bounded
  5352. }
  5353. TEST (synth_spectrum_settles_on_target)
  5354. {
  5355. // ALT DECAY-like morph: harmonic 3 starts at 1 and settles on 0.25 (−12 dB) instead of fading out
  5356. lynx::SynthSettings s;
  5357. s.osc[0] = { lynx::Waveform::spectral, 0, 0.0f, 1.0f };
  5358. s.cutoff = 20000.0f;
  5359. s.decay = 0.0f;
  5360. s.sustain = 1.0f;
  5361. s.spectrum[0] = 1.0f;
  5362. s.spectrum[2] = 1.0f;
  5363. s.spectrumDecay[2] = 0.1f;
  5364. s.spectrumTarget[2] = 0.25f;
  5365. const auto x = renderSynthNote (s, 57, 48000);
  5366. const auto ratio = goertzel (x, 660.0, 24000, 26400) / goertzel (x, 220.0, 24000, 26400);
  5367. CHECK (std::abs (10.0 * std::log10 (ratio) - 20.0 * std::log10 (0.25)) < 1.0);
  5368. }
  5369. TEST (kepler_chorus_is_stereo_and_keeps_level)
  5370. {
  5371. // chorus I on a sine: L and R differ (opposite LFO phases), the level stays close to the dry one
  5372. lynx::SynthSettings s;
  5373. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  5374. s.cutoff = 20000.0f;
  5375. auto dry = s;
  5376. s.chorus = 1;
  5377. auto render = [] (const lynx::SynthSettings& set) {
  5378. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  5379. inst->prepare (48000.0);
  5380. lynx::ChannelDef c;
  5381. c.synth = set;
  5382. inst->configure (c, 120.0);
  5383. inst->noteOn (69, 1.0f);
  5384. std::vector<float> l (96000), r (96000);
  5385. inst->render (l.data(), r.data(), 96000, 1.0f, 1.0f);
  5386. return std::pair { l, r };
  5387. };
  5388. const auto [l, r] = render (s);
  5389. const auto [dl, dr] = render (dry);
  5390. double diff = 0.0, e = 0.0, ed = 0.0;
  5391. for (std::size_t i = 48000; i < 96000; ++i)
  5392. diff += std::abs (l[i] - r[i]), e += (double) l[i] * l[i], ed += (double) dl[i] * dl[i];
  5393. CHECK (diff / 48000.0 > 1e-3);
  5394. CHECK (std::abs (10.0 * std::log10 (e / ed)) < 3.0);
  5395. }
  5396. TEST (fl_pan_law_matches_love_philter_dll)
  5397. {
  5398. // values printed by the installation's Love Philter pan routine for vol 0.8 (REA_rodada27 §3.1, lppan.txt)
  5399. struct Row { double pan, ll, rr, rl, lr; };
  5400. const Row rows[] = { { -1.5, 0.239782482, -0.432956904, 0.805467963, 0.0 }, { -0.5, 0.805467963, 0.432956904, 0.239782482, 0.0 },
  5401. { 0.0, 0.8, 0.8, 0.0, 0.0 }, { 0.75, 0.220719516, 0.707889318, 0.0, 0.401742548 },
  5402. { 1.0, 0.0, 0.565685451, 0.0, 0.565685451 } };
  5403. for (const auto& row : rows)
  5404. {
  5405. float ll, rl, lr, rr;
  5406. lynx::flPanMatrix (row.pan, ll, rl, lr, rr);
  5407. CHECK (std::abs (0.8 * ll - row.ll) < 1e-6 && std::abs (0.8 * rr - row.rr) < 1e-6);
  5408. CHECK (std::abs (0.8 * rl - row.rl) < 1e-6 && std::abs (0.8 * lr - row.lr) < 1e-6);
  5409. }
  5410. }
  5411. TEST (effector_units_match_fl_dll_impulse_responses)
  5412. {
  5413. // impulse responses of the installation's Effector engine (REA_rodada27 §2, eu_<kind>_<X>_<Y>.txt; LFO off,
  5414. // wet 1, blocks of 256): samples 1, 10, 100 and 1000
  5415. struct Case { int kind; float x, y; double v[4]; };
  5416. const Case cases[] = { { 3, 0.5f, 0.5f, { -0.603055418, 0.159798339, -0.0055043716, -1.06241259e-06 } },
  5417. { 4, 0.2f, 0.5f, { 4.68885949e-26, 4.20032622e-19, 0.000487731799, 2.27715846e-09 } },
  5418. { 4, 0.8f, 0.3f, { -0.293783396, -0.0306414738, -0.00068128563, 1.358577e-15 } } };
  5419. for (const auto& c : cases)
  5420. {
  5421. auto fx = lynx::effector::make();
  5422. fx->prepare (44100.0);
  5423. lynx::EffectParams p {};
  5424. p[lynx::effector::type] = c.kind / 11.0f;
  5425. p[lynx::effector::wetMix] = 1.0f;
  5426. p[lynx::effector::paramX] = c.x;
  5427. p[lynx::effector::paramY] = c.y;
  5428. p[lynx::effector::modX] = p[lynx::effector::modY] = 0.5f;
  5429. p[lynx::effector::modRate] = 0.5f;
  5430. p[lynx::effector::inputLevel] = 1.0f;
  5431. p[lynx::effector::outputGain] = 0.5f;
  5432. std::vector<float> l (1024, 0.0f), r (1024, 0.0f);
  5433. l[0] = r[0] = 1.0f;
  5434. for (int d = 0; d < 1024; d += 256)
  5435. fx->process (l.data() + d, r.data() + d, 256, p, 120.0);
  5436. const int at[4] { 1, 10, 100, 1000 };
  5437. for (int k = 0; k < 4; ++k)
  5438. CHECK (std::abs (l[(std::size_t) at[k]] - c.v[k]) < 2e-7 + 1e-5 * std::abs (c.v[k]));
  5439. }
  5440. }
  5441. TEST (harmless_stereo_tremolo_and_vibrato)
  5442. {
  5443. // tremolo d = 1: each side swings between 0 and 1.25 at 5 Hz, L and R in anti-phase; vibrato modulates the pitch
  5444. lynx::SynthSettings s;
  5445. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  5446. s.cutoff = 20000.0f;
  5447. s.stereoTremolo = 1.0f;
  5448. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  5449. inst->prepare (48000.0);
  5450. lynx::ChannelDef c;
  5451. c.synth = s;
  5452. inst->configure (c, 120.0);
  5453. inst->noteOn (69, 1.0f);
  5454. std::vector<float> l (48000), r (48000);
  5455. inst->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  5456. 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; };
  5457. // θ = 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
  5458. CHECK (envelope (l, 19200) > 4.0f * envelope (r, 19200));
  5459. CHECK (envelope (r, 24000) > 4.0f * envelope (l, 24000));
  5460. // vibrato 100 cents: zero crossings vary in spacing; without it they are regular
  5461. auto crossingsSpread = [] (float cents) {
  5462. lynx::SynthSettings v;
  5463. v.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  5464. v.cutoff = 20000.0f;
  5465. v.vibratoCents = cents;
  5466. const auto x = renderSynthNote (v, 69, 48000);
  5467. std::vector<int> zc;
  5468. for (int i = 24000; i < 48000; ++i)
  5469. if (x[(std::size_t) i - 1] < 0.0f && x[(std::size_t) i] >= 0.0f)
  5470. zc.push_back (i);
  5471. int lo = 1 << 30, hi = 0;
  5472. for (std::size_t k = 1; k < zc.size(); ++k)
  5473. lo = std::min (lo, zc[k] - zc[k - 1]), hi = std::max (hi, zc[k] - zc[k - 1]);
  5474. return hi - lo;
  5475. };
  5476. CHECK (crossingsSpread (0.0f) <= 1);
  5477. CHECK (crossingsSpread (100.0f) >= 4);
  5478. }
  5479. TEST (physical_models_sound_and_end)
  5480. {
  5481. // Sakura: a plucked string with default-ish parameters rings and fades after the release; Drumpad: a hit decays
  5482. for (const auto kind : { lynx::InstrumentKind::sakura, lynx::InstrumentKind::drumpad })
  5483. {
  5484. lynx::ChannelDef c;
  5485. c.instrument = kind;
  5486. if (kind == lynx::InstrumentKind::sakura)
  5487. {
  5488. c.modelParams.assign (146, 0.5f);
  5489. c.modelParams[111] = 3.0f; // both strings at the note
  5490. c.modelParams[113] = 0.5f; // octave ×1
  5491. c.modelParams[6] = c.modelParams[11] = 0.99f; // long decay
  5492. c.modelParams[31] = 0.0f; // noise exciter
  5493. }
  5494. else
  5495. {
  5496. c.modelParams.assign (38, 0.5f);
  5497. c.modelParams[0] = 1.0f; // retrigger noise
  5498. c.modelParams[30] = c.modelParams[31] = c.modelParams[32] = c.modelParams[33] = 0.0f; // no velocity morph
  5499. }
  5500. auto inst = lynx::makeInstrument (kind);
  5501. inst->prepare (48000.0);
  5502. inst->configure (c, 120.0);
  5503. inst->noteOn (60, 0.8f);
  5504. std::vector<float> l (48000), r (48000);
  5505. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  5506. inst->noteOff (60);
  5507. inst->render (l.data() + 24000, r.data() + 24000, 24000, 1.0f, 1.0f);
  5508. double early = 0.0;
  5509. for (int i = 0; i < 12000; ++i)
  5510. early += (double) l[(std::size_t) i] * l[(std::size_t) i];
  5511. CHECK (early > 1e-6);
  5512. CHECK (std::all_of (l.begin(), l.end(), [] (float v) { return std::isfinite (v); }));
  5513. std::vector<float> tail (480000), tailR (480000);
  5514. inst->render (tail.data(), tailR.data(), 480000, 1.0f, 1.0f); // 10 s later the voice has ended
  5515. CHECK (inst->idle());
  5516. }
  5517. }
  5518. TEST (squeeze_matches_fl_model)
  5519. {
  5520. // Fruity Squeeze: Steps quantises, Mix 0 passes the input dry ×Volume/127; a silent block is left untouched
  5521. auto slot = lynx::makeEffectSlot (lynx::EffectKind::squeeze);
  5522. slot.params[1] = 0.0f; // mix 0: dry only
  5523. auto fx = lynx::makeEffect (lynx::EffectKind::squeeze);
  5524. fx->prepare (44100.0);
  5525. std::vector<float> l (512, 0.3f), r (512, -0.2f);
  5526. fx->process (l.data(), r.data(), 512, slot.params, 120.0);
  5527. CHECK (std::abs (l[100] - 0.3f) < 1e-6f && std::abs (r[100] + 0.2f) < 1e-6f); // Volume 127/127
  5528. slot.params[1] = 1.0f; // wet only
  5529. slot.params[2] = 32000.0f / 32768.0f; // 32768^(1 − 32000/32768) ≈ 1.27 levels per unit → heavy quantisation
  5530. std::vector<float> a (512), b (512);
  5531. for (int i = 0; i < 512; ++i)
  5532. a[(std::size_t) i] = b[(std::size_t) i] = 0.4f * (float) std::sin (i * 0.05);
  5533. fx->process (a.data(), b.data(), 512, slot.params, 120.0);
  5534. const auto levels = std::pow (32768.0f, 1.0f - 32000.0f / 32768.0f);
  5535. for (int i = 0; i < 512; i += 37)
  5536. CHECK (std::abs (a[(std::size_t) i] * levels - std::nearbyint (a[(std::size_t) i] * levels)) < 1e-3f);
  5537. std::vector<float> z (512, 0.0f), z2 (512, 0.0f);
  5538. fx->process (z.data(), z2.data(), 512, slot.params, 120.0);
  5539. CHECK (z[10] == 0.0f);
  5540. }
  5541. TEST (sakura_matrix_and_effects)
  5542. {
  5543. // REA_rodada29 §1: velocity → level follows 10^(2m)·0.05 (vel 1 vs 0.5 → ×10 in amplitude); the delay leaves
  5544. // an echo after the note has ended and keeps the instrument from going idle until its tail is silent
  5545. auto base = [] {
  5546. lynx::ChannelDef c;
  5547. c.instrument = lynx::InstrumentKind::sakura;
  5548. c.modelParams.assign (146, 0.0f);
  5549. const std::pair<int, float> values[] { { 0, 0.375f }, { 1, 0.5f }, { 3, 0.5f }, { 4, 1.0f }, { 6, 0.95f }, { 9, 0.3f },
  5550. { 11, 0.95f }, { 14, 0.3f }, { 18, 0.5f }, { 19, 0.5f }, { 27, 0.5f }, { 28, 1.0f },
  5551. { 29, 0.7f }, { 31, 1.0f }, { 32, 0.5f }, { 111, 3.0f }, { 113, 0.5f } };
  5552. for (const auto& [i, v] : values)
  5553. c.modelParams[(std::size_t) i] = v;
  5554. return c;
  5555. };
  5556. auto render = [] (const lynx::ChannelDef& c, float velocity, int held, int total) {
  5557. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sakura);
  5558. inst->prepare (48000.0);
  5559. inst->configure (c, 120.0);
  5560. inst->noteOn (60, velocity);
  5561. std::vector<float> l ((std::size_t) total), r ((std::size_t) total);
  5562. for (int s = 0; s < total; s += 256)
  5563. {
  5564. if (s == held)
  5565. inst->noteOff (60);
  5566. inst->render (l.data() + s, r.data() + s, std::min (256, total - s), 1.0f, 1.0f);
  5567. }
  5568. return std::make_pair (l, std::move (inst));
  5569. };
  5570. auto energy = [] (const std::vector<float>& x, int from, int to) {
  5571. double e = 0.0;
  5572. for (int i = from; i < to; ++i)
  5573. e += (double) x[(std::size_t) i] * x[(std::size_t) i];
  5574. return e;
  5575. };
  5576. auto c = base();
  5577. c.modelParams[79] = 6.0f; // slot 1: velocity → level, amount 1
  5578. c.modelParams[80] = 1.0f;
  5579. c.modelParams[82] = 1.0f;
  5580. const auto loud = energy (render (c, 1.0f, 24064, 24064).first, 0, 24064);
  5581. const auto soft = energy (render (c, 0.5f, 24064, 24064).first, 0, 24064);
  5582. CHECK (loud > 1e-6 && std::abs (loud / soft - 100.0) < 1.0);
  5583. auto d = base();
  5584. auto [dry, dryInst] = render (d, 0.8f, 4864, 72000);
  5585. d.modelParams[63] = 1.0f; // delay on: time 0.5 → ≈ 0.52 s, wet 1, no feedback: one echo
  5586. d.modelParams[64] = 0.5f;
  5587. d.modelParams[69] = 1.0f;
  5588. auto [wet, wetInst] = render (d, 0.8f, 4864, 72000);
  5589. CHECK (energy (wet, 26000, 40000) > 100.0 * energy (dry, 26000, 40000) + 1e-9); // the note ends near 0.2 s
  5590. CHECK (dryInst->idle() || energy (dry, 70000, 72000) < 1e-12);
  5591. CHECK (! wetInst->idle()); // the echo tail has not been silent for 3 s yet
  5592. }
  5593. TEST (drumsynth_live_engine)
  5594. {
  5595. // REA_rodada30 §1: key → patch slot, state parsing, the engine against our reference model (no DLL: synthesised
  5596. // sources only, noise from the fallback seed), voice modes, patch level/pan
  5597. CHECK (lynx::drumSynthKeyToSlot (48) == 0 && lynx::drumSynthKeyToSlot (71) == 23 && lynx::drumSynthKeyToSlot (0) == 24);
  5598. CHECK (lynx::drumSynthKeyToSlot (47) == 71 && lynx::drumSynthKeyToSlot (72) == 72 && lynx::drumSynthKeyToSlot (119) == 119);
  5599. CHECK (lynx::drumSynthKeyToSlot (120) == -1);
  5600. // a version 3 state: 120 names, 120 × 38 ints (send track −1 becomes 0 below version 4), flags
  5601. std::vector<std::uint8_t> blob;
  5602. auto put = [&] (std::uint32_t v) { for (int k = 0; k < 4; ++k) blob.push_back ((std::uint8_t) (v >> (8 * k))); };
  5603. put (3);
  5604. put (66);
  5605. for (int i = 0; i < 120; ++i)
  5606. blob.push_back (2), blob.push_back ('a'), blob.push_back ((std::uint8_t) ('0' + i % 10));
  5607. for (int i = 0; i < 120 * 38; ++i)
  5608. put ((std::uint32_t) (i % 38 == 36 ? -1 : i % 38 == 4 ? 300 : 0));
  5609. put (0);
  5610. const auto parsed = lynx::drumSynthLiveParams (blob);
  5611. CHECK (parsed && (int) parsed->size() == lynx::drumSynthParamCount);
  5612. CHECK (parsed && (*parsed)[36] == 0.0f && (*parsed)[38 * 7 + 4] == 300.0f && (*parsed)[(std::size_t) lynx::drumSynthEditorKeyIndex] == 66.0f);
  5613. blob.resize (500);
  5614. CHECK (! lynx::drumSynthLiveParams (blob));
  5615. // patch on key 60 (slot 12): tone-mode Osc1 with sweep and click, noise-band Osc2, ring, 2 retriggers
  5616. const int patch[38] { 100, 0, 10, -20, 300, 40, 50, 70, 90, 30, 600, 60, 10, 60, 80, -1, 0, 0, 2, 40, 60, 127, 0, 20, 0, 0, 0,
  5617. 0, 0, 0, 0, 0, 0, 30, -1, 0, 0, 64 };
  5618. lynx::ChannelDef c;
  5619. c.instrument = lynx::InstrumentKind::drumsynth;
  5620. c.modelParams.assign ((std::size_t) lynx::drumSynthParamCount, 0.0f);
  5621. for (int s = 0; s < 120; ++s)
  5622. c.modelParams[(std::size_t) (38 * s + 15)] = c.modelParams[(std::size_t) (38 * s + 34)] = -1.0f;
  5623. for (int i = 0; i < 38; ++i)
  5624. c.modelParams[(std::size_t) (38 * 12 + i)] = (float) patch[i];
  5625. auto render = [] (const lynx::ChannelDef& def, std::vector<int> keys, int total, float gl = 1.0f, float gr = 1.0f) {
  5626. auto inst = lynx::makeInstrument (lynx::InstrumentKind::drumsynth);
  5627. inst->configure (def, 120.0);
  5628. inst->prepare (48000.0);
  5629. std::vector<float> l ((std::size_t) total), r ((std::size_t) total);
  5630. for (int s = 0; s < total; s += 512)
  5631. {
  5632. for (std::size_t k = 0; k + 1 < keys.size(); k += 2)
  5633. if (keys[k + 1] == s)
  5634. inst->noteOn (keys[k], 100.0f / 128.0f);
  5635. inst->render (l.data() + s, r.data() + s, std::min (512, total - s), gl, gr);
  5636. }
  5637. return std::make_tuple (l, r, std::move (inst));
  5638. };
  5639. {
  5640. auto [l, r, inst] = render (c, { 60, 0 }, 9600);
  5641. // reference model (REA round 30 dsl_model.py, seed 0x56CE, FL velocity 100, V = 1, centre: × g(100)·cos(π/4))
  5642. const std::pair<int, float> golden[] { { 0, -0.0074092713f }, { 10, -0.13961405f }, { 100, -0.47290668f }, { 1000, -0.29188696f },
  5643. { 3000, -0.22130175f }, { 6000, -0.049537566f }, { 9599, 0.010392102f } };
  5644. for (const auto& [i, v] : golden)
  5645. CHECK (std::abs (l[(std::size_t) i] - v) < 2e-6f && std::abs (r[(std::size_t) i] - v) < 2e-6f);
  5646. std::vector<float> tail (48000 * 4), tailR (tail.size());
  5647. inst->render (tail.data(), tailR.data(), (int) tail.size(), 1.0f, 1.0f);
  5648. CHECK (inst->idle()); // the engine reported the voice finished
  5649. }
  5650. auto energy = [] (const std::vector<float>& x, int from, int to) {
  5651. double e = 0.0;
  5652. for (int i = from; i < to; ++i)
  5653. e += (double) x[(std::size_t) i] * x[(std::size_t) i];
  5654. return e;
  5655. };
  5656. // a key without a patch level (slot 0, level 0) and a key outside the 120 patches are silent
  5657. CHECK (energy (std::get<0> (render (c, { 48, 0, 125, 0 }, 4096)), 0, 4096) == 0.0);
  5658. // mono: a second hit on the same key cuts the first; poly: both ring together (Osc2 off: no noise, deterministic)
  5659. auto tone = c;
  5660. tone.modelParams[38 * 12 + 14] = 0.0f;
  5661. const auto single = std::get<0> (render (tone, { 60, 0 }, 8192));
  5662. const auto mono = std::get<0> (render (tone, { 60, 0, 60, 2048 }, 8192));
  5663. auto poly = tone;
  5664. poly.modelParams[38 * 12 + 24] = 1.0f;
  5665. const auto both = std::get<0> (render (poly, { 60, 0, 60, 2048 }, 8192));
  5666. double monoDiff = 0.0, polyDiff = 0.0;
  5667. for (int i = 2048 + 300; i < 8192; ++i) // after the cut fade: mono = only the second hit, a copy of the first
  5668. monoDiff += std::abs (mono[(std::size_t) i] - single[(std::size_t) i - 2048]), polyDiff += std::abs (both[(std::size_t) i] - single[(std::size_t) i - 2048]);
  5669. CHECK (monoDiff < 1e-3 && polyDiff > 1.0);
  5670. // patch pan +64 → right only; channel volume counts twice (FL applies Final.Vol in the engine and at the host)
  5671. auto right = c;
  5672. right.modelParams[38 * 12 + 1] = 64.0f;
  5673. const auto [pl, pr, pi] = render (right, { 60, 0 }, 4096);
  5674. CHECK (energy (pl, 0, 4096) < 1e-12 * energy (pr, 0, 4096) && energy (pr, 0, 4096) > 1.0);
  5675. const auto full = std::get<0> (render (tone, { 60, 0 }, 4096));
  5676. const auto half = std::get<0> (render (tone, { 60, 0 }, 4096, 0.5f, 0.5f));
  5677. CHECK (std::abs (half[100] - 0.25f * full[100]) < 1e-6f && std::abs (full[100]) > 0.01f);
  5678. }
  5679. TEST (kepler_lfo_bpm_sync)
  5680. {
  5681. // REA_rodada33 §3.4: with BPM Sync (k6 ≥ 0.5) the LFO1 period is n/192 beats, n = trunc((2^(7(1 − x)) − 1)·48.370079 + 1.1)
  5682. std::vector<std::uint8_t> state (0x21 + 34 * 4, 0);
  5683. auto putU32 = [&] (std::size_t o, std::uint32_t v) { std::memcpy (state.data() + o, &v, 4); };
  5684. putU32 (12, 9);
  5685. std::memcpy (state.data() + 16, "Kepler-1", 9);
  5686. putU32 (0x19, 4);
  5687. putU32 (0x1D, 34);
  5688. float k[34] {};
  5689. k[5] = 0.602085769f; // "Pads - Kepler" demo: n = 286
  5690. k[6] = 1.0f;
  5691. k[10] = 1.0f; // vibrato on
  5692. k[33] = 1.0f;
  5693. std::memcpy (state.data() + 0x21, k, sizeof k);
  5694. lynx::SynthSettings s;
  5695. float gain = 0.0f;
  5696. CHECK (lynx::synthFromKepler (state, s, gain));
  5697. CHECK (s.lfo[lynx::lfoPitch].sync && s.lfo[lynx::lfoPitch].secondsTiming);
  5698. CHECK (std::abs (s.lfo[lynx::lfoPitch].period - 286.0f / 192.0f) < 1e-6f);
  5699. k[5] = 0.0f; // slowest: 32 beats
  5700. std::memcpy (state.data() + 0x21, k, sizeof k);
  5701. CHECK (lynx::synthFromKepler (state, s, gain) && std::abs (s.lfo[lynx::lfoPitch].period - 32.0f) < 1e-6f);
  5702. k[6] = 0.0f; // free rate in seconds
  5703. std::memcpy (state.data() + 0x21, k, sizeof k);
  5704. CHECK (lynx::synthFromKepler (state, s, gain) && ! s.lfo[lynx::lfoPitch].sync);
  5705. }
  5706. // our own Maximus v7 state (layout REA_rodada8 §1.1): 7 globals, 4 × 13 band parameters, 8 envelopes (dx, y, tension, type)
  5707. static std::vector<std::uint8_t> maximusTestState (const std::array<int, 7>& g, const std::array<std::array<int, 13>, 4>& bands,
  5708. const std::array<std::vector<std::array<double, 4>>, 8>& envs, int oversampling)
  5709. {
  5710. std::vector<std::uint8_t> d;
  5711. auto put = [&] (const void* v, std::size_t n) { d.insert (d.end(), (const std::uint8_t*) v, (const std::uint8_t*) v + n); };
  5712. auto i32 = [&] (std::int32_t v) { put (&v, 4); };
  5713. i32 (7);
  5714. for (int copy = 0; copy < 2; ++copy)
  5715. {
  5716. for (auto v : g)
  5717. i32 (v);
  5718. for (const auto& b : bands)
  5719. for (auto v : b)
  5720. i32 (v);
  5721. }
  5722. d.resize (0x1fe, 0);
  5723. std::memcpy (d.data() + 0x1f4, &oversampling, 4);
  5724. for (const auto& e : envs)
  5725. {
  5726. i32 (3), i32 (2), i32 ((std::int32_t) e.size());
  5727. for (const auto& pt : e)
  5728. {
  5729. const double dx = pt[0], y = pt[1];
  5730. const float t = (float) pt[2];
  5731. put (&dx, 8), put (&y, 8), put (&t, 4);
  5732. const std::uint8_t flags[4] { (std::uint8_t) pt[3], 0, 0, 0 };
  5733. put (flags, 4);
  5734. }
  5735. i32 (0), i32 (-1), i32 (-1), i32 (-1), i32 (-1);
  5736. }
  5737. return d;
  5738. }
  5739. TEST (harmless_rack)
  5740. {
  5741. // REA_rodada36: Harmless's effects rack against our reference model (rack.py / maxmodel.py, which match the
  5742. // installation's Harmless_x64.dll and SG_x64.dll), 44.1 kHz, host blocks of 512
  5743. std::vector<float> inL (8192), inR (8192);
  5744. for (int i = 0; i < 4096; ++i)
  5745. {
  5746. inL[(std::size_t) i] = (float) (1.5 * std::sin (2.0 * 3.141592653589793 * 440.0 * i / 44100.0) * std::min (1.0, i / 400.0));
  5747. inR[(std::size_t) i] = (float) (1.2 * std::sin (2.0 * 3.141592653589793 * 660.0 * i / 44100.0));
  5748. }
  5749. auto run = [&] (const std::array<int, 100>& p, int compType, std::shared_ptr<const lynx::hlfx::MaximusPreset> comp, int total, int voicesUntil) {
  5750. lynx::hlfx::Rack rack;
  5751. std::array<int, 7> t {};
  5752. t[3] = compType;
  5753. rack.prepare (p, t, 44100.0, 120.0, std::move (comp));
  5754. std::vector<float> l (inL.begin(), inL.begin() + total), r (inR.begin(), inR.begin() + total);
  5755. for (int s = 0; s < total; s += 512)
  5756. rack.process (l.data() + s, r.data() + s, std::min (512, total - s), s < voicesUntil);
  5757. return std::make_pair (l, r);
  5758. };
  5759. {
  5760. // chorus type 3 (mix 400), ping-pong delay type 2 (vol 600, feedback 500, 1/4 beat), reverb type 4 (vol 700)
  5761. std::array<int, 100> p {};
  5762. p[90] = 3, p[91] = 400, p[92] = 2, p[93] = 600, p[94] = 500, p[95] = 48, p[96] = 4, p[97] = 700;
  5763. const auto [l, r] = run (p, 0, nullptr, 8192, 4096);
  5764. const std::tuple<int, float, float> golden[] { { 0, 0.0f, 0.0f }, { 500, -0.25248247f, 0.15141529f }, { 3000, -0.65128994f, -0.64854866f },
  5765. { 5000, -0.54308629f, -0.36827448f }, { 6000, -0.98378551f, -0.72790027f },
  5766. { 8191, 0.50599128f, -0.43637198f } };
  5767. for (const auto& [i, gl, gr] : golden)
  5768. CHECK (std::abs (l[(std::size_t) i] - gl) < 2e-6f && std::abs (r[(std::size_t) i] - gr) < 2e-6f);
  5769. }
  5770. {
  5771. // the delay alone: an impulse comes back after round(time·fs·0.3125/bpm) samples × (11^0.6 − 1)/10, then × feedback
  5772. std::array<int, 100> p {};
  5773. p[92] = 1, p[93] = 600, p[94] = 500, p[95] = 48;
  5774. lynx::hlfx::Rack rack;
  5775. rack.prepare (p, {}, 44100.0, 120.0, nullptr);
  5776. std::vector<float> l (16384), r (16384);
  5777. l[0] = 1.0f;
  5778. for (int s = 0; s < 16384; s += 512)
  5779. rack.process (l.data() + s, r.data() + s, 512, s == 0);
  5780. const auto D = 5512; // 48·44100·0.3125/120 = 5512.5 → 5512 (round half to even)
  5781. const auto vol = (float) ((std::exp ((double) (600 * 0.001f) * (double) (float) std::log (11.0)) - 1.0) * (double) 0.1f);
  5782. CHECK (std::abs (l[(std::size_t) D] - vol) < 1e-7f && std::abs (l[(std::size_t) D - 1]) < 1e-12f);
  5783. // the feedback ramps from 0.5 toward 0.5: the second echo is vol·0.5
  5784. CHECK (std::abs (l[(std::size_t) (2 * D)] - vol * 0.5f) < 1e-7f && std::abs (r[(std::size_t) D]) < 1e-12f);
  5785. }
  5786. // the compressor: Maximus states of our own (no preset data), checked against SG_x64.dll by REA round 36
  5787. using Env = std::vector<std::array<double, 4>>;
  5788. const Env def { { 0.0, 0.0, 0.0, 0 }, { 0.5, 0.5, 0.0, 0 }, { 0.5, 0.5, 0.0, 0 } };
  5789. auto band = [] (int mode, int pre = 1000, int post = 1000, int sep = 0, int sat = 0, int ceil = 1000, int att = 1115, int rel2 = 0,
  5790. int sus = 2882) { return std::array<int, 13> { mode, pre, post, sep, sat, ceil, att, rel2, 2, 5000, 3, sus, 0 }; };
  5791. {
  5792. // master brickwall at −0.22 dB only (bands off / compression off)
  5793. const auto st = maximusTestState ({ 19800, 1, 48065, 1, 1115, 1000, -1 }, { band (3), band (1), band (3), band (0) },
  5794. { def, def, def, def, def, def, def, def }, 0);
  5795. const auto preset = lynx::hlfx::makeMaximusPreset (st);
  5796. CHECK (preset != nullptr);
  5797. std::array<int, 100> p {};
  5798. p[98] = 1000;
  5799. const auto [l, r] = run (p, 1, preset, 4096, 4096);
  5800. const std::tuple<int, float, float> golden[] { { 100, 0.02499794f, 0.88166064f }, { 1000, 0.56971455f, -0.62808162f },
  5801. { 2047, -0.27541649f, 0.70913559f }, { 3000, 0.32431602f, -0.37985173f },
  5802. { 4095, -0.12743534f, -0.15237498f } };
  5803. for (const auto& [i, gl, gr] : golden)
  5804. CHECK (std::abs (l[(std::size_t) i] - gl) < 2e-6f && std::abs (r[(std::size_t) i] - gr) < 2e-6f);
  5805. float peak = 0.0f;
  5806. for (int i = 2048; i < 4096; ++i)
  5807. peak = std::max ({ peak, std::abs (l[(std::size_t) i]), std::abs (r[(std::size_t) i]) });
  5808. CHECK (peak < 0.9751f);
  5809. }
  5810. {
  5811. // 24 dB crossovers, ×2 oversampling, low cut, stereo separation, saturation A, a knee with tension (type 7) and
  5812. // exponential tensions (type 0), release 2 on the master, band mix 600
  5813. const Env knee { { 0.0, 0.0, 0.0, 0 }, { 0.35, 0.35, 0.0, 0 }, { 0.65, 0.6, 0.36, 7 } };
  5814. const Env t0 { { 0.0, 0.0, 0.0, 0 }, { 0.5, 0.5, 0.14, 0 }, { 0.5, 0.5, 0.0, 0 } };
  5815. const Env m0 { { 0.0, 0.0, 0.0, 0 }, { 0.5, 0.5, 0.0, 0 }, { 0.5, 0.6, 0.085, 0 } };
  5816. const auto st = maximusTestState ({ 19800, 1, 48065, 1, 891, 600, 32768 },
  5817. { band (1, 1264, 1296, 500, -500, 1200), band (0, 1340, 1000, -348, 0, 1000, 1115, 0, 1570),
  5818. band (0, 1364, 1152, 0, 0, 1000, 1115, 0, 1186), band (0, 1000, 1000, 0, -196, 1000, 1115, 4464, 1538) },
  5819. { def, def, knee, def, t0, def, m0, def }, 1);
  5820. const auto preset = lynx::hlfx::makeMaximusPreset (st);
  5821. CHECK (preset != nullptr);
  5822. std::array<int, 100> p {};
  5823. p[98] = 600;
  5824. const auto [l, r] = run (p, 2, preset, 4096, 4096);
  5825. const std::tuple<int, float, float> golden[] { { 100, 0.0f, 0.0f }, { 1000, -0.46856275f, -0.63261062f },
  5826. { 2047, 0.20268074f, 0.5414567f }, { 3000, -0.25614089f, -0.49984524f },
  5827. { 4095, 0.10172816f, 0.0505573f } };
  5828. for (const auto& [i, gl, gr] : golden)
  5829. CHECK (std::abs (l[(std::size_t) i] - gl) < 2e-6f && std::abs (r[(std::size_t) i] - gr) < 2e-6f);
  5830. }
  5831. {
  5832. // an .fst wrapper around a state is found; unsupported states are rejected
  5833. const auto st = maximusTestState ({ 19800, 1, 48065, 1, 1115, 1000, -1 }, { band (3), band (1), band (3), band (0) },
  5834. { def, def, def, def, def, def, def, def }, 0);
  5835. std::vector<std::uint8_t> fst { 'F', 'L', 'h', 'd', 6, 0, 0, 0, 0, 0, 1, 0, 0x60, 0, 'F', 'L', 'd', 't' };
  5836. std::vector<std::uint8_t> body { 0xC9, 8, 'M', 'a', 'x', 'i', 'm', 'u', 's', 0, 0xD5 };
  5837. for (auto n = st.size(); ; n >>= 7)
  5838. {
  5839. body.push_back ((std::uint8_t) ((n & 0x7f) | (n >= 0x80 ? 0x80 : 0)));
  5840. if (n < 0x80)
  5841. break;
  5842. }
  5843. body.insert (body.end(), st.begin(), st.end());
  5844. const auto len = (std::uint32_t) body.size();
  5845. for (int k = 0; k < 4; ++k)
  5846. fst.push_back ((std::uint8_t) (len >> (8 * k)));
  5847. fst.insert (fst.end(), body.begin(), body.end());
  5848. const auto found = lynx::hlfx::maximusStateFromFst (fst);
  5849. CHECK (found && *found == st);
  5850. auto rms = st;
  5851. rms[4 + 4 * (7 + 13 * 3 + 12)] = 1; // RMS detector on the master: not decoded
  5852. CHECK (lynx::hlfx::makeMaximusPreset (rms) == nullptr);
  5853. }
  5854. }
  5855. // ---- Sytrus (REA_rodada31) -------------------------------------------------------------------------------------------
  5856. // A Sytrus state built from scratch (version 25 layout, our own values — no FL preset data), zlib "stored" blocks.
  5857. namespace
  5858. {
  5859. struct SytrusTestPatch
  5860. {
  5861. std::vector<std::int32_t> main = std::vector<std::int32_t> (240, 0); // 962-byte main block as ints (+ mute bytes)
  5862. struct Op
  5863. {
  5864. int p[10] { 0, 256, 0, 0, 0, 0, 0, 0, 0, 0 };
  5865. int ratio = 20000, offset = 0, noise = 0;
  5866. std::vector<float> amps { 1.0f };
  5867. std::uint8_t flags[8] {};
  5868. int env1[3] { -1, -1, -1 }; // volume envelope: on (≠ −1 → on), decay point, sustain point
  5869. std::vector<std::pair<double, double>> env1pts;
  5870. } ops[6];
  5871. struct Filt
  5872. {
  5873. int p[10] { 0, 0, 128, 0, 128, 0, 0, 128, 128, 0 };
  5874. int type = 3;
  5875. } filts[3];
  5876. std::array<std::array<std::uint8_t, 23>, 3> delays {};
  5877. std::array<std::int32_t, 9> reverb { 19, 221, 0, 50, 80, 30, 221, 2, 0 };
  5878. bool reverbOn = false;
  5879. int eqmode = 0;
  5880. SytrusTestPatch()
  5881. {
  5882. main[0] = 128, main[1] = 128;
  5883. for (int i = 0; i < 8; ++i)
  5884. main[(std::size_t) (165 + i)] = (i % 4 == 2) ? 0 : 128;
  5885. main[173] = 1, main[175] = 128, main[188] = 128, main[189] = -1, main[190] = main[191] = 256;
  5886. }
  5887. void cell (int layer, int row, int col, int v) { main[(std::size_t) (3 + layer * 81 + row * 9 + col)] = v; }
  5888. std::vector<std::uint8_t> blob() const
  5889. {
  5890. std::vector<std::uint8_t> b;
  5891. auto i32 = [&] (std::int32_t v) { for (int k = 0; k < 4; ++k) b.push_back ((std::uint8_t) ((std::uint32_t) v >> (8 * k))); };
  5892. auto f32 = [&] (float v) { std::int32_t x; std::memcpy (&x, &v, 4); i32 (x); };
  5893. auto f64 = [&] (double v) { std::uint64_t x; std::memcpy (&x, &v, 8); for (int k = 0; k < 8; ++k) b.push_back ((std::uint8_t) (x >> (8 * k))); };
  5894. // point lists: kind 1 envelope, 2 LFO, 3 map / shaper curve; format version 3
  5895. auto env = [&] (int kind, const std::vector<std::pair<double, double>>& pts, int on, int decay, int sus) {
  5896. i32 (kind), i32 (3), i32 ((std::int32_t) pts.size());
  5897. for (const auto& [dt, y] : pts)
  5898. f64 (dt), f64 (y), f32 (0.0f), i32 (0);
  5899. i32 (0), i32 (on), i32 (decay), i32 (-1), i32 (sus);
  5900. };
  5901. for (int i = 0; i < 240; ++i)
  5902. if (4 * i + 4 <= 0x320)
  5903. i32 (main[(std::size_t) i]);
  5904. b.resize (962, 0); // mute bytes: none muted
  5905. i32 (0); // global declick amount
  5906. b.push_back (0), b.push_back (0), b.push_back (0); // OSC grouping, DC stage, GIBBS OFF
  5907. for (int k = 0; k < 9; ++k)
  5908. b.push_back (k == 7 ? 1 : 0); // flag group (release multiplier on, as Default.fst)
  5909. for (const auto& d : delays)
  5910. b.insert (b.end(), d.begin(), d.end());
  5911. for (auto v : reverb)
  5912. i32 (v);
  5913. b.push_back (reverbOn ? 1 : 0), b.push_back (0);
  5914. i32 (eqmode);
  5915. for (int k = 0; k < 3; ++k)
  5916. i32 (0), i32 (30000), i32 (20000), i32 (k);
  5917. b.push_back (0); // no info text
  5918. for (int u = 0; u < 10; ++u)
  5919. {
  5920. const int narts = u < 6 ? 6 : (u < 9 ? 8 : 2);
  5921. for (int j = 0; j < 10; ++j)
  5922. i32 (u < 6 ? ops[u].p[j] : (u < 9 ? filts[u - 6].p[j] : 0));
  5923. if (u < 6)
  5924. {
  5925. const auto& o = ops[u];
  5926. const auto at = b.size();
  5927. b.resize (at + 0x828, 0);
  5928. auto put = [&] (std::size_t off, const void* src, std::size_t n) { std::memcpy (b.data() + at + off, src, n); };
  5929. put (0, &o.ratio, 4), put (4, &o.offset, 4), put (8, &o.noise, 4);
  5930. put (0xc, o.amps.data(), 4 * o.amps.size());
  5931. const std::int32_t shape[5] { 0, 0, 0, 0, 128 };
  5932. put (0x80c, shape, sizeof shape);
  5933. put (0x820, o.flags, 8);
  5934. }
  5935. else if (u < 9)
  5936. {
  5937. const auto at = b.size();
  5938. b.resize (at + 0x30, 0);
  5939. std::memcpy (b.data() + at + 0x2c, &filts[u - 6].type, 4);
  5940. env (3, { { 0.0, 0.0 }, { 1.0, 1.0 } }, 0, -1, -1);
  5941. b.push_back (0);
  5942. }
  5943. for (int k = 0; k < narts; ++k)
  5944. {
  5945. const bool add = k == 0 || k == 3 || (u >= 6 && u <= 8 && (k == 2 || k == 3)) || (u < 6 && k == 4);
  5946. const double neutral = add ? 0.5 : 1.0;
  5947. i32 (3), i32 (0), f32 (1.0f), f32 (1.0f);
  5948. if (u < 6 && k == 1 && ops[u].env1[0] != -1)
  5949. env (1, ops[u].env1pts, -1, ops[u].env1[1], ops[u].env1[2]);
  5950. else
  5951. env (1, { { 0.0, 0.0 }, { 1.0, 1.0 } }, 0, -1, -1);
  5952. i32 (128), i32 (128), i32 (0), i32 (128);
  5953. env (2, { { 0.0, 1.0 }, { 1.0, 1.0 } }, 0, -1, -1);
  5954. i32 (40000), i32 (0), i32 (0), i32 (0), i32 (0);
  5955. for (int m = 0; m < 6; ++m)
  5956. env (3, { { 0.0, neutral }, { 1.0, neutral } }, 0, -1, -1);
  5957. }
  5958. }
  5959. b.push_back (0), b.push_back (0);
  5960. // zlib with stored blocks
  5961. std::vector<std::uint8_t> z { 0x78, 0x01 };
  5962. for (std::size_t at = 0; at < b.size(); at += 65535)
  5963. {
  5964. const auto n = std::min<std::size_t> (65535, b.size() - at);
  5965. z.push_back (at + n >= b.size() ? 1 : 0);
  5966. z.push_back ((std::uint8_t) n), z.push_back ((std::uint8_t) (n >> 8));
  5967. z.push_back ((std::uint8_t) ~n), z.push_back ((std::uint8_t) (~n >> 8));
  5968. z.insert (z.end(), b.begin() + (std::ptrdiff_t) at, b.begin() + (std::ptrdiff_t) (at + n));
  5969. }
  5970. std::uint32_t a = 1, c = 0;
  5971. for (auto x : b)
  5972. a = (a + x) % 65521, c = (c + a) % 65521;
  5973. for (int k = 3; k >= 0; --k)
  5974. z.push_back ((std::uint8_t) (((c << 16) | a) >> (8 * k)));
  5975. std::vector<std::uint8_t> out { 25, 0, 0, 0 };
  5976. out.insert (out.end(), z.begin(), z.end());
  5977. return out;
  5978. }
  5979. };
  5980. // renders like FL's Gen_Render calls: notes start/release at the block that contains them
  5981. std::pair<std::vector<float>, std::vector<float>> sytrusRender (const std::vector<std::uint8_t>& blob, bool renderMode, int n,
  5982. std::vector<std::array<int, 3>> notes, double fs = 44100.0)
  5983. {
  5984. lynx::sytrus::Engine e;
  5985. e.setTempo (120.0);
  5986. e.prepare (fs, renderMode, 512);
  5987. e.setPatch (lynx::sytrus::parsePatch (blob));
  5988. std::vector<float> l ((std::size_t) n), r ((std::size_t) n);
  5989. for (int n0 = 0; n0 < n; n0 += 512)
  5990. {
  5991. for (std::size_t k = 0; k < notes.size(); ++k)
  5992. {
  5993. if (notes[k][1] >= n0 && notes[k][1] < n0 + 512)
  5994. {
  5995. lynx::sytrus::NoteParams p;
  5996. p.key = (float) notes[k][0];
  5997. p.id = (std::int64_t) k + 1;
  5998. e.noteOn (p);
  5999. }
  6000. if (notes[k][2] >= n0 && notes[k][2] < n0 + 512)
  6001. e.release ((std::int64_t) k + 1);
  6002. }
  6003. e.render (l.data() + n0, r.data() + n0, std::min (512, n - n0), 1.0f, 0.0f);
  6004. }
  6005. return { l, r };
  6006. }
  6007. } // namespace
  6008. TEST (sytrus_engine_sine)
  6009. {
  6010. // one sine operator, ratio 1, OUT 256, no envelopes: C5 = 523.2511 Hz at 0.7071 (centre of the pan law, §6.1)
  6011. SytrusTestPatch t;
  6012. t.cell (0, 0, 8, 256);
  6013. const auto blob = t.blob();
  6014. CHECK (lynx::sytrus::stateUsable (blob));
  6015. CHECK (lynx::sytrus::parsePatch (blob) != nullptr);
  6016. auto broken = blob;
  6017. broken.resize (broken.size() / 2);
  6018. CHECK (! lynx::sytrus::stateUsable (broken));
  6019. const auto [l, r] = sytrusRender (blob, false, 8192, { { 60, 0, 4096 } });
  6020. double worst = 0.0;
  6021. for (int k = 0; k < 4000; ++k)
  6022. worst = std::max (worst, std::abs ((double) l[(std::size_t) k] - 0.70710678 * std::sin (2.0 * 3.14159265358979 * 523.251130601197 * k / 44100.0)));
  6023. CHECK (worst < 2e-5);
  6024. CHECK (l == r);
  6025. // envelope-less voice end (§4.9, §6.2): finished at a tick after the note-off, then the L/R gains (0.7071) ramp to 0
  6026. // at 0.001 per sample: the last non-zero sample is 4895 for a release at 4096 — the DLL's own figure (EXEC, §6.2)
  6027. int last = 0;
  6028. for (int k = 0; k < 8192; ++k)
  6029. if (l[(std::size_t) k] != 0.0f)
  6030. last = k;
  6031. CHECK (last == 4895);
  6032. // key 69 = 880 Hz; 48 kHz
  6033. const auto [l2, r2] = sytrusRender (blob, false, 4096, { { 69, 0, -1 } }, 48000.0);
  6034. worst = 0.0;
  6035. for (int k = 0; k < 4000; ++k)
  6036. worst = std::max (worst, std::abs ((double) l2[(std::size_t) k] - 0.70710678 * std::sin (2.0 * 3.14159265358979 * 880.0 * k / 48000.0)));
  6037. CHECK (worst < 5e-5);
  6038. (void) r2;
  6039. }
  6040. TEST (sytrus_engine_reference)
  6041. {
  6042. // FM 2→1, Vanilla LP filter, volume envelope, unison 3, delay and reverb, 2× oversampling with the 8-sample
  6043. // envelope tick (render settings): against our Python reference model of REA_rodada31 (sytmodel.render)
  6044. SytrusTestPatch t;
  6045. t.main[195] = 0, t.main[196] = 1, t.main[193] = 0, t.main[194] = 1;
  6046. t.main[173] = 3, t.main[174] = 64, t.main[176] = 100;
  6047. t.ops[1].ratio = 40000;
  6048. t.cell (0, 0, 1, 128); // op 2 → op 1 FM
  6049. t.cell (0, 0, 8, 128);
  6050. t.cell (0, 6, 0, 256); // op 1 → filter 1
  6051. t.cell (0, 6, 8, 256);
  6052. t.cell (0, 0, 7, 200); // FX send
  6053. t.filts[0].p[0] = 1, t.filts[0].p[2] = 180, t.filts[0].p[3] = 60;
  6054. t.ops[0].env1[0] = 0, t.ops[0].env1[1] = 1, t.ops[0].env1[2] = 2;
  6055. t.ops[0].env1pts = { { 0.0, 0.0 }, { 0.05, 1.0 }, { 0.1, 0.6 }, { 0.2, 0.0 } };
  6056. const std::int32_t d0[5] { 40, 100, 50, 100, 0 };
  6057. std::memcpy (t.delays[0].data(), d0, 20);
  6058. t.delays[0][22] = 1;
  6059. t.reverb = { 19, 221, 10, 50, 80, 30, 100, 2, 100 };
  6060. t.reverbOn = true;
  6061. const auto blob = t.blob();
  6062. const auto [l, r] = sytrusRender (blob, true, 12000, { { 60, 0, 6000 } });
  6063. // reference values (model render_mode=True, 44.1 kHz, block 512, key 60, velocity 0.78125, release at 6000); the same
  6064. // state rendered by FL's own Sytrus DLL in render mode differs from this by −136 dB (EXEC, REA round 31 harness)
  6065. const std::array<std::pair<int, float>, 8> golden { { { 100, -0.00235529384f }, { 777, -0.175126165f }, { 2000, 0.30976975f }, { 4321, -0.0213534199f },
  6066. { 6100, 0.202372357f }, { 7000, 0.249530748f }, { 9000, 0.0307101421f }, { 11999, 0.176390275f } } };
  6067. for (const auto& [i, v] : golden)
  6068. CHECK (std::abs (l[(std::size_t) i] - v) < 1e-6f);
  6069. const std::array<std::pair<int, float>, 3> goldenR { { { 777, -0.166890964f }, { 4321, -0.212358952f }, { 9000, -0.0251909085f } } };
  6070. for (const auto& [i, v] : goldenR)
  6071. CHECK (std::abs (r[(std::size_t) i] - v) < 1e-6f);
  6072. }
  6073. TEST (sytrus_instrument)
  6074. {
  6075. // the LYNX instrument: state in ChannelDef::pluginState, channel volume/pan recovered from the rack gains
  6076. SytrusTestPatch t;
  6077. t.cell (0, 0, 8, 256);
  6078. lynx::ChannelDef c;
  6079. c.instrument = lynx::InstrumentKind::sytrus;
  6080. c.pluginState = t.blob();
  6081. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sytrus);
  6082. inst->prepare (44100.0);
  6083. inst->configure (c, 120.0);
  6084. CHECK (inst->idle());
  6085. std::vector<float> l (4096), r (4096);
  6086. inst->noteOn (60, 100.0f / 128.0f);
  6087. // rack gains for volume V and pan p: √2·V·cos((1 + p)π/4), √2·V·sin(…); V = 0.5, p = 0 → Final.Vol 0.5
  6088. inst->render (l.data(), r.data(), 4096, 0.5f, 0.5f);
  6089. double peak = 0.0;
  6090. for (int k = 1000; k < 4096; ++k)
  6091. peak = std::max (peak, (double) std::abs (l[(std::size_t) k]));
  6092. CHECK (std::abs (peak - 0.5 * 0.70710678) < 1e-3); // Final.Vol 0.5 × the plugin's centre pan law
  6093. CHECK (! inst->idle());
  6094. inst->noteOff (60);
  6095. std::vector<float> tail (44100 * 3), tailR (tail.size());
  6096. inst->render (tail.data(), tailR.data(), (int) tail.size(), 0.5f, 0.5f);
  6097. CHECK (inst->idle());
  6098. CHECK (tail.back() == 0.0f);
  6099. }
  6100. TEST (harmless_engine)
  6101. {
  6102. // REA_rodada32: state parsing, the additive engine against our reference model (hlmodel.py), host levels, voice end
  6103. std::vector<std::uint8_t> blob;
  6104. auto put = [&] (std::int32_t v) { for (int k = 0; k < 4; ++k) blob.push_back ((std::uint8_t) ((std::uint32_t) v >> (8 * k))); };
  6105. std::array<std::int32_t, 100> p {}; // the reference's clean patch: Saw, open filter, no modulation
  6106. for (int i = 11; i < 23; ++i)
  6107. p[(std::size_t) i] = 1000;
  6108. p[27] = 1000, p[28] = 250, p[31] = 1000, p[36] = 1000, p[37] = 1, p[47] = 1, p[49] = 500, p[51] = -300, p[54] = 8192;
  6109. p[56] = 500, p[65] = 1, p[66] = 128, p[67] = 128, p[68] = 64, p[89] = 3000, p[91] = 500, p[95] = 144, p[97] = 500, p[98] = 500;
  6110. // + resonance, pluck, 3-voice unison, tremolo, LFO on pitch
  6111. p[54] = 3500, p[59] = 600, p[31] = 500, p[65] = 3, p[67] = 150, p[25] = 300, p[86] = 0, p[42] = 200, p[89] = 5000;
  6112. put (12);
  6113. for (auto v : p)
  6114. put (v);
  6115. for (int i = 0; i < 7; ++i)
  6116. put (0);
  6117. put (524); // Custom colour table: 524 × (amplitude, phase)
  6118. for (int i = 0; i < 1048; ++i)
  6119. {
  6120. const auto f = i < 524 ? 1.0f / (float) (i + 1) : 0.25f;
  6121. std::uint32_t bits = 0;
  6122. std::memcpy (&bits, &f, 4);
  6123. put ((std::int32_t) bits);
  6124. }
  6125. const auto parsed = lynx::harmlessParams (blob);
  6126. CHECK (parsed && (int) parsed->size() == lynx::harmlessParamCount);
  6127. CHECK (parsed && (*parsed)[54] == 3500.0f && (*parsed)[99] == 0.0f && (*parsed)[lynx::harmlessCustomFlagIndex] == 1.0f);
  6128. CHECK (parsed && (*parsed)[lynx::harmlessCustomIndex + 1] == 0.5f && (*parsed)[lynx::harmlessCustomIndex + 524] == 0.25f);
  6129. auto old = blob;
  6130. old[0] = 3; // versions below 4 are not Harmless states we know
  6131. CHECK (! lynx::harmlessParams (old));
  6132. old = blob;
  6133. old.resize (300);
  6134. CHECK (! lynx::harmlessParams (old));
  6135. lynx::ChannelDef c;
  6136. c.instrument = lynx::InstrumentKind::harmless;
  6137. c.modelParams = *parsed;
  6138. c.modelParams[lynx::harmlessCustomFlagIndex] = 0.0f; // colour 0 (Saw): the custom table is not read
  6139. auto render = [] (const lynx::ChannelDef& def, int total, float gl, float gr, int offAt) {
  6140. auto inst = lynx::makeInstrument (lynx::InstrumentKind::harmless);
  6141. inst->configure (def, 120.0);
  6142. inst->prepare (44100.0);
  6143. std::vector<float> l ((std::size_t) total), r ((std::size_t) total);
  6144. inst->noteOn (60, 0.78125f);
  6145. for (int s = 0; s < total; s += 512)
  6146. {
  6147. if (s == offAt)
  6148. inst->noteOff (60);
  6149. inst->render (l.data() + s, r.data() + s, std::min (512, total - s), gl, gr);
  6150. }
  6151. return std::make_tuple (l, r, std::move (inst));
  6152. };
  6153. {
  6154. // reference model (REA round 32 hlmodel.py, C5 at FL velocity 100, channel volume 1, centre, released at 6144)
  6155. auto [l, r, inst] = render (c, 8192, 1.0f, 1.0f, 6144);
  6156. const std::tuple<int, float, float> golden[] {
  6157. { 0, 0.0f, 0.0f }, { 10, -0.02220994f, -0.06232700f }, { 100, 0.40623373f, 0.17308202f }, { 1000, -0.04091963f, -0.26821208f },
  6158. { 3000, 0.14519004f, 0.11027778f }, { 6000, 0.50411958f, 0.27901855f }, { 8191, 0.02117692f, -0.01466602f } };
  6159. for (const auto& [i, gl, gr] : golden)
  6160. CHECK (std::abs (l[(std::size_t) i] - gl) < 2e-6f && std::abs (r[(std::size_t) i] - gr) < 2e-6f);
  6161. // after the release the record fades out (below 1e-4, then 30 ms) and the instrument goes idle
  6162. std::vector<float> tail (44100), tailR (tail.size());
  6163. inst->render (tail.data(), tailR.data(), (int) tail.size(), 1.0f, 1.0f);
  6164. CHECK (inst->idle());
  6165. }
  6166. // FL's level law applied once: half the channel volume halves the output; full right pan silences the left side
  6167. const auto full = std::get<0> (render (c, 2048, 1.0f, 1.0f, -1));
  6168. const auto half = std::get<0> (render (c, 2048, 0.5f, 0.5f, -1));
  6169. CHECK (std::abs (half[100] - 0.5f * full[100]) < 1e-6f && std::abs (full[100]) > 0.1f);
  6170. auto mono = c;
  6171. mono.modelParams[25] = 0.0f; // no tremolo, no unison pan spread
  6172. mono.modelParams[65] = 1.0f;
  6173. const auto [pl, pr, pi] = render (mono, 2048, 0.0f, 1.41421356f, -1);
  6174. double el = 0.0, er = 0.0;
  6175. for (int i = 0; i < 2048; ++i)
  6176. el += (double) pl[(std::size_t) i] * pl[(std::size_t) i], er += (double) pr[(std::size_t) i] * pr[(std::size_t) i];
  6177. CHECK (el < 1e-10 * er && er > 1.0);
  6178. }