tests.cpp 332 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465
  1. // Core tests (no JUCE). Usage: lynx_tests [folder-with-flp-files]
  2. #include <atomic>
  3. #include <cctype>
  4. #include <cmath>
  5. #include <cstdio>
  6. #include <cstring>
  7. #include <filesystem>
  8. #include <map>
  9. #include <set>
  10. #include <sstream>
  11. #include <fstream>
  12. #include <functional>
  13. #include <iterator>
  14. #include <string>
  15. #include <tuple>
  16. #include <vector>
  17. #include "core/Dither.h"
  18. #include "core/DrumSynthLive.h"
  19. #include "core/Effects.h"
  20. #include "core/Effector.h"
  21. #include "core/FlpImport.h"
  22. #include "core/FlEffects.h"
  23. #include "core/FlPatcher.h"
  24. #include "core/FlSamplers.h"
  25. #include "core/FlSynths.h"
  26. #include "core/Inflate.h"
  27. #include "core/WavPack.h"
  28. #include "core/FlWrapper.h"
  29. #include "core/Gms.h"
  30. #include "core/Harmless.h"
  31. #include "core/Harmor.h"
  32. #include "core/Morphine.h"
  33. #include "core/HarmlessFx.h"
  34. #include "core/LiveEventQueue.h"
  35. #include "core/RackRenderer.h"
  36. #include "core/Scheduler.h"
  37. #include "core/SnapshotExchange.h"
  38. #include "core/SoftClip.h"
  39. #include "core/Slicer.h"
  40. #include "core/SytrusEngine.h"
  41. #include "core/Templates.h"
  42. #include "core/Vocodex.h"
  43. #include "core/TimeStretch.h"
  44. #include "core/WorkerPool.h"
  45. #include "core/Song.h"
  46. #include "core/NoteEdit.h"
  47. #include "core/Recorder.h"
  48. #include "core/KeyMap.h"
  49. #include "core/RackOps.h"
  50. #include "core/ValueMath.h"
  51. #include "core/Workspace.h"
  52. #include "core/StartupSound.h"
  53. #include "flp/Flp.h"
  54. #include "ui/I18nData.h"
  55. namespace
  56. {
  57. int failures = 0;
  58. int checks = 0;
  59. std::vector<std::pair<const char*, std::function<void()>>>& registry()
  60. {
  61. static std::vector<std::pair<const char*, std::function<void()>>> r;
  62. return r;
  63. }
  64. struct Register
  65. {
  66. Register (const char* name, std::function<void()> fn) { registry().emplace_back (name, std::move (fn)); }
  67. };
  68. #define TEST(name) \
  69. static void name(); \
  70. static Register reg_##name (#name, name); \
  71. static void name()
  72. #define CHECK(cond) \
  73. do \
  74. { \
  75. ++checks; \
  76. if (! (cond)) \
  77. { \
  78. ++failures; \
  79. std::printf (" FAILED %s:%d: %s\n", __FILE__, __LINE__, #cond); \
  80. } \
  81. } while (false)
  82. std::string realFlpDir;
  83. // --- helpers for building synthetic .flp files -----------------------------
  84. struct FlpBuilder
  85. {
  86. std::vector<std::uint8_t> bytes;
  87. FlpBuilder (std::uint16_t ppq = 96)
  88. {
  89. put ("FLhd");
  90. u32 (6);
  91. u16 (0);
  92. u16 (1);
  93. u16 (ppq);
  94. put ("FLdt");
  95. u32 (0); // size is not used by the reader
  96. }
  97. void put (const char* s) { bytes.insert (bytes.end(), s, s + std::strlen (s)); }
  98. void u8 (std::uint8_t v) { bytes.push_back (v); }
  99. void u16 (std::uint16_t v) { u8 ((std::uint8_t) v); u8 ((std::uint8_t) (v >> 8)); }
  100. void u32 (std::uint32_t v) { u16 ((std::uint16_t) v); u16 ((std::uint16_t) (v >> 16)); }
  101. void varint (std::size_t n)
  102. {
  103. do
  104. {
  105. auto b = (std::uint8_t) (n & 0x7F);
  106. n >>= 7;
  107. u8 (n ? (std::uint8_t) (b | 0x80) : b);
  108. } while (n);
  109. }
  110. void data (std::uint8_t id, const std::vector<std::uint8_t>& payload)
  111. {
  112. u8 (id);
  113. varint (payload.size());
  114. bytes.insert (bytes.end(), payload.begin(), payload.end());
  115. }
  116. void ascii (std::uint8_t id, const std::string& s)
  117. {
  118. std::vector<std::uint8_t> p (s.begin(), s.end());
  119. p.push_back (0);
  120. data (id, p);
  121. }
  122. void utf16 (std::uint8_t id, const std::u16string& s)
  123. {
  124. std::vector<std::uint8_t> p;
  125. for (auto c : s)
  126. {
  127. p.push_back ((std::uint8_t) c);
  128. p.push_back ((std::uint8_t) (c >> 8));
  129. }
  130. p.push_back (0);
  131. p.push_back (0);
  132. data (id, p);
  133. }
  134. };
  135. std::vector<std::uint8_t> noteRecord (std::uint32_t pos, std::uint16_t channel, std::uint32_t len, std::uint16_t key,
  136. std::uint8_t velocity)
  137. {
  138. std::vector<std::uint8_t> r (24, 0);
  139. std::memcpy (&r[0], &pos, 4);
  140. std::memcpy (&r[6], &channel, 2);
  141. std::memcpy (&r[8], &len, 4);
  142. std::memcpy (&r[12], &key, 2);
  143. r[16] = 120;
  144. r[20] = 64;
  145. r[21] = velocity;
  146. return r;
  147. }
  148. } // namespace
  149. // ---------------------------------------------------------------------------
  150. // FLP
  151. TEST (flp_rejects_garbage)
  152. {
  153. std::vector<std::uint8_t> junk (64, 0x41);
  154. bool threw = false;
  155. try { flp::EventReader r (junk); } catch (const flp::Error&) { threw = true; }
  156. CHECK (threw);
  157. }
  158. TEST (flp_reads_size_classes_varint_and_extended_ids)
  159. {
  160. FlpBuilder b;
  161. b.u8 (0x15); b.u8 (2); // u8
  162. b.u8 (0x40); b.u16 (513); // u16
  163. b.u8 (0x9C); b.u32 (128500); // u32
  164. b.data (0xD5, std::vector<std::uint8_t> (300, 7)); // 2-byte varint
  165. b.u8 (0xAC); b.u32 (0xC0000100); b.varint (3); b.u8 (1); b.u8 (2); b.u8 (3); // extended ID
  166. flp::EventReader r (b.bytes);
  167. flp::Event e;
  168. CHECK (r.header().ppq == 96);
  169. CHECK (r.next (e) && e.id == 0x15 && e.value == 2);
  170. CHECK (r.next (e) && e.id == 0x40 && e.value == 513);
  171. CHECK (r.next (e) && e.id == 0x9C && e.value == 128500);
  172. CHECK (r.next (e) && e.id == 0xD5 && e.data.size() == 300 && e.data[299] == 7);
  173. CHECK (r.next (e) && e.id == 0xC0000100 && e.isData() && e.data.size() == 3 && e.data[2] == 3);
  174. CHECK (! r.next (e));
  175. }
  176. TEST (flp_truncated_file_throws)
  177. {
  178. FlpBuilder b;
  179. b.u8 (0x9C); b.u8 (1); // u32 with only 1 byte
  180. flp::EventReader r (b.bytes);
  181. flp::Event e;
  182. bool threw = false;
  183. try { r.next (e); } catch (const flp::Error&) { threw = true; }
  184. CHECK (threw);
  185. }
  186. TEST (flp_version_numbers)
  187. {
  188. CHECK (flp::parseVersionNumber ("25.2.5.5319") == 25002005u);
  189. CHECK (flp::parseVersionNumber ("20.99.3000.3031") == 20102000u);
  190. CHECK (flp::parseVersionNumber ("11.0.3") == 11000003u);
  191. }
  192. TEST (flp_playlist_record_size_by_version)
  193. {
  194. CHECK (flp::playlistRecordSize (12009003, 64) == 32);
  195. CHECK (flp::playlistRecordSize (21000000, 120) == 60);
  196. CHECK (flp::playlistRecordSize (25002005, 160) == 80);
  197. CHECK (flp::playlistRecordSize (25002005, 60) == 60); // size doesn't match the version -> tries the others
  198. CHECK (flp::playlistRecordSize (25002005, 7) == 0);
  199. }
  200. TEST (flp_parses_project_model)
  201. {
  202. FlpBuilder b (96);
  203. b.ascii (0xC7, "25.2.5.5319");
  204. b.u8 (0x9C); b.u32 (174500);
  205. b.utf16 (0xC2, u"Título");
  206. b.u8 (0x41); b.u16 (3);
  207. b.u8 (0x96); b.u32 (0x00A14547); // BGR in the file
  208. auto notes = noteRecord (96, 1, 48, 64, 100);
  209. auto n2 = noteRecord (0, 0, 0, 60, 128);
  210. notes.insert (notes.end(), n2.begin(), n2.end());
  211. b.data (0xE0, notes);
  212. b.u8 (0x40); b.u16 (0);
  213. b.u8 (0x15); b.u8 (0);
  214. b.utf16 (0xCB, u"Kick");
  215. {
  216. std::vector<std::uint8_t> levels (24, 0);
  217. const std::int32_t lv[] = { 3200, 12800, -150 };
  218. std::memcpy (levels.data(), lv, sizeof (lv));
  219. b.data (0xDB, levels);
  220. }
  221. b.u8 (0x68); b.u16 (5);
  222. b.u8 (0x40); b.u16 (1);
  223. b.u8 (0x15); b.u8 (2);
  224. b.utf16 (0xC9, u"FLEX");
  225. b.utf16 (0xCB, u"Lead");
  226. b.u8 (0x63); b.u16 (0);
  227. std::vector<std::uint8_t> item (80, 0);
  228. std::uint32_t pos = 384, len = 768;
  229. std::uint16_t base = 20480, idx = 20480 + 3, rv = 499 - 2;
  230. std::memcpy (&item[0], &pos, 4);
  231. std::memcpy (&item[4], &base, 2);
  232. std::memcpy (&item[6], &idx, 2);
  233. std::memcpy (&item[8], &len, 4);
  234. std::memcpy (&item[12], &rv, 2);
  235. b.data (0xE9, item);
  236. b.utf16 (0xCC, u"Drums");
  237. b.data (0xEC, std::vector<std::uint8_t> (12, 0));
  238. b.data (0xEC, std::vector<std::uint8_t> (12, 0));
  239. const auto p = flp::parseProject (b.bytes);
  240. CHECK (p.version == "25.2.5.5319");
  241. CHECK (std::abs (p.tempo - 174.5) < 1e-9);
  242. CHECK (p.title == "Título");
  243. CHECK (p.channels.size() == 2);
  244. CHECK (p.channels[0].name == "Kick" && p.channels[0].mixerTrack == 5);
  245. CHECK (p.channels[0].hasLevels && p.channels[0].pan == 3200 && p.channels[0].volume == 12800 && p.channels[0].pitchCents == -150);
  246. CHECK (p.channels[1].type == flp::ChannelType::instrument && p.channels[1].pluginName == "FLEX");
  247. CHECK (p.patterns.size() == 1 && p.patterns[0].index == 3);
  248. CHECK (p.patterns[0].colour && *p.patterns[0].colour == 0x4745A1);
  249. CHECK (p.patterns[0].notes.size() == 2 && p.patterns[0].notes[0].position == 0); // sorted
  250. CHECK (p.patterns[0].notes[1].key == 64 && p.patterns[0].notes[1].length == 48);
  251. CHECK (p.arrangements.size() == 1 && p.arrangements[0].items.size() == 1);
  252. const auto& it = p.arrangements[0].items[0];
  253. CHECK (it.kind == flp::PlaylistItem::Kind::pattern && it.index == 3 && it.track == 2 && it.position == 384);
  254. CHECK (p.mixer.size() == 2 && p.mixer[0].name == "Drums" && p.mixer[1].name.empty());
  255. CHECK (p.warnings.empty());
  256. }
  257. TEST (flp_fuzz_corrupted_files_do_not_crash)
  258. {
  259. if (realFlpDir.empty())
  260. return;
  261. // some real .flp files, corrupted in various ways: the parser may reject them (flp::Error), but
  262. // must never hang, read past the buffer or produce a Song with invalid indices
  263. std::vector<std::vector<std::uint8_t>> sources;
  264. for (auto& entry : std::filesystem::recursive_directory_iterator (realFlpDir))
  265. if (entry.path().extension() == ".flp" && sources.size() < 6 && std::filesystem::file_size (entry.path()) < 3'000'000)
  266. {
  267. std::ifstream in (entry.path(), std::ios::binary);
  268. sources.emplace_back ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  269. }
  270. std::uint32_t seed = 2024;
  271. auto rnd = [&] (std::uint32_t n) { seed = seed * 1664525u + 1013904223u; return n == 0 ? 0u : (seed >> 8) % n; };
  272. int parsed = 0, rejected = 0;
  273. for (int round = 0; round < 240 && ! sources.empty(); ++round)
  274. {
  275. auto bytes = sources[(std::size_t) rnd ((std::uint32_t) sources.size())];
  276. switch (round % 4)
  277. {
  278. case 0: bytes.resize (rnd ((std::uint32_t) bytes.size())); break; // truncated
  279. 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;
  280. case 2: // absurd event size
  281. for (int k = 0; k < 5; ++k)
  282. bytes[(std::size_t) rnd ((std::uint32_t) bytes.size())] = 0xFF;
  283. break;
  284. default: // shuffled block
  285. {
  286. const auto a = rnd ((std::uint32_t) bytes.size()), b = rnd ((std::uint32_t) bytes.size());
  287. std::reverse (bytes.begin() + std::min (a, b), bytes.begin() + std::max (a, b));
  288. break;
  289. }
  290. }
  291. try
  292. {
  293. const auto project = flp::parseProject (bytes);
  294. const auto song = lynx::importFlp (project);
  295. ++parsed;
  296. for (const auto& p : song.patterns)
  297. for (const auto& n : p.notes)
  298. CHECK (n.channel >= 0 && n.channel < (int) song.channels.size());
  299. for (const auto& c : song.playlist)
  300. CHECK (c.kind != lynx::ClipKind::pattern || (c.pattern >= 0 && c.pattern < (int) song.patterns.size()));
  301. }
  302. catch (const flp::Error&)
  303. {
  304. ++rejected;
  305. }
  306. }
  307. std::printf (" fuzz: %d imported, %d rejected\n", parsed, rejected);
  308. CHECK (parsed + rejected == 240);
  309. }
  310. TEST (plugin_state_decoders_survive_garbage)
  311. {
  312. // random blobs (varied sizes, including valid headers followed by garbage)
  313. std::uint32_t seed = 77;
  314. auto rnd = [&] { seed = seed * 1664525u + 1013904223u; return seed >> 8; };
  315. const char* plugins[] = { "Fruity Parametric EQ 2", "Fruity Limiter", "Fruity Reeverb 2", "Fruity Delay 2", "Fruity Delay 3",
  316. "Fruity Compressor", "Fruity Balance", "Fruity PanOMatic", "Fruity Stereo Shaper", "Fruity Phase Inverter" };
  317. int decoded = 0;
  318. for (int round = 0; round < 3000; ++round)
  319. {
  320. std::vector<std::uint8_t> blob ((std::size_t) (rnd() % 600));
  321. for (auto& b : blob)
  322. b = (std::uint8_t) rnd();
  323. if (blob.size() >= 4 && round % 3 == 0) // versions the readers accept
  324. {
  325. const std::uint32_t versions[] = { 8, 10001, 10000, 12, 14, 6, 1 };
  326. const auto v = versions[rnd() % 7];
  327. std::memcpy (blob.data(), &v, 4);
  328. }
  329. if (auto fx = lynx::effectFromFl (plugins[rnd() % 10], blob))
  330. {
  331. ++decoded;
  332. for (auto v : fx->params)
  333. CHECK (std::isfinite (v) && v >= 0.0f && v <= 1.0f);
  334. }
  335. lynx::SynthSettings synth;
  336. if (lynx::synthFrom3xOsc (blob, synth))
  337. for (const auto& o : synth.osc)
  338. CHECK (std::isfinite (o.level) && o.level >= 0.0f && o.level <= 1.0f);
  339. float harmlessGain = 1.0f;
  340. if (lynx::synthFromHarmless (blob, 120.0, synth, harmlessGain))
  341. CHECK (std::isfinite (harmlessGain) && std::isfinite (synth.cutoff) && std::isfinite (synth.attack));
  342. if (lynx::synthFromFruitKick (blob, synth))
  343. CHECK (std::isfinite (synth.decay) && std::isfinite (synth.pitchEnv.amount));
  344. if (lynx::synthFromGms (blob, 120.0, synth, harmlessGain) || lynx::synthFromHarmor (blob, synth, harmlessGain) || lynx::synthFromOgun (blob, synth, harmlessGain)
  345. || lynx::synthFromSakura (blob, synth) || lynx::synthFromKepler (blob, synth, harmlessGain))
  346. CHECK (std::isfinite (synth.cutoff) && std::isfinite (synth.attack) && std::isfinite (harmlessGain));
  347. if (auto sound = lynx::drumSynthLiveSound (blob))
  348. CHECK (sound->size() < 256);
  349. if (auto wave = lynx::waveTravellerSample (blob))
  350. CHECK (! wave->first.empty() && wave->second >= 0 && wave->second <= 127);
  351. lynx::synthFromBooBass (blob, synth);
  352. lynx::gmsStateUsable (blob); // (the exact engines' parsers reject garbage without crashing)
  353. lynx::morphineStateUsable (blob);
  354. if (lynx::synthFromPoiZone (blob, synth, harmlessGain) || lynx::synthFromBassDrum (blob, synth, harmlessGain) || lynx::synthFromToxic (blob, synth, harmlessGain)
  355. || lynx::synthFromMorphine (blob, synth, harmlessGain))
  356. CHECK (std::isfinite (synth.cutoff) && std::isfinite (harmlessGain));
  357. if (auto patch = lynx::drumpadPatchName (blob))
  358. CHECK (patch->size() <= 0x30 && std::isfinite (lynx::drumToneForName (*patch).decay));
  359. if (auto flex = lynx::flexPresetName (blob))
  360. CHECK ((! flex->first.empty() || ! flex->second.empty()) && flex->second.size() <= 1024);
  361. if (lynx::synthFromSytrus (blob, 120.0, synth, harmlessGain))
  362. CHECK (std::isfinite (synth.cutoff) && std::isfinite (synth.attack));
  363. if (lynx::synthFromDX10 (blob, synth))
  364. CHECK (std::isfinite (synth.decay) && std::isfinite (synth.release) && std::isfinite (synth.osc[1].level));
  365. if (blob.size() >= 4 && round % 5 == 0) // MiniSynth header followed by garbage
  366. {
  367. std::memcpy (blob.data(), "SSLF", 4);
  368. if (blob.size() > 220)
  369. {
  370. std::memcpy (blob.data() + 40, "DATA", 4);
  371. std::memcpy (blob.data() + 48, "0rev", 4);
  372. }
  373. }
  374. if (lynx::synthFromMiniSynth (blob, 120.0, synth))
  375. CHECK (std::isfinite (synth.cutoff) && std::isfinite (synth.decay) && std::isfinite (synth.attack));
  376. lynx::ForeignPlugin foreign;
  377. lynx::parseFlWrapper (blob, foreign);
  378. std::vector<std::uint8_t> component, controller;
  379. lynx::splitFlVst3State (blob, component, controller);
  380. }
  381. CHECK (decoded == 3000); // every known name yields an effect (default when the blob is unusable)
  382. }
  383. TEST (inflate_zlib)
  384. {
  385. // fixed Huffman with back-references
  386. const std::uint8_t fixed[] = { 0x78, 0xda, 0x4b, 0x4c, 0x4a, 0x4e, 0xc4, 0x86, 0x22, 0x00, 0x7c, 0x69, 0x09, 0x89 };
  387. const auto a = lynx::inflateZlib (fixed, sizeof (fixed));
  388. CHECK (a && std::string (a->begin(), a->end()) == "abcabcabcabcabcabcabcabcX");
  389. // stored (uncompressed) block
  390. const std::uint8_t stored[] = { 0x78, 0x01, 0x01, 0x03, 0x00, 0xfc, 0xff, 'L', 'Y', 'N', 0x00, 0x00, 0x00, 0x00 };
  391. const auto b = lynx::inflateZlib (stored, sizeof (stored));
  392. CHECK (b && std::string (b->begin(), b->end()) == "LYN");
  393. // truncated, bad header and size limit
  394. CHECK (! lynx::inflateZlib (fixed, 6));
  395. const std::uint8_t bad[] = { 0x12, 0x34, 0x00 };
  396. CHECK (! lynx::inflateZlib (bad, sizeof (bad)));
  397. CHECK (! lynx::inflateZlib (fixed, sizeof (fixed), false, 10));
  398. }
  399. TEST (fl_round15_effects_convert_known_values)
  400. {
  401. auto blob = [] (std::vector<std::int32_t> words) {
  402. std::vector<std::uint8_t> b (words.size() * 4);
  403. std::memcpy (b.data(), words.data(), b.size());
  404. return b;
  405. };
  406. // Frequency Shifter "+800 Hz": frequency 51542 in the 20 kHz range, 100% wet
  407. const auto fs = lynx::effectFromFl ("Frequency Shifter", blob ({ 4, 10000, 0, 51542, 0, 10000, 10000, 5000, 10000, 0, 5000, 0, 0 }));
  408. CHECK (fs && fs->kind == lynx::EffectKind::freqShift);
  409. if (fs)
  410. {
  411. const auto x = (fs->params[0] - 0.5) * 2.0;
  412. CHECK (std::abs (2000.0 * x * std::abs (x) - 800.0) < 10.0);
  413. CHECK (std::abs (fs->params[1] - 1.0f) < 1e-4f);
  414. }
  415. // Emphasis: input 0.0625 (= +1.5 dB) and ceiling 0.9308 (≈ −1.6 dB) -> limiter
  416. const auto em = lynx::effectFromFl ("Emphasis", blob ({ 8, 0, 0, 2, 1, 0, 0, 625, 10000, 10000, 9308, 0, 2, 7, 0 }));
  417. CHECK (em && em->kind == lynx::EffectKind::limiter && em->enabled);
  418. if (em)
  419. {
  420. CHECK (std::abs (em->params[1] * 24.0f - 1.5f) < 0.05f);
  421. CHECK (std::abs (em->params[0] * 12.0f - 12.0f + 1.6f) < 0.1f);
  422. }
  423. // Pitch Shifter +12 st, mix 100%
  424. 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 }));
  425. CHECK (ps && ps->kind == lynx::EffectKind::pitchShift && std::abs (ps->params[0] - (0.5f + 12.0f / 48.0f)) < 1e-4f);
  426. }
  427. TEST (frequency_shifter_moves_spectrum_by_hz)
  428. {
  429. auto fx = lynx::makeEffect (lynx::EffectKind::freqShift);
  430. fx->prepare (48000.0);
  431. auto slot = lynx::makeEffectSlot (lynx::EffectKind::freqShift);
  432. // +200 Hz: x·|x|·2000 = 200 -> x = sqrt(0.1)
  433. slot.params[0] = (float) (0.5 + std::sqrt (0.1) / 2.0);
  434. std::vector<float> l (48000), r (48000);
  435. for (int i = 0; i < 48000; ++i)
  436. l[(std::size_t) i] = r[(std::size_t) i] = (float) std::sin (2.0 * 3.141592653589793 * 1000.0 * i / 48000.0);
  437. for (int done = 0; done < 48000; done += 480)
  438. fx->process (l.data() + done, r.data() + done, 480, slot.params, 120.0);
  439. auto energy = [&] (double f) {
  440. const auto w = 2.0 * 3.141592653589793 * f / 48000.0, k = 2.0 * std::cos (w);
  441. double s1 = 0.0, s2 = 0.0;
  442. for (int i = 9600; i < 48000; ++i)
  443. {
  444. const auto s0 = l[(std::size_t) i] + k * s1 - s2;
  445. s2 = s1;
  446. s1 = s0;
  447. }
  448. return s1 * s1 + s2 * s2 - k * s1 * s2;
  449. };
  450. // the energy moves to 1200 Hz; little remains at 1000 and almost nothing at the image (800)
  451. CHECK (energy (1200.0) > 50.0 * energy (1000.0));
  452. CHECK (energy (1200.0) > 50.0 * energy (800.0));
  453. }
  454. TEST (pitch_shift_moves_frequency_keeps_length)
  455. {
  456. auto fx = lynx::makeEffect (lynx::EffectKind::pitchShift);
  457. fx->prepare (48000.0);
  458. auto slot = lynx::makeEffectSlot (lynx::EffectKind::pitchShift);
  459. auto crossingsAfter = [&] (float semitoneParam) {
  460. fx->reset();
  461. slot.params[0] = semitoneParam;
  462. std::vector<float> l (48000), r (48000);
  463. for (int i = 0; i < 48000; ++i)
  464. l[(std::size_t) i] = r[(std::size_t) i] = (float) std::sin (2.0 * 3.141592653589793 * 220.0 * i / 48000.0);
  465. for (int done = 0; done < 48000; done += 512)
  466. fx->process (l.data() + done, r.data() + done, std::min (512, 48000 - done), slot.params, 120.0);
  467. int crossings = 0;
  468. for (int i = 9600; i < 48000; ++i)
  469. crossings += (l[(std::size_t) i - 1] < 0.0f) != (l[(std::size_t) i] < 0.0f);
  470. for (auto v : l)
  471. CHECK (std::isfinite (v) && std::abs (v) < 1.6f);
  472. return crossings / 0.8 / 2.0; // cycles per second
  473. };
  474. CHECK (std::abs (crossingsAfter (0.5f) - 220.0) < 8.0); // 0 st
  475. CHECK (std::abs (crossingsAfter (0.5f + 12.0f / 48.0f) - 440.0) < 25.0); // +12 st
  476. CHECK (std::abs (crossingsAfter (0.5f - 12.0f / 48.0f) - 110.0) < 12.0); // −12 st
  477. }
  478. TEST (volume_gate_follows_bar_position)
  479. {
  480. auto fx = lynx::makeEffect (lynx::EffectKind::volumeGate);
  481. fx->prepare (48000.0);
  482. auto slot = lynx::makeEffectSlot (lynx::EffectKind::volumeGate);
  483. for (int i = 0; i < 32; ++i)
  484. slot.params[(std::size_t) i] = i < 16 ? 1.0f : 0.0f; // first two beats open, two closed
  485. slot.params[33] = slot.params[34] = 0.0f; // no smoothing
  486. // 120 BPM: one beat = 0.5 s = 24000 samples; the 4-beat bar starts at tick 0
  487. std::vector<float> l (96000, 1.0f), r (96000, 1.0f);
  488. fx->setSongPosition (0.0);
  489. for (int done = 0; done < 96000; done += 512)
  490. fx->process (l.data() + done, r.data() + done, std::min (512, 96000 - done), slot.params, 120.0);
  491. CHECK (l[10000] > 0.99f && l[40000] > 0.99f); // beats 1 and 2
  492. CHECK (l[60000] < 0.01f && l[90000] < 0.01f); // beats 3 and 4
  493. // starting mid-bar (beat 3): already closed
  494. std::vector<float> l2 (4800, 1.0f), r2 (4800, 1.0f);
  495. fx->reset();
  496. fx->setSongPosition (2.0 * lynx::ppq);
  497. fx->process (l2.data(), r2.data(), 4800, slot.params, 120.0);
  498. CHECK (l2[4000] < 0.01f);
  499. // mix 0: transparent
  500. slot.params[32] = 0.0f;
  501. std::vector<float> l3 (4800, 1.0f), r3 (4800, 1.0f);
  502. fx->setSongPosition (2.0 * lynx::ppq);
  503. fx->process (l3.data(), r3.data(), 4800, slot.params, 120.0);
  504. CHECK (l3[4000] > 0.99f);
  505. }
  506. TEST (patcher_branch_heads_follow_rea)
  507. {
  508. auto words = [] (std::vector<std::int32_t> v) {
  509. std::vector<std::uint8_t> b (v.size() * 4);
  510. std::memcpy (b.data(), v.data(), b.size());
  511. return b;
  512. };
  513. // Frequency Splitter, 2 bands, destinations 1/2/3, slope combo 3 (24 dB/oct), high send −6 dB
  514. std::vector<std::int32_t> fs (18, 0);
  515. fs[0] = 4;
  516. fs[1] = 32768;
  517. fs[3] = 3;
  518. fs[6] = 0;
  519. fs[11] = -600;
  520. fs[15] = 1;
  521. fs[16] = 2;
  522. fs[17] = 3;
  523. const auto split = words (fs);
  524. const auto low = lynx::patcherBranchHead ("Frequency Splitter", split, 1);
  525. CHECK (low.valid && low.slot && low.note.empty());
  526. if (low.slot)
  527. {
  528. // low band = just the Crossover low-pass, combo 3 (24 dB/oct)
  529. CHECK (low.slot->kind == lynx::EffectKind::crossover && low.slot->params[0] == 0.0f && low.slot->params[3] == 1.0f);
  530. CHECK (std::lround (low.slot->params[5] * 7.0f) == 3);
  531. }
  532. const auto mid = lynx::patcherBranchHead ("Frequency Splitter", split, 2);
  533. CHECK (mid.valid && mid.gain == 0.0f); // with 2 bands the mid is silent
  534. const auto high = lynx::patcherBranchHead ("Frequency Splitter", split, 3);
  535. CHECK (high.valid && std::abs (high.gain - std::pow (10.0f, -6.0f / 20.0f)) < 1e-4f);
  536. CHECK (! lynx::patcherBranchHead ("Frequency Splitter", split, 7).valid);
  537. // Stereo Shaper with identity matrix: the difference (destination 4) is zero
  538. const auto shaper = words ({ 3, 0, 12800, 12800, 0, 0, 0, 4, 0 });
  539. const auto diff = lynx::patcherBranchHead ("Fruity Stereo Shaper", shaper, 4);
  540. 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);
  541. CHECK (! lynx::patcherBranchHead ("Fruity Stereo Shaper", shaper, 2).valid);
  542. }
  543. TEST (parallel_container_sums_branches)
  544. {
  545. // two branches: dry with gain 0.5 and a utility that flips phase (matrix −1) with gain 0.5 -> silence
  546. auto slot = lynx::makeEffectSlot (lynx::EffectKind::parallel);
  547. lynx::EffectBranch dry;
  548. dry.gain = 0.5f;
  549. lynx::EffectBranch inverted;
  550. inverted.gain = 0.5f;
  551. auto flip = lynx::makeEffectSlot (lynx::EffectKind::utility);
  552. flip.params[2] = flip.params[5] = 0.25f; // (−1 + 2)/4
  553. inverted.chain.push_back (flip);
  554. slot.branches = { dry, inverted };
  555. auto fx = lynx::makeParallelEffect (slot);
  556. fx->prepare (48000.0);
  557. std::vector<float> l (9000, 0.8f), r (9000, -0.4f);
  558. fx->process (l.data(), r.data(), 9000, slot.params, 120.0);
  559. CHECK (std::abs (l[100]) < 1e-5f && std::abs (r[8999]) < 1e-5f);
  560. // only the dry branch with gain 2: doubles
  561. slot.branches = { lynx::EffectBranch { {}, 2.0f } };
  562. auto doubler = lynx::makeParallelEffect (slot);
  563. doubler->prepare (48000.0);
  564. std::fill (l.begin(), l.end(), 0.25f);
  565. doubler->process (l.data(), r.data(), 9000, slot.params, 120.0);
  566. CHECK (std::abs (l[5000] - 0.5f) < 1e-6f);
  567. }
  568. TEST (fl_controller_constant_outputs)
  569. {
  570. std::vector<std::int32_t> xy { 2, 32768, 0, 65536, 0, 16384, 0, 65536, 0, 1024, 256 };
  571. std::vector<std::uint8_t> blob (xy.size() * 4 + 8, 0);
  572. std::memcpy (blob.data(), xy.data(), xy.size() * 4);
  573. CHECK (std::abs (lynx::controllerConstantOutput ("Fruity X-Y Controller", blob, 0).value_or (-1.0f) - 0.5f) < 1e-4f);
  574. CHECK (std::abs (lynx::controllerConstantOutput ("Fruity X-Y Controller", blob, 1).value_or (-1.0f) - 0.25f) < 1e-4f);
  575. // Control Surface: version + group { 0x836: value 0.75, -, output 2 }
  576. std::vector<std::uint8_t> cs (4, 0);
  577. cs[0] = 1;
  578. auto chunk = [] (std::vector<std::uint8_t>& out, std::uint32_t id, const std::vector<std::uint8_t>& body) {
  579. const auto size = (std::uint64_t) body.size();
  580. out.insert (out.end(), reinterpret_cast<const std::uint8_t*> (&id), reinterpret_cast<const std::uint8_t*> (&id) + 4);
  581. out.insert (out.end(), reinterpret_cast<const std::uint8_t*> (&size), reinterpret_cast<const std::uint8_t*> (&size) + 8);
  582. out.insert (out.end(), body.begin(), body.end());
  583. };
  584. std::vector<std::uint8_t> value (12, 0);
  585. const float v = 0.75f;
  586. const std::int32_t out = 2;
  587. std::memcpy (value.data(), &v, 4);
  588. std::memcpy (value.data() + 8, &out, 4);
  589. std::vector<std::uint8_t> group;
  590. chunk (group, 0x836, value);
  591. chunk (cs, 0, group);
  592. CHECK (std::abs (lynx::controllerConstantOutput ("Control Surface", cs, 2).value_or (-1.0f) - 0.75f) < 1e-6f);
  593. CHECK (! lynx::controllerConstantOutput ("Control Surface", cs, 0).has_value());
  594. }
  595. TEST (flp_midi_out_notes_reach_wrapper_on_same_port)
  596. {
  597. auto record = [] (std::vector<std::uint8_t>& out, std::uint32_t id, std::vector<std::uint8_t> body) {
  598. const auto size = (std::uint64_t) body.size();
  599. out.insert (out.end(), reinterpret_cast<const std::uint8_t*> (&id), reinterpret_cast<const std::uint8_t*> (&id) + 4);
  600. out.insert (out.end(), reinterpret_cast<const std::uint8_t*> (&size), reinterpret_cast<const std::uint8_t*> (&size) + 8);
  601. out.insert (out.end(), body.begin(), body.end());
  602. };
  603. auto i32s = [] (std::vector<std::int32_t> v) {
  604. std::vector<std::uint8_t> b (v.size() * 4);
  605. std::memcpy (b.data(), v.data(), b.size());
  606. return b;
  607. };
  608. flp::Project p;
  609. flp::Channel midiOut;
  610. midiOut.index = 0;
  611. midiOut.type = flp::ChannelType::native;
  612. midiOut.pluginName = "MIDI Out";
  613. midiOut.pluginState = i32s ({ 7, 0, -1, -1, -1, 0, 3, 0 }); // channel 1, port 3 (@24)
  614. flp::Channel wrapper;
  615. wrapper.index = 1;
  616. wrapper.type = flp::ChannelType::native;
  617. wrapper.pluginName = "Fruity Wrapper";
  618. wrapper.pluginState = i32s ({ 9 });
  619. record (wrapper.pluginState, 0x32, i32s ({ 7 })); // VST3
  620. record (wrapper.pluginState, 0x01, i32s ({ 3, -1, 0, 0, 0 })); // input port 3
  621. p.channels = { midiOut, wrapper };
  622. flp::Pattern pattern;
  623. pattern.index = 1;
  624. flp::Note note;
  625. note.channel = 0;
  626. note.key = 64;
  627. note.length = 96;
  628. pattern.notes.push_back (note);
  629. p.patterns.push_back (pattern);
  630. const auto song = lynx::importFlp (p);
  631. CHECK (song.channels.size() == 2 && song.channels[0].muted);
  632. CHECK (song.channels[1].plugin.foreign.midiInPort == 3);
  633. int toWrapper = 0;
  634. for (const auto& pat : song.patterns)
  635. for (const auto& n : pat.notes)
  636. toWrapper += n.channel == 1 && n.key == 64;
  637. CHECK (toWrapper == 1);
  638. }
  639. TEST (flp_effect_automation_follows_slots_and_params)
  640. {
  641. // track 1: slot 0 with an effect that has no equivalent (dropped), slot 2 with Parametric EQ 2
  642. flp::Project p;
  643. flp::MixerInsert insert;
  644. insert.index = 1;
  645. insert.slots.push_back ({ 0, "Some Unknown FX", {} });
  646. insert.slots.push_back ({ 2, "Fruity Parametric EQ 2", {} });
  647. p.mixer.push_back (insert);
  648. auto clip = [&] (int index, std::uint32_t target) {
  649. flp::Channel c;
  650. c.index = index;
  651. c.type = flp::ChannelType::automationClip;
  652. c.automation = { { 0.0, 0.0 }, { 96.0, 1.0 } };
  653. p.channels.push_back (c);
  654. p.automationLinks.push_back ({ index, { target } });
  655. };
  656. 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; };
  657. clip (0, mixer (1, 2, 0x8000 + 7)); // EQ band 1 frequency
  658. clip (1, mixer (1, 2, 0x1F01)); // EQ slot mix
  659. clip (2, mixer (1, 0, 0x8000)); // parameter of the dropped effect
  660. clip (3, mixer (1, 2, 0x8000 + 21)); // band type: no equivalent
  661. const auto song = lynx::importFlp (p);
  662. CHECK (song.automations.size() == 4);
  663. CHECK (song.mixer[1].effects.size() == 1 && song.mixer[1].effects[0].kind == lynx::EffectKind::parametricEq);
  664. const auto& freq = song.automations[0];
  665. CHECK (freq.target.kind == lynx::AutomationTargetKind::effectParam && freq.target.index == 1 && freq.target.slot == 0);
  666. CHECK (freq.target.param == lynx::peq::param (0, 1));
  667. // FL's 0..1 (20 Hz..20 kHz) becomes our frequency scale
  668. CHECK (std::abs (freq.points.front().value - lynx::peq::hzValue (20.0)) < 1e-4f);
  669. CHECK (std::abs (freq.points.back().value - lynx::peq::hzValue (20000.0)) < 1e-4f);
  670. CHECK (song.automations[1].target.kind == lynx::AutomationTargetKind::effectMix && song.automations[1].target.slot == 0);
  671. CHECK (song.automations[2].target.kind == lynx::AutomationTargetKind::none);
  672. CHECK (song.automations[3].target.kind == lynx::AutomationTargetKind::none);
  673. // the automated mix is read/written through the target
  674. auto copy = song;
  675. CHECK (copy.setTargetValue (song.automations[1].target, 0.25f) && std::abs (copy.mixer[1].effects[0].mix - 0.25f) < 1e-6f);
  676. CHECK (std::abs (copy.targetValue (song.automations[1].target) - 0.25f) < 1e-6f);
  677. }
  678. TEST (flp_real_files)
  679. {
  680. if (realFlpDir.empty())
  681. {
  682. std::printf (" (skipped: pass a folder with .flp files as argument)\n");
  683. return;
  684. }
  685. int files = 0, withNotes = 0, withPlaylist = 0, automations = 0, automationsWithTarget = 0, sends = 0;
  686. int threeOsc = 0, threeOscDecoded = 0, wrapped = 0, wrappedParsed = 0, markers = 0, signatures = 0, trackEqs = 0;
  687. int harmless = 0, harmlessDecoded = 0, harmlessParsed = 0, harmlessKind = 0, sytrus = 0, sytrusDecoded = 0, sytrusEngine = 0, sytrusRendered = 0,
  688. sytrusSounding = 0;
  689. int harmor = 0, harmorUsable = 0, harmorKind = 0, harmorSounding = 0;
  690. int gms = 0, gmsUsable = 0, gmsKind = 0, gmsSounding = 0, morphine = 0, morphineUsable = 0, morphineKind = 0, morphineSounding = 0, demoGoldens = 0;
  691. std::map<std::string, std::pair<int, int>> generators; // GMS/Ogun/Autogun/Sakura/DrumSynth: channels, decoded
  692. int ogunTrumpet = 0; // Ogun channels whose spectrum matches the REA "Trumpet" reference
  693. int peqSlots = 0, peqShaped = 0, reverbs = 0, reverbsDryless = 0, reverbsLowCut = 0;
  694. int dwChannels = 0, dwZones = 0, fpcKits = 0, padChannels = 0, padNotes = 0;
  695. int harmlessCompWanted = 0, harmlessCompLoaded = 0; // Harmless rack compressors / presets read from the installation
  696. // import with the installation's samples (realFlpDir is ...\Data): for DirectWave/FPC
  697. lynx::FlpImportOptions withFiles;
  698. const auto flRoot = std::filesystem::path (realFlpDir).parent_path().string();
  699. withFiles.roots = { flRoot, realFlpDir, "" };
  700. withFiles.fileExists = [] (const std::string& path) {
  701. auto local = path;
  702. std::replace (local.begin(), local.end(), '\\', '/');
  703. return std::filesystem::exists (local);
  704. };
  705. withFiles.readFile = [] (const std::string& path) {
  706. auto local = path;
  707. std::replace (local.begin(), local.end(), '\\', '/');
  708. std::ifstream in (local, std::ios::binary);
  709. return std::vector<std::uint8_t> ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  710. };
  711. int embeddedSaved = 0;
  712. withFiles.saveEmbedded = [&embeddedSaved] (const std::vector<std::uint8_t>& wav, const std::string&) {
  713. ++embeddedSaved;
  714. return wav.size() > 44 ? std::string ("embutido.wav") : std::string();
  715. };
  716. int slicedChannels = 0, flKeysChannels = 0;
  717. for (auto& entry : std::filesystem::recursive_directory_iterator (realFlpDir))
  718. {
  719. if (entry.path().extension() != ".flp")
  720. continue;
  721. std::ifstream in (entry.path(), std::ios::binary);
  722. std::vector<std::uint8_t> bytes ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  723. ++files;
  724. try
  725. {
  726. const auto p = flp::parseProject (bytes);
  727. CHECK (! p.version.empty());
  728. CHECK (p.tempo > 10.0 && p.tempo < 1000.0);
  729. const auto song = lynx::importFlp (p);
  730. CHECK (! song.patterns.empty());
  731. {
  732. const auto full = lynx::importFlp (p, withFiles);
  733. bool hasFpc = false;
  734. for (const auto& c : p.channels)
  735. hasFpc = hasFpc || c.pluginName == "FPC";
  736. // GMS and Morphine (REA_rodada39): every state plays on the exact engine (GMS with its waves from the
  737. // installation) and sounds; two demo channels match golden samples of our round-39 models
  738. for (const auto& c : p.channels)
  739. {
  740. if (c.pluginName == "GMS")
  741. ++gms, gmsUsable += lynx::gmsStateUsable (c.pluginState) ? 1 : 0;
  742. if (c.pluginName == "Morphine")
  743. ++morphine, morphineUsable += lynx::morphineStateUsable (c.pluginState) ? 1 : 0;
  744. }
  745. const auto file = entry.path().filename().string();
  746. for (const auto& c : full.channels)
  747. {
  748. const auto isGms = c.instrument == lynx::InstrumentKind::gms, isMorphine = c.instrument == lynx::InstrumentKind::morphine;
  749. if (! isGms && ! isMorphine)
  750. continue;
  751. (isGms ? gmsKind : morphineKind)++;
  752. auto iv = [] (double vel) { return (std::pow (11.0, vel / 100.0) - 1.0) / 10.0; };
  753. const auto golden = (isGms && c.name == "GMS" && file.find ("Song For You") != std::string::npos)
  754. || (isMorphine && c.name == "Morphine" && file.find ("SHINE") != std::string::npos);
  755. std::vector<float> y;
  756. if (isGms)
  757. y = lynx::gms::renderReference (c.pluginState,
  758. { { 0, 60, (float) iv (100), 1.0, 0.0, 0.0, 30000 }, { 11025, 64, (float) iv (80), 1.0, 0.0, 0.0, 40000 },
  759. { 22050, 67, (float) iv (110), 1.0, 0.0, 0.0, 52000 }, { 60000, 48, (float) iv (127), 1.0, 0.0, 0.0, 70000 } },
  760. 44100.0, golden ? 88200 : 22050, c.samplePath);
  761. else
  762. y = lynx::morphine::renderReference (c.pluginState, { { 0, 60, 1.0, 1.0, 0.0, 0.0, 30000 }, { 11025, 64, 0.5, 1.0, 0.0, 0.0, 50000 }, { 22050, 67, 2.0, 1.0, 0.0, 0.0, 70000 } },
  763. 44100.0, golden ? 100000 : 22050, c.samplePath);
  764. double e = 0.0;
  765. bool finite = ! y.empty();
  766. for (auto v : y)
  767. finite = finite && std::isfinite (v), e += (double) v * v;
  768. CHECK (finite);
  769. (isGms ? gmsSounding : morphineSounding) += e > 1e-6 ? 1 : 0;
  770. if (golden && ! y.empty())
  771. {
  772. // our model, same events (GMS: tempo 140; Morphine: tempo 120), state as saved, 44.1 kHz
  773. const auto rms = std::sqrt (e / (double) y.size());
  774. CHECK (std::abs (rms - (isGms ? 0.213602668574 : 0.0673606448152)) < 1e-5);
  775. static const struct { int i; float l, r; } gmsAt[] = { { 2000, 0.0890912563f, 0.00406081323f }, { 15000, 0.395968914f, 0.213082865f }, { 30000, -0.33275044f, -0.530703545f }, { 50000, 0.277897179f, 0.482887864f }, { 65000, 0.266831428f, 0.366135627f }, { 80000, 0.00021339106f, 0.000807374308f } },
  776. morAt[] = { { 2000, 0.0620051622f, 0.0791224241f }, { 15000, 0.000745030935f, 0.0800722092f }, { 30000, 0.102371402f, 0.0262862686f }, { 50000, 0.000215340013f, 0.0249186736f }, { 65000, -0.0414967388f, -0.0449344926f }, { 90000, -0.00397050008f, -0.00165477558f } };
  777. for (const auto& g : isGms ? std::vector (std::begin (gmsAt), std::end (gmsAt)) : std::vector (std::begin (morAt), std::end (morAt)))
  778. CHECK (std::abs (y[2 * (std::size_t) g.i] - g.l) < 1e-5f && std::abs (y[2 * (std::size_t) g.i + 1] - g.r) < 1e-5f);
  779. ++demoGoldens;
  780. }
  781. }
  782. for (const auto& c : full.channels)
  783. {
  784. if (c.instrument == lynx::InstrumentKind::harmless && c.modelParams.size() >= (std::size_t) lynx::harmlessParamCount
  785. && c.modelParams[(std::size_t) lynx::harmlessComboIndex + 3] > 0.5f)
  786. {
  787. ++harmlessCompWanted;
  788. harmlessCompLoaded += c.modelParams.size() > (std::size_t) lynx::harmlessCompIndex + 1000 ? 1 : 0;
  789. }
  790. flKeysChannels += c.zones.size() == 30 && c.zones.front().path.find ("CHANGPIANO") != std::string::npos ? 1 : 0;
  791. if (c.sampler.slices.size() >= 4)
  792. {
  793. ++slicedChannels;
  794. CHECK (std::is_sorted (c.sampler.slices.begin(), c.sampler.slices.end()));
  795. CHECK (c.sampler.slices.back() < 1.0f);
  796. }
  797. if (! c.zones.empty() && c.name.find (" - ") == std::string::npos)
  798. {
  799. ++dwChannels;
  800. dwZones += (int) c.zones.size();
  801. }
  802. padChannels += c.name.find (" - ") != std::string::npos && c.instrument == lynx::InstrumentKind::sampler ? 1 : 0;
  803. }
  804. fpcKits += hasFpc;
  805. for (const auto& pat : full.patterns)
  806. for (const auto& n : pat.notes)
  807. {
  808. CHECK (n.channel >= 0 && n.channel < (int) full.channels.size());
  809. padNotes += full.channels[(std::size_t) n.channel].name.find (" - ") != std::string::npos ? 1 : 0;
  810. }
  811. }
  812. const auto peqDefaults = lynx::makeEffectSlot (lynx::EffectKind::parametricEq).params;
  813. for (const auto& t : song.mixer)
  814. for (const auto& fx : t.effects)
  815. {
  816. if (fx.kind == lynx::EffectKind::parametricEq)
  817. {
  818. ++peqSlots;
  819. peqShaped += fx.params != peqDefaults;
  820. for (double hz : { 50.0, 1000.0, 10000.0 })
  821. CHECK (std::isfinite (lynx::peq::responseDb (fx.params, 48000.0, hz)));
  822. }
  823. if (fx.kind == lynx::EffectKind::reverb)
  824. {
  825. ++reverbs;
  826. reverbsDryless += fx.params[4] < 0.01f;
  827. reverbsLowCut += fx.params[5] > 0.0f;
  828. }
  829. }
  830. for (const auto& t : song.mixer)
  831. if (t.eq.active())
  832. {
  833. ++trackEqs;
  834. for (std::size_t b = 0; b < 3; ++b)
  835. CHECK (t.eq.hz[b] >= 10.0f && t.eq.hz[b] <= 16000.0f && std::abs (t.eq.gainDb[b]) <= 18.0f);
  836. }
  837. for (const auto& a : song.arrangements)
  838. for (const auto& m : a.markers)
  839. {
  840. ++markers;
  841. signatures += m.isSignature();
  842. CHECK (m.tick >= 0);
  843. }
  844. // Fruity Wrapper (channels and mixer slots): every blob in the demos is read
  845. auto countWrapper = [&] (const std::string& plugin, const std::vector<std::uint8_t>& state) {
  846. if (plugin != "Fruity Wrapper")
  847. return;
  848. ++wrapped;
  849. lynx::ForeignPlugin f;
  850. wrappedParsed += lynx::parseFlWrapper (state, f) && f.format != lynx::ForeignPlugin::Format::none && ! f.name.empty();
  851. };
  852. for (const auto& c : p.channels)
  853. countWrapper (c.pluginName, c.pluginState);
  854. for (const auto& insert : p.mixer)
  855. for (const auto& slot : insert.slots)
  856. countWrapper (slot.plugin, slot.state);
  857. // Harmless: every state in the demos becomes a synth, with finite values
  858. for (const auto& c : p.channels)
  859. if (c.pluginName == "Harmless")
  860. {
  861. ++harmless;
  862. lynx::SynthSettings hs;
  863. float g = 1.0f;
  864. if (lynx::synthFromHarmless (c.pluginState, 128.0, hs, g))
  865. {
  866. ++harmlessDecoded;
  867. CHECK (std::isfinite (g) && hs.cutoff >= 20.0f && hs.cutoff <= 20000.0f && std::isfinite (hs.decay) && std::isfinite (hs.release));
  868. }
  869. if (const auto hp = lynx::harmlessParams (c.pluginState))
  870. harmlessParsed += (int) hp->size() == lynx::harmlessParamCount ? 1 : 0;
  871. }
  872. for (const auto& c : song.channels)
  873. harmlessKind += c.instrument == lynx::InstrumentKind::harmless ? 1 : 0;
  874. // Harmor: every state in the demos plays on the exact engine (REA_rodada34) and sounds, with finite samples
  875. for (const auto& c : p.channels)
  876. if (c.pluginName == "Harmor")
  877. {
  878. ++harmor;
  879. harmorUsable += lynx::harmorStateUsable (c.pluginState) ? 1 : 0;
  880. }
  881. for (const auto& c : song.channels)
  882. if (c.instrument == lynx::InstrumentKind::harmor)
  883. {
  884. ++harmorKind;
  885. const auto y = lynx::harmor::renderReference (c.pluginState, { { 0, 60, 0.8, 1.0, 0.0, 6000 }, { 2000, 67, 0.6, 1.0, 0.0, 8000 } }, 44100.0, 11025);
  886. double e = 0.0;
  887. bool finite = ! y.empty();
  888. for (auto v : y)
  889. finite = finite && std::isfinite (v), e += (double) v * v;
  890. CHECK (finite);
  891. harmorSounding += e > 1e-6 ? 1 : 0;
  892. }
  893. // Sytrus: every state in the demos (zlib + 10 units) decodes, with finite values
  894. for (const auto& c : p.channels)
  895. if (c.pluginName == "Sytrus")
  896. {
  897. ++sytrus;
  898. lynx::SynthSettings ss;
  899. float g = 1.0f;
  900. // the Sytrus engine (REA_rodada31) reads every demo state; the first 24 play a short note (render settings)
  901. if (lynx::sytrus::stateUsable (c.pluginState))
  902. {
  903. ++sytrusEngine;
  904. if (sytrusRendered < 24)
  905. {
  906. ++sytrusRendered;
  907. lynx::sytrus::Engine e;
  908. e.prepare (44100.0, true, 512);
  909. e.setPatch (lynx::sytrus::parsePatch (c.pluginState));
  910. lynx::sytrus::NoteParams note;
  911. e.noteOn (note);
  912. std::vector<float> l (8192), r (8192);
  913. e.render (l.data(), r.data(), 8192, 0.551f, 0.0f);
  914. bool finite = true;
  915. double energy = 0.0;
  916. for (std::size_t k = 0; k < l.size(); ++k)
  917. finite = finite && std::isfinite (l[k]) && std::isfinite (r[k]), energy += (double) l[k] * l[k];
  918. CHECK (finite);
  919. sytrusSounding += energy > 1e-6;
  920. }
  921. }
  922. if (lynx::synthFromSytrus (c.pluginState, 128.0, ss, g))
  923. {
  924. ++sytrusDecoded;
  925. CHECK (std::isfinite (g) && ss.cutoff >= 20.0f && ss.cutoff <= 20000.0f && std::isfinite (ss.attack) && std::isfinite (ss.decay)
  926. && std::isfinite (ss.release) && ss.sustain >= 0.0f && ss.sustain <= 1.0f && std::isfinite (ss.filterEnv.amount));
  927. for (const auto& o : ss.osc)
  928. CHECK (o.level >= 0.0f && o.level <= 1.0f && o.octave >= -3 && o.octave <= 3);
  929. }
  930. }
  931. // round 12 generators
  932. for (const auto& c : p.channels)
  933. {
  934. lynx::SynthSettings gs;
  935. float g = 1.0f;
  936. int decoded = -1;
  937. if (c.pluginName == "Harmor")
  938. {
  939. decoded = lynx::synthFromHarmor (c.pluginState, gs, g);
  940. if (decoded)
  941. {
  942. // REA_rodada25 §4: most resonant settings stay below Q ≈ 3, a few saturate
  943. CHECK (gs.resonance >= 0.0f && gs.resonance <= 1.0f);
  944. static int resonant = 0, strong = 0, total = 0;
  945. resonant += gs.resonance > 0.0f;
  946. strong += gs.resonance > 0.9f;
  947. if (++total % 50 == 0)
  948. std::printf (" Harmor resonance: %d with a peak, %d with Q > ~5 (of %d)\n", resonant, strong, total);
  949. }
  950. static int saw = 0, square = 0, other = 0, total = 0;
  951. if (decoded && std::any_of (gs.osc.begin(), gs.osc.end(), [] (const lynx::SynthOscillator& o) { return o.wave == lynx::Waveform::spectral; }))
  952. {
  953. auto isSaw = true, isSquare = true;
  954. for (int n = 1; n <= 16; ++n)
  955. {
  956. isSaw = isSaw && std::abs (gs.spectrum[(std::size_t) n - 1] - 1.0f / n) < 1e-3f;
  957. isSquare = isSquare && std::abs (gs.spectrum[(std::size_t) n - 1] - (n % 2 == 1 ? 1.1535f / n : 0.0f)) < 2e-3f;
  958. }
  959. ++(isSaw ? saw : isSquare ? square : other);
  960. if (++total % 20 == 0 || total == 100)
  961. std::printf (" Harmor spectrum: %d saw, %d square, %d other (of %d)\n", saw, square, other, total);
  962. }
  963. }
  964. else if (c.pluginName == "GMS")
  965. decoded = lynx::synthFromGms (c.pluginState, 128.0, gs, g);
  966. else if (c.pluginName == "Ogun" || c.pluginName == "Autogun")
  967. {
  968. decoded = lynx::synthFromOgun (c.pluginState, gs, g);
  969. // REA_rodada24 §1.9: the "Trumpet" preset (richness 7, no seeds) has partials 0.9087, 0.8610,
  970. // 0.8151… at the fixed seed-3 phases 0.919, 0.380, 0.130
  971. if (decoded && gs.osc[0].wave == lynx::Waveform::spectral)
  972. {
  973. CHECK (std::all_of (gs.spectrum.begin(), gs.spectrum.end(), [] (float a) { return std::isfinite (a) && a >= 0.0f; }));
  974. static constexpr float trumpet[3] { 0.9087f, 0.8610f, 0.8151f }, phases[3] { 0.919f, 0.380f, 0.130f };
  975. auto match = true;
  976. for (std::size_t k = 0; k < 3; ++k)
  977. match = match && std::abs (gs.spectrum[k] * 2.0f / 3.14159265f - trumpet[k]) < 1e-3f && std::abs (gs.spectrumPhase[k] - phases[k]) < 1e-3f;
  978. ogunTrumpet += match ? 1 : 0;
  979. }
  980. }
  981. else if (c.pluginName == "Sakura")
  982. decoded = lynx::synthFromSakura (c.pluginState, gs);
  983. else if (c.pluginName == "Kepler")
  984. decoded = lynx::synthFromKepler (c.pluginState, gs, g);
  985. else if (c.pluginName == "Wave Traveller")
  986. decoded = lynx::waveTravellerSample (c.pluginState).has_value() ? 2 : 0;
  987. else if (c.pluginName == "PoiZone")
  988. decoded = lynx::synthFromPoiZone (c.pluginState, gs, g);
  989. else if (c.pluginName == "BassDrum")
  990. decoded = lynx::synthFromBassDrum (c.pluginState, gs, g);
  991. else if (c.pluginName == "Toxic Biohazard")
  992. decoded = lynx::synthFromToxic (c.pluginState, gs, g);
  993. else if (c.pluginName == "Morphine")
  994. decoded = lynx::synthFromMorphine (c.pluginState, gs, g);
  995. else if (c.pluginName == "BooBass")
  996. decoded = lynx::synthFromBooBass (c.pluginState, gs);
  997. else if (c.pluginName == "Drumpad" || c.pluginName == "DrumPad")
  998. decoded = lynx::drumpadPatchName (c.pluginState).has_value() ? 2 : 0;
  999. else if (c.pluginName == "Fruity Envelope Controller" && c.pluginState.size() >= 4 && c.pluginState[2] >= 6) // v >= 6
  1000. decoded = lynx::parseEnvelopeController (c.pluginState).has_value() ? 2 : 0;
  1001. else if (c.pluginName == "FLEX")
  1002. decoded = lynx::flexPresetName (c.pluginState).has_value() ? 2 : 0;
  1003. else if (c.pluginName == "Fruity DrumSynth Live")
  1004. decoded = lynx::drumSynthLiveParams (c.pluginState).has_value() ? 2 : 0;
  1005. if (decoded < 0)
  1006. continue;
  1007. auto& counter = generators[c.pluginName];
  1008. ++counter.first;
  1009. counter.second += decoded != 0;
  1010. if (decoded == 1 && c.pluginName != "Fruity DrumSynth Live")
  1011. {
  1012. CHECK (std::isfinite (g) && g >= 0.0f && gs.cutoff >= 20.0f && gs.cutoff <= 20000.0f && gs.sustain >= 0.0f && gs.sustain <= 1.0f);
  1013. 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));
  1014. for (const auto& o : gs.osc)
  1015. CHECK (o.level >= 0.0f && o.level <= 4.0f && std::isfinite (o.detune) && std::isfinite (o.pan));
  1016. }
  1017. }
  1018. // 3x Osc: every state in the demos decodes, with levels summing to at most 1
  1019. for (const auto& c : p.channels)
  1020. if (c.pluginName == "3x Osc")
  1021. {
  1022. ++threeOsc;
  1023. lynx::SynthSettings s;
  1024. if (lynx::synthFrom3xOsc (c.pluginState, s))
  1025. {
  1026. ++threeOscDecoded;
  1027. // with AM, osc 3 is the modulation depth and is left out of the sum
  1028. const auto sum = s.osc[0].level + s.osc[1].level + (s.am ? 0.0f : s.osc[2].level);
  1029. CHECK (sum <= 1.001f && s.osc[2].level <= 1.0f);
  1030. for (const auto& o : s.osc)
  1031. CHECK (o.octave >= -2 && o.octave <= 2 && std::abs (o.semitones) <= 11 && std::abs (o.pan) <= 1.0f);
  1032. }
  1033. }
  1034. for (auto& pat : p.patterns)
  1035. if (! pat.notes.empty())
  1036. {
  1037. ++withNotes;
  1038. break;
  1039. }
  1040. for (auto& a : p.arrangements)
  1041. for (auto& item : a.items)
  1042. CHECK (item.track >= 0 && item.track < 500);
  1043. for (auto& clip : song.playlist)
  1044. {
  1045. CHECK (clip.pattern >= 0 && clip.pattern < (int) song.patterns.size());
  1046. CHECK (clip.length > 0 && clip.offset >= 0);
  1047. if (clip.kind == lynx::ClipKind::automation)
  1048. CHECK (clip.automation >= 0 && clip.automation < (int) song.automations.size());
  1049. }
  1050. for (auto& a : song.automations)
  1051. {
  1052. ++automations;
  1053. automationsWithTarget += a.target.kind != lynx::AutomationTargetKind::none;
  1054. CHECK (a.isLive() || ! a.points.empty());
  1055. for (std::size_t i = 1; i < a.points.size(); ++i)
  1056. CHECK (a.points[i].tick >= a.points[i - 1].tick);
  1057. }
  1058. // imported routing has no cycles and valid destinations
  1059. CHECK (song.mixerOrder().size() + 1 == song.mixer.size());
  1060. for (auto& t : song.mixer)
  1061. for (auto& s : t.sends)
  1062. {
  1063. ++sends;
  1064. CHECK (s.target > 0 && s.target < (int) song.mixer.size());
  1065. }
  1066. if (! song.playlist.empty())
  1067. ++withPlaylist;
  1068. }
  1069. catch (const flp::Error& e)
  1070. {
  1071. ++failures;
  1072. std::printf (" FAILED %s: %s\n", entry.path().string().c_str(), e.what());
  1073. }
  1074. }
  1075. CHECK (threeOscDecoded == threeOsc);
  1076. std::printf (" Harmless: %d channels, %d decoded\n", harmless, harmlessDecoded);
  1077. std::printf (" Sytrus: %d channels, %d decoded, %d by the engine (%d of %d rendered sound)\n", sytrus, sytrusDecoded, sytrusEngine,
  1078. sytrusSounding, sytrusRendered);
  1079. CHECK (sytrusEngine == sytrus);
  1080. CHECK (sytrusSounding >= sytrusRendered * 3 / 4);
  1081. for (const auto& [name, counter] : generators)
  1082. {
  1083. std::printf (" %s: %d channels, %d decoded\n", name.c_str(), counter.first, counter.second);
  1084. CHECK (counter.second == counter.first);
  1085. }
  1086. std::printf (" Ogun spectra matching the Trumpet reference: %d\n", ogunTrumpet);
  1087. CHECK (ogunTrumpet >= 1);
  1088. // demo Gross Beat: the volume slot becomes the gate (those using an envelope slot get steps < 1)
  1089. {
  1090. int vocodexes = 0, vocodexSides = 0;
  1091. int lovePhilterLinks[4] {}; // live links: cutoff, resonance; inside containers: cutoff, resonance
  1092. int embeddedZones = 0, lovePhilters = 0, lovePhiltersRead = 0, lovePhiltersConverted = 0, gates = 0, shaped = 0, effectors = 0, patchers = 0, serial = 0, parallel = 0, generatorPatchers = 0;
  1093. for (const auto& entry : std::filesystem::recursive_directory_iterator (std::filesystem::path (realFlpDir) / "Demo projects"))
  1094. if (entry.path().extension() == ".flp")
  1095. {
  1096. std::ifstream in (entry.path(), std::ios::binary);
  1097. const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1098. try
  1099. {
  1100. const auto project = flp::parseProject (file);
  1101. for (const auto& insert : project.mixer)
  1102. for (const auto& slot : insert.slots)
  1103. if (slot.plugin == "Gross Beat")
  1104. {
  1105. const auto fx = lynx::effectFromFl (slot.plugin, slot.state);
  1106. CHECK (fx && fx->kind == lynx::EffectKind::volumeGate);
  1107. ++gates;
  1108. if (fx && std::any_of (fx->params.begin(), fx->params.begin() + 32, [] (float v) { return v < 0.99f; }))
  1109. ++shaped;
  1110. }
  1111. else if (slot.plugin == "Fruity Love Philter")
  1112. {
  1113. ++lovePhilters;
  1114. lovePhiltersRead += lynx::parseLovePhilter (slot.state).has_value();
  1115. if (const auto conv = lynx::lovePhilterEffects (slot.state))
  1116. {
  1117. ++lovePhiltersConverted;
  1118. CHECK (! conv->slots.empty());
  1119. for (const auto& fx : conv->slots)
  1120. for (auto v : fx.params)
  1121. CHECK (std::isfinite (v) && v >= 0.0f && v <= 1.0f);
  1122. for (const auto& fx : conv->slots)
  1123. for (const auto& link : fx.links)
  1124. {
  1125. const auto& chain = fx.branches[(std::size_t) link.branch].chain;
  1126. CHECK (link.source < (int) chain.size() && chain[(std::size_t) link.target].kind == lynx::EffectKind::parametricEq);
  1127. lovePhilterLinks[2 + (link.param == lynx::peq::param (0, 3) ? 1 : 0)]++;
  1128. }
  1129. for (const auto& link : conv->links)
  1130. {
  1131. lovePhilterLinks[link.param == lynx::peq::param (0, 3) ? 1 : 0]++;
  1132. CHECK (link.curve.size() == 33);
  1133. for (auto v : link.curve)
  1134. CHECK (std::isfinite (v) && v >= 0.0f && v <= 1.0f);
  1135. }
  1136. }
  1137. }
  1138. else if (slot.plugin == "Vocodex")
  1139. {
  1140. const auto v = lynx::vocodexEffect (slot.state);
  1141. CHECK (v.has_value());
  1142. vocodexes += v.has_value();
  1143. vocodexSides += v && (v->modIn > 0 || v->carIn > 0);
  1144. }
  1145. else if (slot.plugin == "Effector")
  1146. effectors += lynx::effectFromFl (slot.plugin, slot.state).has_value();
  1147. else if (slot.plugin == "Patcher")
  1148. {
  1149. const auto graph = lynx::parsePatcher (slot.state);
  1150. CHECK (graph.has_value());
  1151. ++patchers;
  1152. if (graph && ! graph->serialChain.empty())
  1153. ++serial;
  1154. if (graph && graph->serialChain.empty() && graph->audio)
  1155. ++parallel;
  1156. }
  1157. for (const auto& c : project.channels)
  1158. if (c.pluginName == "DirectWave")
  1159. if (const auto program = lynx::directWaveProgram (c.pluginState))
  1160. for (const auto& wav : program->embeddedWav)
  1161. if (! wav.empty())
  1162. {
  1163. ++embeddedZones;
  1164. CHECK (wav.size() > 44 && std::memcmp (wav.data(), "RIFF", 4) == 0);
  1165. }
  1166. for (const auto& c : project.channels)
  1167. if (c.pluginName == "Patcher")
  1168. {
  1169. const auto graph = lynx::parsePatcher (c.pluginState);
  1170. CHECK (graph.has_value());
  1171. generatorPatchers += graph && graph->mainGenerator >= 0;
  1172. }
  1173. }
  1174. catch (const flp::Error&) {}
  1175. }
  1176. std::printf (" Gross Beat: %d slots, %d with gate; Effector: %d converted; Love Philter: %d, %d read\n", gates, shaped, effectors,
  1177. lovePhilters, lovePhiltersRead);
  1178. CHECK (lovePhiltersRead == lovePhilters && lovePhiltersConverted == lovePhilters);
  1179. std::printf (" Vocodex: %d converted, %d with side inputs\n", vocodexes, vocodexSides);
  1180. CHECK (vocodexes >= 9);
  1181. std::printf (" Love Philter live links: %d cutoff, %d resonance; in multi-unit containers: %d cutoff, %d resonance\n",
  1182. lovePhilterLinks[0], lovePhilterLinks[1], lovePhilterLinks[2], lovePhilterLinks[3]);
  1183. CHECK (lovePhilterLinks[2] + lovePhilterLinks[3] > 0);
  1184. std::printf (" DirectWave: %d zones with embedded audio\n", embeddedZones);
  1185. CHECK (embeddedZones == 12);
  1186. std::printf (" Patcher: %d in the mixer (%d serial, %d reduced to serial/parallel), %d as instrument with generator\n", patchers, serial,
  1187. parallel, generatorPatchers);
  1188. CHECK (gates == 0 || shaped > 0);
  1189. }
  1190. // Envelope Controller "Basic Sidechain" (Future House): drops on the note and returns to ~1 within ~1/3 s
  1191. {
  1192. const auto path = std::filesystem::path (realFlpDir) / "Demo projects" / "Demo songs" / "Asher Postman - Future House.flp";
  1193. if (std::filesystem::exists (path))
  1194. {
  1195. std::ifstream in (path, std::ios::binary);
  1196. const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1197. const auto song = lynx::importFlp (flp::parseProject (file));
  1198. const lynx::ChannelDef* controller = nullptr;
  1199. for (const auto& c : song.channels)
  1200. if (c.instrument == lynx::InstrumentKind::controller)
  1201. controller = &c;
  1202. CHECK (controller != nullptr);
  1203. if (controller != nullptr)
  1204. {
  1205. auto inst = lynx::makeInstrument (lynx::InstrumentKind::controller);
  1206. inst->prepare (48000.0);
  1207. inst->configure (*controller, song.bpm);
  1208. std::vector<float> l (480), r (480);
  1209. inst->render (l.data(), r.data(), 480, 1.0f, 1.0f);
  1210. inst->noteOn (60, 1.0f);
  1211. inst->render (l.data(), r.data(), 480, 1.0f, 1.0f); // 10 ms
  1212. const auto ducked = inst->controlOutput (0);
  1213. for (int i = 0; i < 100; ++i) // +1 s
  1214. inst->render (l.data(), r.data(), 480, 1.0f, 1.0f);
  1215. const auto recovered = inst->controlOutput (0);
  1216. std::printf (" Envelope Controller (Basic Sidechain): %.2f on the note, %.2f after 1 s\n", ducked, recovered);
  1217. CHECK (ducked < 0.3f && recovered > 0.9f);
  1218. }
  1219. }
  1220. }
  1221. // mutation fuzz: real states with flipped and truncated bytes must not crash the readers
  1222. {
  1223. std::map<std::string, std::vector<std::uint8_t>> samples; // one real blob per plugin
  1224. for (const auto& entry : std::filesystem::recursive_directory_iterator (std::filesystem::path (realFlpDir) / "Demo projects"))
  1225. {
  1226. if (entry.path().extension() != ".flp")
  1227. continue;
  1228. std::ifstream in (entry.path(), std::ios::binary);
  1229. const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1230. try
  1231. {
  1232. const auto project = flp::parseProject (file);
  1233. for (const auto& c : project.channels)
  1234. if (! c.pluginState.empty())
  1235. samples.emplace (c.pluginName, c.pluginState);
  1236. for (const auto& insert : project.mixer)
  1237. for (const auto& slot : insert.slots)
  1238. if (! slot.state.empty())
  1239. samples.emplace (slot.plugin, slot.state);
  1240. }
  1241. catch (const flp::Error&) {}
  1242. }
  1243. std::uint32_t seed = 12345;
  1244. auto rnd = [&seed] { seed = seed * 1664525u + 1013904223u; return seed >> 8; };
  1245. int mutations = 0;
  1246. for (const auto& [name, original] : samples)
  1247. for (int round = 0; round < 40; ++round)
  1248. {
  1249. auto blob = original;
  1250. if (round % 4 == 3 && ! blob.empty())
  1251. blob.resize (rnd() % blob.size()); // truncated
  1252. else
  1253. for (int k = 0; k < 1 + (int) (rnd() % 8) && ! blob.empty(); ++k)
  1254. blob[rnd() % blob.size()] = (std::uint8_t) rnd();
  1255. ++mutations;
  1256. lynx::SynthSettings synth;
  1257. float gain = 1.0f;
  1258. lynx::synthFromSytrus (blob, 120.0, synth, gain);
  1259. lynx::synthFromHarmor (blob, synth, gain);
  1260. lynx::synthFromGms (blob, 120.0, synth, gain);
  1261. lynx::synthFromOgun (blob, synth, gain);
  1262. lynx::synthFromMorphine (blob, synth, gain);
  1263. lynx::synthFromKepler (blob, synth, gain);
  1264. lynx::synthFromPoiZone (blob, synth, gain);
  1265. lynx::synthFromToxic (blob, synth, gain);
  1266. lynx::synthFromBassDrum (blob, synth, gain);
  1267. lynx::synthFromHarmless (blob, 120.0, synth, gain);
  1268. lynx::harmlessParams (blob);
  1269. if (lynx::harmorStateUsable (blob))
  1270. lynx::harmorFallbacks (blob);
  1271. lynx::parseEnvelopeController (blob);
  1272. lynx::parseKeyboardController (blob);
  1273. lynx::parseLovePhilter (blob);
  1274. lynx::parsePatcher (blob);
  1275. lynx::effectFromFl (name, blob);
  1276. lynx::fpcPads (blob);
  1277. lynx::directWaveProgram (blob);
  1278. CHECK (std::isfinite (gain) && std::isfinite (synth.cutoff));
  1279. }
  1280. std::printf (" mutation fuzz: %d blobs from %d plugins\n", mutations, (int) samples.size());
  1281. }
  1282. // WavPack (.wv) samples from FL packs: all decode, with finite, non-silent audio
  1283. {
  1284. int files = 0, decoded = 0, audible = 0;
  1285. double seconds = 0.0;
  1286. for (const auto& entry : std::filesystem::recursive_directory_iterator (std::filesystem::path (realFlpDir) / "Patches" / "Packs"))
  1287. if (entry.path().extension() == ".wv")
  1288. {
  1289. std::ifstream in (entry.path(), std::ios::binary);
  1290. const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1291. ++files;
  1292. lynx::DecodedAudio audio;
  1293. if (! lynx::decodeWavPack (file.data(), file.size(), audio))
  1294. continue;
  1295. ++decoded;
  1296. float peak = 0.0f;
  1297. bool finite = true;
  1298. for (const auto& ch : audio.channels)
  1299. for (auto v : ch)
  1300. {
  1301. finite = finite && std::isfinite (v);
  1302. peak = std::max (peak, std::abs (v));
  1303. }
  1304. CHECK (finite && peak <= 4.0f);
  1305. audible += peak > 1e-4f;
  1306. seconds += (double) audio.channels[0].size() / audio.sampleRate;
  1307. }
  1308. std::printf (" WavPack: %d .wv files, %d decoded, %d audible, %.0f s of audio\n", files, decoded, audible, seconds);
  1309. CHECK (decoded == files);
  1310. }
  1311. // native GMS presets (.gmsynth = the contents of 0xD5 without the "SSLF")
  1312. int gmsPresets = 0, gmsDecoded = 0;
  1313. const auto gmsFolder = std::filesystem::path (realFlpDir) / "Patches" / "Plugin presets" / "Generators" / "GMS";
  1314. if (std::filesystem::exists (gmsFolder))
  1315. for (const auto& entry : std::filesystem::recursive_directory_iterator (gmsFolder))
  1316. if (entry.path().extension() == ".gmsynth")
  1317. {
  1318. std::ifstream in (entry.path(), std::ios::binary);
  1319. std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1320. std::vector<std::uint8_t> blob { 'S', 'S', 'L', 'F' };
  1321. const auto n = (std::uint32_t) file.size();
  1322. blob.insert (blob.end(), reinterpret_cast<const std::uint8_t*> (&n), reinterpret_cast<const std::uint8_t*> (&n) + 4);
  1323. blob.insert (blob.end(), file.begin(), file.end());
  1324. lynx::SynthSettings gs;
  1325. float g = 1.0f;
  1326. ++gmsPresets;
  1327. if (lynx::synthFromGms (blob, 120.0, gs, g))
  1328. {
  1329. ++gmsDecoded;
  1330. CHECK (std::isfinite (g) && gs.cutoff >= 20.0f && std::isfinite (gs.pitchEnv.amount) && std::isfinite (gs.lfo[lynx::lfoPitch].period));
  1331. }
  1332. }
  1333. std::printf (" GMS presets: %d, %d decoded\n", gmsPresets, gmsDecoded);
  1334. // the synth's "FL presets" button: Sytrus/Harmor .fst and .gmsynth become synth settings
  1335. int presetFiles = 0, presetsRead = 0;
  1336. for (const auto* name : { "Sytrus", "Harmor", "GMS", "Harmless", "Ogun", "Sakura", "Fruit Kick", "Fruity DX10", "MiniSynth", "Kepler",
  1337. "PoiZone", "Toxic Biohazard", "BassDrum" })
  1338. {
  1339. const auto folder = std::filesystem::path (realFlpDir) / "Patches" / "Plugin presets" / "Generators" / name;
  1340. if (! std::filesystem::exists (folder))
  1341. continue;
  1342. for (const auto& entry : std::filesystem::recursive_directory_iterator (folder))
  1343. if (entry.path().extension() == ".fst" || entry.path().extension() == ".gmsynth")
  1344. {
  1345. std::ifstream in (entry.path(), std::ios::binary);
  1346. const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1347. ++presetFiles;
  1348. presetsRead += lynx::synthFromFlPreset (file).has_value();
  1349. }
  1350. }
  1351. std::printf (" FL synth presets: %d files, %d read\n", presetFiles, presetsRead);
  1352. CHECK (presetsRead >= presetFiles * 95 / 100);
  1353. CHECK (gmsDecoded == gmsPresets);
  1354. CHECK (sytrusDecoded == sytrus);
  1355. CHECK (harmlessDecoded == harmless && harmless > 100);
  1356. std::printf (" Harmless: %d states parsed for the engine, %d channels imported as Harmless\n", harmlessParsed, harmlessKind);
  1357. CHECK (harmlessParsed == harmless && harmlessKind >= harmless);
  1358. std::printf (" Harmor: %d channels, %d states usable by the engine, %d imported as Harmor (%d sounding)\n", harmor, harmorUsable, harmorKind, harmorSounding);
  1359. CHECK (harmorUsable == harmor && harmor > 90 && harmorKind >= harmor && harmorSounding >= harmorKind * 9 / 10);
  1360. std::printf (" GMS: %d channels, %d usable, %d imported as GMS (%d sounding); Morphine: %d channels, %d usable, %d imported (%d sounding); %d demo goldens\n",
  1361. gms, gmsUsable, gmsKind, gmsSounding, morphine, morphineUsable, morphineKind, morphineSounding, demoGoldens);
  1362. CHECK (gmsUsable == gms && gms >= 9 && gmsKind == gms && gmsSounding == gmsKind);
  1363. CHECK (morphineUsable == morphine && morphine >= 7 && morphineKind == morphine && morphineSounding == morphineKind && demoGoldens == 2);
  1364. std::printf (" Harmless rack compressor: %d of %d presets read from the installation\n", harmlessCompLoaded, harmlessCompWanted);
  1365. CHECK (harmlessCompLoaded == harmlessCompWanted && harmlessCompWanted > 100);
  1366. // 3x Osc channel presets shipped with FL (.fst): all become synth settings
  1367. int presets = 0, presetsDecoded = 0;
  1368. const auto presetDir = std::filesystem::path (realFlpDir) / "Patches" / "Channel presets" / "3x Osc";
  1369. if (std::filesystem::is_directory (presetDir))
  1370. for (auto& entry : std::filesystem::directory_iterator (presetDir))
  1371. if (entry.path().extension() == ".fst")
  1372. {
  1373. ++presets;
  1374. std::ifstream in (entry.path(), std::ios::binary);
  1375. std::vector<std::uint8_t> bytes ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  1376. if (auto synth = lynx::synthFromFlPreset (bytes))
  1377. {
  1378. ++presetsDecoded;
  1379. CHECK (synth->osc[0].level + synth->osc[1].level + (synth->am ? 0.0f : synth->osc[2].level) <= 1.001f);
  1380. }
  1381. }
  1382. std::printf (" %d 3x Osc presets, %d read\n", presets, presetsDecoded);
  1383. CHECK (presetsDecoded == presets);
  1384. // FL effect presets that become built-in effects
  1385. int fxPresets = 0, fxDecoded = 0;
  1386. for (auto kind : { lynx::EffectKind::parametricEq, lynx::EffectKind::limiter, lynx::EffectKind::reverb, lynx::EffectKind::delay,
  1387. lynx::EffectKind::utility })
  1388. for (const auto& plugin : lynx::flPluginsForEffect (kind))
  1389. {
  1390. const auto dir = std::filesystem::path (realFlpDir) / "Patches" / "Plugin presets" / "Effects" / plugin;
  1391. if (! std::filesystem::is_directory (dir))
  1392. continue;
  1393. for (auto& entry : std::filesystem::recursive_directory_iterator (dir))
  1394. if (entry.path().extension() == ".fst")
  1395. {
  1396. ++fxPresets;
  1397. std::ifstream in (entry.path(), std::ios::binary);
  1398. std::vector<std::uint8_t> bytes ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  1399. fxDecoded += lynx::effectFromFlPreset (bytes).has_value();
  1400. }
  1401. }
  1402. std::printf (" %d FL effect presets, %d read\n", fxPresets, fxDecoded);
  1403. CHECK (fxDecoded == fxPresets);
  1404. CHECK (wrappedParsed == wrapped);
  1405. std::printf (" %d plugins in Fruity Wrapper, %d read\n", wrapped, wrappedParsed);
  1406. std::printf (" %d markers, %d time signature changes, %d tracks with EQ\n", markers, signatures, trackEqs);
  1407. std::printf (" %d parametric EQs (%d with FL settings), %d reverbs (%d without dry)\n", peqSlots, peqShaped, reverbs, reverbsDryless);
  1408. std::printf (" DirectWave: %d channels, %d zones; FPC: %d projects, %d pad channels, %d pad notes\n", dwChannels, dwZones, fpcKits,
  1409. padChannels, padNotes);
  1410. CHECK (dwZones > 1000 && padChannels > 250 && padNotes > 500);
  1411. std::printf (" sliced channels (Slicer/Slicex): %d; embedded WAVs saved: %d\n", slicedChannels, embeddedSaved);
  1412. CHECK (slicedChannels >= 25 && embeddedSaved >= 10); // without decoding Ogg here, some loops have no duration
  1413. std::printf (" FL Keys (Grand Piano, 30 zones): %d channels\n", flKeysChannels);
  1414. CHECK (flKeysChannels >= 8);
  1415. CHECK (peqSlots > 1000 && peqShaped > 900 && reverbsDryless > 20 && reverbsLowCut > 250);
  1416. CHECK (markers > 300 && signatures > 60);
  1417. std::printf (" %d 3x Osc channels, %d decoded\n", threeOsc, threeOscDecoded);
  1418. std::printf (" %d .flp files read, %d with notes, %d with playlist, %d automations (%d with target), %d sends\n",
  1419. files, withNotes, withPlaylist, automations, automationsWithTarget, sends);
  1420. CHECK (files > 0);
  1421. CHECK (automations > 0 && sends > 0);
  1422. }
  1423. // ---------------------------------------------------------------------------
  1424. // Sequencer
  1425. TEST (pattern_toggle_step_and_length)
  1426. {
  1427. lynx::Pattern p;
  1428. CHECK (! p.hasStep (0, 4));
  1429. p.toggleStep (0, 4);
  1430. CHECK (p.hasStep (0, 4));
  1431. CHECK (p.notes.size() == 1 && p.notes[0].start == 4 * lynx::ticksPerStep);
  1432. CHECK (p.effectiveLength (4) == 4 * lynx::ppq); // one bar
  1433. p.toggleStep (1, 20); // second bar
  1434. CHECK (p.effectiveLength (4) == 8 * lynx::ppq);
  1435. p.toggleStep (0, 4);
  1436. CHECK (! p.hasStep (0, 4) && p.notes.size() == 1);
  1437. }
  1438. TEST (scheduler_places_events_at_exact_samples)
  1439. {
  1440. lynx::Pattern p;
  1441. p.toggleStep (0, 0);
  1442. p.toggleStep (0, 4); // tick 960 = 1 beat
  1443. const double sr = 48000.0, bpm = 120.0; // 1 beat = 0.5 s = 24000 samples
  1444. const auto tps = lynx::ticksPerSample (bpm, sr);
  1445. lynx::EventBuffer ev;
  1446. lynx::schedulePatternLoop (p, p.effectiveLength (4), 23900.0 * tps, 512, tps, ev);
  1447. // the beat-2 note starts at sample 24000 -> offset 100 in this block
  1448. int ons = 0;
  1449. for (auto& e : ev)
  1450. if (e.type == lynx::NoteEvent::Type::on)
  1451. {
  1452. ++ons;
  1453. CHECK (e.sampleOffset == 100);
  1454. }
  1455. CHECK (ons == 1);
  1456. }
  1457. TEST (scheduler_wraps_the_loop)
  1458. {
  1459. lynx::Pattern p;
  1460. p.toggleStep (2, 0);
  1461. const auto len = p.effectiveLength (4); // 3840 ticks
  1462. const double sr = 48000.0;
  1463. const auto tps = lynx::ticksPerSample (120.0, sr);
  1464. lynx::EventBuffer ev;
  1465. // block that crosses the loop end: starts 10 samples before
  1466. const auto start = (double) len - 10.0 * tps;
  1467. lynx::schedulePatternLoop (p, len, start, 64, tps, ev);
  1468. bool found = false;
  1469. for (auto& e : ev)
  1470. if (e.type == lynx::NoteEvent::Type::on && e.channel == 2)
  1471. {
  1472. found = true;
  1473. CHECK (e.sampleOffset == 10);
  1474. }
  1475. CHECK (found);
  1476. }
  1477. TEST (scheduler_off_before_on_at_same_sample)
  1478. {
  1479. lynx::Pattern p;
  1480. lynx::Note a;
  1481. a.start = 0; a.length = 240; a.channel = 0;
  1482. lynx::Note b = a;
  1483. b.start = 240;
  1484. p.notes = { a, b };
  1485. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  1486. lynx::EventBuffer ev;
  1487. lynx::schedulePatternLoop (p, p.effectiveLength (4), 200.0, 4000, tps, ev);
  1488. CHECK (ev.size() >= 2);
  1489. CHECK (ev[0].type == lynx::NoteEvent::Type::off);
  1490. CHECK (ev[1].type == lynx::NoteEvent::Type::on);
  1491. CHECK (ev[0].sampleOffset == ev[1].sampleOffset);
  1492. }
  1493. TEST (snapshot_exchange_hands_over_and_recycles)
  1494. {
  1495. struct Counted
  1496. {
  1497. int value;
  1498. int* alive;
  1499. Counted (int v, int* a) : value (v), alive (a) { ++*alive; }
  1500. ~Counted() { --*alive; }
  1501. };
  1502. int alive = 0;
  1503. {
  1504. lynx::SnapshotExchange<Counted> x;
  1505. CHECK (x.acquire() == nullptr);
  1506. x.publish (std::make_unique<Counted> (1, &alive));
  1507. CHECK (x.acquire()->value == 1);
  1508. x.publish (std::make_unique<Counted> (2, &alive));
  1509. x.publish (std::make_unique<Counted> (3, &alive)); // 2 was never read: freed immediately
  1510. CHECK (alive == 2);
  1511. CHECK (x.acquire()->value == 3);
  1512. CHECK (alive == 2); // 1 was returned, but only the UI frees it
  1513. x.collectGarbage();
  1514. CHECK (alive == 1);
  1515. // without collection, the return slots fill up and the audio side holds on to the current one
  1516. for (int i = 0; i < 20; ++i)
  1517. {
  1518. x.publish (std::make_unique<Counted> (10 + i, &alive));
  1519. CHECK (x.acquire() != nullptr);
  1520. }
  1521. }
  1522. CHECK (alive == 0);
  1523. }
  1524. TEST (rack_renderer_makes_sound_and_reuses_instruments)
  1525. {
  1526. auto song = lynx::Song::makeDefault();
  1527. song.bpm = 120.0;
  1528. const double sr = 48000.0;
  1529. auto state = lynx::RackState::build (song, nullptr, sr);
  1530. lynx::RackRenderer r;
  1531. r.prepare (sr);
  1532. std::vector<float> l (512), rr (512);
  1533. double tick = 0.0;
  1534. float peak = 0.0f;
  1535. int kicks = 0;
  1536. for (int block = 0; block < 93; ++block) // 47616 samples: just before 1 s
  1537. {
  1538. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  1539. for (auto& e : r.lastEvents())
  1540. if (e.type == lynx::NoteEvent::Type::on && e.channel == 0)
  1541. ++kicks;
  1542. for (int i = 0; i < 512; ++i)
  1543. {
  1544. CHECK (std::isfinite (l[(std::size_t) i]));
  1545. peak = std::max (peak, std::abs (l[(std::size_t) i]));
  1546. }
  1547. tick += 512 * lynx::ticksPerSample (song.bpm, sr);
  1548. }
  1549. CHECK (peak > 0.1f && peak < 4.0f);
  1550. CHECK (kicks == 2); // 120 BPM: beats at 0 and 0.5 s
  1551. // editing the song keeps the instruments of channels whose type didn't change
  1552. song.channels[4].instrument = lynx::InstrumentKind::kick;
  1553. auto next = lynx::RackState::build (song, state.get(), sr);
  1554. CHECK (next->instruments[0] == state->instruments[0]);
  1555. CHECK (next->instruments[4] != state->instruments[4]);
  1556. // stopping silences the synth and triggers no new notes
  1557. r.process (next.get(), false, tick, 512, l.data(), rr.data());
  1558. CHECK (r.lastEvents().size() == 0);
  1559. }
  1560. TEST (flp_import_maps_channels_and_rescales)
  1561. {
  1562. flp::Project p;
  1563. p.header.ppq = 96;
  1564. p.tempo = 150.0;
  1565. p.channels = { { 0, flp::ChannelType::sampler, "Kick 808", "", "", 1 },
  1566. { 1, flp::ChannelType::audioClip, "Vocal", "", "", 2 },
  1567. { 2, flp::ChannelType::instrument, "Lead", "FLEX", "", 3 } };
  1568. flp::Pattern pat;
  1569. pat.index = 1;
  1570. flp::Note n;
  1571. n.position = 96;
  1572. n.length = 0;
  1573. n.channel = 2;
  1574. n.key = 72;
  1575. n.velocity = 64;
  1576. pat.notes.push_back (n);
  1577. p.patterns.push_back (pat);
  1578. const auto s = lynx::importFlp (p);
  1579. CHECK (s.bpm == 150.0);
  1580. CHECK (s.channels.size() == 3); // audio clip channels stay in the rack, as in FL
  1581. CHECK (s.channels[0].instrument == lynx::InstrumentKind::kick);
  1582. CHECK (s.channels[1].instrument == lynx::InstrumentKind::audioClip);
  1583. CHECK (s.channels[2].instrument == lynx::InstrumentKind::synth);
  1584. CHECK (s.patterns.size() == 1);
  1585. CHECK (s.patterns[0].notes[0].start == lynx::ppq); // 96 @ PPQ 96 = 1 beat
  1586. CHECK (s.patterns[0].notes[0].channel == 2);
  1587. CHECK (s.patterns[0].notes[0].length == lynx::ticksPerStep); // step note
  1588. CHECK (std::abs (s.patterns[0].notes[0].velocity - 0.5f) < 1e-6f);
  1589. }
  1590. TEST (live_queue_is_fifo_and_bounded)
  1591. {
  1592. lynx::LiveEventQueue q;
  1593. lynx::NoteEvent e;
  1594. CHECK (! q.pop (e));
  1595. for (int i = 0; i < 10; ++i)
  1596. {
  1597. lynx::NoteEvent in;
  1598. in.key = i;
  1599. CHECK (q.push (in));
  1600. }
  1601. for (int i = 0; i < 10; ++i)
  1602. CHECK (q.pop (e) && e.key == i);
  1603. int pushed = 0;
  1604. while (q.push (e))
  1605. ++pushed;
  1606. CHECK (pushed == (int) lynx::LiveEventQueue::capacity - 1); // one slot stays free to tell full from empty
  1607. }
  1608. TEST (sampler_plays_pitched_one_shot)
  1609. {
  1610. // 1000-frame ramp sample: the position can be measured from the amplitude
  1611. auto data = std::make_shared<lynx::SampleData>();
  1612. data->sampleRate = 48000.0;
  1613. for (int i = 0; i < 1000; ++i)
  1614. data->left.push_back (1.0f);
  1615. auto sampler = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  1616. sampler->prepare (48000.0);
  1617. std::vector<float> l (2048, 0.0f), r (2048, 0.0f);
  1618. sampler->noteOn (60, 1.0f);
  1619. sampler->noteOff (60); // one-shot: noteOff doesn't cut
  1620. sampler->render (l.data(), r.data(), 2048, 1.0f, 1.0f);
  1621. int sounding = 0;
  1622. for (auto s : l)
  1623. sounding += s > 0.5f;
  1624. CHECK (sounding >= 995 && sounding <= 1000); // plays the whole sample at the original pitch
  1625. std::fill (l.begin(), l.end(), 0.0f);
  1626. sampler->noteOn (72, 1.0f); // one octave up: half the duration
  1627. sampler->render (l.data(), r.data(), 2048, 1.0f, 1.0f);
  1628. sounding = 0;
  1629. for (auto s : l)
  1630. sounding += s > 0.5f;
  1631. CHECK (sounding >= 495 && sounding <= 500);
  1632. CHECK (r[10] > 0.5f); // mono goes to both sides
  1633. auto silent = lynx::makeInstrument (lynx::InstrumentKind::sampler, nullptr);
  1634. silent->prepare (48000.0);
  1635. silent->noteOn (60, 1.0f);
  1636. std::fill (l.begin(), l.end(), 0.0f);
  1637. silent->render (l.data(), r.data(), 64, 1.0f, 1.0f);
  1638. CHECK (l[0] == 0.0f);
  1639. }
  1640. TEST (rack_live_notes_and_sample_provider)
  1641. {
  1642. lynx::Song song;
  1643. lynx::ChannelDef c;
  1644. c.name = "Smp";
  1645. c.instrument = lynx::InstrumentKind::sampler;
  1646. c.samplePath = "a.wav";
  1647. song.channels.push_back (c);
  1648. song.patterns.emplace_back();
  1649. int loads = 0;
  1650. auto provider = [&] (const std::string& path) -> std::shared_ptr<const lynx::SampleData> {
  1651. ++loads;
  1652. CHECK (path == "a.wav");
  1653. auto d = std::make_shared<lynx::SampleData>();
  1654. d->left.assign (4800, 0.5f);
  1655. return d;
  1656. };
  1657. auto state = lynx::RackState::build (song, nullptr, 48000.0, provider);
  1658. CHECK (loads == 1);
  1659. lynx::RackRenderer renderer;
  1660. renderer.prepare (48000.0);
  1661. lynx::LiveEventQueue live;
  1662. lynx::NoteEvent on;
  1663. on.channel = 0;
  1664. on.velocity = 1.0f;
  1665. live.push (on);
  1666. std::vector<float> l (256), r (256);
  1667. renderer.process (state.get(), false, 0.0, 256, l.data(), r.data(), &live); // stopped, but the live note plays
  1668. CHECK (l[0] > 0.1f);
  1669. // same sample: reused; different sample: reloaded
  1670. auto same = lynx::RackState::build (song, state.get(), 48000.0, provider);
  1671. CHECK (loads == 1 && same->instruments[0] == state->instruments[0]);
  1672. song.channels[0].samplePath = "b.wav";
  1673. auto other = lynx::RackState::build (song, state.get(), 48000.0, [&] (const std::string&) { ++loads; return nullptr; });
  1674. CHECK (loads == 2 && other->instruments[0] != state->instruments[0]);
  1675. }
  1676. TEST (flp_paths_resolve_and_samplers_import)
  1677. {
  1678. lynx::FlPathRoots roots { "C:\\FL", "C:\\FL\\Data", "D:\\User" };
  1679. CHECK (lynx::resolveFlPath ("%FLStudioFactoryData%\\Data\\x.wav", roots) == "C:\\FL\\Data\\x.wav");
  1680. CHECK (lynx::resolveFlPath ("%FLStudioData%\\Patches\\y.wav", roots) == "C:\\FL\\Data\\Patches\\y.wav");
  1681. CHECK (lynx::resolveFlPath ("%FLStudioUserData%\\z.wav", roots) == "D:\\User\\z.wav");
  1682. CHECK (lynx::resolveFlPath ("E:\\abs.wav", roots) == "E:\\abs.wav");
  1683. CHECK (lynx::resolveFlPath ("%FLStudioUserData%\\z.wav", {}) == "");
  1684. flp::Project p;
  1685. p.channels = { { 0, flp::ChannelType::sampler, "Kick", "", "%FLStudioData%\\k.wav", 1 },
  1686. { 1, flp::ChannelType::sampler, "Hat", "", "%FLStudioData%\\missing.wav", 1 } };
  1687. lynx::FlpImportOptions options;
  1688. options.roots = roots;
  1689. options.fileExists = [] (const std::string& path) { return path == "C:\\FL\\Data\\k.wav"; };
  1690. const auto s = lynx::importFlp (p, options);
  1691. CHECK (s.channels[0].instrument == lynx::InstrumentKind::sampler);
  1692. CHECK (s.channels[0].samplePath == "C:\\FL\\Data\\k.wav");
  1693. CHECK (s.channels[1].instrument == lynx::InstrumentKind::hat); // no file: built-in instrument
  1694. }
  1695. TEST (soft_clip_is_transparent_below_knee_and_bounded)
  1696. {
  1697. float s[] = { 0.5f, -0.89f, 1.5f, -3.0f, 0.95f };
  1698. lynx::softClip (s, 5);
  1699. CHECK (s[0] == 0.5f && s[1] == -0.89f);
  1700. CHECK (s[2] > 0.9f && s[2] <= 1.0f);
  1701. CHECK (s[3] < -0.9f && s[3] >= -1.0f);
  1702. CHECK (s[4] > 0.9f && s[4] < 0.95f);
  1703. }
  1704. TEST (song_scheduler_plays_clips_with_offset_and_cut)
  1705. {
  1706. lynx::Song s;
  1707. s.channels.resize (1);
  1708. auto& p = s.patterns.emplace_back();
  1709. for (int step : { 0, 4, 8, 12 }) // one note per beat
  1710. p.toggleStep (0, step);
  1711. // clip at bar 2 playing only the second half of the pattern (beats 3 and 4)
  1712. lynx::Clip c;
  1713. c.pattern = 0;
  1714. c.start = 4 * lynx::ppq;
  1715. c.length = 2 * lynx::ppq;
  1716. c.offset = 2 * lynx::ppq;
  1717. s.playlist.push_back (c);
  1718. CHECK (s.songLength() == 8 * lynx::ppq);
  1719. const double sr = 48000.0;
  1720. const auto tps = lynx::ticksPerSample (120.0, sr); // 1 beat = 24000 samples
  1721. lynx::EventBuffer ev;
  1722. // whole song in a single block (8 beats = 192000 samples)
  1723. lynx::scheduleSong (s, 0.0, 192000, tps, ev);
  1724. std::vector<int> ons;
  1725. for (auto& e : ev)
  1726. if (e.type == lynx::NoteEvent::Type::on)
  1727. ons.push_back (e.sampleOffset);
  1728. CHECK (ons.size() == 2);
  1729. CHECK (ons.size() == 2 && ons[0] == 4 * 24000 && ons[1] == 5 * 24000);
  1730. // crossing the loop: bar 1 is empty, so nothing at the start of the second pass
  1731. ev.clear();
  1732. lynx::scheduleSong (s, 8.0 * lynx::ppq - 100 * tps, 200, tps, ev);
  1733. CHECK (ev.size() == 0);
  1734. // a note longer than the clip is cut at the clip end
  1735. p.notes[3].length = 4 * lynx::ppq;
  1736. ev.clear();
  1737. lynx::scheduleSong (s, 0.0, 192000, tps, ev);
  1738. int lastOff = -1;
  1739. for (auto& e : ev)
  1740. if (e.type == lynx::NoteEvent::Type::off)
  1741. lastOff = std::max (lastOff, e.sampleOffset);
  1742. CHECK (lastOff == 6 * 24000);
  1743. }
  1744. TEST (remove_pattern_fixes_clips)
  1745. {
  1746. lynx::Song s;
  1747. s.patterns.resize (3);
  1748. s.currentPattern = 2;
  1749. s.playlist = { { 0, 0, 0, 100, 0 }, { 1, 0, 100, 100, 0 }, { 2, 1, 0, 100, 0 } };
  1750. s.removePattern (1);
  1751. CHECK (s.patterns.size() == 2);
  1752. CHECK (s.playlist.size() == 2 && s.playlist[1].pattern == 1);
  1753. CHECK (s.currentPattern == 1);
  1754. }
  1755. TEST (flp_import_3x_osc_state_and_channel_filter)
  1756. {
  1757. // new 3x Osc patch (version 14): osc 2 mix 64 coarse -12, osc 3 mix 32 coarse -24
  1758. std::vector<std::uint8_t> blob (460, 0);
  1759. auto put = [&] (std::size_t off, std::int32_t v) {
  1760. for (int b = 0; b < 4; ++b)
  1761. blob[off + (std::size_t) b] = (std::uint8_t) ((std::uint32_t) v >> (8 * b));
  1762. };
  1763. put (0x00, 14);
  1764. put (0x08, 3); // osc 1 saw
  1765. put (0x10, 7); // osc 1 fine +7
  1766. put (0x04, -32); // osc 1 pan -0.5
  1767. put (0x1C, 64); // osc 2 mix
  1768. put (0x28, -12); // osc 2 coarse
  1769. put (0x38, 32); // osc 3 mix
  1770. put (0x40, 2); // osc 3 square
  1771. put (0x44, -19); // osc 3 coarse: -1 octave and -7 semitones
  1772. lynx::SynthSettings s;
  1773. CHECK (lynx::synthFrom3xOsc (blob, s));
  1774. 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);
  1775. CHECK (s.osc[0].wave == lynx::Waveform::saw && s.osc[0].detune == 7.0f && s.osc[0].pan == -0.5f);
  1776. CHECK (s.osc[1].wave == lynx::Waveform::sine && s.osc[1].octave == -1 && s.osc[1].semitones == 0);
  1777. CHECK (s.osc[2].wave == lynx::Waveform::square && s.osc[2].octave == -1 && s.osc[2].semitones == -7);
  1778. CHECK (! lynx::synthFrom3xOsc (std::vector<std::uint8_t> (40, 0), s));
  1779. // channel filter: open by default; LP with Mod X 128 ~ 2.71 kHz; Fast LP with Mod X 128 ~ 280 Hz
  1780. float hz = 0.0f, res = 1.0f;
  1781. int mode = -1;
  1782. lynx::synthFilterFromChannel (256, 0, 0, hz, res, mode);
  1783. CHECK (hz >= 19999.0f && res == 0.0f);
  1784. lynx::synthFilterFromChannel (128, 0, 1, hz, res, mode);
  1785. CHECK (std::abs (hz - 2710.0f) < 30.0f && res == 0.0f);
  1786. lynx::synthFilterFromChannel (128, 0, 0, hz, res, mode);
  1787. CHECK (hz > 240.0f && hz < 320.0f);
  1788. lynx::synthFilterFromChannel (128, 256, 1, hz, res, mode);
  1789. CHECK (res > 0.8f);
  1790. CHECK (mode == 0);
  1791. lynx::synthFilterFromChannel (64, 0, 3, hz, res, mode); // high-pass at ~840 Hz
  1792. CHECK (mode == 2 && std::abs (hz - 840.0f) < 40.0f);
  1793. lynx::synthFilterFromChannel (128, 0, 2, hz, res, mode); // band-pass
  1794. CHECK (mode == 1);
  1795. }
  1796. TEST (synth_pitch_and_filter_envelopes)
  1797. {
  1798. auto render = [] (const lynx::SynthSettings& s, int frames) {
  1799. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  1800. inst->prepare (48000.0);
  1801. lynx::ChannelDef c;
  1802. c.synth = s;
  1803. inst->configure (c, 120.0);
  1804. inst->noteOn (45, 1.0f); // A2 = 110 Hz
  1805. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  1806. inst->render (l.data(), r.data(), frames, 1.0f, 1.0f);
  1807. return l;
  1808. };
  1809. auto crossings = [] (const std::vector<float>& b, int from, int to) {
  1810. int n = 0;
  1811. for (int i = from + 1; i < to; ++i)
  1812. n += (b[(std::size_t) i - 1] < 0.0f) != (b[(std::size_t) i] < 0.0f);
  1813. return n;
  1814. };
  1815. // 3x Osc "kick": sine with a +24 st pitch envelope falling fast
  1816. lynx::SynthSettings kick;
  1817. kick.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  1818. kick.cutoff = 20000.0f;
  1819. kick.pitchEnv = { 24.0f, 0.0f, 0.0f, 0.05f, 0.0f, 0.05f };
  1820. const auto k = render (kick, 48000);
  1821. const auto early = crossings (k, 0, 2400); // first 50 ms: well above 110 Hz
  1822. const auto late = crossings (k, 24000, 48000); // then back to 110 Hz (~110 crossings in 0.5 s)
  1823. CHECK (early > 20); // +24 st ramp over 50 ms: ~2.2x the average frequency (11 crossings without envelope)
  1824. CHECK (std::abs (late - 110) < 4);
  1825. // cutoff envelope: saw closed at 200 Hz opens +5 octaves on attack and closes again
  1826. lynx::SynthSettings pluck;
  1827. pluck.cutoff = 200.0f;
  1828. pluck.filterEnv = { 5.0f, 0.0f, 0.0f, 0.1f, 0.0f, 0.1f };
  1829. const auto p = render (pluck, 48000);
  1830. auto hf = [&] (int from, int to) { // energy of the difference (highs)
  1831. double e = 0.0;
  1832. for (int i = from + 1; i < to; ++i)
  1833. e += std::pow ((double) p[(std::size_t) i] - p[(std::size_t) i - 1], 2.0);
  1834. return e;
  1835. };
  1836. CHECK (hf (0, 2400) > 4.0 * hf (40000, 42400));
  1837. // Toxic Biohazard's envelope (REA_rodada33 §2): exponential towards 5 clipped at 1, so the cutoff is still near
  1838. // its base early in the attack, fully open at A = 0.2 s and back down after the exponential decay
  1839. lynx::SynthSettings toxic = pluck;
  1840. toxic.filterEnv = { 5.0f, 0.2f, 0.0f, 0.1f, 0.0f, 0.1f, 1 };
  1841. const auto t = render (toxic, 48000);
  1842. auto thf = [&] (int from, int to) {
  1843. double e = 0.0;
  1844. for (int i = from + 1; i < to; ++i)
  1845. e += std::pow ((double) t[(std::size_t) i] - t[(std::size_t) i - 1], 2.0);
  1846. return e;
  1847. };
  1848. CHECK (thf (9000, 9600) > 4.0 * thf (300, 900));
  1849. CHECK (thf (9000, 9600) > 4.0 * thf (40000, 40600));
  1850. }
  1851. TEST (synth_mono_reuses_the_sounding_voice)
  1852. {
  1853. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  1854. inst->prepare (48000.0);
  1855. lynx::ChannelDef c;
  1856. c.synth.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  1857. c.synth.cutoff = 20000.0f;
  1858. c.synth.mono = true;
  1859. inst->configure (c, 120.0);
  1860. std::vector<float> l (48000), r (48000);
  1861. inst->noteOn (57, 1.0f);
  1862. inst->render (l.data(), r.data(), 4800, 1.0f, 1.0f);
  1863. inst->noteOn (69, 1.0f); // A4 takes over the A3 voice: only one note sounding
  1864. inst->render (l.data() + 4800, r.data() + 4800, 43200, 1.0f, 1.0f);
  1865. int crossings = 0;
  1866. float peak = 0.0f;
  1867. for (std::size_t i = 24001; i < 48000; ++i)
  1868. {
  1869. crossings += (l[i - 1] < 0.0f) != (l[i] < 0.0f);
  1870. peak = std::max (peak, std::abs (l[i]));
  1871. }
  1872. CHECK (std::abs (crossings - 440) < 4); // 0.5 s of 440 Hz, without the A3 underneath
  1873. CHECK (peak < 0.35f); // one voice (0.3 level), not two summed
  1874. // no click on the handover: the jump between neighbouring samples stays sine-sized
  1875. float jump = 0.0f;
  1876. for (std::size_t i = 4790; i < 4810; ++i)
  1877. jump = std::max (jump, std::abs (l[i] - l[i - 1]));
  1878. CHECK (jump < 0.05f);
  1879. }
  1880. TEST (synth_porta_glides_and_am_modulates)
  1881. {
  1882. auto make = [] (const lynx::SynthSettings& s) {
  1883. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  1884. inst->prepare (48000.0);
  1885. lynx::ChannelDef c;
  1886. c.synth = s;
  1887. inst->configure (c, 120.0);
  1888. return inst;
  1889. };
  1890. auto crossings = [] (const std::vector<float>& b, std::size_t from, std::size_t to) {
  1891. int n = 0;
  1892. for (auto i = from + 1; i < to; ++i)
  1893. n += (b[i - 1] < 0.0f) != (b[i] < 0.0f);
  1894. return n;
  1895. };
  1896. // mono + 1-beat porta (0.5 s at 120 BPM): from A3 to A4, halfway ~E4 (329.6 Hz)
  1897. lynx::SynthSettings s;
  1898. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  1899. s.cutoff = 20000.0f;
  1900. s.mono = true;
  1901. s.porta = true;
  1902. s.portaBeats = 1.0f;
  1903. auto inst = make (s);
  1904. std::vector<float> l (96000), r (96000);
  1905. inst->noteOn (57, 1.0f);
  1906. inst->render (l.data(), r.data(), 4800, 1.0f, 1.0f);
  1907. inst->noteOn (69, 1.0f);
  1908. inst->render (l.data() + 4800, r.data() + 4800, 91200, 1.0f, 1.0f);
  1909. const auto middle = crossings (l, 4800 + 12000 - 2400, 4800 + 12000 + 2400); // 0.1 s around 0.25 s
  1910. CHECK (std::abs (middle - 66) < 6); // ~330 Hz * 0.1 s * 2
  1911. CHECK (std::abs (crossings (l, 48000, 96000) - 880) < 4); // reached A4 (1 s = 880 crossings)
  1912. // AM: osc 3 at level 1.0, slow sine, modulates osc 1 (the average level drops, the sum doesn't gain osc 3)
  1913. lynx::SynthSettings am;
  1914. am.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  1915. am.osc[2] = { lynx::Waveform::sine, -3, 0.0f, 1.0f };
  1916. am.cutoff = 20000.0f;
  1917. am.am = true;
  1918. auto modulated = make (am);
  1919. modulated->noteOn (69, 1.0f);
  1920. std::fill (l.begin(), l.end(), 0.0f);
  1921. modulated->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  1922. float peak = 0.0f;
  1923. for (std::size_t i = 4800; i < 48000; ++i)
  1924. peak = std::max (peak, std::abs (l[i]));
  1925. CHECK (peak > 0.45f && peak < 0.65f); // 0.3 · (1 + 1) at most: (1 − o3) goes up to 2
  1926. }
  1927. TEST (channel_lfo_vibrato_and_tremolo)
  1928. {
  1929. auto render = [] (const lynx::SynthSettings& s) {
  1930. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  1931. inst->prepare (48000.0);
  1932. lynx::ChannelDef c;
  1933. c.synth = s;
  1934. inst->configure (c, 120.0);
  1935. inst->noteOn (69, 1.0f);
  1936. std::vector<float> l (48000), r (48000);
  1937. inst->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  1938. return l;
  1939. };
  1940. lynx::SynthSettings s;
  1941. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  1942. s.cutoff = 20000.0f;
  1943. // tremolo: 100% volume LFO at 4 Hz (0.25 s period) -> the amplitude envelope goes from ~0 to ~2x
  1944. auto tremolo = s;
  1945. tremolo.lfo[lynx::lfoVolume] = { 1.0f, 0.25f, false, 0, 0.0f, 0.0f };
  1946. const auto t = render (tremolo);
  1947. float lowest = 1.0f, highest = 0.0f;
  1948. for (std::size_t w = 4800; w + 480 <= 48000; w += 480) // 10 ms windows (4.4 cycles of 440 Hz)
  1949. {
  1950. float peak = 0.0f;
  1951. for (auto i = w; i < w + 480; ++i)
  1952. peak = std::max (peak, std::abs (t[i]));
  1953. lowest = std::min (lowest, peak);
  1954. highest = std::max (highest, peak);
  1955. }
  1956. CHECK (lowest < 0.08f && highest > 0.5f);
  1957. // synced vibrato: ±1 semitone, 1-beat period (0.5 s at 120 BPM); the average stays at 440 Hz
  1958. auto vibrato = s;
  1959. vibrato.lfo[lynx::lfoPitch] = { 1.0f, 1.0f, true, 0, 0.0f, 0.0f };
  1960. const auto v = render (vibrato);
  1961. int crossings = 0;
  1962. for (std::size_t i = 1; i < 48000; ++i)
  1963. crossings += (v[i - 1] < 0.0f) != (v[i] < 0.0f);
  1964. CHECK (std::abs (crossings - 880) < 12);
  1965. int firstQuarter = 0; // first quarter of the cycle: rising sine -> higher than 440
  1966. for (std::size_t i = 1; i < 6000; ++i)
  1967. firstQuarter += (v[i - 1] < 0.0f) != (v[i] < 0.0f);
  1968. CHECK (firstQuarter > 112);
  1969. }
  1970. TEST (sampler_porta_glides_from_previous_note)
  1971. {
  1972. auto data = std::make_shared<lynx::SampleData>();
  1973. data->sampleRate = 48000.0;
  1974. data->left.resize (96000);
  1975. for (std::size_t i = 0; i < data->left.size(); ++i)
  1976. data->left[i] = 0.5f * (float) std::sin (6.283185307 * 220.0 * (double) i / 48000.0);
  1977. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  1978. inst->prepare (48000.0);
  1979. lynx::ChannelDef c;
  1980. c.sampler.cut = true;
  1981. c.sampler.porta = true;
  1982. c.sampler.portaBeats = 1.0f; // 0.5 s at 120 BPM
  1983. inst->configure (c, 120.0);
  1984. std::vector<float> l (24000), r (24000);
  1985. inst->noteOn (60, 1.0f);
  1986. inst->render (l.data(), r.data(), 2400, 1.0f, 1.0f);
  1987. inst->noteOn (72, 1.0f); // one octave up: starts at 220 Hz and rises
  1988. std::fill (l.begin(), l.end(), 0.0f);
  1989. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  1990. auto crossings = [&] (std::size_t from, std::size_t to) {
  1991. int n = 0;
  1992. for (auto i = from + 1; i < to; ++i)
  1993. n += (l[i - 1] < 0.0f) != (l[i] < 0.0f);
  1994. return n;
  1995. };
  1996. const auto start = crossings (600, 2400); // 37.5 ms still near 220 Hz: ~17 crossings (440 Hz would give 33)
  1997. const auto end = crossings (21600, 24000); // 50 ms at the end of the glide: near 440 Hz (~44; 220 Hz would give 22)
  1998. CHECK (start < 22);
  1999. CHECK (end > 36);
  2000. }
  2001. TEST (zoned_sampler_picks_zone_by_key_and_velocity)
  2002. {
  2003. auto sine = [] (double hz, float amp) {
  2004. auto d = std::make_shared<lynx::SampleData>();
  2005. d->sampleRate = 48000.0;
  2006. d->left.resize (48000);
  2007. for (std::size_t i = 0; i < d->left.size(); ++i)
  2008. d->left[i] = amp * (float) std::sin (6.283185307 * hz * (double) i / 48000.0);
  2009. return d;
  2010. };
  2011. // lows: 220 Hz sine recorded as A3 (57), up to key 69; highs: 880 Hz as A5 (81)
  2012. // hard layer on the highs: same tuning, louder
  2013. std::vector<lynx::LoadedZone> zones {
  2014. { { "graves.wav", 57, 0, 69, 0, 127, 0.0f, 1.0f }, sine (220.0, 0.5f) },
  2015. { { "agudos.wav", 81, 70, 127, 0, 99, 0.0f, 1.0f }, sine (880.0, 0.25f) },
  2016. { { "agudos forte.wav", 81, 70, 127, 100, 127, 0.0f, 1.0f }, sine (880.0, 0.9f) },
  2017. };
  2018. auto inst = lynx::makeZonedSampler (zones);
  2019. inst->prepare (48000.0);
  2020. inst->configure (lynx::ChannelDef {}, 120.0);
  2021. auto play = [&] (int key, float velocity) {
  2022. inst->allNotesOff();
  2023. std::vector<float> l (24000), r (24000);
  2024. inst->render (l.data(), r.data(), 2000, 1.0f, 1.0f); // let the old voices die out
  2025. std::fill (l.begin(), l.end(), 0.0f);
  2026. inst->noteOn (key, velocity);
  2027. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  2028. int crossings = 0;
  2029. float peak = 0.0f;
  2030. for (std::size_t i = 1; i < 24000; ++i)
  2031. {
  2032. crossings += (l[i - 1] < 0.0f) != (l[i] < 0.0f);
  2033. peak = std::max (peak, std::abs (l[i]));
  2034. }
  2035. return std::pair { crossings, peak };
  2036. };
  2037. const auto low = play (69, 0.5f); // A4 from root A3: 440 Hz -> 440 crossings in 0.5 s
  2038. CHECK (std::abs (low.first - 440) < 4);
  2039. const auto soft = play (81, 0.5f); // high zone at the root: 880 Hz
  2040. CHECK (std::abs (soft.first - 880) < 6);
  2041. const auto hard = play (81, 0.95f); // high velocity: hard layer
  2042. CHECK (hard.second > soft.second * 2.0f);
  2043. // overlapping layers round-robin: two identical zones at different levels, notes alternate
  2044. auto rr = lynx::makeZonedSampler ({ { { "a.wav", 60 }, sine (440.0, 0.2f) }, { { "b.wav", 60 }, sine (440.0, 0.8f) } });
  2045. rr->prepare (48000.0);
  2046. rr->configure (lynx::ChannelDef {}, 120.0);
  2047. float peaks[2] {};
  2048. for (int k = 0; k < 2; ++k)
  2049. {
  2050. rr->allNotesOff();
  2051. std::vector<float> l (4800), r (4800);
  2052. rr->render (l.data(), r.data(), 2000, 1.0f, 1.0f);
  2053. std::fill (l.begin(), l.end(), 0.0f);
  2054. rr->noteOn (60, 1.0f);
  2055. rr->render (l.data(), r.data(), 4800, 1.0f, 1.0f);
  2056. for (auto v : l)
  2057. peaks[k] = std::max (peaks[k], std::abs (v));
  2058. }
  2059. CHECK (std::abs (peaks[0] - peaks[1]) > 0.3f);
  2060. }
  2061. TEST (zoned_sampler_loops_while_held)
  2062. {
  2063. // 0.1 s sample with a loop in the middle: holding the note it keeps sounding well past the end of the file;
  2064. // on release, it leaves the loop and ends
  2065. auto data = std::make_shared<lynx::SampleData>();
  2066. data->sampleRate = 48000.0;
  2067. data->left.resize (4800);
  2068. for (std::size_t i = 0; i < data->left.size(); ++i)
  2069. data->left[i] = 0.5f * (float) std::sin (6.283185307 * 480.0 * (double) i / 48000.0); // 100 frames per cycle
  2070. lynx::SampleZone zone { "loop.wav", 60 };
  2071. zone.loopStart = 1000;
  2072. zone.loopEnd = 3000;
  2073. zone.loopMode = 2;
  2074. auto inst = lynx::makeZonedSampler ({ { zone, data } });
  2075. inst->prepare (48000.0);
  2076. lynx::ChannelDef c;
  2077. c.sampler.release = 0.01f;
  2078. inst->configure (c, 120.0);
  2079. inst->noteOn (60, 1.0f);
  2080. std::vector<float> l (48000), r (48000);
  2081. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f); // 0.5 s held
  2082. float held = 0.0f;
  2083. for (std::size_t i = 20000; i < 24000; ++i)
  2084. held = std::max (held, std::abs (l[i]));
  2085. CHECK (held > 0.3f);
  2086. inst->noteOff (60);
  2087. inst->render (l.data() + 24000, r.data() + 24000, 24000, 1.0f, 1.0f);
  2088. float after = 0.0f;
  2089. for (std::size_t i = 40000; i < 48000; ++i)
  2090. after = std::max (after, std::abs (l[i]));
  2091. CHECK (after == 0.0f);
  2092. }
  2093. TEST (global_lfo_follows_song_position)
  2094. {
  2095. // global volume LFO (1-beat period): a note mid-cycle starts mid-wave; the
  2096. // same note with a per-note LFO starts at phase 0
  2097. auto first = [] (bool global, double songTicks) {
  2098. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  2099. inst->prepare (48000.0);
  2100. lynx::ChannelDef c;
  2101. c.synth.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  2102. c.synth.cutoff = 20000.0f;
  2103. c.synth.lfo[lynx::lfoVolume] = { 1.0f, 1.0f, true, 2, 0.0f, 0.0f, global }; // pulse: +1 in the first half
  2104. inst->configure (c, 120.0);
  2105. inst->setSongPosition (songTicks);
  2106. inst->noteOn (69, 1.0f);
  2107. std::vector<float> l (4800), r (4800);
  2108. inst->render (l.data(), r.data(), 4800, 1.0f, 1.0f);
  2109. float peak = 0.0f;
  2110. for (std::size_t i = 2400; i < 4800; ++i)
  2111. peak = std::max (peak, std::abs (l[i]));
  2112. return peak;
  2113. };
  2114. // mid-cycle (phase 0.6) the pulse is at −1: volume ~0; per note (phase 0) it is at +1: ~2x
  2115. const auto globalLate = first (true, 0.6 * lynx::ppq);
  2116. const auto perNote = first (false, 0.6 * lynx::ppq);
  2117. CHECK (globalLate < 0.05f);
  2118. CHECK (perNote > 0.4f);
  2119. }
  2120. TEST (sampler_channel_filter_darkens_and_bypasses_when_open)
  2121. {
  2122. // white noise in the sampler: with a 300 Hz cutoff the energy drops a lot; open passes unchanged
  2123. auto data = std::make_shared<lynx::SampleData>();
  2124. data->sampleRate = 48000.0;
  2125. data->left.resize (48000);
  2126. std::uint32_t seed = 7;
  2127. for (auto& v : data->left)
  2128. {
  2129. seed = seed * 1664525u + 1013904223u;
  2130. v = ((float) (seed >> 8) / 16777216.0f - 0.5f);
  2131. }
  2132. data->right = data->left;
  2133. auto energy = [&] (float cutoff) {
  2134. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  2135. inst->prepare (48000.0);
  2136. lynx::ChannelDef c;
  2137. c.sampler.cutoff = cutoff;
  2138. inst->configure (c, 120.0);
  2139. inst->noteOn (60, 1.0f);
  2140. std::vector<float> l (24000), r (24000);
  2141. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  2142. double e = 0.0;
  2143. for (auto v : l)
  2144. e += (double) v * v;
  2145. return e;
  2146. };
  2147. const auto open = energy (20000.0f), dark = energy (300.0f);
  2148. {
  2149. // high-pass at 10 kHz: also removes most of the noise energy, but from the other side
  2150. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  2151. inst->prepare (48000.0);
  2152. lynx::ChannelDef hp;
  2153. hp.sampler.cutoff = 10000.0f;
  2154. hp.sampler.filterType = 2;
  2155. inst->configure (hp, 120.0);
  2156. inst->noteOn (60, 1.0f);
  2157. std::vector<float> l (24000), r (24000);
  2158. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  2159. double e = 0.0, lowE = 0.0;
  2160. float lp = 0.0f;
  2161. for (auto v : l)
  2162. {
  2163. e += (double) v * v;
  2164. lp += 0.01f * (v - lp); // crude low-pass: almost nothing should remain below
  2165. lowE += (double) lp * lp;
  2166. }
  2167. CHECK (e > 10.0 && e < 0.7 * energy (20000.0f));
  2168. CHECK (lowE < e * 0.01);
  2169. }
  2170. CHECK (open > 100.0);
  2171. CHECK (dark < open * 0.05);
  2172. // +12 st pitch envelope with sustain 1: the sample runs at double speed
  2173. // and ends in half the time (1 s of sample -> 0.5 s)
  2174. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  2175. inst->prepare (48000.0);
  2176. lynx::ChannelDef c;
  2177. c.sampler.pitchEnv = { 12.0f, 0.0f, 0.0f, 0.1f, 1.0f, 0.1f };
  2178. inst->configure (c, 120.0);
  2179. inst->noteOn (60, 1.0f);
  2180. std::vector<float> l (48000), r (48000);
  2181. inst->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  2182. float tail = 0.0f, body = 0.0f;
  2183. for (std::size_t i = 20000; i < 23000; ++i)
  2184. body = std::max (body, std::abs (l[i]));
  2185. for (std::size_t i = 25000; i < 48000; ++i)
  2186. tail = std::max (tail, std::abs (l[i]));
  2187. CHECK (body > 0.1f);
  2188. CHECK (tail == 0.0f);
  2189. }
  2190. TEST (synth_oscillator_pan_and_semitones)
  2191. {
  2192. auto render = [] (lynx::SynthSettings s, std::vector<float>& l, std::vector<float>& r) {
  2193. auto synth = lynx::makeInstrument (lynx::InstrumentKind::synth);
  2194. synth->prepare (48000.0);
  2195. lynx::ChannelDef c;
  2196. c.synth = s;
  2197. synth->configure (c, 120.0);
  2198. synth->noteOn (69, 1.0f);
  2199. l.assign (24000, 0.0f);
  2200. r.assign (24000, 0.0f);
  2201. synth->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  2202. };
  2203. lynx::SynthSettings s;
  2204. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f, 7, 1.0f }; // a fifth up, fully right
  2205. s.cutoff = 20000.0f;
  2206. std::vector<float> l, r;
  2207. render (s, l, r);
  2208. float peakL = 0.0f, peakR = 0.0f;
  2209. int crossings = 0;
  2210. for (std::size_t i = 4800; i < 24000; ++i)
  2211. {
  2212. peakL = std::max (peakL, std::abs (l[i]));
  2213. peakR = std::max (peakR, std::abs (r[i]));
  2214. crossings += (r[i - 1] < 0.0f) != (r[i] < 0.0f);
  2215. }
  2216. CHECK (peakL < 1e-4f && peakR > 0.1f);
  2217. // 440 * 2^(7/12) = 659.3 Hz; 0.4 s = 263.7 cycles = ~527 crossings
  2218. CHECK (std::abs (crossings - 527) < 6);
  2219. }
  2220. TEST (fl_wrapper_state_parses_records_and_vst3_state)
  2221. {
  2222. // Fruity Wrapper blob (version 12): VST3 generator type, class ID, name, path and state
  2223. std::vector<std::uint8_t> blob;
  2224. 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))); };
  2225. auto record = [&] (std::vector<std::uint8_t>& b, std::uint32_t id, const std::vector<std::uint8_t>& payload) {
  2226. u32 (b, id);
  2227. u32 (b, (std::uint32_t) payload.size());
  2228. u32 (b, 0);
  2229. b.insert (b.end(), payload.begin(), payload.end());
  2230. };
  2231. auto bytes = [] (const std::string& s) { return std::vector<std::uint8_t> (s.begin(), s.end()); };
  2232. std::vector<std::uint8_t> vst3State;
  2233. u32 (vst3State, 1);
  2234. record (vst3State, 1, std::vector<std::uint8_t> (64, 0));
  2235. record (vst3State, 3, bytes ("COMPONENTE"));
  2236. record (vst3State, 2, bytes ("CONTROLADOR"));
  2237. // record 4: 3 slots → ParamIDs 700, −1 (empty), 0xFFFFFF01
  2238. std::vector<std::uint8_t> slots;
  2239. for (auto v : { 3u, 700u, 0xFFFFFFFFu, 0xFFFFFF01u })
  2240. u32 (slots, v);
  2241. record (vst3State, 4, slots);
  2242. u32 (blob, 12);
  2243. record (blob, 0x01, std::vector<std::uint8_t> (20, 0xFF));
  2244. record (blob, 0x32, { 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });
  2245. std::vector<std::uint8_t> cid;
  2246. for (int i = 0; i < 16; ++i)
  2247. cid.push_back ((std::uint8_t) (0xA0 + i));
  2248. record (blob, 0x34, cid);
  2249. record (blob, 0x36, bytes ("Surge XT"));
  2250. record (blob, 0x37, bytes ("C:/Program Files/Common Files/VST3/Surge XT.vst3"));
  2251. record (blob, 0x35, vst3State);
  2252. lynx::ForeignPlugin p;
  2253. CHECK (lynx::parseFlWrapper (blob, p));
  2254. CHECK (p.format == lynx::ForeignPlugin::Format::vst3);
  2255. CHECK (p.hasClassId && p.classId[0] == 0xA0 && p.classId[15] == 0xAF);
  2256. CHECK (p.name == "Surge XT" && p.path.find ("Surge XT.vst3") != std::string::npos);
  2257. std::vector<std::uint8_t> component, controller;
  2258. CHECK (lynx::splitFlVst3State (p.state, component, controller));
  2259. CHECK (component == bytes ("COMPONENTE") && controller == bytes ("CONTROLADOR"));
  2260. const auto saved = lynx::flVst3ParamSlots (p.state);
  2261. CHECK (saved == (std::vector<std::int32_t> { 700, -1, (std::int32_t) 0xFFFFFF01u }));
  2262. // FL's slot assignment: saved slots keep their ParamID wherever it now sits; the empty slot stays empty;
  2263. // a vanished ParamID (0xFFFFFF01) leaves its slot dead; parameters without a slot get slots 3, 4… in list order
  2264. const auto positions = lynx::flVst3SlotPositions (saved, { 5u, 700u, 9u });
  2265. CHECK (positions == (std::vector<int> { 1, -1, -1, 0, 2 }));
  2266. CHECK (lynx::flVst3SlotPositions ({}, { 5u, 6u }) == (std::vector<int> { 0, 1 })); // new instance: slot = position
  2267. // version out of range or no type: not a usable wrapper
  2268. blob[0] = 13;
  2269. CHECK (! lynx::parseFlWrapper (blob, p));
  2270. CHECK (! lynx::parseFlWrapper ({ 12, 0, 0, 0 }, p));
  2271. }
  2272. TEST (schedule_index_matches_full_scan)
  2273. {
  2274. // random song (long notes, swing, clips with offset); indexed scheduling must yield
  2275. // exactly the same events as the full scan, including in the block that wraps around
  2276. lynx::Song s = lynx::Song::makeDefault();
  2277. s.swing = 0.6f;
  2278. std::uint32_t seed = 12345;
  2279. auto rnd = [&] (int n) { seed = seed * 1664525u + 1013904223u; return (int) ((seed >> 8) % (std::uint32_t) n); };
  2280. s.patterns.resize (3);
  2281. for (auto& p : s.patterns)
  2282. {
  2283. p.notes.clear();
  2284. for (int i = 0; i < 60; ++i)
  2285. {
  2286. lynx::Note n;
  2287. n.start = rnd (16 * lynx::ppq);
  2288. n.length = rnd (5) == 0 ? rnd (12 * lynx::ppq) + 1 : rnd (lynx::ppq) + 1;
  2289. n.channel = rnd (4);
  2290. n.key = 40 + rnd (40);
  2291. n.slide = rnd (20) == 0;
  2292. p.notes.push_back (n);
  2293. }
  2294. p.sortNotes();
  2295. }
  2296. s.playlist.clear();
  2297. for (int i = 0; i < 12; ++i)
  2298. {
  2299. lynx::Clip c;
  2300. c.pattern = rnd (3);
  2301. c.track = rnd (4);
  2302. c.start = rnd (40) * lynx::ppq;
  2303. c.length = (rnd (12) + 1) * lynx::ppq;
  2304. c.offset = rnd (4) * lynx::ppq;
  2305. s.playlist.push_back (c);
  2306. }
  2307. s.mode = lynx::PlayMode::song;
  2308. const auto index = lynx::makeScheduleIndex (s);
  2309. const auto tps = lynx::ticksPerSample (140.0, 48000.0);
  2310. const auto loop = (double) s.songLength();
  2311. int mismatches = 0, events = 0;
  2312. for (int block = 0; block < 400; ++block)
  2313. {
  2314. const auto start = block == 0 ? loop - 100.0 * tps : (double) rnd ((int) loop * 2);
  2315. const auto samples = 64 + rnd (24000); // up to ~1 beat per block
  2316. lynx::EventBuffer a, b;
  2317. lynx::scheduleSong (s, start, samples, tps, a, false, nullptr);
  2318. lynx::scheduleSong (s, start, samples, tps, b, false, &index);
  2319. events += a.size();
  2320. if (a.size() != b.size())
  2321. {
  2322. ++mismatches;
  2323. continue;
  2324. }
  2325. for (int i = 0; i < a.size(); ++i)
  2326. {
  2327. const auto& x = *(a.begin() + i);
  2328. const auto& y = *(b.begin() + i);
  2329. mismatches += x.sampleOffset != y.sampleOffset || x.type != y.type || x.key != y.key || x.channel != y.channel;
  2330. }
  2331. }
  2332. CHECK (events > 500);
  2333. CHECK (mismatches == 0);
  2334. }
  2335. TEST (mixer_track_eq_defaults_and_boost)
  2336. {
  2337. // FL defaults: 90 Hz, 1.5 kHz and 8 kHz; peak Q 0.632; shelf slope 0.607
  2338. lynx::TrackEq eq;
  2339. CHECK (std::abs (lynx::TrackEq::peakQ (eq.width[1]) - 0.632) < 0.01);
  2340. CHECK (std::abs (lynx::TrackEq::shelfSlope (eq.width[0]) - 0.607) < 0.01);
  2341. CHECK (! eq.active());
  2342. // +12 dB peak at 1.5 kHz on a track: a 1.5 kHz sine rises ~4x
  2343. lynx::Song song = lynx::Song::makeDefault();
  2344. song.mixer[1].eq.gainDb[1] = 12.0f;
  2345. for (auto& c : song.channels)
  2346. c.mixerTrack = 1;
  2347. song.channels[4].instrument = lynx::InstrumentKind::synth;
  2348. song.channels[4].synth = {};
  2349. song.channels[4].synth.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  2350. song.channels[4].synth.cutoff = 20000.0f;
  2351. auto render = [] (const lynx::Song& s) {
  2352. auto state = lynx::RackState::build (s, nullptr, 48000.0);
  2353. lynx::RackRenderer renderer;
  2354. renderer.prepare (48000.0);
  2355. lynx::LiveEventQueue live;
  2356. lynx::NoteEvent on; // 1.5 kHz ~ key 90.6: use 91 (1568 Hz), still within the wide peak
  2357. on.channel = 4;
  2358. on.key = 91;
  2359. on.velocity = 1.0f;
  2360. live.push (on);
  2361. std::vector<float> l (24000), r (24000);
  2362. for (int pos = 0; pos < 24000; pos += 480)
  2363. renderer.process (state.get(), false, 0.0, 480, l.data() + pos, r.data() + pos, pos == 0 ? &live : nullptr);
  2364. float peak = 0.0f;
  2365. for (std::size_t i = 12000; i < 24000; ++i)
  2366. peak = std::max (peak, std::abs (l[i]));
  2367. return peak;
  2368. };
  2369. const auto boosted = render (song);
  2370. song.mixer[1].eq.gainDb[1] = 0.0f;
  2371. const auto flat = render (song);
  2372. CHECK (flat > 0.01f);
  2373. CHECK (boosted / flat > 3.0f && boosted / flat < 4.2f);
  2374. }
  2375. TEST (bars_follow_time_signature_markers)
  2376. {
  2377. lynx::Song song;
  2378. song.beatsPerBar = 4;
  2379. const auto bar4 = (std::int64_t) lynx::ppq * 4;
  2380. auto bars = song.barsBetween (0, bar4 * 3);
  2381. CHECK (bars.size() == 3 && bars[2].tick == bar4 * 2 && bars[2].number == 3);
  2382. // 7/4 from bar 3, and 3/4 in the middle of a 7 bar (cuts and restarts)
  2383. song.addMarker ({ bar4 * 2, "Verso", 7, 4 });
  2384. song.addMarker ({ bar4, "Nome só", 0, 4 });
  2385. const auto seven = (std::int64_t) lynx::ppq * 7;
  2386. song.addMarker ({ bar4 * 2 + seven + lynx::ppq * 2, "", 3, 4 });
  2387. bars = song.barsBetween (0, bar4 * 2 + seven * 2);
  2388. CHECK (bars.size() >= 5);
  2389. CHECK (bars[1].length == bar4 && bars[2].tick == bar4 * 2 && bars[2].length == seven);
  2390. CHECK (bars[3].length == lynx::ppq * 2); // cut short by the change
  2391. CHECK (bars[4].length == lynx::ppq * 3 && bars[4].number == 5);
  2392. CHECK (song.markers()[0].name == "Nome só"); // sorted by tick
  2393. // from far away: starts at the right bar without losing the numbering
  2394. const auto far = song.barsBetween (lynx::ppq * 3000, lynx::ppq * 3001);
  2395. CHECK (far.size() == 1 && far[0].length == lynx::ppq * 3);
  2396. CHECK (song.barAt (lynx::ppq * 3000).number == far[0].number);
  2397. CHECK ((lynx::ppq * 3000 - far[0].tick) < far[0].length);
  2398. }
  2399. TEST (split_drum_channel_moves_notes_to_pads)
  2400. {
  2401. lynx::Song song = lynx::Song::makeDefault();
  2402. const auto channels = (int) song.channels.size();
  2403. song.patterns[0].notes.clear();
  2404. song.patterns[0].notes.push_back ({ 0, 240, 1, 36, 0.9f }); // kit kick (channel 1)
  2405. song.patterns[0].notes.push_back ({ 240, 240, 1, 38, 0.8f }); // snare
  2406. song.patterns[0].notes.push_back ({ 480, 240, 1, 50, 0.8f }); // key without a pad: dropped
  2407. song.patterns[0].notes.push_back ({ 480, 240, 3, 60, 0.8f }); // other channel: shifts by 1 position
  2408. lynx::Automation a;
  2409. a.target = { lynx::AutomationTargetKind::channelVolume, 3, 0, 0 };
  2410. song.automations.push_back (a);
  2411. std::vector<lynx::DrumPad> pads (2);
  2412. pads[0].name = "Kick";
  2413. pads[0].key = 36;
  2414. pads[0].layers = { { "kick.wav" } };
  2415. pads[1].name = "Snare";
  2416. pads[1].key = 38;
  2417. pads[1].layers = { { "snare soft.wav", 60, 0, 127, 0, 90 }, { "snare hard.wav", 60, 0, 127, 91, 127 } };
  2418. pads[1].cutGroup = 2;
  2419. pads[1].cutBy = 2;
  2420. lynx::splitDrumChannel (song, 1, pads);
  2421. CHECK ((int) song.channels.size() == channels + 1);
  2422. CHECK (song.channels[1].samplePath == "kick.wav" && song.channels[1].instrument == lynx::InstrumentKind::sampler);
  2423. CHECK (song.channels[2].zones.size() == 2 && song.channels[2].cutGroup == song.channels[2].cutBy && song.channels[2].cutGroup != 0);
  2424. const auto& notes = song.patterns[0].notes;
  2425. CHECK (notes.size() == 3);
  2426. CHECK (notes[0].channel == 1 && notes[0].key == 60);
  2427. CHECK (notes[1].channel == 2 && notes[1].key == 60);
  2428. CHECK (notes[2].channel == 4); // the old channel 3
  2429. CHECK (song.automations[0].target.index == 4);
  2430. }
  2431. TEST (flp_import_brings_playlist)
  2432. {
  2433. flp::Project p;
  2434. p.header.ppq = 96;
  2435. p.channels = { { 0, flp::ChannelType::sampler, "Kick", "", "", 1 } };
  2436. flp::Pattern empty;
  2437. empty.index = 1;
  2438. flp::Pattern full;
  2439. full.index = 2;
  2440. flp::Note n;
  2441. n.channel = 0;
  2442. full.notes.push_back (n);
  2443. p.patterns = { empty, full };
  2444. flp::Arrangement a;
  2445. flp::PlaylistItem item;
  2446. item.kind = flp::PlaylistItem::Kind::pattern;
  2447. item.index = 2;
  2448. item.position = 384;
  2449. item.length = 192;
  2450. item.track = 3;
  2451. item.patternStartTick = 96;
  2452. a.items.push_back (item);
  2453. item.index = 1; // empty pattern: discarded
  2454. a.items.push_back (item);
  2455. item.kind = flp::PlaylistItem::Kind::channelClip; // audio: not supported yet
  2456. a.items.push_back (item);
  2457. p.arrangements.push_back (a);
  2458. const auto s = lynx::importFlp (p);
  2459. CHECK (s.mode == lynx::PlayMode::song);
  2460. CHECK (s.playlist.size() == 1);
  2461. CHECK (s.playlist[0].pattern == 0 && s.playlist[0].track == 3);
  2462. CHECK (s.playlist[0].start == 4 * lynx::ppq && s.playlist[0].length == 2 * lynx::ppq && s.playlist[0].offset == lynx::ppq);
  2463. }
  2464. TEST (rack_releases_notes_on_position_jump)
  2465. {
  2466. lynx::Song s;
  2467. lynx::ChannelDef c;
  2468. c.instrument = lynx::InstrumentKind::synth;
  2469. s.channels.push_back (c);
  2470. auto& p = s.patterns.emplace_back();
  2471. lynx::Note n;
  2472. n.start = 0;
  2473. n.length = 4 * lynx::ppq; // long note
  2474. p.notes.push_back (n);
  2475. s.bpm = 120.0;
  2476. auto state = lynx::RackState::build (s, nullptr, 48000.0);
  2477. lynx::RackRenderer r;
  2478. r.prepare (48000.0);
  2479. std::vector<float> l (512), rr (512);
  2480. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  2481. double tick = 0.0;
  2482. for (int i = 0; i < 20; ++i, tick += 512 * tps)
  2483. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  2484. // jump to tick 2000 (mid-note, no new "on"): the synth must go silent
  2485. for (int i = 0; i < 40; ++i)
  2486. r.process (state.get(), true, 2000.0 + i * 512 * tps, 512, l.data(), rr.data());
  2487. float tail = 0.0f;
  2488. for (auto v : l)
  2489. tail = std::max (tail, std::abs (v));
  2490. CHECK (tail < 0.001f);
  2491. }
  2492. namespace
  2493. {
  2494. // Two samplers with a constant 0.5 signal on different inserts; returns the output peak.
  2495. float juce_db (float gain)
  2496. {
  2497. return 20.0f * std::log10 (gain);
  2498. }
  2499. float renderMixerCase (const std::function<void (lynx::Song&)>& tweak, lynx::MeterBank* meters = nullptr)
  2500. {
  2501. lynx::Song s;
  2502. s.mixer = lynx::Song::defaultMixer (4);
  2503. for (int i = 0; i < 2; ++i)
  2504. {
  2505. lynx::ChannelDef c;
  2506. c.instrument = lynx::InstrumentKind::sampler;
  2507. c.samplePath = "dc";
  2508. c.volume = 1.0f;
  2509. c.mixerTrack = i + 1;
  2510. s.channels.push_back (c);
  2511. }
  2512. s.patterns.emplace_back();
  2513. tweak (s);
  2514. auto provider = [] (const std::string&) {
  2515. auto d = std::make_shared<lynx::SampleData>();
  2516. d->left.assign (48000, 0.5f);
  2517. return std::shared_ptr<const lynx::SampleData> (d);
  2518. };
  2519. auto state = lynx::RackState::build (s, nullptr, 48000.0, provider);
  2520. lynx::RackRenderer r;
  2521. r.prepare (48000.0, 256);
  2522. lynx::LiveEventQueue live;
  2523. for (int ch = 0; ch < 2; ++ch)
  2524. {
  2525. lynx::NoteEvent on;
  2526. on.channel = ch;
  2527. on.velocity = 1.0f;
  2528. live.push (on);
  2529. }
  2530. std::vector<float> l (1000), rr (1000); // larger than the mixer block: tests the chunking
  2531. r.process (state.get(), false, 0.0, 1000, l.data(), rr.data(), &live, meters);
  2532. return std::max (std::abs (l[999]), std::abs (rr[999]));
  2533. }
  2534. } // namespace
  2535. TEST (mixer_routes_mutes_solos_and_meters)
  2536. {
  2537. // two 0.5 channels summed on the Master at 0 dB
  2538. CHECK (std::abs (renderMixerCase ([] (lynx::Song&) {}) - 1.0f) < 1e-4f);
  2539. // insert 1 muted: only channel 2 remains
  2540. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.mixer[1].muted = true; }) - 0.5f) < 1e-4f);
  2541. // solo on insert 2: same
  2542. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.mixer[2].solo = true; }) - 0.5f) < 1e-4f);
  2543. // FL fader curve: 0.8 = 0 dB, max ≈ +5.6 dB, half travel ≈ -12.7 dB
  2544. CHECK (std::abs (lynx::faderGain (0.8f) - 1.0f) < 1e-5f);
  2545. CHECK (std::abs (juce_db (lynx::faderGain (1.0f)) - 5.59f) < 0.05f);
  2546. CHECK (lynx::faderGain (0.0f) == 0.0f);
  2547. // Master fader at max
  2548. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.mixer[0].volume = 1.0f; }) - lynx::faderGain (1.0f)) < 1e-4f);
  2549. // both channels on the same insert, insert fader at 0.4
  2550. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) {
  2551. s.channels[1].mixerTrack = 1;
  2552. s.mixer[1].volume = 0.4f;
  2553. }) - lynx::faderGain (0.4f)) < 1e-4f);
  2554. // a route outside the mixer falls to the last existing insert, without crashing
  2555. CHECK (renderMixerCase ([] (lynx::Song& s) { s.channels[0].mixerTrack = 100; }) > 0.9f);
  2556. // no mixer: everything straight to the output at 0 dB
  2557. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.mixer.clear(); }) - 1.0f) < 1e-4f);
  2558. lynx::MeterBank meters;
  2559. renderMixerCase ([] (lynx::Song&) {}, &meters);
  2560. CHECK (std::abs (meters.takePeak (1, 0) - 0.5f) < 1e-4f);
  2561. CHECK (std::abs (meters.takePeak (0, 1) - 1.0f) < 1e-4f);
  2562. CHECK (meters.takePeak (1, 0) == 0.0f); // reading resets
  2563. CHECK (meters.takePeak (3, 0) == 0.0f); // insert with no channel
  2564. }
  2565. TEST (next_free_insert_and_flp_mixer_import)
  2566. {
  2567. auto s = lynx::Song::makeDefault();
  2568. CHECK (s.mixer.size() == 17 && s.mixer[0].name == "Master");
  2569. CHECK (s.nextFreeInsert() == 6); // the 5 default channels take 1..5
  2570. flp::Project p;
  2571. p.channels = { { 0, flp::ChannelType::sampler, "Kick", "", "", 30 } };
  2572. p.mixer = { { 0, "" }, { 30, "Drums" } };
  2573. const auto song = lynx::importFlp (p);
  2574. CHECK (song.channels[0].mixerTrack == 30);
  2575. CHECK (song.mixer.size() == 31);
  2576. CHECK (song.mixer[30].name == "Drums" && song.mixer[0].name == "Master");
  2577. }
  2578. namespace
  2579. {
  2580. float runEffectOnSine (lynx::EffectKind kind, const std::function<void (lynx::EffectSlot&)>& tweak, double hz, float amp,
  2581. int frames = 48000)
  2582. {
  2583. auto fx = lynx::makeEffect (kind);
  2584. fx->prepare (48000.0);
  2585. auto slot = lynx::makeEffectSlot (kind);
  2586. tweak (slot);
  2587. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  2588. for (int i = 0; i < frames; ++i)
  2589. l[(std::size_t) i] = r[(std::size_t) i] = amp * (float) std::sin (6.283185307 * hz * i / 48000.0);
  2590. for (int i = 0; i < frames; i += 480)
  2591. fx->process (l.data() + i, r.data() + i, std::min (480, frames - i), slot.params, 120.0);
  2592. float peak = 0.0f;
  2593. for (int i = frames / 2; i < frames; ++i) // second half: already settled
  2594. {
  2595. CHECK (std::isfinite (l[(std::size_t) i]));
  2596. peak = std::max (peak, std::abs (l[(std::size_t) i]));
  2597. }
  2598. return peak;
  2599. }
  2600. } // namespace
  2601. TEST (parametric_eq_bands_and_response)
  2602. {
  2603. // default: transparent
  2604. auto slot = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  2605. CHECK (std::abs (lynx::peq::responseDb (slot.params, 48000.0, 1000.0)) < 0.01);
  2606. CHECK (std::abs (runEffectOnSine (lynx::EffectKind::parametricEq, [] (auto&) {}, 1000.0, 0.5f) - 0.5f) < 0.005f);
  2607. // +12 dB peak at 1 kHz on band 4: the response and the signal agree
  2608. auto boost = [] (lynx::EffectSlot& s) {
  2609. s.params[(std::size_t) lynx::peq::param (3, 1)] = lynx::peq::hzValue (1000.0);
  2610. s.params[(std::size_t) lynx::peq::param (3, 2)] = lynx::peq::gainValue (12.0);
  2611. };
  2612. boost (slot);
  2613. CHECK (std::abs (lynx::peq::responseDb (slot.params, 48000.0, 1000.0) - 12.0) < 0.2);
  2614. CHECK (std::abs (lynx::peq::responseDb (slot.params, 48000.0, 100.0)) < 1.0);
  2615. const auto peak = runEffectOnSine (lynx::EffectKind::parametricEq, boost, 1000.0, 0.1f);
  2616. CHECK (std::abs (peak - 0.1f * std::pow (10.0f, 12.0f / 20.0f)) < 0.01f);
  2617. // low cut at 48 dB/oct at 200 Hz: 50 Hz (2 octaves below) drops ~96 dB; 2 kHz passes
  2618. auto cut = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  2619. cut.params[(std::size_t) lynx::peq::param (0, 0)] = lynx::peq::typeValue (lynx::peq::BandType::lowCut);
  2620. cut.params[(std::size_t) lynx::peq::param (0, 1)] = lynx::peq::hzValue (200.0);
  2621. cut.params[(std::size_t) lynx::peq::param (0, 3)] = lynx::peq::qValue (0.70710678); // Butterworth
  2622. cut.params[(std::size_t) (lynx::peq::slopeParam + 0)] = 1.0f;
  2623. CHECK (lynx::peq::responseDb (cut.params, 48000.0, 50.0) < -80.0);
  2624. CHECK (std::abs (lynx::peq::responseDb (cut.params, 48000.0, 200.0) + 3.0) < 0.5); // -3 dB at the cutoff (Butterworth)
  2625. CHECK (std::abs (lynx::peq::responseDb (cut.params, 48000.0, 2000.0)) < 0.1);
  2626. // round-trip conversions
  2627. CHECK (std::abs (lynx::peq::hz (lynx::peq::hzValue (440.0)) - 440.0) < 0.5);
  2628. CHECK (std::abs (lynx::peq::q (lynx::peq::qValue (2.5)) - 2.5) < 0.01);
  2629. CHECK (lynx::peq::type (lynx::peq::typeValue (lynx::peq::BandType::notch)) == lynx::peq::BandType::notch);
  2630. }
  2631. TEST (fl_parametric_eq2_state_maps_to_bands)
  2632. {
  2633. // v8 blob: band 1 low cut at 100 Hz "Steep 8", band 4 peak +6 dB at 1 kHz, output −3 dB
  2634. std::vector<std::uint8_t> blob (354, 0);
  2635. auto put = [&] (std::size_t off, std::int32_t v) { std::memcpy (blob.data() + off, &v, 4); };
  2636. put (0, 8);
  2637. auto param = [&] (int i, std::int32_t v) { put (4 + 4 * (std::size_t) i, v); };
  2638. auto hzRaw = [] (double hz) { return (std::int32_t) std::lround (std::log (hz / 20.0) / std::log (1000.0) * 65536.0); };
  2639. for (int b = 0; b < 7; ++b)
  2640. param (21 + b, 0); // all off
  2641. param (21 + 0, 3); // high pass (= low cut)
  2642. param (7 + 0, hzRaw (100.0));
  2643. param (14 + 0, 40124); // default width -> Q ~0.68
  2644. param (28 + 0, -3); // Steep 8 -> 4 biquads
  2645. param (21 + 3, 6); // peaking
  2646. param (7 + 3, hzRaw (1000.0));
  2647. param (3, 600); // +6 dB
  2648. param (14 + 3, 25412);
  2649. param (35, -300); // main level −3 dB
  2650. put (0x13E, 0x7F);
  2651. const auto slot = lynx::effectFromFl ("Fruity Parametric EQ 2", blob);
  2652. CHECK (slot.has_value() && slot->kind == lynx::EffectKind::parametricEq);
  2653. const auto& p = slot->params;
  2654. CHECK (lynx::peq::type (p[(std::size_t) lynx::peq::param (0, 0)]) == lynx::peq::BandType::lowCut);
  2655. CHECK (lynx::peq::slopeStages (p[(std::size_t) lynx::peq::slopeParam]) == 4);
  2656. CHECK (lynx::peq::type (p[(std::size_t) lynx::peq::param (3, 0)]) == lynx::peq::BandType::peak);
  2657. CHECK (lynx::peq::type (p[(std::size_t) lynx::peq::param (1, 0)]) == lynx::peq::BandType::off);
  2658. CHECK (std::abs (lynx::peq::responseDb (p, 48000.0, 1000.0) - 3.0) < 0.3); // +6 from the peak −3 from the output
  2659. CHECK (lynx::peq::responseDb (p, 48000.0, 30.0) < -40.0); // 48 dB/oct below 100 Hz
  2660. CHECK (std::abs (lynx::peq::responseDb (p, 48000.0, 8000.0) + 3.0) < 0.3);
  2661. // a band muted by the mask doesn't sound
  2662. put (0x13E, 0x7F & ~(1 << 3));
  2663. const auto muted = lynx::effectFromFl ("Fruity Parametric EQ 2", blob);
  2664. CHECK (lynx::peq::type (muted->params[(std::size_t) lynx::peq::param (3, 0)]) == lynx::peq::BandType::off);
  2665. }
  2666. TEST (reverb_low_cut_and_predelay)
  2667. {
  2668. // impulse: with 100 ms predelay the wet only starts later; with a 3 kHz low cut a
  2669. // 100 Hz sine barely enters the reverb
  2670. auto run = [] (const std::function<void (lynx::EffectSlot&)>& tweak, double hz, bool impulse) {
  2671. auto fx = lynx::makeEffect (lynx::EffectKind::reverb);
  2672. fx->prepare (48000.0);
  2673. auto slot = lynx::makeEffectSlot (lynx::EffectKind::reverb);
  2674. slot.params[4] = 0.0f; // wet only
  2675. slot.params[3] = 1.0f;
  2676. tweak (slot);
  2677. std::vector<float> l (48000), r (48000);
  2678. for (int i = 0; i < 48000; ++i)
  2679. 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);
  2680. for (int i = 0; i < 48000; i += 480)
  2681. fx->process (l.data() + i, r.data() + i, 480, slot.params, 120.0);
  2682. return l;
  2683. };
  2684. const auto delayed = run ([] (auto& s) { s.params[7] = 0.1f; }, 0.0, true);
  2685. float early = 0.0f, later = 0.0f;
  2686. for (std::size_t i = 0; i < 4800; ++i)
  2687. early = std::max (early, std::abs (delayed[i]));
  2688. for (std::size_t i = 4800; i < 24000; ++i)
  2689. later = std::max (later, std::abs (delayed[i]));
  2690. CHECK (early == 0.0f && later > 0.0f);
  2691. 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; };
  2692. const auto open = energy (run ([] (auto&) {}, 100.0, false));
  2693. const auto cut = energy (run ([] (auto& s) { s.params[5] = 1.0f; }, 100.0, false));
  2694. CHECK (cut < open * 0.01);
  2695. }
  2696. TEST (utility_effect_and_fl_stereo_tools)
  2697. {
  2698. // transparent by default; balance fully right silences the left
  2699. CHECK (std::abs (runEffectOnSine (lynx::EffectKind::utility, [] (auto&) {}, 440.0, 0.5f) - 0.5f) < 0.001f);
  2700. CHECK (runEffectOnSine (lynx::EffectKind::utility, [] (auto& s) { s.params[1] = 1.0f; }, 440.0, 0.5f) < 0.001f);
  2701. // Stereo Shaper in "mono": each output = 0.5 L + 0.5 R
  2702. std::vector<std::uint8_t> blob (36, 0);
  2703. auto put = [&] (std::size_t off, std::int32_t v) { std::memcpy (blob.data() + off, &v, 4); };
  2704. put (4, 6400); put (8, 6400); put (12, 6400); put (16, 6400);
  2705. const auto slot = lynx::effectFromFl ("Fruity Stereo Shaper", blob);
  2706. CHECK (slot && slot->kind == lynx::EffectKind::utility);
  2707. auto fx = lynx::makeEffect (lynx::EffectKind::utility);
  2708. float l = 1.0f, r = 0.0f;
  2709. fx->process (&l, &r, 1, slot->params, 120.0);
  2710. CHECK (std::abs (l - 0.5f) < 1e-4f && std::abs (r - 0.5f) < 1e-4f);
  2711. // Balance: volume 256 = 0 dB, pan −128 = fully left
  2712. std::vector<std::uint8_t> bal (8, 0);
  2713. std::int32_t pan = -128, vol = 256;
  2714. std::memcpy (bal.data(), &pan, 4);
  2715. std::memcpy (bal.data() + 4, &vol, 4);
  2716. const auto b = lynx::effectFromFl ("Fruity Balance", bal);
  2717. l = 0.5f; r = 0.5f;
  2718. fx->process (&l, &r, 1, b->params, 120.0);
  2719. CHECK (std::abs (l - 0.5f) < 1e-3f && std::abs (r) < 1e-4f);
  2720. }
  2721. TEST (effects_eq_compressor_behave)
  2722. {
  2723. // EQ at default is transparent
  2724. CHECK (std::abs (runEffectOnSine (lynx::EffectKind::eq, [] (auto&) {}, 1000.0, 0.5f) - 0.5f) < 0.01f);
  2725. // +18 dB on the lows: 60 Hz rises a lot, 5 kHz barely
  2726. CHECK (runEffectOnSine (lynx::EffectKind::eq, [] (auto& s) { s.params[0] = 1.0f; }, 60.0, 0.05f) > 0.3f);
  2727. CHECK (runEffectOnSine (lynx::EffectKind::eq, [] (auto& s) { s.params[0] = 1.0f; }, 5000.0, 0.05f) < 0.06f);
  2728. // compressor: threshold -20 dB, ratio 20:1 flattens a 0 dBFS signal to near the threshold
  2729. const auto squashed = runEffectOnSine (lynx::EffectKind::compressor, [] (auto& s) {
  2730. s.params[0] = 40.0f / 60.0f;
  2731. s.params[1] = 1.0f;
  2732. }, 200.0, 1.0f);
  2733. CHECK (squashed < 0.2f && squashed > 0.05f);
  2734. // a signal below the threshold passes intact
  2735. CHECK (std::abs (runEffectOnSine (lynx::EffectKind::compressor, [] (auto& s) { s.params[0] = 1.0f; }, 200.0, 0.3f) - 0.3f) < 0.01f);
  2736. }
  2737. TEST (effects_delay_echoes_on_tempo_and_reverb_has_tail)
  2738. {
  2739. auto delay = lynx::makeEffect (lynx::EffectKind::delay);
  2740. delay->prepare (48000.0);
  2741. auto slot = lynx::makeEffectSlot (lynx::EffectKind::delay);
  2742. slot.params[0] = 3.5f / 8.0f; // index 3 = 1/4 = 0.5 s at 120 BPM
  2743. slot.params[1] = 0.0f; // no feedback: a single echo
  2744. slot.params[2] = 1.0f;
  2745. slot.params[4] = 0.0f; // no damping
  2746. std::vector<float> l (48000, 0.0f), r (48000, 0.0f);
  2747. l[0] = r[0] = 1.0f;
  2748. delay->process (l.data(), r.data(), 48000, slot.params, 120.0);
  2749. CHECK (std::abs (l[24000] - 1.0f) < 1e-4f);
  2750. CHECK (std::abs (l[12000]) < 1e-6f);
  2751. auto reverb = lynx::makeEffect (lynx::EffectKind::reverb);
  2752. reverb->prepare (48000.0);
  2753. auto rs = lynx::makeEffectSlot (lynx::EffectKind::reverb);
  2754. rs.params[3] = 1.0f;
  2755. std::fill (l.begin(), l.end(), 0.0f);
  2756. std::fill (r.begin(), r.end(), 0.0f);
  2757. l[0] = r[0] = 1.0f;
  2758. reverb->process (l.data(), r.data(), 48000, rs.params, 120.0);
  2759. float tail = 0.0f;
  2760. for (int i = 4800; i < 9600; ++i) // between 100 and 200 ms after the impulse
  2761. tail = std::max (tail, std::abs (l[(std::size_t) i]));
  2762. CHECK (tail > 1e-4f && tail < 1.0f);
  2763. CHECK (lynx::formatEffectParam (lynx::EffectKind::delay, 0, slot.params[0], 120.0) == "1/4 (500 ms)");
  2764. }
  2765. TEST (rack_runs_insert_effects_and_reuses_them)
  2766. {
  2767. // an insert with EQ at -inf doesn't exist; we use the EQ output at -18 dB to see the effect act
  2768. const auto quiet = renderMixerCase ([] (lynx::Song& s) {
  2769. auto eq = lynx::makeEffectSlot (lynx::EffectKind::eq);
  2770. eq.params[4] = 0.0f; // output -18 dB
  2771. s.mixer[1].effects.push_back (eq);
  2772. });
  2773. CHECK (quiet > 0.55f && quiet < 0.6f); // 0.5 from channel 2 + 0.5 * 0.126 from channel 1
  2774. const auto bypassed = renderMixerCase ([] (lynx::Song& s) {
  2775. auto eq = lynx::makeEffectSlot (lynx::EffectKind::eq);
  2776. eq.params[4] = 0.0f;
  2777. eq.enabled = false;
  2778. s.mixer[1].effects.push_back (eq);
  2779. });
  2780. CHECK (std::abs (bypassed - 1.0f) < 1e-4f);
  2781. auto s = lynx::Song::makeDefault();
  2782. s.mixer[2].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::reverb));
  2783. auto a = lynx::RackState::build (s, nullptr, 48000.0);
  2784. s.mixer[2].effects[0].params[0] = 0.9f; // turning a knob doesn't recreate the effect
  2785. auto b = lynx::RackState::build (s, a.get(), 48000.0);
  2786. CHECK (b->effects[2][0] == a->effects[2][0]);
  2787. s.mixer[2].effects[0] = lynx::makeEffectSlot (lynx::EffectKind::delay);
  2788. auto c = lynx::RackState::build (s, b.get(), 48000.0);
  2789. CHECK (c->effects[2][0] != b->effects[2][0]);
  2790. }
  2791. TEST (audio_clips_trigger_cut_and_resume)
  2792. {
  2793. lynx::Song s;
  2794. s.bpm = 120.0; // 1 beat = 0.5 s = 24000 samples at 48 kHz
  2795. lynx::ChannelDef c;
  2796. c.instrument = lynx::InstrumentKind::audioClip;
  2797. c.samplePath = "ramp";
  2798. c.volume = 1.0f;
  2799. s.channels.push_back (c);
  2800. s.patterns.emplace_back();
  2801. lynx::Clip clip;
  2802. clip.kind = lynx::ClipKind::audio;
  2803. clip.channel = 0;
  2804. clip.start = lynx::ppq; // starts at beat 2
  2805. clip.length = 2 * lynx::ppq; // lasts 2 beats
  2806. clip.offset = lynx::ppq; // skips the first beat of the audio
  2807. s.playlist.push_back (clip);
  2808. s.mode = lynx::PlayMode::song;
  2809. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  2810. lynx::EventBuffer ev;
  2811. lynx::scheduleSong (s, 0.0, 4 * 24000, tps, ev);
  2812. CHECK (ev.size() == 2);
  2813. CHECK (ev[0].type == lynx::NoteEvent::Type::on && ev[0].sampleOffset == 24000 && std::abs (ev[0].startSeconds - 0.5) < 1e-9);
  2814. CHECK (ev[1].type == lynx::NoteEvent::Type::off && ev[1].sampleOffset == 3 * 24000);
  2815. // seek to the middle of the clip (beat 2.5): with resume, starts at the block's first sample
  2816. ev.clear();
  2817. lynx::scheduleSong (s, 1.5 * lynx::ppq, 256, tps, ev, true);
  2818. CHECK (ev.size() == 1 && ev[0].sampleOffset == 0 && std::abs (ev[0].startSeconds - 0.75) < 1e-9);
  2819. ev.clear();
  2820. lynx::scheduleSong (s, 1.5 * lynx::ppq, 256, tps, ev, false);
  2821. CHECK (ev.size() == 0);
  2822. // sample whose value = position in seconds: lets us check where playback started
  2823. auto provider = [] (const std::string&) {
  2824. auto d = std::make_shared<lynx::SampleData>();
  2825. d->sampleRate = 48000.0;
  2826. for (int i = 0; i < 48000 * 3; ++i)
  2827. d->left.push_back ((float) i / 48000.0f);
  2828. return std::shared_ptr<const lynx::SampleData> (d);
  2829. };
  2830. auto state = lynx::RackState::build (s, nullptr, 48000.0, provider);
  2831. lynx::RackRenderer r;
  2832. r.prepare (48000.0, 512);
  2833. std::vector<float> l (256), rr (256);
  2834. // first block already playing mid-clip
  2835. r.process (state.get(), true, 1.5 * lynx::ppq, 256, l.data(), rr.data());
  2836. CHECK (std::abs (l[0] - 0.75f) < 0.001f);
  2837. // the clip ends at beat 3: after the short fade, silence (the sample would still have audio)
  2838. double tick = 3.0 * lynx::ppq - 10 * tps;
  2839. r.process (state.get(), false, tick, 256, l.data(), rr.data()); // stops (fade)
  2840. for (int i = 0; i < 4; ++i)
  2841. r.process (state.get(), false, tick, 256, l.data(), rr.data());
  2842. CHECK (std::abs (l[255]) < 1e-6f);
  2843. }
  2844. TEST (remove_channel_fixes_notes_and_audio_clips)
  2845. {
  2846. lynx::Song s;
  2847. s.channels.resize (3);
  2848. s.patterns.resize (1);
  2849. s.patterns[0].notes = { { 0, 240, 0, 60, 1.0f }, { 0, 240, 1, 60, 1.0f }, { 0, 240, 2, 60, 1.0f } };
  2850. lynx::Clip a;
  2851. a.kind = lynx::ClipKind::audio;
  2852. a.channel = 1;
  2853. a.length = 100;
  2854. lynx::Clip b = a;
  2855. b.channel = 2;
  2856. s.playlist = { a, b };
  2857. s.removeChannel (1);
  2858. CHECK (s.channels.size() == 2);
  2859. CHECK (s.patterns[0].notes.size() == 2 && s.patterns[0].notes[1].channel == 1);
  2860. CHECK (s.playlist.size() == 1 && s.playlist[0].channel == 1);
  2861. }
  2862. TEST (flp_import_audio_clips_with_offsets)
  2863. {
  2864. flp::Project p;
  2865. p.header.ppq = 96;
  2866. p.tempo = 120.0;
  2867. p.channels = { { 0, flp::ChannelType::audioClip, "Vocal", "", "%FLStudioData%\\v.wav", 2 },
  2868. { 1, flp::ChannelType::audioClip, "Loop", "", "%FLStudioData%\\l.wav", 3 } };
  2869. flp::Arrangement arr;
  2870. flp::PlaylistItem beats; // offset in beats: end - start = duration in beats
  2871. beats.kind = flp::PlaylistItem::Kind::channelClip;
  2872. beats.index = 0;
  2873. beats.position = 192;
  2874. beats.length = 384; // 4 beats
  2875. beats.startOffset = 2.0f;
  2876. beats.endOffset = 6.0f;
  2877. flp::PlaylistItem ms = beats; // offset in ms: 4 beats at 120 BPM = 2000 ms
  2878. ms.index = 1;
  2879. ms.startOffset = 500.0f;
  2880. ms.endOffset = 2500.0f;
  2881. arr.items = { beats, ms };
  2882. p.arrangements.push_back (arr);
  2883. lynx::FlpImportOptions options;
  2884. options.roots = { "C:\\FL", "C:\\FL\\Data", "" };
  2885. options.fileExists = [] (const std::string&) { return true; };
  2886. const auto s = lynx::importFlp (p, options);
  2887. CHECK (s.channels.size() == 2 && s.channels[0].instrument == lynx::InstrumentKind::audioClip);
  2888. CHECK (s.channels[0].samplePath == "C:\\FL\\Data\\v.wav");
  2889. CHECK (s.playlist.size() == 2);
  2890. CHECK (s.playlist[0].kind == lynx::ClipKind::audio && s.playlist[0].start == 2 * lynx::ppq);
  2891. CHECK (s.playlist[0].offset == 2 * lynx::ppq);
  2892. CHECK (s.playlist[1].offset == lynx::ppq); // 500 ms at 120 BPM = 1 beat
  2893. CHECK (s.mode == lynx::PlayMode::song);
  2894. }
  2895. TEST (plugin_factories_create_reuse_and_fallback)
  2896. {
  2897. lynx::Song s;
  2898. s.mixer = lynx::Song::defaultMixer (2);
  2899. lynx::ChannelDef c;
  2900. c.instrument = lynx::InstrumentKind::plugin;
  2901. c.plugin.id = "VST3-Synth-123";
  2902. c.mixerTrack = 1;
  2903. s.channels.push_back (c);
  2904. lynx::ChannelDef missing = c;
  2905. missing.plugin.id = "VST3-Ausente-0";
  2906. s.channels.push_back (missing);
  2907. lynx::EffectSlot fx;
  2908. fx.kind = lynx::EffectKind::plugin;
  2909. fx.plugin.id = "VST3-Reverb-9";
  2910. s.mixer[1].effects.push_back (fx);
  2911. s.patterns.emplace_back();
  2912. int instrumentsMade = 0, effectsMade = 0;
  2913. lynx::RackState::Factories f;
  2914. f.pluginInstruments = [&] (const lynx::PluginRef& ref, double) -> std::shared_ptr<lynx::Instrument> {
  2915. if (ref.id != "VST3-Synth-123")
  2916. return nullptr;
  2917. ++instrumentsMade;
  2918. auto synth = lynx::makeInstrument (lynx::InstrumentKind::synth);
  2919. synth->prepare (48000.0);
  2920. return synth;
  2921. };
  2922. f.pluginEffects = [&] (const lynx::PluginRef&, double) -> std::shared_ptr<lynx::Effect> {
  2923. ++effectsMade;
  2924. auto eq = lynx::makeEffect (lynx::EffectKind::eq);
  2925. eq->prepare (48000.0);
  2926. return eq;
  2927. };
  2928. auto a = lynx::RackState::build (s, nullptr, 48000.0, f);
  2929. CHECK (instrumentsMade == 1 && effectsMade == 1);
  2930. CHECK (a->instruments.size() == 2 && a->instruments[1] != nullptr); // missing: muted, but it exists
  2931. // changing the saved state doesn't recreate; swapping the plugin does
  2932. s.channels[0].plugin.state = "abc";
  2933. auto b = lynx::RackState::build (s, a.get(), 48000.0, f);
  2934. CHECK (instrumentsMade == 1 && b->instruments[0] == a->instruments[0] && b->effects[1][0] == a->effects[1][0]);
  2935. s.mixer[1].effects[0].plugin.id = "VST3-Outro-1";
  2936. auto c2 = lynx::RackState::build (s, b.get(), 48000.0, f);
  2937. CHECK (effectsMade == 2);
  2938. // rendering with a missing plugin and a plugin slot breaks nothing
  2939. lynx::RackRenderer r;
  2940. r.prepare (48000.0, 256);
  2941. lynx::LiveEventQueue live;
  2942. lynx::NoteEvent on;
  2943. on.channel = 0;
  2944. on.velocity = 1.0f;
  2945. live.push (on);
  2946. on.channel = 1;
  2947. live.push (on);
  2948. std::vector<float> l (256), rr (256);
  2949. r.process (c2.get(), false, 0.0, 256, l.data(), rr.data(), &live);
  2950. float peak = 0.0f;
  2951. for (auto v : l)
  2952. {
  2953. CHECK (std::isfinite (v));
  2954. peak = std::max (peak, std::abs (v));
  2955. }
  2956. CHECK (peak > 0.0f);
  2957. }
  2958. TEST (export_song_adds_silent_tail_and_never_restarts)
  2959. {
  2960. auto s = lynx::Song::makeDefault();
  2961. s.playlist.clear();
  2962. std::int64_t length = 0;
  2963. auto pat = lynx::makeExportSong (s, true, lynx::ppq * 8, length); // empty Playlist: uses the pattern
  2964. CHECK (length == lynx::ppq * 4);
  2965. CHECK (pat.mode == lynx::PlayMode::song && pat.playlist.size() == 2);
  2966. CHECK (pat.songLength() >= length + lynx::ppq * 8);
  2967. // no new notes after the song ends, only silence until the end of the tail
  2968. lynx::EventBuffer events;
  2969. const auto tps = lynx::ticksPerSample (pat.bpm, 48000.0);
  2970. int onsAfterEnd = 0, onsBefore = 0;
  2971. for (double tick = 0.0; tick < (double) (length + lynx::ppq * 8); tick += 512 * tps)
  2972. {
  2973. events.clear();
  2974. lynx::scheduleSong (pat, tick, 512, tps, events);
  2975. for (const auto& e : events)
  2976. if (e.type == lynx::NoteEvent::Type::on)
  2977. (tick + e.sampleOffset * tps >= (double) length ? onsAfterEnd : onsBefore)++;
  2978. }
  2979. CHECK (onsBefore == (int) s.patterns[0].notes.size());
  2980. CHECK (onsAfterEnd == 0);
  2981. // with Playlist: the end is the last clip's, without rounding
  2982. s.playlist.push_back ({ 0, 0, lynx::ppq * 2, lynx::ppq * 3, 0 });
  2983. auto song = lynx::makeExportSong (s, true, 0, length);
  2984. CHECK (length == lynx::ppq * 5 && song.playlist.size() == 1);
  2985. song = lynx::makeExportSong (s, false, 0, length);
  2986. CHECK (length == lynx::ppq * 4 && song.playlist[0].start == 0);
  2987. }
  2988. TEST (note_edit_selection_operations)
  2989. {
  2990. namespace ne = lynx::noteedit;
  2991. lynx::Pattern p;
  2992. p.notes = { { 0, 240, 0, 60 }, { 480, 240, 0, 64 }, { 960, 480, 1, 67 } };
  2993. // sorting keeps the indices in step
  2994. p.notes[0].start = 1200;
  2995. std::vector<int> tracked { 0, 2 };
  2996. ne::sortTracking (p, tracked);
  2997. CHECK (p.notes[2].start == 1200 && p.notes[(std::size_t) tracked[0]].start == 1200);
  2998. CHECK (p.notes[(std::size_t) tracked[1]].key == 67);
  2999. // group move respects the limits
  3000. std::int64_t dt = -5000;
  3001. int dk = 100;
  3002. ne::move (p, { 0, 1 }, dt, dk);
  3003. CHECK (dt == -480 && dk == 127 - 67 && p.notes[0].start == 0 && p.notes[1].key == 127);
  3004. // duplicate: right after the selection, rounded to the grid
  3005. lynx::Pattern q;
  3006. q.notes = { { 0, 240, 0, 60 }, { 240, 300, 0, 62 } }; // 540-tick selection
  3007. const auto added = ne::duplicate (q, { 0, 1 }, 960);
  3008. CHECK (added.size() == 2 && q.notes[(std::size_t) added[0]].start == 960 && q.notes[(std::size_t) added[1]].start == 1200);
  3009. // paste onto another channel with an offset
  3010. const auto pasted = ne::paste (q, ne::copy (q, { 1 }), 100, 3);
  3011. CHECK (pasted.size() == 1 && q.notes.back().channel == 3 && q.notes.back().start == 340);
  3012. // quantize rounds to the nearest
  3013. q.notes[0].start = 130;
  3014. q.notes[1].start = 100;
  3015. ne::quantize (q, { 0, 1 }, 240);
  3016. CHECK (q.notes[0].start == 240 && q.notes[1].start == 0);
  3017. // remove several (order and duplicates don't matter)
  3018. const auto before = q.notes.size();
  3019. ne::remove (q, { 1, 0, 1 });
  3020. CHECK (q.notes.size() == before - 2);
  3021. }
  3022. TEST (note_edit_quick_operations)
  3023. {
  3024. namespace ne = lynx::noteedit;
  3025. const std::int64_t step = lynx::ticksPerStep, bar = lynx::ppq * 4;
  3026. // split: only strictly inside; the tail is appended and does not slide again
  3027. lynx::Pattern p;
  3028. p.notes = { { 0, 4 * step, 0, 60 } };
  3029. p.notes[0].slide = true;
  3030. CHECK (ne::split (p, 0, 0) == -1 && ne::split (p, 0, 4 * step) == -1);
  3031. CHECK (ne::split (p, 0, step) == 1 && p.notes[0].length == step && p.notes[1].start == step && p.notes[1].length == 3 * step
  3032. && ! p.notes[1].slide);
  3033. // chop to grid: a 2.5-step note from half a step becomes 3 pieces cut on the step lines
  3034. lynx::Pattern c;
  3035. c.notes = { { step / 2, step * 5 / 2, 0, 60 }, { 0, step, 1, 50 } };
  3036. const auto pieces = ne::chop (c, { 0, 1 }, step);
  3037. CHECK (pieces.size() == 4 && c.notes.size() == 4);
  3038. CHECK (c.notes[0].length == step / 2 && c.notes[2].start == step && c.notes[2].length == step && c.notes[3].start == 2 * step
  3039. && c.notes[3].length == step);
  3040. // join: touching and overlapping notes of the same key and channel merge; others stay
  3041. lynx::Pattern j;
  3042. j.notes = { { 0, step, 0, 60 }, { step, step, 0, 60 }, { step * 3 / 2, step * 2, 0, 60 }, { 5 * step, step, 0, 60 },
  3043. { step, step, 0, 62 }, { step, step, 1, 60 } };
  3044. CHECK (ne::join (j, { 0, 1, 2, 3, 4, 5 }) == 2 && j.notes.size() == 4);
  3045. CHECK (j.notes[0].start == 0 && j.notes[0].length == step * 7 / 2);
  3046. // legato: each note reaches the next start (a chord ends together); the last keeps its length
  3047. lynx::Pattern l;
  3048. l.notes = { { 0, 10, 0, 60 }, { 0, 10, 0, 64 }, { step, 10, 0, 62 }, { 3 * step, 10, 0, 65 }, { step, 10, 1, 40 } };
  3049. ne::legato (l, { 0, 1, 2, 3, 4 });
  3050. CHECK (l.notes[0].length == step && l.notes[1].length == step && l.notes[2].length == 2 * step && l.notes[3].length == 10
  3051. && l.notes[4].length == 10);
  3052. // shrink to grid and full quantise (start and end)
  3053. ne::shrinkToGrid (l, { 3 }, step / 2);
  3054. CHECK (l.notes[3].length == step / 2);
  3055. lynx::Pattern q;
  3056. q.notes = { { 10, step - 30, 0, 60 }, { step + 100, 20, 0, 60 } };
  3057. ne::quantizeFull (q, { 0, 1 }, step);
  3058. CHECK (q.notes[0].start == 0 && q.notes[0].length == step && q.notes[1].start == step && q.notes[1].length == step);
  3059. // rotate inside the bar, wrapping
  3060. lynx::Pattern r;
  3061. r.notes = { { 0, step, 0, 60 }, { bar - step, step, 0, 62 } };
  3062. ne::rotate (r, { 0, 1 }, step, bar, 1);
  3063. CHECK (r.notes[0].start == step && r.notes[1].start == 0);
  3064. ne::rotate (r, { 0, 1 }, step, bar, -2);
  3065. CHECK (r.notes[0].start == bar - step && r.notes[1].start == bar - 2 * step);
  3066. r.notes.push_back ({ bar + step, step, 0, 64 }); // alone in the second bar: wraps inside that bar
  3067. ne::rotate (r, { 2 }, step, bar, -2);
  3068. CHECK (r.notes[2].start == 2 * bar - step);
  3069. }
  3070. TEST (note_edit_grid_and_time_text)
  3071. {
  3072. namespace ne = lynx::noteedit;
  3073. const std::int64_t step = lynx::ticksPerStep, bar = lynx::ppq * 4;
  3074. CHECK (ne::snapDown (250.0, step) == step && ne::snapDown (-1.0, step) == -step && ne::snapDown (17.9, 1) == 17);
  3075. CHECK (ne::snapNearest (1000.0, { 400, 1100, 980 }, 50.0, step) == 980);
  3076. CHECK (ne::snapNearest (1000.0, { 400 }, 50.0, step) == 960); // too far: falls back to the grid
  3077. // screen grid: 24 px per step shows steps; zoomed out it climbs to beats, bars and bar multiples
  3078. CHECK (ne::screenStep (24.0 / step, bar) == step);
  3079. CHECK (ne::screenStep (96.0 / bar, bar) == lynx::ppq);
  3080. CHECK (ne::screenStep (8.0 / bar, bar) == 2 * bar);
  3081. CHECK (ne::screenStep (200.0 / step, bar) == step / 4);
  3082. CHECK (ne::formatTime (0, 4) == "1:1:0" && ne::formatTime (bar + 5 * step + 7, 4) == "2:6:7");
  3083. CHECK (ne::formatTime (step * 2, 4, true) == "0:2:0");
  3084. std::int64_t t = 0;
  3085. CHECK (ne::parseTime ("2:6:7", 4, t) && t == bar + 5 * step + 7);
  3086. CHECK (ne::parseTime ("3", 4, t) && t == 2 * bar);
  3087. CHECK (ne::parseTime ("0:2:0", 4, t, true) && t == 2 * step);
  3088. CHECK (! ne::parseTime ("0:1:0", 4, t) && ! ne::parseTime ("1:17:0", 4, t) && ! ne::parseTime ("1:1:240", 4, t)
  3089. && ! ne::parseTime ("a", 4, t) && ! ne::parseTime ("", 4, t));
  3090. CHECK (ne::parseTime ("1:12:0", 3, t) && ! ne::parseTime ("1:13:0", 3, t)); // 3/4: 12 steps per bar
  3091. }
  3092. TEST (playlist_clip_edges_and_time_selection)
  3093. {
  3094. namespace ne = lynx::noteedit;
  3095. const std::int64_t beat = lynx::ppq;
  3096. // left-edge trim: content stays in place, cannot reveal what is before the content's start
  3097. lynx::Clip c { 0, 0, 4 * beat, 4 * beat, beat };
  3098. ne::trimStart (c, 5 * beat, beat);
  3099. CHECK (c.start == 5 * beat && c.offset == 2 * beat && c.length == 3 * beat);
  3100. ne::trimStart (c, 0, beat);
  3101. CHECK (c.start == 3 * beat && c.offset == 0 && c.length == 5 * beat);
  3102. ne::trimStart (c, 100 * beat, beat);
  3103. CHECK (c.length == beat && c.end() == 8 * beat);
  3104. // slip moves the content, not the clip
  3105. lynx::Clip s { 0, 0, 0, 2 * beat, beat };
  3106. ne::slip (s, beat / 2);
  3107. CHECK (s.offset == beat / 2 && s.start == 0 && s.length == 2 * beat);
  3108. ne::slip (s, beat);
  3109. CHECK (s.offset == 0);
  3110. ne::slip (s, -3 * beat);
  3111. CHECK (s.offset == 3 * beat);
  3112. // insert / delete time across all tracks, markers included
  3113. std::vector<lynx::Clip> clips { { 0, 0, 0, 2 * beat, 0 }, { 0, 1, 4 * beat, 2 * beat, 0 }, { 0, 2, beat, 6 * beat, 0 } };
  3114. std::vector<lynx::Marker> markers { { 5 * beat, "A" }, { beat / 2, "B" } };
  3115. ne::insertTime (clips, markers, 2 * beat, 4 * beat);
  3116. CHECK (clips[0].start == 0 && clips[1].start == 8 * beat && clips[2].start == beat && markers[0].tick == 9 * beat
  3117. && markers[1].tick == beat / 2);
  3118. std::vector<lynx::Clip> d { { 0, 0, 0, 2 * beat, 0 }, // before: kept
  3119. { 0, 1, 3 * beat, beat, 0 }, // inside: deleted
  3120. { 0, 2, beat, 6 * beat, 0 }, // spans the cut: head + tail
  3121. { 0, 3, 3 * beat, 4 * beat, 0 }, // tail outside: trimmed and moved
  3122. { 0, 4, 8 * beat, beat, 0 } }; // after: moved left
  3123. std::vector<lynx::Marker> dm { { 3 * beat, "in" }, { 9 * beat, "after" } };
  3124. ne::deleteTime (d, dm, 2 * beat, 5 * beat);
  3125. CHECK (d.size() == 5);
  3126. CHECK (d[1].track == 2 && d[1].start == beat && d[1].length == beat);
  3127. CHECK (d[2].track == 2 && d[2].start == 2 * beat && d[2].offset == 4 * beat && d[2].length == 2 * beat);
  3128. CHECK (d[3].track == 3 && d[3].start == 2 * beat && d[3].offset == 2 * beat && d[3].length == 2 * beat);
  3129. CHECK (d[4].start == 5 * beat && dm.size() == 1 && dm[0].tick == 6 * beat);
  3130. // time selection: overlapping clips; Ctrl+B repeats what starts inside it after itself
  3131. std::vector<lynx::Clip> r { { 0, 0, 0, beat, 0 }, { 0, 1, beat, 2 * beat, 0 }, { 0, 0, 4 * beat, beat, 0 } };
  3132. CHECK ((ne::clipsInTime (r, beat / 2, 2 * beat) == std::vector<int> { 0, 1 }));
  3133. const auto added = ne::repeatTime (r, 0, 4 * beat, {});
  3134. CHECK (added.size() == 2 && r[3].start == 4 * beat && r[4].start == 5 * beat && r[4].track == 1);
  3135. CHECK (ne::repeatTime (r, 0, 2 * beat, { 2 }).size() == 1 && r.back().start == 6 * beat);
  3136. }
  3137. TEST (recorder_builds_notes_in_pattern_and_song_mode)
  3138. {
  3139. auto song = lynx::Song::makeDefault();
  3140. const auto loop = song.patterns[0].effectiveLength (4); // 1 bar = 3840
  3141. lynx::NoteRecorder r;
  3142. r.add (song, { 100.0, 4, 60, 0.5f, true }); // no take: ignored
  3143. CHECK (r.takeFinished().empty());
  3144. r.begin (loop);
  3145. r.add (song, { 4000.0, 4, 60, 0.5f, true }); // second loop pass
  3146. r.add (song, { 4480.0, 4, 60, 0.0f, false });
  3147. r.add (song, { 5000.0, 4, 64, 0.9f, true }); // held until stop
  3148. r.end (song, 5240.0);
  3149. const auto notes = r.takeFinished();
  3150. CHECK (notes.size() == 2);
  3151. CHECK (notes[0].start == 4000 - 3840 && notes[0].length == 480 && notes[0].velocity == 0.5f && notes[0].channel == 4);
  3152. CHECK (notes[1].key == 64 && notes[1].start == 5000 - 3840 && notes[1].length == 240);
  3153. // song mode: position inside the current pattern's clip (with offset)
  3154. song.mode = lynx::PlayMode::song;
  3155. song.playlist = { { 0, 0, 7680, 3840, 960 } };
  3156. CHECK (lynx::patternPositionForTick (song, 7680.0 + 100.0, loop) == 1060);
  3157. CHECK (lynx::patternPositionForTick (song, 100.0, loop) == 100); // outside the clip: like loop
  3158. }
  3159. TEST (automation_curve_and_playback)
  3160. {
  3161. lynx::Automation a;
  3162. a.points = { { 0, 0.0f }, { 960, 1.0f }, { 1920, 0.5f, 0.0f } };
  3163. CHECK (a.valueAt (-10.0) == 0.0f && a.valueAt (480.0) == 0.5f && a.valueAt (5000.0) == 0.5f);
  3164. CHECK (a.length() == 1920);
  3165. a.points[0].tension = 1.0f; // curve: starts slow
  3166. CHECK (a.valueAt (480.0) < 0.2f && a.valueAt (480.0) > 0.0f);
  3167. // automated Master: silence in the first bar, sound in the second, and the last value
  3168. // keeps applying after the automation clip ends
  3169. auto song = lynx::Song::makeDefault();
  3170. song.bpm = 120.0;
  3171. song.mode = lynx::PlayMode::song;
  3172. const auto bar = (std::int64_t) lynx::ppq * 4;
  3173. for (int b = 0; b < 3; ++b)
  3174. song.playlist.push_back ({ 0, 0, bar * b, bar, 0 });
  3175. lynx::Automation master;
  3176. master.target = { lynx::AutomationTargetKind::mixerVolume, 0 };
  3177. master.points = { { 0, 0.0f }, { bar - 1, 0.0f }, { bar, 0.8f } };
  3178. song.automations.push_back (master);
  3179. lynx::Clip ac;
  3180. ac.kind = lynx::ClipKind::automation;
  3181. ac.automation = 0;
  3182. ac.track = 1;
  3183. ac.length = bar + bar / 2;
  3184. song.playlist.push_back (ac);
  3185. const double sr = 48000.0;
  3186. auto state = lynx::RackState::build (song, nullptr, sr);
  3187. CHECK (state->hasAutomation && state->mixerVolumeAuto[0] == 0 && state->automationClips[0].size() == 1);
  3188. lynx::RackRenderer r;
  3189. r.prepare (sr, 512);
  3190. std::vector<float> l (512), rr (512);
  3191. const auto tps = lynx::ticksPerSample (song.bpm, sr);
  3192. float peakBar1 = 0.0f, peakBar2 = 0.0f, peakBar3 = 0.0f;
  3193. for (double tick = 0.0; tick < (double) (bar * 3); tick += 512 * tps)
  3194. {
  3195. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  3196. auto& peak = tick < (double) bar - 512 * tps ? peakBar1 : tick < (double) bar * 2 ? peakBar2 : peakBar3;
  3197. for (auto v : l)
  3198. peak = std::max (peak, std::abs (v));
  3199. }
  3200. CHECK (peakBar1 < 1.0e-6f);
  3201. CHECK (peakBar2 > 0.05f);
  3202. CHECK (peakBar3 > 0.05f); // after the clip: keeps the last value
  3203. // target removed: automation disappears from the tables
  3204. song.removeChannel (0);
  3205. song.automations[0].target = { lynx::AutomationTargetKind::channelVolume, 0 };
  3206. song.removeChannel (0);
  3207. CHECK (song.automations[0].target.kind == lynx::AutomationTargetKind::none);
  3208. song.removeAutomation (0);
  3209. CHECK (song.automations.empty() && song.playlist.size() == 3);
  3210. }
  3211. TEST (mixer_sends_between_inserts)
  3212. {
  3213. // insert 1 goes only to 3; 3 goes to the Master: same sum (0.5 + 0.5)
  3214. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.setRoute (1, 3, true); s.setRoute (1, 0, false); }) - 1.0f) < 1e-4f);
  3215. // send at 50% and muted destination
  3216. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.setRoute (1, 3, true, 0.5f); s.setRoute (1, 0, false); }) - 0.75f) < 1e-4f);
  3217. 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);
  3218. // going to the Master and to 3: the signal doubles
  3219. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.setRoute (1, 3, true); }) - 1.5f) < 1e-4f);
  3220. // solo on 3 lets what reaches it sound (insert 1), but not 2
  3221. 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);
  3222. // solo on 1 lets the path to the Master (3) sound
  3223. 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);
  3224. // order and cycles
  3225. auto song = lynx::Song::makeDefault();
  3226. song.setRoute (4, 2, true);
  3227. song.setRoute (2, 1, true);
  3228. CHECK (! song.canRoute (1, 4) && ! song.canRoute (1, 2) && song.canRoute (1, 5));
  3229. song.setRoute (1, 4, true); // ignored: would create a cycle
  3230. CHECK (! song.routes (1, 4));
  3231. const auto order = song.mixerOrder();
  3232. const auto pos = [&] (int t) { return std::find (order.begin(), order.end(), t) - order.begin(); };
  3233. CHECK ((int) order.size() == (int) song.mixer.size() - 1);
  3234. CHECK (pos (4) < pos (2) && pos (2) < pos (1));
  3235. song.setRoute (4, 2, false);
  3236. CHECK (! song.routes (4, 2) && song.routes (4, 0));
  3237. }
  3238. namespace
  3239. {
  3240. // Test effect: delays the signal by `latency` samples and reports that latency (like a lookahead plugin).
  3241. class LatentEffect final : public lynx::Effect
  3242. {
  3243. public:
  3244. explicit LatentEffect (int samples) : latency (samples), line (samples) {}
  3245. void prepare (double) noexcept override {}
  3246. void reset() noexcept override {}
  3247. void process (float* l, float* r, int n, const lynx::EffectParams&, double) noexcept override { line.process (l, r, n); }
  3248. int latencySamples() const noexcept override { return latency; }
  3249. private:
  3250. int latency;
  3251. lynx::DelayLine line;
  3252. };
  3253. } // namespace
  3254. TEST (delay_line_mix_into_matches_process_and_drains_tail)
  3255. {
  3256. // mixInto = process over source*level, added to the destination; in stretches that cross the ring
  3257. lynx::DelayLine a (37), b (37);
  3258. std::vector<float> sl (300), sr (300), dl (300, 0.5f), dr (300, -0.5f), xl (300), xr (300);
  3259. for (int i = 0; i < 300; ++i)
  3260. {
  3261. sl[(std::size_t) i] = (float) std::sin (i * 0.1);
  3262. sr[(std::size_t) i] = (float) std::cos (i * 0.07);
  3263. }
  3264. for (int start = 0; start < 300; start += 100)
  3265. {
  3266. b.mixInto (sl.data() + start, sr.data() + start, 0.25f, dl.data() + start, dr.data() + start, 100);
  3267. for (int i = start; i < start + 100; ++i)
  3268. {
  3269. xl[(std::size_t) i] = sl[(std::size_t) i] * 0.25f;
  3270. xr[(std::size_t) i] = sr[(std::size_t) i] * 0.25f;
  3271. }
  3272. a.process (xl.data() + start, xr.data() + start, 100);
  3273. }
  3274. float worst = 0.0f;
  3275. for (int i = 0; i < 300; ++i)
  3276. worst = std::max ({ worst, std::abs (dl[(std::size_t) i] - 0.5f - xl[(std::size_t) i]),
  3277. std::abs (dr[(std::size_t) i] + 0.5f - xr[(std::size_t) i]) });
  3278. CHECK (worst < 1e-6f);
  3279. // silenced source: the tail still in the line comes out, then nothing remains
  3280. std::vector<float> tl (64, 0.0f), tr (64, 0.0f);
  3281. b.mixInto (nullptr, nullptr, 1.0f, tl.data(), tr.data(), 64);
  3282. CHECK (std::abs (tl[0] - sl[263] * 0.25f) < 1e-6f);
  3283. std::vector<float> zl (64, 0.0f), zr (64, 0.0f);
  3284. b.mixInto (nullptr, nullptr, 1.0f, zl.data(), zr.data(), 64);
  3285. CHECK (*std::max_element (zl.begin(), zl.end()) == 0.0f && *std::min_element (zl.begin(), zl.end()) == 0.0f);
  3286. }
  3287. TEST (limiter_lookahead_holds_ceiling_on_bursts)
  3288. {
  3289. // short bursts over a low floor: the sliding maximum must see each peak before it leaves
  3290. auto fx = lynx::makeEffect (lynx::EffectKind::limiter);
  3291. fx->prepare (48000.0);
  3292. auto slot = lynx::makeEffectSlot (lynx::EffectKind::limiter);
  3293. slot.params[2] = 0.0f; // 10 ms release
  3294. std::vector<float> l (48000), r (48000);
  3295. std::uint32_t seed = 1;
  3296. for (int i = 0; i < 48000; ++i)
  3297. {
  3298. seed = seed * 1664525u + 1013904223u;
  3299. const auto noise = ((float) (seed >> 8) / 16777216.0f - 0.5f) * 0.1f;
  3300. l[(std::size_t) i] = noise + ((i % 9973) < 3 ? 3.0f : 0.0f);
  3301. r[(std::size_t) i] = -noise;
  3302. }
  3303. for (int i = 0; i < 48000; i += 333)
  3304. fx->process (l.data() + i, r.data() + i, std::min (333, 48000 - i), slot.params, 120.0);
  3305. float peak = 0.0f, quiet = 0.0f;
  3306. for (int i = 0; i < 48000; ++i)
  3307. peak = std::max (peak, std::abs (l[(std::size_t) i]));
  3308. for (int i = 9973 * 2 + 2000; i < 9973 * 2 + 2400; ++i) // 40 ms after the burst the gain has already recovered
  3309. quiet = std::max (quiet, std::abs (r[(std::size_t) i]));
  3310. const auto ceiling = 1.0f; // the default ceiling is at 0 dBFS or below
  3311. CHECK (peak <= ceiling + 1e-5f);
  3312. CHECK (quiet > 0.03f);
  3313. }
  3314. TEST (pdc_aligns_paths_through_latent_effects)
  3315. {
  3316. // plan: channel 0 -> insert 1 (effect of 100) -> insert 3; channel 1 -> insert 2 -> Master
  3317. lynx::Song s;
  3318. s.mixer = lynx::Song::defaultMixer (4);
  3319. s.channels.resize (3);
  3320. s.channels[0].mixerTrack = 1;
  3321. s.channels[1].mixerTrack = 2;
  3322. s.channels[2].mixerTrack = 3;
  3323. s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::eq));
  3324. s.setRoute (1, 3, true);
  3325. s.setRoute (1, 0, false);
  3326. auto plan = lynx::computePdc (s, { 0, 0, 30 }, { {}, { 100 } });
  3327. CHECK (plan.inAlign[1] == 0 && plan.outLat[1] == 100);
  3328. CHECK (plan.inAlign[3] == 100 && plan.channelDelay[2] == 70); // instrument of 30 on insert 3
  3329. CHECK (plan.sendDelay[1][1] == 0); // the slowest path isn't delayed
  3330. CHECK (plan.sendDelay[2][0] == 100 && plan.sendDelay[3][0] == 0 && plan.total == 100);
  3331. // bypass zeroes the slot's latency
  3332. s.mixer[1].effects[0].enabled = false;
  3333. CHECK (lynx::computePdc (s, { 0, 0, 30 }, { {}, { 100 } }).total == 30);
  3334. // rendered: two impulses played together come out together
  3335. lynx::Song r;
  3336. r.mixer = lynx::Song::defaultMixer (2);
  3337. for (int i = 0; i < 2; ++i)
  3338. {
  3339. lynx::ChannelDef c;
  3340. c.instrument = lynx::InstrumentKind::sampler;
  3341. c.samplePath = "impulso";
  3342. c.volume = 1.0f;
  3343. c.mixerTrack = i + 1;
  3344. r.channels.push_back (c);
  3345. }
  3346. r.patterns.emplace_back();
  3347. lynx::EffectSlot fx;
  3348. fx.kind = lynx::EffectKind::plugin;
  3349. fx.plugin.id = "latente";
  3350. r.mixer[1].effects.push_back (fx);
  3351. lynx::RackState::Factories f;
  3352. f.samples = [] (const std::string&) {
  3353. auto d = std::make_shared<lynx::SampleData>();
  3354. d->left.assign (64, 0.0f);
  3355. d->left[0] = 1.0f;
  3356. return std::shared_ptr<const lynx::SampleData> (d);
  3357. };
  3358. f.pluginEffects = [] (const lynx::PluginRef&, double) -> std::shared_ptr<lynx::Effect> { return std::make_shared<LatentEffect> (100); };
  3359. auto state = lynx::RackState::build (r, nullptr, 48000.0, f);
  3360. CHECK (state->pdc.total == 100 && state->sendDelays[2][0] != nullptr && state->sendDelays[2][0]->length() == 100);
  3361. lynx::RackRenderer renderer;
  3362. renderer.prepare (48000.0, 256);
  3363. lynx::LiveEventQueue live;
  3364. for (int ch = 0; ch < 2; ++ch)
  3365. {
  3366. lynx::NoteEvent on;
  3367. on.channel = ch;
  3368. on.key = 60;
  3369. on.velocity = 1.0f;
  3370. live.push (on);
  3371. }
  3372. std::vector<float> l (256), rr (256);
  3373. renderer.process (state.get(), false, 0.0, 256, l.data(), rr.data(), &live);
  3374. int first = -1;
  3375. for (int i = 0; i < 256 && first < 0; ++i)
  3376. if (std::abs (l[(std::size_t) i]) > 0.01f)
  3377. first = i;
  3378. CHECK (first == 100 && std::abs (l[100] - 2.0f) < 1e-3f); // both impulses arrive together, summed
  3379. // editing without changing latencies reuses the lines
  3380. r.channels[0].volume = 0.5f;
  3381. auto next = lynx::RackState::build (r, state.get(), 48000.0, f);
  3382. CHECK (next->sendDelays[2][0] == state->sendDelays[2][0]);
  3383. }
  3384. TEST (mixer_mute_fades_instead_of_clicking)
  3385. {
  3386. lynx::Song s;
  3387. s.mixer = lynx::Song::defaultMixer (2);
  3388. lynx::ChannelDef c;
  3389. c.instrument = lynx::InstrumentKind::sampler;
  3390. c.samplePath = "dc";
  3391. c.volume = 1.0f;
  3392. c.mixerTrack = 1;
  3393. s.channels.push_back (c);
  3394. s.patterns.emplace_back();
  3395. auto provider = [] (const std::string&) {
  3396. auto d = std::make_shared<lynx::SampleData>();
  3397. d->left.assign (48000, 0.5f);
  3398. return std::shared_ptr<const lynx::SampleData> (d);
  3399. };
  3400. auto on = lynx::RackState::build (s, nullptr, 48000.0, provider);
  3401. s.mixer[1].muted = true;
  3402. auto off = lynx::RackState::build (s, on.get(), 48000.0, provider);
  3403. lynx::RackRenderer r;
  3404. r.prepare (48000.0, 256);
  3405. lynx::LiveEventQueue live;
  3406. lynx::NoteEvent note;
  3407. note.velocity = 1.0f;
  3408. live.push (note);
  3409. std::vector<float> l (256), rr (256);
  3410. r.process (on.get(), false, 0.0, 256, l.data(), rr.data(), &live);
  3411. CHECK (std::abs (l[255] - 0.5f) < 1e-3f);
  3412. r.process (off.get(), false, 0.0, 256, l.data(), rr.data());
  3413. CHECK (l[0] > 0.45f && l[128] > 0.2f && l[128] < 0.3f && std::abs (l[255]) < 1e-6f); // ramp down to zero
  3414. r.process (off.get(), false, 0.0, 256, l.data(), rr.data());
  3415. CHECK (std::abs (l[0]) < 1e-9f);
  3416. }
  3417. TEST (dither_quantizes_to_lsb_grid_with_small_error)
  3418. {
  3419. lynx::Dither d (16);
  3420. std::vector<float> x (4800);
  3421. for (std::size_t i = 0; i < x.size(); ++i)
  3422. x[i] = 0.25f * std::sin ((float) i * 0.05f);
  3423. auto y = x;
  3424. d.process (y.data(), (int) y.size(), 0);
  3425. double errorSum = 0.0;
  3426. bool onGrid = true;
  3427. for (std::size_t i = 0; i < x.size(); ++i)
  3428. {
  3429. const auto steps = y[i] * 32768.0f;
  3430. onGrid = onGrid && std::abs (steps - std::round (steps)) < 1e-3f;
  3431. errorSum += std::abs (y[i] - x[i]);
  3432. }
  3433. CHECK (onGrid);
  3434. CHECK (errorSum / (double) x.size() < 4.0 / 32768.0); // a few LSBs of noise on average
  3435. }
  3436. TEST (parallel_rendering_matches_sequential)
  3437. {
  3438. // 32 channels (worth parallelizing), inserts with chained sends
  3439. auto song = lynx::Song::makeDefault();
  3440. song.mixer = lynx::Song::defaultMixer (16);
  3441. for (int i = 5; i < 32; ++i)
  3442. {
  3443. lynx::ChannelDef c;
  3444. c.instrument = i % 2 ? lynx::InstrumentKind::synth : lynx::InstrumentKind::hat;
  3445. c.mixerTrack = 1 + i % 12;
  3446. c.volume = 0.3f;
  3447. song.channels.push_back (c);
  3448. for (int step = i % 4; step < 16; step += 3)
  3449. song.patterns[0].notes.push_back ({ (std::int64_t) step * lynx::ticksPerStep, 200, i, 48 + i, 0.7f });
  3450. }
  3451. song.patterns[0].sortNotes();
  3452. song.setRoute (3, 7, true, 0.6f);
  3453. song.setRoute (7, 9, true, 0.5f);
  3454. song.setRoute (2, 9, true);
  3455. song.mixer[9].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::reverb));
  3456. auto seqState = lynx::RackState::build (song, nullptr, 48000.0);
  3457. auto parState = lynx::RackState::build (song, nullptr, 48000.0);
  3458. CHECK (parState->parallel && parState->mixerLayers.size() == 3);
  3459. lynx::WorkerPool pool (3);
  3460. lynx::RackRenderer seq, par;
  3461. seq.prepare (48000.0, 512);
  3462. par.prepare (48000.0, 512);
  3463. par.setWorkerPool (&pool);
  3464. std::vector<float> l1 (512), r1 (512), l2 (512), r2 (512);
  3465. const auto tps = lynx::ticksPerSample (song.bpm, 48000.0);
  3466. bool same = true;
  3467. float peak = 0.0f;
  3468. for (int block = 0; block < 200; ++block)
  3469. {
  3470. seq.process (seqState.get(), true, block * 512 * tps, 512, l1.data(), r1.data());
  3471. par.process (parState.get(), true, block * 512 * tps, 512, l2.data(), r2.data());
  3472. same = same && l1 == l2 && r1 == r2;
  3473. for (auto v : l1)
  3474. peak = std::max (peak, std::abs (v));
  3475. }
  3476. CHECK (same);
  3477. CHECK (peak > 0.05f);
  3478. // the pool handles many small rounds in a row
  3479. std::atomic<int> sum { 0 };
  3480. auto add = [&sum] (int i) { sum.fetch_add (i + 1); };
  3481. for (int round = 0; round < 2000; ++round)
  3482. pool.parallelFor (5, add);
  3483. CHECK (sum.load() == 2000 * 15);
  3484. }
  3485. TEST (arrangements_switch_and_keep_clip_indices)
  3486. {
  3487. auto s = lynx::Song::makeDefault();
  3488. s.patterns.emplace_back().name = "B";
  3489. s.playlist = { { 1, 0, 0, 960, 0 } };
  3490. s.loopEnd = 960;
  3491. CHECK (s.arrangements.size() == 1 && s.currentArrangement == 0);
  3492. const auto second = s.addArrangement ("Versão curta", true);
  3493. CHECK (second == 1 && s.currentArrangement == 1 && s.playlist.size() == 1 && s.loopEnd == 960);
  3494. s.playlist.push_back ({ 0, 1, 960, 960, 0 });
  3495. s.loopEnd = 0;
  3496. s.selectArrangement (0);
  3497. CHECK (s.playlist.size() == 1 && s.loopEnd == 960 && s.arrangements[1].clips.size() == 2);
  3498. // removing pattern 0 fixes the clips stored in the other arrangement
  3499. s.removePattern (0);
  3500. CHECK (s.playlist.size() == 1 && s.playlist[0].pattern == 0);
  3501. CHECK (s.arrangements[1].clips.size() == 1 && s.arrangements[1].clips[0].pattern == 0);
  3502. s.removeArrangement (0);
  3503. CHECK (s.arrangements.size() == 1 && s.currentArrangement == 0 && s.playlist.size() == 1 && s.loopEnd == 0);
  3504. }
  3505. namespace
  3506. {
  3507. // Test effect that inverts the signal and counts how many times it processed.
  3508. class CountingInverter final : public lynx::Effect
  3509. {
  3510. public:
  3511. void prepare (double) noexcept override {}
  3512. void reset() noexcept override {}
  3513. void process (float* l, float* r, int n, const lynx::EffectParams&, double) noexcept override
  3514. {
  3515. ++calls;
  3516. for (int i = 0; i < n; ++i)
  3517. {
  3518. l[i] = -l[i];
  3519. r[i] = -r[i];
  3520. }
  3521. }
  3522. int calls = 0;
  3523. };
  3524. } // namespace
  3525. TEST (keyboard_controller_outputs_key_value)
  3526. {
  3527. std::vector<std::uint8_t> blob (554, 0);
  3528. const std::uint32_t version = 3;
  3529. std::memcpy (blob.data(), &version, 4);
  3530. const float key60 = 0.7f, off = 0.2f;
  3531. std::memcpy (blob.data() + 12 + 60 * 4, &key60, 4);
  3532. std::memcpy (blob.data() + 548, &off, 4);
  3533. blob[552] = 1; // auto release
  3534. lynx::ChannelDef c;
  3535. c.instrument = lynx::InstrumentKind::controller;
  3536. c.controllerState = blob;
  3537. auto inst = lynx::makeInstrument (lynx::InstrumentKind::controller);
  3538. inst->prepare (48000.0);
  3539. inst->configure (c, 120.0);
  3540. std::vector<float> l (64), r (64);
  3541. inst->noteOn (60, 1.0f);
  3542. inst->render (l.data(), r.data(), 64, 1.0f, 1.0f);
  3543. CHECK (std::abs (inst->controlOutput (0) - 0.7f) < 1e-6f);
  3544. inst->noteOff (60);
  3545. CHECK (std::abs (inst->controlOutput (0) - 0.2f) < 1e-6f);
  3546. }
  3547. TEST (envelope_controller_ducks_on_each_note)
  3548. {
  3549. // a unipolar articulator like "Basic Sidechain": base 0.05, drops to 0 on the note and rises to 1 in 0.3 s
  3550. lynx::ControllerArticulator a;
  3551. a.envOn = true;
  3552. a.base = 0.05f;
  3553. a.envLevel = 1.0f;
  3554. a.count = 3;
  3555. a.time = { 0.0f, 0.2f, 0.3f };
  3556. a.level = { 0.0f, 0.75f, 1.0f };
  3557. CHECK (std::abs (lynx::controllerValue (a, 0.0, -1.0) - 0.05f) < 1e-4f);
  3558. CHECK (std::abs (lynx::controllerValue (a, 0.1, -1.0) - 0.425f) < 1e-3f);
  3559. CHECK (lynx::controllerValue (a, 1.0, -1.0) > 0.99f); // no sustain: runs to the end and stays
  3560. a.sustain = 1;
  3561. CHECK (std::abs (lynx::controllerValue (a, 1.0, -1.0) - 0.8f) < 1e-3f); // held at sustain
  3562. CHECK (lynx::controllerValue (a, 1.0, 0.5) > 0.99f); // released: continues to the end
  3563. a.bipolar = true;
  3564. a.base = 0.5f;
  3565. a.sustain = -1;
  3566. CHECK (std::abs (lynx::controllerValue (a, 0.0, -1.0) - 0.0f) < 1e-4f); // bipolar: 0.5 + (0 − 0.5)
  3567. }
  3568. TEST (peak_controller_drives_live_automation)
  3569. {
  3570. // track 1: source (DC 0.5) with Peak Controller; track 2: DC 0.5 with volume linked to the controller
  3571. auto render = [] (bool linked) {
  3572. lynx::Song s;
  3573. s.mixer = lynx::Song::defaultMixer (2);
  3574. for (int t = 1; t <= 2; ++t)
  3575. {
  3576. lynx::ChannelDef c;
  3577. c.instrument = lynx::InstrumentKind::sampler;
  3578. c.samplePath = "dc";
  3579. c.volume = 1.0f;
  3580. c.mixerTrack = t;
  3581. s.channels.push_back (c);
  3582. }
  3583. s.patterns.emplace_back();
  3584. auto peak = lynx::makeEffectSlot (lynx::EffectKind::peakController);
  3585. peak.params[0] = 1.0f; // base 1
  3586. peak.params[1] = 0.0f; // amount −1: 1 − peak
  3587. peak.params[2] = 0.5f; // no tension
  3588. s.mixer[1].effects.push_back (peak);
  3589. if (linked)
  3590. {
  3591. lynx::Automation a;
  3592. a.name = "Peak";
  3593. a.target = { lynx::AutomationTargetKind::mixerVolume, 2 };
  3594. a.source = { 1, 0, 0 };
  3595. s.automations.push_back (a);
  3596. }
  3597. lynx::RackState::Factories f;
  3598. f.samples = [] (const std::string&) {
  3599. auto d = std::make_shared<lynx::SampleData>();
  3600. d->left.assign (48000, 0.5f);
  3601. return std::shared_ptr<const lynx::SampleData> (d);
  3602. };
  3603. auto state = lynx::RackState::build (s, nullptr, 48000.0, f);
  3604. lynx::RackRenderer r;
  3605. r.prepare (48000.0, 512);
  3606. lynx::LiveEventQueue live;
  3607. for (int ch = 0; ch < 2; ++ch)
  3608. {
  3609. lynx::NoteEvent on;
  3610. on.channel = ch;
  3611. on.velocity = 1.0f;
  3612. live.push (on);
  3613. }
  3614. std::vector<float> l (4800), rr (4800);
  3615. r.process (state.get(), false, 0.0, 4800, l.data(), rr.data(), &live);
  3616. return l[4000];
  3617. };
  3618. const auto free = render (false), ducked = render (true);
  3619. CHECK (std::isfinite (ducked) && ducked > 0.0f);
  3620. CHECK (ducked < free - 0.05f); // the 0.5 peak on track 1 lowers track 2's volume
  3621. }
  3622. TEST (effect_slot_dry_wet_and_smart_disable)
  3623. {
  3624. lynx::Song s;
  3625. s.mixer = lynx::Song::defaultMixer (1);
  3626. lynx::ChannelDef c;
  3627. c.instrument = lynx::InstrumentKind::sampler;
  3628. c.samplePath = "dc";
  3629. c.volume = 1.0f;
  3630. c.mixerTrack = 1;
  3631. s.channels.push_back (c);
  3632. s.patterns.emplace_back();
  3633. lynx::EffectSlot fx;
  3634. fx.kind = lynx::EffectKind::plugin;
  3635. fx.plugin.id = "inversor";
  3636. fx.mix = 0.25f; // 75% dry (+0.5) and 25% wet (-0.5) = +0.25
  3637. s.mixer[1].effects.push_back (fx);
  3638. auto inverter = std::make_shared<CountingInverter>();
  3639. lynx::RackState::Factories f;
  3640. f.samples = [] (const std::string&) {
  3641. auto d = std::make_shared<lynx::SampleData>();
  3642. d->left.assign (4800, 0.5f);
  3643. return std::shared_ptr<const lynx::SampleData> (d);
  3644. };
  3645. f.pluginEffects = [inverter] (const lynx::PluginRef&, double) -> std::shared_ptr<lynx::Effect> { return inverter; };
  3646. auto state = lynx::RackState::build (s, nullptr, 48000.0, f);
  3647. lynx::RackRenderer r;
  3648. r.prepare (48000.0, 512);
  3649. lynx::LiveEventQueue live;
  3650. lynx::NoteEvent on;
  3651. on.velocity = 1.0f;
  3652. live.push (on);
  3653. std::vector<float> l (480), rr (480);
  3654. r.process (state.get(), false, 0.0, 480, l.data(), rr.data(), &live);
  3655. CHECK (std::abs (l[100] - 0.25f) < 1e-4f);
  3656. // after the sample ends: 4 s of silence and the plugin stops being called
  3657. for (int i = 0; i < 100 * 6; ++i) // 6 s
  3658. r.process (state.get(), false, 0.0, 480, l.data(), rr.data());
  3659. const auto callsAfterSilence = inverter->calls;
  3660. for (int i = 0; i < 100; ++i)
  3661. r.process (state.get(), false, 0.0, 480, l.data(), rr.data());
  3662. CHECK (inverter->calls == callsAfterSilence);
  3663. CHECK (callsAfterSilence < 100 * 6);
  3664. // sound again: processing resumes in the same block
  3665. live.push (on);
  3666. r.process (state.get(), false, 0.0, 480, l.data(), rr.data(), &live);
  3667. CHECK (inverter->calls == callsAfterSilence + 1 && std::abs (l[100] - 0.25f) < 1e-4f);
  3668. }
  3669. TEST (swing_delays_offbeat_sixteenths)
  3670. {
  3671. CHECK (lynx::swingDelay (0, 1.0f) == 0);
  3672. CHECK (lynx::swingDelay (lynx::ticksPerStep, 1.0f) == lynx::ticksPerStep / 2);
  3673. CHECK (lynx::swingDelay (lynx::ticksPerStep * 2, 1.0f) == 0);
  3674. CHECK (lynx::swingDelay (lynx::ticksPerStep + 10, 1.0f) == (lynx::ticksPerStep - 20) / 2); // off the grid: triangular weight (FL)
  3675. CHECK (lynx::swingDelay (lynx::ticksPerStep, 1.0f, 0.5f) == lynx::ticksPerStep / 4); // channel mix
  3676. CHECK (lynx::swingDelay (lynx::ticksPerStep * 3, 0.5f) == lynx::ticksPerStep / 4);
  3677. lynx::Pattern p;
  3678. p.notes = { { 0, 100, 0, 60 }, { lynx::ticksPerStep, 100, 0, 62 } };
  3679. lynx::EventBuffer ev;
  3680. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  3681. lynx::schedulePatternLoop (p, p.effectiveLength (4), 0.0, 12000, tps, ev, 1.0f);
  3682. int onOffset = -1;
  3683. for (auto& e : ev)
  3684. if (e.type == lynx::NoteEvent::Type::on && e.key == 62)
  3685. onOffset = e.sampleOffset;
  3686. CHECK (onOffset == (int) std::floor ((lynx::ticksPerStep * 1.5) / tps));
  3687. }
  3688. TEST (sampler_settings_pitch_reverse_envelope_cut)
  3689. {
  3690. auto ramp = std::make_shared<lynx::SampleData>();
  3691. for (int i = 0; i < 48000; ++i)
  3692. ramp->left.push_back ((float) i / 48000.0f); // ramp: the value tells where the read position is
  3693. ramp->sampleRate = 48000.0;
  3694. auto play = [&] (const lynx::SamplerSettings& s, int key, int frames, bool releaseAfterHalf) {
  3695. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  3696. inst->prepare (48000.0);
  3697. lynx::ChannelDef c;
  3698. c.sampler = s;
  3699. inst->configure (c, 120.0);
  3700. inst->noteOn (key, 1.0f);
  3701. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  3702. inst->render (l.data(), r.data(), frames / 2, 1.0f, 1.0f);
  3703. if (releaseAfterHalf)
  3704. inst->noteOff (key);
  3705. inst->render (l.data() + frames / 2, r.data() + frames / 2, frames - frames / 2, 1.0f, 1.0f);
  3706. return l;
  3707. };
  3708. // +12 semitones: reads twice as fast
  3709. lynx::SamplerSettings up;
  3710. up.pitch = 12.0f;
  3711. CHECK (std::abs (play (up, 60, 1000, false)[999] - 2.0f * 999.0f / 48000.0f) < 1e-3f);
  3712. // reversed: starts from the end
  3713. lynx::SamplerSettings back;
  3714. back.reverse = true;
  3715. CHECK (play (back, 60, 100, false)[10] > 0.99f);
  3716. // 10 ms attack: starts silent and reaches full level
  3717. lynx::SamplerSettings slow;
  3718. slow.attack = 0.01f;
  3719. const auto a = play (slow, 60, 2000, false);
  3720. CHECK (a[10] < 0.2f * (10.0f / 48000.0f) + 1e-6f && std::abs (a[1500] - 1500.0f / 48000.0f) < 1e-4f);
  3721. // 5 ms release: gone right after release; without release it plays in full
  3722. lynx::SamplerSettings rel;
  3723. rel.release = 0.005f;
  3724. CHECK (play (rel, 60, 2000, true)[1999] == 0.0f);
  3725. CHECK (play (lynx::SamplerSettings {}, 60, 2000, true)[1999] > 0.0f);
  3726. // cut itself: the second note cuts the first (one voice remains)
  3727. lynx::SamplerSettings cut;
  3728. cut.cut = true;
  3729. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  3730. inst->prepare (48000.0);
  3731. lynx::ChannelDef cutChannel;
  3732. cutChannel.sampler = cut;
  3733. inst->configure (cutChannel, 120.0);
  3734. inst->noteOn (60, 1.0f);
  3735. std::vector<float> l (2000), r (2000);
  3736. inst->render (l.data(), r.data(), 1000, 1.0f, 1.0f);
  3737. inst->noteOn (60, 1.0f);
  3738. std::fill (l.begin(), l.end(), 0.0f);
  3739. inst->render (l.data(), r.data(), 2000, 1.0f, 1.0f);
  3740. CHECK (std::abs (l[1999] - 1999.0f / 48000.0f) < 1e-4f); // only the new note
  3741. }
  3742. TEST (playlist_split_and_track_mute)
  3743. {
  3744. lynx::Clip c { 0, 3, 960, 3840, 480 };
  3745. const auto rest = lynx::splitClip (c, 2000);
  3746. CHECK (c.start == 960 && c.length == 1040 && c.offset == 480);
  3747. CHECK (rest.start == 2000 && rest.length == 2800 && rest.offset == 480 + 1040 && rest.track == 3);
  3748. auto s = lynx::Song::makeDefault();
  3749. s.mode = lynx::PlayMode::song;
  3750. s.playlist = { { 0, 0, 0, 3840, 0 } };
  3751. lynx::EventBuffer ev;
  3752. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  3753. lynx::scheduleSong (s, 0.0, 48000, tps, ev);
  3754. CHECK (ev.size() > 0);
  3755. s.playlistTracks.resize (1);
  3756. s.playlistTracks[0].muted = true;
  3757. ev.clear();
  3758. lynx::scheduleSong (s, 0.0, 48000, tps, ev);
  3759. CHECK (ev.size() == 0);
  3760. }
  3761. TEST (note_pan_pitch_and_mute)
  3762. {
  3763. lynx::Pattern p;
  3764. lynx::Note a { 0, 240, 0, 60 };
  3765. a.pan = -1.0f;
  3766. a.finePitch = 50.0f;
  3767. lynx::Note b { 240, 240, 0, 62 };
  3768. b.muted = true;
  3769. p.notes = { a, b };
  3770. lynx::EventBuffer ev;
  3771. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  3772. lynx::schedulePatternLoop (p, p.effectiveLength (4), 0.0, 48000, tps, ev);
  3773. int ons = 0;
  3774. for (auto& e : ev)
  3775. if (e.type == lynx::NoteEvent::Type::on)
  3776. {
  3777. ++ons;
  3778. CHECK (e.key == 60 && e.pan == -1.0f && e.cents == 50.0f);
  3779. }
  3780. CHECK (ons == 1); // the muted one doesn't play
  3781. // note pan in the sampler: fully left
  3782. auto dc = std::make_shared<lynx::SampleData>();
  3783. dc->left.assign (4800, 0.5f);
  3784. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, dc);
  3785. inst->prepare (48000.0);
  3786. inst->setNextNoteExpression (-1.0f, 0.0f);
  3787. inst->noteOn (60, 1.0f);
  3788. std::vector<float> l (100), r (100);
  3789. inst->render (l.data(), r.data(), 100, 1.0f, 1.0f);
  3790. CHECK (l[50] > 0.6f && std::abs (r[50]) < 1e-6f);
  3791. }
  3792. TEST (tempo_automation_changes_speed_and_duration)
  3793. {
  3794. auto song = lynx::Song::makeDefault();
  3795. song.bpm = 120.0;
  3796. song.mode = lynx::PlayMode::song;
  3797. const auto bar = (std::int64_t) lynx::ppq * 4;
  3798. song.playlist = { { 0, 0, 0, bar, 0 }, { 0, 0, bar, bar, 0 } };
  3799. lynx::Automation tempo;
  3800. tempo.target = { lynx::AutomationTargetKind::tempo, 0 };
  3801. const auto v120 = lynx::valueFromTempo (120.0), v240 = lynx::valueFromTempo (240.0);
  3802. tempo.points = { { 0, v120 }, { bar - 1, v120 }, { bar, v240 } }; // step: 120 -> 240 at bar 2
  3803. song.automations.push_back (tempo);
  3804. lynx::Clip clip;
  3805. clip.kind = lynx::ClipKind::automation;
  3806. clip.automation = 0;
  3807. clip.track = 1;
  3808. clip.length = bar * 2;
  3809. song.playlist.push_back (clip);
  3810. CHECK (std::abs (song.tempoAt (100.0) - 120.0) < 0.01 && std::abs (song.tempoAt ((double) bar + 100.0) - 240.0) < 0.01);
  3811. // 1 bar at 120 (2 s) + 1 at 240 (1 s)
  3812. CHECK (std::abs (song.secondsForTicks (bar * 2) - 3.0) < 0.01);
  3813. auto state = lynx::RackState::build (song, nullptr, 48000.0);
  3814. CHECK (state->tempoAutomation == 0);
  3815. lynx::RackRenderer r;
  3816. r.prepare (48000.0, 512);
  3817. std::vector<float> l (512), rr (512);
  3818. r.process (state.get(), true, 10.0, 512, l.data(), rr.data());
  3819. CHECK (std::abs (r.currentBpm() - 120.0) < 0.01);
  3820. r.process (state.get(), true, (double) bar + 10.0, 512, l.data(), rr.data());
  3821. CHECK (std::abs (r.currentBpm() - 240.0) < 0.01);
  3822. }
  3823. TEST (bounce_insert_song_and_apply)
  3824. {
  3825. auto s = lynx::Song::makeDefault();
  3826. s.setRoute (3, 7, true, 0.5f);
  3827. s.mixer[0].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::reverb));
  3828. s.mixer[2].solo = true;
  3829. const auto b = lynx::makeBounceSong (s, 3);
  3830. CHECK (b.mixer[3].solo && ! b.mixer[2].solo && b.mixer[3].toMaster && b.mixer[3].sends.empty());
  3831. CHECK (b.mixer[0].effects.empty() && b.mode == lynx::PlayMode::song);
  3832. const auto audible = b.soloAudible();
  3833. CHECK (audible[3] && ! audible[1] && ! audible[7]);
  3834. const auto channels = s.channels.size();
  3835. const auto inserts = s.mixer.size();
  3836. const auto created = lynx::applyBounce (s, 3, "C:/x.wav", 3840);
  3837. CHECK (created == (int) inserts && s.mixer.size() == inserts + 1 && s.mixer[3].muted);
  3838. CHECK (s.mixer[(std::size_t) created].sends.size() == 1 && s.mixer[(std::size_t) created].sends[0].target == 7);
  3839. CHECK (s.channels.size() == channels + 1 && s.channels.back().mixerTrack == created);
  3840. CHECK (s.playlist.back().kind == lynx::ClipKind::audio && s.playlist.back().length == 3840);
  3841. }
  3842. TEST (mixer_stereo_separation_phase_swap)
  3843. {
  3844. lynx::MixerTrack t;
  3845. std::vector<float> l { 1.0f }, r { 0.0f };
  3846. t.stereo = 1.0f; // mono
  3847. lynx::RackRenderer::applyStereoForTest (t, l.data(), r.data(), 1);
  3848. CHECK (std::abs (l[0] - 0.5f) < 1e-6f && std::abs (r[0] - 0.5f) < 1e-6f);
  3849. l = { 1.0f };
  3850. r = { 0.0f };
  3851. t.stereo = -1.0f; // doubled side: 1.5 L - 0.5 R
  3852. lynx::RackRenderer::applyStereoForTest (t, l.data(), r.data(), 1);
  3853. CHECK (std::abs (l[0] - 1.5f) < 1e-6f && std::abs (r[0] + 0.5f) < 1e-6f);
  3854. l = { 1.0f };
  3855. r = { 0.25f };
  3856. t.stereo = 0.0f;
  3857. t.swapChannels = true;
  3858. t.invertPhase = true;
  3859. lynx::RackRenderer::applyStereoForTest (t, l.data(), r.data(), 1);
  3860. CHECK (l[0] == -0.25f && r[0] == -1.0f);
  3861. }
  3862. TEST (effects_limiter_filter_distortion_chorus)
  3863. {
  3864. const double sr = 48000.0;
  3865. auto sine = [] (float hz, float amp, int n) {
  3866. std::vector<float> v ((std::size_t) n);
  3867. for (int i = 0; i < n; ++i)
  3868. v[(std::size_t) i] = amp * std::sin (2.0f * 3.14159265f * hz * (float) i / 48000.0f);
  3869. return v;
  3870. };
  3871. auto peak = [] (const std::vector<float>& v, int from) {
  3872. float p = 0.0f;
  3873. for (std::size_t i = (std::size_t) from; i < v.size(); ++i)
  3874. p = std::max (p, std::abs (v[i]));
  3875. return p;
  3876. };
  3877. // limiter: +12 dB on a 0.9 sine never exceeds the ceiling (-1 dB) and reports the latency
  3878. auto lim = lynx::makeEffect (lynx::EffectKind::limiter);
  3879. lim->prepare (sr);
  3880. auto slot = lynx::makeEffectSlot (lynx::EffectKind::limiter);
  3881. slot.params[0] = 11.0f / 12.0f; // -1 dB
  3882. slot.params[1] = 0.5f; // +12 dB
  3883. auto l = sine (100.0f, 0.9f, 48000), r = l;
  3884. lim->process (l.data(), r.data(), 48000, slot.params, 120.0);
  3885. CHECK (peak (l, 0) <= std::pow (10.0f, -1.0f / 20.0f) + 1e-4f);
  3886. CHECK (peak (l, 4800) > 0.8f);
  3887. CHECK (lim->latencySamples() == 72);
  3888. // low-pass filter at 500 Hz knocks down an 8 kHz sine
  3889. auto lp = lynx::makeEffect (lynx::EffectKind::filter);
  3890. lp->prepare (sr);
  3891. auto fs = lynx::makeEffectSlot (lynx::EffectKind::filter);
  3892. fs.params[1] = std::log (500.0f / 20.0f) / std::log (1000.0f);
  3893. l = sine (8000.0f, 1.0f, 9600);
  3894. r = l;
  3895. lp->process (l.data(), r.data(), 9600, fs.params, 120.0);
  3896. CHECK (peak (l, 4800) < 0.05f);
  3897. // distortion and chorus: finite, audible output
  3898. for (auto kind : { lynx::EffectKind::distortion, lynx::EffectKind::chorus })
  3899. {
  3900. auto fx = lynx::makeEffect (kind);
  3901. fx->prepare (sr);
  3902. auto ps = lynx::makeEffectSlot (kind);
  3903. l = sine (220.0f, 0.5f, 9600);
  3904. r = l;
  3905. fx->process (l.data(), r.data(), 9600, ps.params, 120.0);
  3906. bool finite = true;
  3907. for (auto v : l)
  3908. finite = finite && std::isfinite (v);
  3909. CHECK (finite && peak (l, 2400) > 0.1f && peak (l, 0) < 2.0f);
  3910. }
  3911. }
  3912. TEST (slide_notes_glide_without_retrigger)
  3913. {
  3914. // sampler with a ramp: the read speed doubles after a one-octave slide
  3915. auto ramp = std::make_shared<lynx::SampleData>();
  3916. for (int i = 0; i < 96000; ++i)
  3917. ramp->left.push_back ((float) i / 96000.0f);
  3918. ramp->sampleRate = 48000.0;
  3919. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  3920. inst->prepare (48000.0);
  3921. inst->noteOn (60, 1.0f);
  3922. std::vector<float> l (2000), r (2000);
  3923. inst->render (l.data(), r.data(), 1000, 1.0f, 1.0f);
  3924. const auto stepBefore = l[999] - l[998];
  3925. inst->slideTo (72, 0.0f, 100.0f);
  3926. std::fill (l.begin(), l.end(), 0.0f);
  3927. inst->render (l.data(), r.data(), 1000, 1.0f, 1.0f);
  3928. const auto stepAfter = l[999] - l[998];
  3929. CHECK (std::abs (stepAfter / stepBefore - 2.0f) < 0.01f);
  3930. // the sequencer sends "slide" (no off) for the slide note
  3931. lynx::Pattern p;
  3932. lynx::Note base { 0, 960, 0, 48 };
  3933. lynx::Note glide { 480, 240, 0, 55 };
  3934. glide.slide = true;
  3935. p.notes = { base, glide };
  3936. lynx::EventBuffer ev;
  3937. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  3938. lynx::schedulePatternLoop (p, p.effectiveLength (4), 0.0, 30000, tps, ev);
  3939. int ons = 0, offs = 0, slides = 0;
  3940. for (auto& e : ev)
  3941. {
  3942. ons += e.type == lynx::NoteEvent::Type::on;
  3943. offs += e.type == lynx::NoteEvent::Type::off;
  3944. if (e.type == lynx::NoteEvent::Type::slide)
  3945. {
  3946. ++slides;
  3947. CHECK (e.key == 55 && std::abs (e.slideSamples - 240.0f / (float) tps) < 1.0f);
  3948. }
  3949. }
  3950. CHECK (ons == 1 && offs == 1 && slides == 1);
  3951. }
  3952. TEST (synth_fm_phase_modulation)
  3953. {
  3954. auto render = [] (const lynx::SynthSettings& s) {
  3955. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  3956. inst->prepare (48000.0);
  3957. lynx::ChannelDef c;
  3958. c.synth = s;
  3959. inst->configure (c, 120.0);
  3960. inst->noteOn (69, 1.0f); // 440 Hz
  3961. std::vector<float> l (48000), r (48000);
  3962. inst->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  3963. return l;
  3964. };
  3965. // energy (Goertzel) at frequency f over frames [from, to)
  3966. auto energy = [] (const std::vector<float>& x, double f, int from, int to) {
  3967. const auto w = 2.0 * 3.141592653589793 * f / 48000.0, k = 2.0 * std::cos (w);
  3968. double s1 = 0.0, s2 = 0.0;
  3969. for (int i = from; i < to; ++i)
  3970. {
  3971. const auto s0 = x[(std::size_t) i] + k * s1 - s2;
  3972. s2 = s1;
  3973. s1 = s0;
  3974. }
  3975. return s1 * s1 + s2 * s2 - k * s1 * s2;
  3976. };
  3977. lynx::SynthSettings plain;
  3978. plain.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  3979. plain.osc[2] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  3980. plain.cutoff = 20000.0f;
  3981. auto fm = plain;
  3982. fm.fm = 1.0f;
  3983. const auto a = render (plain), b = render (fm);
  3984. // no FM: osc 3 adds (same pitch) and there's no 2nd harmonic; with FM the sidebands appear
  3985. CHECK (energy (a, 880.0, 4800, 24000) < 1e-3 * energy (a, 440.0, 4800, 24000));
  3986. CHECK (energy (b, 880.0, 4800, 24000) > 0.1 * energy (b, 440.0, 4800, 24000));
  3987. CHECK (energy (b, 1320.0, 4800, 24000) > 0.01 * energy (b, 440.0, 4800, 24000));
  3988. for (auto v : b)
  3989. CHECK (std::isfinite (v) && std::abs (v) < 1.0f);
  3990. // index decaying to 0: the start is bright, the end is nearly a sine again
  3991. auto decaying = fm;
  3992. decaying.fmDecay = 0.1f;
  3993. decaying.fmSustain = 0.0f;
  3994. const auto c = render (decaying);
  3995. const auto early = energy (c, 880.0, 0, 2400) / energy (c, 440.0, 0, 2400);
  3996. const auto late = energy (c, 880.0, 36000, 48000) / energy (c, 440.0, 36000, 48000);
  3997. CHECK (early > 0.05 && late < 1e-3);
  3998. }
  3999. TEST (synth_three_oscillators_adsr_filter)
  4000. {
  4001. auto render = [] (const lynx::SynthSettings& s, int frames, int releaseAt) {
  4002. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  4003. inst->prepare (48000.0);
  4004. lynx::ChannelDef c;
  4005. c.synth = s;
  4006. inst->configure (c, 120.0);
  4007. inst->noteOn (69, 1.0f); // A4 = 440 Hz
  4008. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  4009. inst->render (l.data(), r.data(), releaseAt, 1.0f, 1.0f);
  4010. inst->noteOff (69);
  4011. inst->render (l.data() + releaseAt, r.data() + releaseAt, frames - releaseAt, 1.0f, 1.0f);
  4012. return l;
  4013. };
  4014. auto peakIn = [] (const std::vector<float>& v, int from, int to) {
  4015. float p = 0.0f;
  4016. for (int i = from; i < to; ++i)
  4017. p = std::max (p, std::abs (v[(std::size_t) i]));
  4018. return p;
  4019. };
  4020. // default: sounds and fades after the release
  4021. const lynx::SynthSettings standard;
  4022. const auto a = render (standard, 48000, 24000);
  4023. CHECK (peakIn (a, 1000, 20000) > 0.05f && peakIn (a, 40000, 48000) < 1e-3f);
  4024. // pure sine with an open filter: zero-crossing count gives ~440 Hz
  4025. lynx::SynthSettings sine;
  4026. sine.osc[0].wave = lynx::Waveform::sine;
  4027. sine.cutoff = 20000.0f;
  4028. const auto b = render (sine, 48000, 47000);
  4029. int crossings = 0;
  4030. for (int i = 4800; i < 4800 + 48000 / 2; ++i)
  4031. crossings += (b[(std::size_t) i - 1] < 0.0f) != (b[(std::size_t) i] < 0.0f);
  4032. CHECK (std::abs (crossings - 440) < 6); // half a second = 220 cycles = 440 crossings
  4033. float sinePeak = 0.0f;
  4034. for (int i = 4800; i < 9600; ++i)
  4035. sinePeak = std::max (sinePeak, std::abs (b[(std::size_t) i]));
  4036. CHECK (sinePeak > 0.2f && sinePeak < 0.35f); // 0.3 level, approximated sine without clipping
  4037. // second oscillator an octave up adds energy; sustain 0 makes the note decay on its own
  4038. lynx::SynthSettings two = sine;
  4039. two.osc[1] = { lynx::Waveform::sine, 1, 0.0f, 1.0f };
  4040. two.sustain = 0.0f;
  4041. two.decay = 0.1f;
  4042. const auto c = render (two, 48000, 47000);
  4043. CHECK (peakIn (c, 100, 2000) > peakIn (b, 100, 2000) && peakIn (c, 30000, 40000) < 1e-3f);
  4044. }
  4045. TEST (set_target_value_round_trips)
  4046. {
  4047. auto s = lynx::Song::makeDefault();
  4048. s.mixer[2].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay));
  4049. const lynx::AutomationTarget targets[] = {
  4050. { lynx::AutomationTargetKind::channelVolume, 1 }, { lynx::AutomationTargetKind::channelPan, 2 },
  4051. { lynx::AutomationTargetKind::mixerVolume, 3 }, { lynx::AutomationTargetKind::mixerPan, 0 },
  4052. { lynx::AutomationTargetKind::effectParam, 2, 0, 1 }, { lynx::AutomationTargetKind::tempo, 0 },
  4053. };
  4054. for (const auto& t : targets)
  4055. {
  4056. CHECK (s.setTargetValue (t, 0.25f));
  4057. CHECK (std::abs (s.targetValue (t) - 0.25f) < 1e-5f);
  4058. }
  4059. CHECK (! s.setTargetValue ({ lynx::AutomationTargetKind::channelParam, 0, 0, 3 }, 0.5f)); // lives in the plugin
  4060. }
  4061. TEST (cut_groups_stretch_and_envelope_import)
  4062. {
  4063. // open hat (cut by 1) is cut when the closed one (group 1) plays
  4064. lynx::Song s;
  4065. s.mixer = lynx::Song::defaultMixer (2);
  4066. for (int i = 0; i < 2; ++i)
  4067. {
  4068. lynx::ChannelDef c;
  4069. c.instrument = lynx::InstrumentKind::sampler;
  4070. c.samplePath = "dc";
  4071. c.volume = 1.0f;
  4072. c.mixerTrack = i + 1;
  4073. s.channels.push_back (c);
  4074. }
  4075. s.channels[0].cutBy = 1; // open
  4076. s.channels[1].cutGroup = 1; // closed
  4077. auto& p = s.patterns.emplace_back();
  4078. p.notes = { { 0, 100, 0, 60 }, { 960, 100, 1, 60 } };
  4079. auto provider = [] (const std::string&) {
  4080. auto d = std::make_shared<lynx::SampleData>();
  4081. d->left.assign (96000, 0.5f);
  4082. return std::shared_ptr<const lynx::SampleData> (d);
  4083. };
  4084. auto state = lynx::RackState::build (s, nullptr, 48000.0, provider);
  4085. CHECK (state->hasCutGroups && state->cutTargets[1].size() == 1 && state->cutTargets[1][0] == 0);
  4086. lynx::RackRenderer r;
  4087. r.prepare (48000.0, 512);
  4088. std::vector<float> l (512), rr (512);
  4089. const auto tps = lynx::ticksPerSample (s.bpm, 48000.0);
  4090. float afterCut = 0.0f;
  4091. for (double tick = 0.0; tick < 960.0 * 3; tick += 512 * tps)
  4092. {
  4093. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  4094. if (tick > 960.0 * 2) // the closed one continues; the open one has stopped
  4095. afterCut = std::max (afterCut, std::abs (l[256]));
  4096. }
  4097. CHECK (std::abs (afterCut - 0.5f * 0.78f) < 0.01f); // only the closed one (default velocity 0.78)
  4098. // resampling stretch: 1 s of sample stretched to 4 beats at 120 BPM = 2 s
  4099. auto ramp = std::make_shared<lynx::SampleData>();
  4100. for (int i = 0; i < 48000; ++i)
  4101. ramp->left.push_back ((float) i / 48000.0f);
  4102. ramp->sampleRate = 48000.0;
  4103. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  4104. inst->prepare (48000.0);
  4105. lynx::ChannelDef c;
  4106. c.sampler.stretchBeats = 4.0f;
  4107. inst->configure (c, 120.0);
  4108. inst->noteOn (72, 1.0f); // the note pitch doesn't change the speed
  4109. std::vector<float> a (48000), b (48000);
  4110. inst->render (a.data(), b.data(), 48000, 1.0f, 1.0f);
  4111. CHECK (std::abs (a[47999] - 0.5f) < 0.01f); // after 1 s it has read half
  4112. // FL envelope time: 32950 = 2 s; < 101 = 0
  4113. CHECK (std::abs (flp::Channel::envelopeTime (32950) - 2.0) < 0.01 && flp::Channel::envelopeTime (50) == 0.0);
  4114. }
  4115. TEST (time_stretch_keeps_pitch)
  4116. {
  4117. lynx::SampleData sine;
  4118. sine.sampleRate = 48000.0;
  4119. for (int i = 0; i < 48000; ++i)
  4120. sine.left.push_back (0.5f * std::sin (2.0f * 3.14159265f * 440.0f * (float) i / 48000.0f));
  4121. auto crossingsPerSecond = [] (const lynx::SampleData& d) {
  4122. int c = 0;
  4123. const auto n = (int) d.frames();
  4124. for (int i = 4800; i < n - 4800; ++i)
  4125. c += (d.left[(std::size_t) i - 1] < 0.0f) != (d.left[(std::size_t) i] < 0.0f);
  4126. return (double) c / ((double) (n - 9600) / d.sampleRate);
  4127. };
  4128. for (double ratio : { 2.0, 0.5, 1.37 })
  4129. {
  4130. const auto out = lynx::timeStretch (sine, ratio);
  4131. CHECK (std::abs ((double) out->frames() - 48000.0 * ratio) < 2.0);
  4132. CHECK (std::abs (crossingsPerSecond (*out) - 880.0) < 15.0); // 440 Hz stays 440 Hz
  4133. float peak = 0.0f;
  4134. for (std::size_t i = 4800; i + 4800 < out->frames(); ++i)
  4135. peak = std::max (peak, std::abs (out->left[i]));
  4136. CHECK (peak > 0.4f && peak < 0.6f); // no gaps or clipping in the overlap
  4137. }
  4138. }
  4139. TEST (sampler_region_start_and_end)
  4140. {
  4141. auto ramp = std::make_shared<lynx::SampleData>();
  4142. for (int i = 0; i < 10000; ++i)
  4143. ramp->left.push_back ((float) i / 10000.0f);
  4144. ramp->sampleRate = 48000.0;
  4145. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  4146. inst->prepare (48000.0);
  4147. lynx::ChannelDef c;
  4148. c.sampler.regionStart = 0.25f;
  4149. c.sampler.regionEnd = 0.5f;
  4150. inst->configure (c, 120.0);
  4151. inst->noteOn (60, 1.0f);
  4152. std::vector<float> l (6000), r (6000);
  4153. inst->render (l.data(), r.data(), 6000, 1.0f, 1.0f);
  4154. CHECK (std::abs (l[0] - 0.25f) < 0.001f); // starts at the beginning of the slice
  4155. CHECK (l[2400] > 0.48f && l[2600] == 0.0f); // and stops at its end
  4156. }
  4157. TEST (arpeggiator_plays_held_chord_in_steps)
  4158. {
  4159. auto song = lynx::Song::makeDefault();
  4160. song.bpm = 120.0;
  4161. song.patterns[0].notes.clear();
  4162. for (int key : { 60, 64, 67 })
  4163. song.patterns[0].notes.push_back ({ 0, lynx::ppq * 4, 4, key, 0.8f }); // chord held for 1 bar
  4164. song.channels[4].arp.direction = 1; // up
  4165. song.channels[4].arp.stepBeats = 0.25f;
  4166. auto state = lynx::RackState::build (song, nullptr, 48000.0);
  4167. CHECK (state->arpeggiators[4] != nullptr && state->arpeggiators[0] == nullptr);
  4168. // the arpeggiator generates the notes; we count what it hands to the instrument
  4169. auto& arp = *state->arpeggiators[4];
  4170. const auto tps = lynx::ticksPerSample (song.bpm, 48000.0);
  4171. std::vector<int> keys;
  4172. lynx::EventBuffer ev;
  4173. for (double tick = 0.0; tick < lynx::ppq * 2.0; tick += 512 * tps)
  4174. {
  4175. ev.clear();
  4176. lynx::schedulePatternLoop (song.patterns[0], song.patterns[0].effectiveLength (4), tick, 512, tps, ev);
  4177. int in = 0, out = 0;
  4178. for (auto& e : ev)
  4179. if (e.channel == 4)
  4180. arp.input[(std::size_t) in++] = e;
  4181. arp.process (4, arp.input.data(), in, tick, tps, 512, song.channels[4].arp, arp.output.data(), out);
  4182. for (int i = 0; i < out; ++i)
  4183. if (arp.output[(std::size_t) i].type == lynx::NoteEvent::Type::on)
  4184. keys.push_back (arp.output[(std::size_t) i].key);
  4185. }
  4186. // 2 beats = 8 sixteenth steps: 60 64 67 60 64 67 60 64
  4187. CHECK (keys.size() >= 8); // the last block goes slightly past 2 beats
  4188. const int expected[] = { 60, 64, 67, 60, 64, 67, 60, 64 };
  4189. for (std::size_t i = 0; i < keys.size() && i < 8; ++i)
  4190. CHECK (keys[i] == expected[i]);
  4191. // actually rendering also makes sound
  4192. lynx::RackRenderer r;
  4193. r.prepare (48000.0, 512);
  4194. std::vector<float> l (512), rr (512);
  4195. float peak = 0.0f;
  4196. for (double tick = 0.0; tick < lynx::ppq; tick += 512 * tps)
  4197. {
  4198. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  4199. for (auto v : l)
  4200. peak = std::max (peak, std::abs (v));
  4201. }
  4202. CHECK (peak > 0.01f);
  4203. }
  4204. TEST (audio_clip_fades_and_gain)
  4205. {
  4206. lynx::Song s;
  4207. s.bpm = 120.0;
  4208. s.mode = lynx::PlayMode::song;
  4209. s.mixer = lynx::Song::defaultMixer (1);
  4210. lynx::ChannelDef c;
  4211. c.instrument = lynx::InstrumentKind::audioClip;
  4212. c.samplePath = "dc";
  4213. c.volume = 1.0f;
  4214. c.mixerTrack = 1;
  4215. s.channels.push_back (c);
  4216. s.patterns.emplace_back();
  4217. lynx::Clip clip;
  4218. clip.kind = lynx::ClipKind::audio;
  4219. clip.channel = 0;
  4220. clip.length = lynx::ppq * 4; // 2 s at 120 BPM
  4221. clip.fadeIn = lynx::ppq; // 0.5 s
  4222. clip.fadeOut = lynx::ppq;
  4223. clip.gain = 0.5f;
  4224. s.playlist.push_back (clip);
  4225. auto provider = [] (const std::string&) {
  4226. auto d = std::make_shared<lynx::SampleData>();
  4227. d->left.assign (48000 * 4, 1.0f);
  4228. return std::shared_ptr<const lynx::SampleData> (d);
  4229. };
  4230. auto state = lynx::RackState::build (s, nullptr, 48000.0, provider);
  4231. lynx::RackRenderer r;
  4232. r.prepare (48000.0, 512);
  4233. std::vector<float> all;
  4234. std::vector<float> l (512), rr (512);
  4235. const auto tps = lynx::ticksPerSample (s.bpm, 48000.0);
  4236. for (double tick = 0.0; tick < lynx::ppq * 4.0; tick += 512 * tps)
  4237. {
  4238. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  4239. all.insert (all.end(), l.begin(), l.end());
  4240. }
  4241. CHECK (all[100] < 0.01f); // fade-in start
  4242. CHECK (std::abs (all[12000] - 0.25f) < 0.02f); // fade-in midpoint: half of 0.5
  4243. CHECK (std::abs (all[48000] - 0.5f) < 0.01f); // body: the clip gain
  4244. CHECK (std::abs (all[96000 - 12000] - 0.25f) < 0.02f); // fade-out midpoint
  4245. }
  4246. TEST (slicer_detects_hits_and_plays_slices_by_key)
  4247. {
  4248. // 4 hits (decaying noise) every 0.25 s
  4249. lynx::SampleData loop;
  4250. loop.sampleRate = 48000.0;
  4251. loop.left.assign (48000, 0.0f);
  4252. lynx::Noise noise;
  4253. for (int hit = 0; hit < 4; ++hit)
  4254. for (int i = 0; i < 6000; ++i)
  4255. loop.left[(std::size_t) (hit * 12000 + i)] = noise.next() * 0.8f * std::exp (-(float) i / 1500.0f);
  4256. const auto slices = lynx::detectSlices (loop, 0.5f);
  4257. CHECK (slices.size() == 4);
  4258. for (std::size_t i = 0; i < slices.size(); ++i)
  4259. CHECK (std::abs (slices[i] - 0.25f * (float) i) < 0.01f);
  4260. // key 61 plays the second slice, which starts at 0.25 and ends before 0.5
  4261. auto ramp = std::make_shared<lynx::SampleData>();
  4262. for (int i = 0; i < 48000; ++i)
  4263. ramp->left.push_back ((float) i / 48000.0f);
  4264. ramp->sampleRate = 48000.0;
  4265. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  4266. inst->prepare (48000.0);
  4267. lynx::ChannelDef c;
  4268. c.sampler.slices = slices;
  4269. inst->configure (c, 120.0);
  4270. inst->noteOn (61, 1.0f);
  4271. std::vector<float> l (20000), r (20000);
  4272. inst->render (l.data(), r.data(), 20000, 1.0f, 1.0f);
  4273. CHECK (std::abs (l[0] - 0.25f) < 0.01f && l[11000] > 0.45f && l[13000] == 0.0f);
  4274. }
  4275. TEST (project_templates_render_sound)
  4276. {
  4277. const auto names = lynx::templateNames();
  4278. CHECK (names.size() == 4);
  4279. for (int t = 1; t < (int) names.size(); ++t)
  4280. {
  4281. auto song = lynx::makeTemplate (t);
  4282. auto state = lynx::RackState::build (song, nullptr, 48000.0);
  4283. lynx::RackRenderer r;
  4284. r.prepare (48000.0, 512);
  4285. std::vector<float> l (512), rr (512);
  4286. const auto tps = lynx::ticksPerSample (song.bpm, 48000.0);
  4287. float peak = 0.0f;
  4288. for (double tick = 0.0; tick < lynx::ppq * 4.0; tick += 512 * tps)
  4289. {
  4290. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  4291. for (auto v : l)
  4292. peak = std::max (peak, std::abs (v));
  4293. }
  4294. CHECK (peak > 0.05f && peak < 4.0f);
  4295. }
  4296. CHECK (lynx::makeTemplate (0).patterns[0].notes.empty());
  4297. }
  4298. // --- interface translations (resources/i18n) -------------------------------------------------------
  4299. namespace i18ntest
  4300. {
  4301. std::string readFile (const std::filesystem::path& path)
  4302. {
  4303. std::ifstream in (path, std::ios::binary);
  4304. return { std::istreambuf_iterator<char> (in), std::istreambuf_iterator<char>() };
  4305. }
  4306. std::string unescape (const std::string& s)
  4307. {
  4308. std::string out;
  4309. for (std::size_t i = 0; i < s.size(); ++i)
  4310. {
  4311. if (s[i] == '\\' && i + 1 < s.size())
  4312. {
  4313. const auto n = s[++i];
  4314. out += n == 'n' ? '\n' : n == 't' ? '\t' : n;
  4315. }
  4316. else
  4317. out += s[i];
  4318. }
  4319. return out;
  4320. }
  4321. // reads a quoted string starting at s[pos] == '"'; returns the raw (escaped) contents and moves pos past the closing quote
  4322. bool quoted (const std::string& s, std::size_t& pos, std::string& raw)
  4323. {
  4324. if (pos >= s.size() || s[pos] != '"')
  4325. return false;
  4326. raw.clear();
  4327. for (++pos; pos < s.size() && s[pos] != '"' && s[pos] != '\n'; ++pos)
  4328. {
  4329. if (s[pos] == '\\' && pos + 1 < s.size())
  4330. raw += s[pos++];
  4331. raw += s[pos];
  4332. }
  4333. if (pos >= s.size() || s[pos] != '"')
  4334. return false;
  4335. ++pos;
  4336. return true;
  4337. }
  4338. // JUCE LocalisedStrings format: "english" = "translation"; duplicates are reported in `duplicates`
  4339. std::map<std::string, std::string> parseTable (const std::string& text, std::vector<std::string>& duplicates)
  4340. {
  4341. std::map<std::string, std::string> table;
  4342. std::istringstream lines (text);
  4343. std::string line;
  4344. while (std::getline (lines, line))
  4345. {
  4346. std::size_t pos = line.find_first_not_of (" \t");
  4347. std::string key, value;
  4348. if (pos == std::string::npos || ! quoted (line, pos, key))
  4349. continue;
  4350. pos = line.find ('"', pos);
  4351. if (pos == std::string::npos || ! quoted (line, pos, value))
  4352. value.clear();
  4353. const auto k = unescape (key);
  4354. if (table.count (k) != 0)
  4355. duplicates.push_back (k);
  4356. table[k] = unescape (value);
  4357. }
  4358. return table;
  4359. }
  4360. // string literals passed to tr() / TR_NOOP() in the sources (adjacent literals are concatenated)
  4361. std::map<std::string, std::string> sourceKeys (const std::filesystem::path& srcDir)
  4362. {
  4363. std::map<std::string, std::string> keys;
  4364. for (const auto& entry : std::filesystem::recursive_directory_iterator (srcDir))
  4365. {
  4366. const auto ext = entry.path().extension().string();
  4367. if (! entry.is_regular_file() || (ext != ".cpp" && ext != ".h"))
  4368. continue;
  4369. // drop // comment lines (they may quote tr ("...") as an example)
  4370. std::string text, line;
  4371. std::istringstream in (readFile (entry.path()));
  4372. while (std::getline (in, line))
  4373. {
  4374. const auto first = line.find_first_not_of (" \t");
  4375. text += (first != std::string::npos && line.compare (first, 2, "//") == 0) ? std::string() : line;
  4376. text += '\n';
  4377. }
  4378. auto isIdent = [] (char c) { return std::isalnum ((unsigned char) c) || c == '_'; };
  4379. for (const std::string name : { "tr", "TR_NOOP" })
  4380. for (auto at = text.find (name); at != std::string::npos; at = text.find (name, at + 1))
  4381. {
  4382. if ((at > 0 && isIdent (text[at - 1])) || isIdent (text[at + name.size()]))
  4383. continue;
  4384. auto pos = text.find_first_not_of (" \t\n", at + name.size());
  4385. if (pos == std::string::npos || text[pos] != '(')
  4386. continue;
  4387. pos = text.find_first_not_of (" \t\n", pos + 1);
  4388. std::string key, raw;
  4389. bool any = false;
  4390. while (pos != std::string::npos && quoted (text, pos, raw))
  4391. {
  4392. key += raw;
  4393. any = true;
  4394. pos = text.find_first_not_of (" \t\n", pos);
  4395. }
  4396. if (any)
  4397. keys.emplace (unescape (key), entry.path().filename().string());
  4398. }
  4399. }
  4400. return keys;
  4401. }
  4402. std::set<std::string> placeholders (const std::string& s)
  4403. {
  4404. std::set<std::string> found;
  4405. for (auto open = s.find ('{'); open != std::string::npos; open = s.find ('{', open + 1))
  4406. if (const auto close = s.find ('}', open); close != std::string::npos && close - open <= 3)
  4407. found.insert (s.substr (open, close - open + 1));
  4408. return found;
  4409. }
  4410. } // namespace i18ntest
  4411. TEST (translations_cover_every_ui_string)
  4412. {
  4413. using namespace i18ntest;
  4414. const auto text = readFile ("resources/i18n/pt-BR.txt");
  4415. CHECK (! text.empty());
  4416. std::vector<std::string> duplicates;
  4417. const auto table = parseTable (text, duplicates);
  4418. CHECK (table.size() > 300);
  4419. CHECK (duplicates.empty());
  4420. for (const auto& d : duplicates)
  4421. std::printf (" duplicate pt-BR entry: \"%s\"\n", d.c_str());
  4422. const auto keys = sourceKeys ("src");
  4423. CHECK (keys.size() > 300);
  4424. int missing = 0;
  4425. for (const auto& [key, file] : keys)
  4426. if (auto it = table.find (key); it == table.end() || it->second.empty())
  4427. {
  4428. ++missing;
  4429. std::printf (" no pt-BR translation for \"%s\" (%s)\n", key.c_str(), file.c_str());
  4430. }
  4431. CHECK (missing == 0);
  4432. // no empty values, and every {n} placeholder survives the translation
  4433. int empty = 0, badPlaceholders = 0;
  4434. for (const auto& [english, portuguese] : table)
  4435. {
  4436. empty += portuguese.empty() ? 1 : 0;
  4437. if (placeholders (english) != placeholders (portuguese))
  4438. {
  4439. ++badPlaceholders;
  4440. std::printf (" placeholders differ: \"%s\"\n", english.c_str());
  4441. }
  4442. }
  4443. CHECK (empty == 0);
  4444. CHECK (badPlaceholders == 0);
  4445. }
  4446. TEST (translations_embedded_table_is_up_to_date)
  4447. {
  4448. // src/ui/I18nData.h must be regenerated (tools/make_i18n.py) whenever the .txt changes
  4449. const auto text = i18ntest::readFile ("resources/i18n/pt-BR.txt");
  4450. CHECK (text.size() == sizeof (lynx::i18n::data::ptBR));
  4451. CHECK (std::memcmp (text.data(), lynx::i18n::data::ptBR, std::min (text.size(), sizeof (lynx::i18n::data::ptBR))) == 0);
  4452. }
  4453. // --- workflow shell: pattern/channel operations, key map, workspace layout, control math -------------
  4454. TEST (workflow_pattern_navigation_and_insert)
  4455. {
  4456. auto song = lynx::Song::makeDefault();
  4457. song.patterns.resize (3);
  4458. song.patterns[1].name = "B";
  4459. song.patterns[2].name = "C";
  4460. song.patterns[2].notes.push_back ({});
  4461. song.currentPattern = 0;
  4462. CHECK (lynx::stepPattern (song, 1) == 1 && lynx::stepPattern (song, -1) == 0 && lynx::stepPattern (song, 10) == 2);
  4463. // pattern 0 has the default notes, 1 is empty, 2 has a note
  4464. CHECK (! lynx::isPatternEmpty (song.patterns[0]) && lynx::isPatternEmpty (song.patterns[1]));
  4465. CHECK (lynx::findNextEmptyPattern (song, 0) == 1 && lynx::findNextEmptyPattern (song, 1) == -1);
  4466. CHECK (lynx::gotoNextEmptyPattern (song) == 1 && song.currentPattern == 1);
  4467. song.patterns[1].notes.push_back ({});
  4468. const auto before = song.patterns.size();
  4469. CHECK (lynx::gotoNextEmptyPattern (song) == (int) before && song.patterns.size() == before + 1);
  4470. CHECK (song.patterns.back().name == "Pattern 1" || song.patterns.back().name.rfind ("Pattern ", 0) == 0);
  4471. // insert keeps Playlist clips on their patterns
  4472. lynx::Clip clip;
  4473. clip.pattern = 2;
  4474. song.playlist = { clip };
  4475. song.arrangements.push_back ({ "Other", { clip }, 0, 0, {} });
  4476. CHECK (lynx::insertPattern (song, 1, "New") == 1 && song.currentPattern == 1);
  4477. CHECK (song.patterns[1].name == "New" && song.patterns[1].notes.empty() && song.patterns[3].name == "C");
  4478. CHECK (song.playlist[0].pattern == 3 && song.arrangements[1].clips[0].pattern == 3);
  4479. }
  4480. TEST (workflow_split_pattern_by_channel)
  4481. {
  4482. auto song = lynx::Song::makeDefault();
  4483. song.patterns.resize (1);
  4484. auto& p = song.patterns[0];
  4485. p.name = "Beat";
  4486. p.notes.clear();
  4487. for (int i = 0; i < 4; ++i)
  4488. p.notes.push_back ({ (std::int64_t) i * lynx::ticksPerStep, lynx::ticksPerStep, i % 2 == 0 ? 0 : 2, 60 });
  4489. song.channels[2].colour = 0xff112233;
  4490. lynx::Clip clip;
  4491. clip.pattern = 0;
  4492. song.playlist = { clip };
  4493. const auto created = lynx::splitPatternByChannel (song, 0);
  4494. CHECK (created == 2 && song.patterns.size() == 3);
  4495. CHECK (song.patterns[0].notes.size() == 4); // the original is unchanged
  4496. CHECK (song.patterns[1].name == "Beat - " + song.channels[0].name && song.patterns[1].notes.size() == 2);
  4497. CHECK (song.patterns[2].colour == 0xff112233u && song.patterns[2].notes.size() == 2 && song.patterns[2].notes[0].channel == 2);
  4498. CHECK (song.playlist[0].pattern == 0);
  4499. CHECK (lynx::splitPatternByChannel (song, 99) == 0);
  4500. }
  4501. TEST (workflow_channel_selection)
  4502. {
  4503. lynx::ChannelSelection s;
  4504. s.selectOnly (2);
  4505. s.toggle (5);
  4506. s.toggle (0);
  4507. CHECK ((s.rows == std::vector<int> { 0, 2, 5 }) && s.contains (5) && ! s.contains (3));
  4508. s.toggle (2);
  4509. CHECK ((s.rows == std::vector<int> { 0, 5 }));
  4510. s.selectOnly (3);
  4511. s.extendTo (6);
  4512. CHECK ((s.rows == std::vector<int> { 3, 4, 5, 6 }));
  4513. s.extendTo (1);
  4514. CHECK ((s.rows == std::vector<int> { 1, 2, 3 }));
  4515. s.selectOnly (4);
  4516. s.toggle (4); // the last one stays
  4517. CHECK ((s.rows == std::vector<int> { 4 }));
  4518. s.selectAll (3);
  4519. CHECK ((s.rows == std::vector<int> { 0, 1, 2 }));
  4520. s.rows = { 7, 9 };
  4521. s.clamp (5);
  4522. CHECK (s.rows.size() == 1 && s.rows[0] < 5);
  4523. }
  4524. TEST (workflow_move_clone_insert_channels)
  4525. {
  4526. auto song = lynx::Song::makeDefault();
  4527. const auto names = [&] {
  4528. std::vector<std::string> n;
  4529. for (const auto& c : song.channels)
  4530. n.push_back (c.name);
  4531. return n;
  4532. };
  4533. const auto original = names();
  4534. const auto count = (int) song.channels.size();
  4535. CHECK (count >= 4);
  4536. // references that must follow their channel
  4537. song.patterns[0].notes.push_back ({ 0, 240, 1, 64 });
  4538. lynx::Automation a;
  4539. a.target = { lynx::AutomationTargetKind::channelVolume, 1 };
  4540. song.automations.push_back (a);
  4541. song.midiLinks.push_back ({ 7, -1, { lynx::AutomationTargetKind::channelPan, 3 } });
  4542. lynx::Clip audio;
  4543. audio.kind = lynx::ClipKind::audio;
  4544. audio.channel = 3;
  4545. song.playlist.push_back (audio);
  4546. std::vector<int> selection { 1, 3 };
  4547. CHECK (lynx::moveChannels (song, selection, -1));
  4548. CHECK ((selection == std::vector<int> { 0, 2 }));
  4549. CHECK (song.channels[0].name == original[1] && song.channels[1].name == original[0] && song.channels[2].name == original[3]
  4550. && song.channels[3].name == original[2]);
  4551. CHECK (song.automations[0].target.index == 0 && song.midiLinks[0].target.index == 2 && song.playlist.back().channel == 2);
  4552. CHECK (std::any_of (song.patterns[0].notes.begin(), song.patterns[0].notes.end(),
  4553. [] (const lynx::Note& n) { return n.channel == 0 && n.key == 64; }));
  4554. CHECK (! lynx::moveChannels (song, selection, -1)); // the block is at the top
  4555. CHECK (lynx::moveChannels (song, selection, 1) && (selection == std::vector<int> { 1, 3 }) && names() == original);
  4556. // clone: settings, not notes, right below, with a new name
  4557. song.channels[1].volume = 0.33f;
  4558. const auto notesBefore = song.patterns[0].notes.size();
  4559. const auto clone = lynx::cloneChannel (song, 1);
  4560. CHECK (clone == 2 && (int) song.channels.size() == count + 1);
  4561. CHECK (song.channels[2].name == original[1] + " #2" && song.channels[2].volume == 0.33f);
  4562. CHECK (song.patterns[0].notes.size() == notesBefore);
  4563. CHECK (song.channels[3].name == original[2] && song.automations[0].target.index == 1);
  4564. CHECK (lynx::cloneChannel (song, 1) == 2 && song.channels[2].name == original[1] + " #3");
  4565. // remove several
  4566. CHECK (lynx::removeChannels (song, { 2, 3, 2 }) == 2 && (int) song.channels.size() == count);
  4567. CHECK (names() == original);
  4568. }
  4569. TEST (workflow_send_channels_to_free_inserts)
  4570. {
  4571. auto song = lynx::Song::makeDefault();
  4572. for (auto& c : song.channels)
  4573. c.mixerTrack = 0;
  4574. song.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay)); // not free: has effects
  4575. song.channels[0].mixerTrack = 2; // not free: used
  4576. song.setRoute (5, 3, true); // 3 is not free: receives a send
  4577. CHECK (! lynx::isInsertFree (song, 1) && ! lynx::isInsertFree (song, 2) && ! lynx::isInsertFree (song, 3) && lynx::isInsertFree (song, 4));
  4578. song.channels[1].colour = 0xff445566;
  4579. const auto tracks = lynx::sendChannelsToFreeInserts (song, { 1, 2 });
  4580. CHECK ((tracks == std::vector<int> { 4, 5 }) || (tracks == std::vector<int> { 4, 6 }));
  4581. CHECK (song.channels[1].mixerTrack == 4 && song.mixer[4].name == song.channels[1].name && song.mixer[4].colour == 0xff445566u);
  4582. CHECK (song.mixer[(std::size_t) tracks[1]].name == song.channels[2].name);
  4583. // with no free insert left, a new one is added at the end
  4584. auto full = lynx::Song::makeDefault();
  4585. full.mixer = lynx::Song::defaultMixer (1);
  4586. full.channels[0].mixerTrack = 1;
  4587. const auto added = lynx::sendChannelsToFreeInserts (full, { 1 });
  4588. CHECK (added.size() == 1 && added[0] == 2 && full.mixer.size() == 3 && full.channels[1].mixerTrack == 2);
  4589. }
  4590. TEST (workflow_palette_random_colour)
  4591. {
  4592. const auto& palette = lynx::lynxPalette();
  4593. for (std::uint32_t seed = 0; seed < 50; ++seed)
  4594. {
  4595. const auto current = palette[seed % palette.size()];
  4596. const auto c = lynx::randomPaletteColour (current, seed);
  4597. CHECK (c != current && std::find (palette.begin(), palette.end(), c) != palette.end());
  4598. }
  4599. }
  4600. TEST (workflow_key_map)
  4601. {
  4602. using namespace lynx::keys;
  4603. KeyMap map;
  4604. const auto global = Context::global, rack = Context::channelRack;
  4605. CHECK (map.find ({ space, none }, global, true) == "transport.playStop");
  4606. CHECK (map.find ({ space, ctrl }, global, true) == "transport.pause");
  4607. CHECK (map.find ({ f6, none }, global, true) == "panel.channelRack");
  4608. CHECK (map.find ({ f8, alt }, global, false) == "panel.browser");
  4609. CHECK (map.find ({ insert, ctrl | shift }, global, false) == "pattern.insert");
  4610. CHECK (map.find ({ numpadPlus, none }, rack, true) == "pattern.next");
  4611. // panel context: only while focused
  4612. CHECK (map.find ({ 'L', ctrl }, rack, true) == "rack.sendToInserts");
  4613. CHECK (map.find ({ 'L', ctrl }, global, true).empty());
  4614. CHECK (map.find ({ up, alt }, rack, false) == "rack.moveUp");
  4615. // typing piano: note keys play, other plain keys only for whilePiano actions; chords always work
  4616. CHECK (KeyMap::playsNote ({ 'Z', none }, true) && ! KeyMap::playsNote ({ 'Z', none }, false) && ! KeyMap::playsNote ({ 'Z', ctrl }, true));
  4617. CHECK (map.find ({ 'L', none }, global, true) == "transport.toggleMode");
  4618. CHECK (map.find ({ '1', none }, rack, false) == "rack.mute1" && map.find ({ '0', none }, rack, false) == "rack.mute10");
  4619. CHECK (map.find ({ '1', none }, rack, true).empty()); // a plain digit is not a shortcut while the piano is on
  4620. CHECK (map.find ({ '2', ctrl }, rack, true) == "rack.solo2");
  4621. CHECK (typingPianoNote ('Z') == 60 && typingPianoNote ('q') == 72 && typingPianoNote ('P') == 88 && typingPianoNote ('L') == -1);
  4622. CHECK (map.conflicts().empty());
  4623. // chord text
  4624. CHECK (toString ({ f4, ctrl | shift }) == "Ctrl+Shift+F4" && toString ({ numpadMinus, none }) == "Numpad -");
  4625. CHECK (parseChord ("Shift+Ctrl+Ins") == (Chord { insert, ctrl | shift }));
  4626. CHECK (parseChord ("alt+up") == (Chord { up, alt }) && parseChord ("k") == (Chord { 'K', none }));
  4627. CHECK (parseChord ("Numpad +") == (Chord { numpadPlus, none }) && ! parseChord ("F13") && ! parseChord ("Ctrl+"));
  4628. for (const auto& a : actions())
  4629. for (const auto& c : a.defaults)
  4630. CHECK (parseChord (toString (c)) == c);
  4631. // JSON overrides
  4632. std::vector<std::string> errors;
  4633. CHECK (map.loadJson (R"({ "pattern.next": "Ctrl+Right", "rack.clone": ["Alt+D", "Ctrl+D"], "help.shortcuts": "", "nope": "F1", "file.open": "Hyper+Q" })", &errors));
  4634. CHECK (errors.size() == 2);
  4635. CHECK (map.find ({ right, ctrl }, global, false) == "pattern.next" && map.find ({ numpadPlus, none }, global, false).empty());
  4636. CHECK (map.find ({ 'D', ctrl }, rack, false) == "rack.clone" && map.find ({ f1, none }, global, false).empty());
  4637. map.setChords ("pattern.previous", { { right, ctrl } });
  4638. CHECK (map.conflicts().size() == 1);
  4639. KeyMap reloaded;
  4640. CHECK (reloaded.loadJson (map.toJson()) && reloaded.chordsFor ("rack.clone") == map.chordsFor ("rack.clone"));
  4641. CHECK (! map.loadJson ("[1, 2]") && ! map.loadJson ("{\"a\": }"));
  4642. map.resetToDefaults();
  4643. CHECK (map.find ({ numpadPlus, none }, global, false) == "pattern.next");
  4644. }
  4645. TEST (workflow_workspace_layout)
  4646. {
  4647. using namespace lynx::workspace;
  4648. auto l = Layout::makeDefault (1280, 620);
  4649. // every visible panel is inside the desktop; the default shows Browser, Playlist and Channel Rack
  4650. for (const auto& p : l.panels)
  4651. CHECK (p.bounds.x >= 0 && p.bounds.y >= 0 && p.bounds.right() <= 1280 && p.bounds.bottom() <= 620 && p.bounds.w >= minWidth);
  4652. CHECK (l[Panel::browser].visible && l[Panel::playlist].visible && l[Panel::channelRack].visible);
  4653. CHECK (! l[Panel::pianoRoll].visible && ! l[Panel::mixer].visible);
  4654. CHECK (l[Panel::playlist].bounds.x == l[Panel::browser].bounds.right() && l[Panel::playlist].bounds.right() == 1280);
  4655. CHECK (l.isFrontmost (Panel::channelRack) && l.focused == Panel::channelRack);
  4656. // toggle: show+focus, focus, hide
  4657. CHECK (l.toggle (Panel::mixer) && l.focused == Panel::mixer && l.isFrontmost (Panel::mixer));
  4658. CHECK (l.toggle (Panel::channelRack) && l.focused == Panel::channelRack && l.isFrontmost (Panel::channelRack));
  4659. CHECK (! l.toggle (Panel::channelRack) && ! l[Panel::channelRack].visible && l.focused == Panel::mixer);
  4660. l.toggleMaximised (Panel::playlist);
  4661. CHECK (l[Panel::playlist].maximised && l.focused == Panel::playlist);
  4662. // save and load at another size: positions scale
  4663. l[Panel::mixer].detached = true;
  4664. l[Panel::mixer].windowBounds = { 100, 50, 900, 500 };
  4665. const auto text = l.serialise();
  4666. const auto big = Layout::parse (text, 2560, 1240);
  4667. CHECK (big.has_value());
  4668. if (big)
  4669. {
  4670. CHECK ((*big)[Panel::playlist].maximised && (*big)[Panel::mixer].detached && (*big)[Panel::mixer].windowBounds.w == 900);
  4671. CHECK (std::abs ((*big)[Panel::playlist].bounds.x - 2 * l[Panel::playlist].bounds.x) <= 1);
  4672. CHECK (big->order == l.order && big->focused == l.focused);
  4673. }
  4674. 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));
  4675. // resize keeps panels inside and edges glued to the border
  4676. l.resize (1000, 500);
  4677. CHECK (l[Panel::playlist].bounds.right() == 1000 && l[Panel::browser].bounds.bottom() == 500);
  4678. for (const auto& p : l.panels)
  4679. CHECK (p.bounds.right() <= 1000 && p.bounds.bottom() <= 500);
  4680. // off-screen panels come back
  4681. l[Panel::pianoRoll].bounds = { 5000, -300, 400, 300 };
  4682. CHECK (l.bringBackOffscreen() == 1 && l[Panel::pianoRoll].bounds.x + 400 <= 1000 && l[Panel::pianoRoll].bounds.y == 0);
  4683. // snapping: to the desktop, to another panel, and resizing one edge
  4684. CHECK ((snap ({ 5, 6, 200, 100 }, {}, 1000, 500) == Rect { 0, 0, 200, 100 }));
  4685. CHECK ((snap ({ 304, 50, 200, 100 }, { { 0, 0, 300, 400 } }, 1000, 500) == Rect { 300, 50, 200, 100 }));
  4686. CHECK ((snap ({ 304, 50, 200, 100 }, { { 0, 0, 300, 400 } }, 1000, 500, 2) == Rect { 304, 50, 200, 100 })); // out of range
  4687. CHECK ((snap ({ 100, 100, 195, 100 }, { { 300, 0, 300, 400 } }, 1000, 500, 8, right) == Rect { 100, 100, 200, 100 }));
  4688. CHECK ((snap ({ 100, 100, 195, 100 }, { { 300, 1000, 300, 400 } }, 2000, 2000, 8, right) == Rect { 100, 100, 195, 100 })); // not facing
  4689. }
  4690. TEST (workflow_control_math)
  4691. {
  4692. using namespace lynx::controls;
  4693. CHECK (std::abs (dragValue (0.5, 75, 0, 1, 150, false) - 1.0) < 1e-9);
  4694. CHECK (std::abs (dragValue (0.5, 75, 0, 1, 150, true) - 0.55) < 1e-9);
  4695. CHECK (dragValue (0.5, -1000, -1, 1, 150, false) == -1.0);
  4696. 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);
  4697. CHECK (wheelValue (3, 1, 0, 10, true, 1) == 4.0); // integer controls move at least one step
  4698. CHECK (std::abs (snapToInterval (0.234, 0, 0.1) - 0.2) < 1e-9);
  4699. CHECK (tempoDrag (130.0, 8, false, false) == 132.0 && tempoDrag (130.0, -3, false, false) == 130.0);
  4700. CHECK (std::abs (tempoDrag (130.0, 25, true, false) - 130.25) < 1e-9);
  4701. CHECK (std::abs (tempoDrag (130.0, 8, false, true) - 130.2) < 1e-9);
  4702. CHECK (tempoDrag (520.0, 400, false, false) == lynx::maxTempo && halfTempo (15.0) == lynx::minTempo && doubleTempo (130.0) == 260.0);
  4703. TapTempo tap;
  4704. CHECK (! tap.tap (1000.0));
  4705. CHECK (tap.tap (1500.0) == 120.0);
  4706. CHECK (tap.tap (2000.0) == 120.0 && tap.count() == 3);
  4707. CHECK (std::abs (*tap.tap (2400.0) - 128.57) < 0.01); // average of 500, 500, 400 ms
  4708. CHECK (! tap.tap (9000.0) && tap.count() == 1); // a long pause starts over
  4709. }
  4710. int main (int argc, char** argv)
  4711. {
  4712. if (argc > 1)
  4713. realFlpDir = argv[1];
  4714. const char* only = std::getenv ("LYNX_TEST"); // optional: run only the tests whose name contains this
  4715. for (auto& [name, fn] : registry())
  4716. {
  4717. if (only != nullptr && std::strstr (name, only) == nullptr)
  4718. continue;
  4719. std::printf ("%s\n", name);
  4720. fn();
  4721. }
  4722. std::printf ("\n%d checks, %d failures\n", checks, failures);
  4723. return failures == 0 ? 0 : 1;
  4724. }
  4725. TEST (synth_cutoff_keytrack)
  4726. {
  4727. // the cutoff follows the note from key 48 (130.81 Hz), like Harmor's "Key to filter frequency"
  4728. auto rms = [] (float keyTrack, int key) {
  4729. lynx::SynthSettings s;
  4730. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  4731. s.cutoff = 130.81f;
  4732. s.keyTrack = keyTrack;
  4733. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  4734. inst->prepare (48000.0);
  4735. lynx::ChannelDef c;
  4736. c.synth = s;
  4737. inst->configure (c, 120.0);
  4738. inst->noteOn (key, 1.0f);
  4739. std::vector<float> l (24000), r (24000);
  4740. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  4741. double e = 0.0;
  4742. for (int i = 4800; i < 24000; ++i)
  4743. e += (double) l[(std::size_t) i] * l[(std::size_t) i];
  4744. return std::sqrt (e / 19200.0);
  4745. };
  4746. const auto fixed = rms (0.0f, 72), tracked = rms (1.0f, 72);
  4747. CHECK (tracked > 4.0 * fixed); // 2 octaves up: without keytrack the low-pass cuts
  4748. CHECK (std::abs (rms (1.0f, 48) - rms (0.0f, 48)) < 0.05 * rms (0.0f, 48)); // unchanged at the reference key
  4749. }
  4750. namespace
  4751. {
  4752. std::vector<float> renderSynthNote (const lynx::SynthSettings& s, int key, int frames)
  4753. {
  4754. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  4755. inst->prepare (48000.0);
  4756. lynx::ChannelDef c;
  4757. c.synth = s;
  4758. inst->configure (c, 120.0);
  4759. inst->noteOn (key, 1.0f);
  4760. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  4761. inst->render (l.data(), r.data(), frames, 1.0f, 1.0f);
  4762. return l;
  4763. }
  4764. double goertzel (const std::vector<float>& x, double f, int from, int to)
  4765. {
  4766. const auto w = 2.0 * 3.141592653589793 * f / 48000.0, k = 2.0 * std::cos (w);
  4767. double s1 = 0.0, s2 = 0.0;
  4768. for (int i = from; i < to; ++i)
  4769. {
  4770. const auto s0 = x[(std::size_t) i] + k * s1 - s2;
  4771. s2 = s1;
  4772. s1 = s0;
  4773. }
  4774. return s1 * s1 + s2 * s2 - k * s1 * s2;
  4775. }
  4776. } // namespace
  4777. TEST (synth_pitch_sweep_ring_and_bands)
  4778. {
  4779. lynx::SynthSettings sine;
  4780. sine.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  4781. sine.cutoff = 20000.0f;
  4782. // sweep: starts at f·(1 + sweep) and returns to f (time constant s = 10 ms; s⁴ falls 4× faster)
  4783. auto sweep = sine;
  4784. sweep.sweep = 1.0f;
  4785. sweep.sweepTime = 0.01f;
  4786. const auto a = renderSynthNote (sweep, 69, 24000);
  4787. auto crossings = [] (const std::vector<float>& x, int to) {
  4788. int n = 0;
  4789. for (int i = 1; i < to; ++i)
  4790. n += (x[(std::size_t) i - 1] < 0.0f) != (x[(std::size_t) i] < 0.0f);
  4791. return n;
  4792. };
  4793. CHECK (crossings (a, 480) > 1.3 * crossings (renderSynthNote (sine, 69, 480), 480)); // 10 ms: much higher
  4794. CHECK (goertzel (a, 440.0, 12000, 24000) > 100.0 * goertzel (a, 880.0, 12000, 24000));
  4795. // ring with |a| = 1: carrier 440 × modulator 110 -> only 330 and 550, no 440
  4796. auto ring = sine;
  4797. ring.am = ring.ring = true;
  4798. ring.osc[2] = { lynx::Waveform::sine, -2, 0.0f, 1.0f };
  4799. const auto b = renderSynthNote (ring, 69, 24000);
  4800. CHECK (goertzel (b, 330.0, 4800, 24000) > 100.0 * goertzel (b, 440.0, 4800, 24000));
  4801. CHECK (goertzel (b, 550.0, 4800, 24000) > 100.0 * goertzel (b, 440.0, 4800, 24000));
  4802. // 3 bands: muting the high knocks down a 4 kHz note and barely touches an 80 Hz one
  4803. auto bands = sine;
  4804. bands.bandGain = { 1.0f, 1.0f, 0.0f };
  4805. auto rms = [] (const std::vector<float>& x) {
  4806. double e = 0.0;
  4807. for (std::size_t i = 4800; i < x.size(); ++i)
  4808. e += (double) x[i] * x[i];
  4809. return std::sqrt (e / (double) (x.size() - 4800));
  4810. };
  4811. CHECK (rms (renderSynthNote (bands, 107, 24000)) < 0.3 * rms (renderSynthNote (sine, 107, 24000)));
  4812. CHECK (rms (renderSynthNote (bands, 28, 24000)) > 0.85 * rms (renderSynthNote (sine, 28, 24000)));
  4813. }
  4814. TEST (love_philter_map_evaluation)
  4815. {
  4816. lynx::LovePhilterMap line { { { 0.0, 0.0 }, { 1.0, 1.0 } } };
  4817. CHECK (std::abs (lynx::lovePhilterMapAt (line, 0.5) - 0.5) < 1e-9);
  4818. CHECK (std::abs (lynx::lovePhilterMapAt (line, 1.0) - 1.0) < 1e-9);
  4819. // steps (Δx = 0): 1 until 0.4375, ramp to 0 at 0.5, then 0
  4820. lynx::LovePhilterMap steps { { { 0.0, 1.0 }, { 0.4375, 1.0 }, { 0.0625, 0.0 }, { 0.5, 0.0 } } };
  4821. CHECK (lynx::lovePhilterMapAt (steps, 0.27) == 1.0);
  4822. CHECK (lynx::lovePhilterMapAt (steps, 0.75) == 0.0);
  4823. CHECK (std::abs (lynx::lovePhilterMapAt (steps, 0.46875) - 0.5) < 1e-9);
  4824. CHECK (lynx::lovePhilterMapAt ({}, 0.3) == 1.0);
  4825. }
  4826. TEST (lofi_holds_and_quantizes)
  4827. {
  4828. auto fx = lynx::makeEffect (lynx::EffectKind::lofi);
  4829. fx->prepare (48000.0);
  4830. auto slot = lynx::makeEffectSlot (lynx::EffectKind::lofi);
  4831. slot.params[0] = 0.5f; // 128·0.125 + 1 = 17 samples
  4832. slot.params[1] = 1.0f; // 65536/2049 ≈ 32 levels
  4833. std::vector<float> l (170), r (170);
  4834. for (std::size_t i = 0; i < l.size(); ++i)
  4835. l[i] = r[i] = 0.9f * (float) std::sin (0.05 * (double) i);
  4836. const auto original = l;
  4837. fx->process (l.data(), r.data(), 170, slot.params, 120.0);
  4838. for (int i = 0; i < 17; ++i)
  4839. CHECK (l[(std::size_t) i] == l[0]);
  4840. CHECK (l[17] != l[16]);
  4841. const auto step = 2.0f * 2049.0f / 65536.0f;
  4842. for (auto v : l)
  4843. CHECK (std::abs (v / step - std::round (v / step)) < 1e-3f);
  4844. CHECK (std::abs (l[0] - original[0]) <= step);
  4845. CHECK (lynx::formatEffectParam (lynx::EffectKind::lofi, 1, 0.0f, 120.0) == "16.0 bits");
  4846. }
  4847. namespace
  4848. {
  4849. lynx::EffectParams effectorParams (int type, float x, float y)
  4850. {
  4851. auto slot = lynx::makeEffectSlot (lynx::EffectKind::effector);
  4852. slot.params[0] = (float) type / 11.0f;
  4853. slot.params[3] = x;
  4854. slot.params[4] = y;
  4855. return slot.params;
  4856. }
  4857. } // namespace
  4858. TEST (effector_algorithms)
  4859. {
  4860. CHECK (lynx::effector::typeOf (8.0f / 11.0f) == 8);
  4861. CHECK (std::string (lynx::effector::typeName (11)) == "Ring");
  4862. CHECK (std::abs (lynx::effector::rateBeats (0.5f, 0.0f) - 0.75) < 1e-9); // trunc(8·0.5 + 0.5) = 4 -> 3/4
  4863. CHECK (std::abs (lynx::effector::rateBeats (1.0f, 0.5f) - 2.0) < 1e-9); // 8 × (1 − 0.5)²
  4864. auto run = [] (const lynx::EffectParams& p, std::vector<float> in, double bpm = 120.0) {
  4865. auto fx = lynx::makeEffect (lynx::EffectKind::effector);
  4866. fx->prepare (48000.0);
  4867. fx->setSongPosition (0.0);
  4868. auto r = in;
  4869. fx->process (in.data(), r.data(), (int) in.size(), p, bpm);
  4870. return in;
  4871. };
  4872. // Distort with Y = 1 (everything goes to the cascade): 0.5 comes out 0.5 (compensation G = 0.5/F(0.5))
  4873. {
  4874. auto p = effectorParams (0, 0.5f, 1.0f);
  4875. const auto out = run (p, std::vector<float> (4800, 0.5f));
  4876. CHECK (std::abs (out.back() - 0.5f) < 1e-3f);
  4877. const auto small = run (p, std::vector<float> (4800, 0.05f));
  4878. CHECK (small.back() > 0.45f && small.back() < 0.5f); // saturates near ±0.5
  4879. }
  4880. // Ring: DC 1 becomes the carrier sine, 2^(8.7·0 + 5) = 32 Hz -> 32 cycles per second
  4881. {
  4882. auto p = effectorParams (11, 0.0f, 0.0f);
  4883. const auto out = run (p, std::vector<float> (48000, 1.0f));
  4884. int crossings = 0;
  4885. for (std::size_t i = 4800; i < out.size(); ++i)
  4886. crossings += (out[i - 1] < 0.0f) != (out[i] < 0.0f);
  4887. CHECK (crossings >= 56 && crossings <= 60); // 0.9 s × 32 Hz × 2
  4888. }
  4889. // Trancer, Y = 0: at the start of the period the gain drops to zero; X = 1 returns only at the end of the period
  4890. {
  4891. auto p = effectorParams (8, 1.0f, 0.0f);
  4892. p[5] = 1.0f; // 8/1 = 8 beats = 4 s at 120 BPM
  4893. const auto out = run (p, std::vector<float> (48000, 1.0f));
  4894. CHECK (out[100] > 0.3f); // still rising on the "and" (1% of the period = 40 ms)
  4895. CHECK (out[24000] < 0.05f); // 0.5 s: trough
  4896. }
  4897. // Reverb with Wet = 0: the dry passes intact
  4898. {
  4899. auto p = effectorParams (6, 0.5f, 0.5f);
  4900. p[2] = 0.0f;
  4901. std::vector<float> in (4800);
  4902. for (std::size_t i = 0; i < in.size(); ++i)
  4903. in[i] = (float) std::sin (0.01 * (double) i);
  4904. const auto out = run (p, in);
  4905. for (std::size_t i = 0; i < in.size(); ++i)
  4906. CHECK (std::abs (out[i] - in[i]) < 1e-6f);
  4907. }
  4908. // Delay: the echo arrives after the Mod Rate period (1/4 beat at 120 BPM = 125 ms), at level X²
  4909. {
  4910. auto p = effectorParams (5, 0.7f, 0.5f);
  4911. p[5] = 1.0f / 8.0f; // index 1 = 1/4
  4912. std::vector<float> in (12000, 0.0f);
  4913. in[0] = 1.0f;
  4914. const auto out = run (p, in);
  4915. CHECK (std::abs (out[6000] - 0.49f) < 0.02f);
  4916. CHECK (std::abs (out[3000]) < 1e-6f);
  4917. }
  4918. // Stutter: repeats the recorded start every period
  4919. {
  4920. auto p = effectorParams (9, 0.0f, 0.0f);
  4921. p[5] = 0.0f; // 1/8 beat = 62.5 ms = 3000 samples
  4922. std::vector<float> in (9000);
  4923. for (std::size_t i = 0; i < in.size(); ++i)
  4924. in[i] = (float) i / 9000.0f;
  4925. const auto out = run (p, in);
  4926. CHECK (std::abs (out[3000 + 500] - in[500]) < 0.01f); // after the crossfade, it's the start again
  4927. CHECK (std::abs (out[1000] - in[1000]) < 1e-6f);
  4928. }
  4929. }
  4930. TEST (crossover_linkwitz_riley_sums_flat)
  4931. {
  4932. // low band + high band of the same crossover: sum with magnitude 1 (Linkwitz-Riley; for 12 and 36 dB the HP is inverted)
  4933. for (const auto combo : { 1, 3, 4, 5, 6, 7 })
  4934. for (const auto testHz : { 200.0, 1000.0, 5000.0 })
  4935. {
  4936. auto run = [&] (bool high) {
  4937. auto fx = lynx::makeEffect (lynx::EffectKind::crossover);
  4938. fx->prepare (48000.0);
  4939. auto slot = lynx::makeEffectSlot (lynx::EffectKind::crossover);
  4940. const auto value = (float) (std::log2 (1000.0 / 30.0) / 9.0589);
  4941. slot.params[high ? 0 : 3] = 1.0f;
  4942. slot.params[high ? 1 : 4] = value;
  4943. slot.params[high ? 2 : 5] = (float) combo / 7.0f;
  4944. std::vector<float> l (24000), r (24000);
  4945. for (std::size_t i = 0; i < l.size(); ++i)
  4946. l[i] = r[i] = (float) std::sin (2.0 * 3.141592653589793 * testHz * (double) i / 48000.0);
  4947. fx->process (l.data(), r.data(), 24000, slot.params, 120.0);
  4948. return l;
  4949. };
  4950. const auto low = run (false), high = run (true);
  4951. double peak = 0.0;
  4952. for (std::size_t i = 12000; i < low.size(); ++i)
  4953. peak = std::max (peak, (double) std::abs (low[i] + high[i]));
  4954. CHECK (std::abs (peak - 1.0) < 0.02);
  4955. }
  4956. // 96 dB/oct: two octaves above the cutoff the low-pass is already below −150 dB... in practice, very low
  4957. auto fx = lynx::makeEffect (lynx::EffectKind::crossover);
  4958. fx->prepare (48000.0);
  4959. auto slot = lynx::makeEffectSlot (lynx::EffectKind::crossover);
  4960. slot.params[3] = 1.0f;
  4961. slot.params[4] = (float) (std::log2 (500.0 / 30.0) / 9.0589);
  4962. slot.params[5] = 1.0f;
  4963. std::vector<float> l (24000), r (24000);
  4964. for (std::size_t i = 0; i < l.size(); ++i)
  4965. l[i] = r[i] = (float) std::sin (2.0 * 3.141592653589793 * 2000.0 * (double) i / 48000.0);
  4966. fx->process (l.data(), r.data(), 24000, slot.params, 120.0);
  4967. float peak = 0.0f;
  4968. for (std::size_t i = 12000; i < l.size(); ++i)
  4969. peak = std::max (peak, std::abs (l[i]));
  4970. CHECK (peak < 1e-4f);
  4971. }
  4972. TEST (rhythm_gain_and_autopan)
  4973. {
  4974. // 1-beat gate: 1 → 0 at 0.5 beat (linear) → 1 at the end; at 120 BPM 1 beat = 24000 samples at 48 kHz
  4975. auto slot = lynx::makeEffectSlot (lynx::EffectKind::rhythmGain);
  4976. slot.params[0] = 1.0f / 64.0f;
  4977. slot.params[1] = 3.0f / 12.0f;
  4978. const float pts[3][3] = { { 0.0f, 1.0f, 0.5f }, { 0.5f, 0.0f, 0.5f }, { 1.0f, 1.0f, 0.5f } };
  4979. for (int k = 0; k < 3; ++k)
  4980. for (int j = 0; j < 3; ++j)
  4981. slot.params[(std::size_t) (2 + 3 * k + j)] = pts[k][j];
  4982. auto fx = lynx::makeEffect (lynx::EffectKind::rhythmGain);
  4983. fx->prepare (48000.0);
  4984. fx->setSongPosition (960.0 * 2.0); // beat 2: phase 0
  4985. std::vector<float> l (24000, 1.0f), r (24000, 1.0f);
  4986. fx->process (l.data(), r.data(), 24000, slot.params, 120.0);
  4987. CHECK (std::abs (l[0] - 1.0f) < 1e-3f);
  4988. CHECK (std::abs (l[6000] - 0.5f) < 1e-3f);
  4989. CHECK (l[12000] < 1e-3f);
  4990. CHECK (std::abs (l[18000] - 0.5f) < 1e-3f);
  4991. // positive tension: changes quickly at the start of the segment
  4992. CHECK (lynx::effectInfo (lynx::EffectKind::rhythmGain).params.size() == 39);
  4993. // auto-pan: 1-beat period, full depth; start phase 0.75 -> W = 0 rising (pan centered)
  4994. auto pan = lynx::makeEffectSlot (lynx::EffectKind::autoPan);
  4995. pan.params[0] = 1.0f / 64.0f;
  4996. pan.params[1] = 1.0f;
  4997. auto ap = lynx::makeEffect (lynx::EffectKind::autoPan);
  4998. ap->prepare (48000.0);
  4999. ap->setSongPosition (0.0);
  5000. std::vector<float> a (24000, 1.0f), b (24000, 1.0f);
  5001. ap->process (a.data(), b.data(), 24000, pan.params, 120.0);
  5002. CHECK (std::abs (a[0] - 1.0f) < 1e-3f && std::abs (b[0] - 1.0f) < 1e-3f);
  5003. CHECK (a[6000] < 0.01f && std::abs (b[6000] - 1.0f) < 1e-3f); // ¼ cycle later: fully right
  5004. }
  5005. TEST (vocoder_side_inputs_split_modulator_and_carrier)
  5006. {
  5007. // "Side inputs" mode (Vocodex): modulator from side input 1 (noise in the first half), carrier from side input 2
  5008. // (saw), own input silent → the output follows the side modulator; with input 1 silent, the output is silent
  5009. auto slot = lynx::makeEffectSlot (lynx::EffectKind::vocoder);
  5010. slot.params[16] = 1.0f;
  5011. auto fx = lynx::makeEffect (lynx::EffectKind::vocoder);
  5012. fx->prepare (48000.0);
  5013. std::vector<float> modL (48000), car (48000), l (48000, 0.0f), r (48000, 0.0f);
  5014. std::uint32_t seed = 1;
  5015. for (std::size_t i = 0; i < modL.size(); ++i)
  5016. {
  5017. seed = seed * 1664525u + 1013904223u;
  5018. modL[i] = i < 24000 ? ((float) (seed >> 8) / 16777216.0f - 0.5f) : 0.0f;
  5019. car[i] = (float) (2.0 * std::fmod ((double) i * 220.0 / 48000.0, 1.0) - 1.0) * 0.5f;
  5020. }
  5021. for (int done = 0; done < 48000; done += 480)
  5022. {
  5023. fx->setSidechain (modL.data() + done, modL.data() + done);
  5024. fx->setSidechain2 (car.data() + done, car.data() + done);
  5025. fx->process (l.data() + done, r.data() + done, 480, slot.params, 120.0);
  5026. }
  5027. auto rms = [&] (int from, int to) {
  5028. double e = 0.0;
  5029. for (int i = from; i < to; ++i)
  5030. e += (double) l[(std::size_t) i] * l[(std::size_t) i];
  5031. return std::sqrt (e / (to - from));
  5032. };
  5033. CHECK (rms (6000, 20000) > 0.01);
  5034. CHECK (rms (40000, 48000) < 0.1 * rms (6000, 20000));
  5035. // the side modulator configured but silent: nothing comes out (the own input is not used instead)
  5036. std::vector<float> a (4800, 0.3f), b (4800, 0.3f);
  5037. for (int done = 0; done < 4800; done += 480)
  5038. {
  5039. fx->setSidechain (nullptr, nullptr);
  5040. fx->setSidechain2 (car.data() + done, car.data() + done);
  5041. fx->process (a.data() + done, b.data() + done, 480, slot.params, 120.0);
  5042. }
  5043. CHECK (std::abs (a[4700]) < 0.05f);
  5044. }
  5045. TEST (vocoder_follows_modulator)
  5046. {
  5047. // modulator (L) plays only in the first half; carrier (R) is a continuous saw: the wet follows the modulator
  5048. auto slot = lynx::makeEffectSlot (lynx::EffectKind::vocoder);
  5049. auto fx = lynx::makeEffect (lynx::EffectKind::vocoder);
  5050. fx->prepare (48000.0);
  5051. std::vector<float> l (48000), r (48000);
  5052. std::uint32_t seed = 1;
  5053. for (std::size_t i = 0; i < l.size(); ++i)
  5054. {
  5055. seed = seed * 1664525u + 1013904223u;
  5056. l[i] = i < 24000 ? ((float) (seed >> 8) / 16777216.0f - 0.5f) : 0.0f;
  5057. r[i] = (float) (2.0 * std::fmod ((double) i * 220.0 / 48000.0, 1.0) - 1.0) * 0.5f;
  5058. }
  5059. fx->process (l.data(), r.data(), 48000, slot.params, 120.0);
  5060. auto rms = [&] (int from, int to) {
  5061. double e = 0.0;
  5062. for (int i = from; i < to; ++i)
  5063. e += (double) l[(std::size_t) i] * l[(std::size_t) i];
  5064. return std::sqrt (e / (to - from));
  5065. };
  5066. CHECK (rms (6000, 20000) > 0.01);
  5067. CHECK (rms (40000, 48000) < 0.1 * rms (6000, 20000)); // modulator silent: the vocoder fades out (100 ms release)
  5068. for (std::size_t i = 0; i < l.size(); ++i)
  5069. CHECK (l[i] == r[i] && std::isfinite (l[i])); // mono output
  5070. }
  5071. // Vocodex (REA_rodada35): a synthetic state in FL's layout (version 8, 13 maps, 20 parameters, the 0x24 block,
  5072. // 13 map-axis bytes, tone, notes)
  5073. struct VocodexSpec
  5074. {
  5075. // Wet, SG, ModVol, ModHP, CarVol, CarLP, CarNoise, CarNoiseHP, Hold, Att, AttCurve, Rel, RelCurve, Freeze, BW,
  5076. // Flatness, ModBW, ModPitch, FatPitch, FatPan
  5077. 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 };
  5078. std::array<std::int32_t, 7> block { 0, 2, 0, 24, 1, 1, 2 }; // hold mode, order, unison, bands, draft field, ModIn, CarIn
  5079. 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
  5080. std::vector<std::uint8_t> bytes() const
  5081. {
  5082. std::vector<std::uint8_t> d;
  5083. 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); };
  5084. auto i32 = [&] (std::int32_t v) { put (&v, 4); };
  5085. i32 (8 << 16);
  5086. for (int m = 0; m < 13; ++m)
  5087. {
  5088. const double y0 = m == 8 ? 0.1429 : (m == 3 || m == 4 || m == 11) ? 0.0 : 0.5;
  5089. const double y1 = m == 8 ? 0.9918 : y0;
  5090. i32 (1), i32 (0), i32 (2);
  5091. for (const auto& [dx, y] : { std::pair { 0.0, y0 }, std::pair { 1.0, y1 } })
  5092. {
  5093. put (&dx, 8), put (&y, 8);
  5094. i32 (0), i32 (0); // tension (f32 0), flags
  5095. }
  5096. const std::array<std::uint8_t, 20> tail {};
  5097. put (tail.data(), tail.size());
  5098. }
  5099. for (auto v : params)
  5100. i32 (v);
  5101. for (auto v : block)
  5102. i32 (v);
  5103. put (flags.data(), flags.size());
  5104. const std::array<std::uint8_t, 13> axis {};
  5105. put (axis.data(), axis.size());
  5106. d.push_back (3), put ("PWM", 3);
  5107. i32 (1), i32 (60);
  5108. return d;
  5109. }
  5110. };
  5111. std::vector<float> vocodexSaw (int n, double hz, double fs)
  5112. {
  5113. std::vector<float> out ((std::size_t) n);
  5114. for (int i = 0; i < n; ++i)
  5115. out[(std::size_t) i] = (float) (2.0 * std::fmod (i * hz / fs, 1.0) - 1.0) * 0.4f;
  5116. return out;
  5117. }
  5118. TEST (vocodex_state_parse_and_conversion)
  5119. {
  5120. VocodexSpec spec;
  5121. spec.block = { 1, 3, 2, 40, 0, 2, 1 };
  5122. spec.params[17] = -1200;
  5123. const auto raw = spec.bytes();
  5124. const auto s = lynx::vocodex::parseState (raw);
  5125. CHECK (s.has_value());
  5126. if (! s)
  5127. return;
  5128. CHECK (s->version == 8 && s->holdMode == 1 && s->order == 3 && s->unison == 2 && s->bands == 40);
  5129. CHECK (s->draft() && s->modIn == 2 && s->carIn == 1 && s->minTimes && s->subtractiveGate && ! s->lrEncoding);
  5130. CHECK (s->params[lynx::vocodex::modPitch] == -1200 && s->params[lynx::vocodex::carLp] == 65536);
  5131. 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);
  5132. CHECK (s->tone == "PWM" && s->notes.size() == 1 && s->notes[0] == 60);
  5133. const auto v = lynx::vocodexEffect (raw);
  5134. CHECK (v && v->slot.kind == lynx::EffectKind::vocodex && v->slot.state == raw && v->modIn == 2 && v->carIn == 1 && v->notes.empty());
  5135. spec.block[6] = -1; // internal synth carrier: not available yet → reported
  5136. spec.params[1] = 150; // Soundgoodizer stage
  5137. const auto w = lynx::vocodexEffect (spec.bytes());
  5138. CHECK (w && w->carIn == -1 && w->notes.size() == 2);
  5139. CHECK (! lynx::vocodex::parseState ({ 1, 2, 3 }).has_value());
  5140. }
  5141. TEST (vocodex_vocodes_side_inputs)
  5142. {
  5143. // modulator on side input 1 (noise in the first half), carrier on side input 2 (saw), own input silent: the
  5144. // output follows the modulator's envelope and fades after it stops
  5145. VocodexSpec spec;
  5146. lynx::EffectSlot slot = lynx::makeEffectSlot (lynx::EffectKind::vocodex);
  5147. slot.state = spec.bytes();
  5148. auto fx = lynx::makeEffect (slot);
  5149. fx->prepare (48000.0);
  5150. CHECK (fx->latencySamples() == 0);
  5151. const auto car = vocodexSaw (48000, 110.0, 48000.0);
  5152. std::vector<float> mod (48000), l (48000, 0.0f), r (48000, 0.0f);
  5153. std::uint32_t seed = 7;
  5154. for (std::size_t i = 0; i < mod.size(); ++i)
  5155. {
  5156. seed = seed * 1664525u + 1013904223u;
  5157. mod[i] = i < 24000 ? ((float) (seed >> 8) / 16777216.0f - 0.5f) : 0.0f;
  5158. }
  5159. for (int done = 0; done < 48000; done += 512)
  5160. {
  5161. const int n = std::min (512, 48000 - done);
  5162. fx->setSidechain (mod.data() + done, mod.data() + done);
  5163. fx->setSidechain2 (car.data() + done, car.data() + done);
  5164. fx->process (l.data() + done, r.data() + done, n, slot.params, 120.0);
  5165. }
  5166. auto rms = [&] (int from, int to) {
  5167. double e = 0.0;
  5168. for (int i = from; i < to; ++i)
  5169. e += (double) l[(std::size_t) i] * l[(std::size_t) i] + (double) r[(std::size_t) i] * r[(std::size_t) i];
  5170. return std::sqrt (e / (2.0 * (to - from)));
  5171. };
  5172. CHECK (rms (6000, 20000) > 0.02);
  5173. CHECK (rms (40000, 48000) < 0.01 * rms (6000, 20000));
  5174. CHECK (std::abs (l[0]) < 1e-6f); // the gains ramp up from 0 when the plugin is created
  5175. }
  5176. TEST (vocodex_draft_latency_and_pass_through)
  5177. {
  5178. // carrier pass-through at unit gain only (Wet 0): after a Flush the gains snap, so the output is the carrier,
  5179. // 16 samples late in Draft
  5180. VocodexSpec spec;
  5181. spec.params[0] = 0; // Wet
  5182. spec.params[4] = 12800; // CarVol = 1
  5183. for (const int draftField : { 1, 0 })
  5184. {
  5185. spec.block[4] = draftField;
  5186. const auto s = lynx::vocodex::parseState (spec.bytes());
  5187. CHECK (s.has_value());
  5188. lynx::vocodex::Engine engine;
  5189. engine.prepare (*s, 44100.0, 300, s->draft());
  5190. CHECK (engine.latencySamples() == (draftField == 0 ? 16 : 0));
  5191. engine.flush();
  5192. const auto saw = vocodexSaw (3000, 220.0, 44100.0);
  5193. std::vector<float> car (6000), mod (6000, 0.0f), out (6000);
  5194. for (int i = 0; i < 3000; ++i)
  5195. car[(std::size_t) (2 * i)] = car[(std::size_t) (2 * i + 1)] = saw[(std::size_t) i];
  5196. static constexpr int sizes[] { 300, 37, 128, 1, 255, 16, 299 }; // uneven blocks exercise the FIFOs
  5197. for (int done = 0, k = 0, n = 0; done < 3000; done += n, ++k)
  5198. {
  5199. n = std::min (sizes[k % 7], 3000 - done);
  5200. engine.process (mod.data() + 2 * done, mod.data() + 2 * done, car.data() + 2 * done, out.data() + 2 * done, n);
  5201. }
  5202. const int lag = engine.latencySamples();
  5203. auto maxError = 0.0f;
  5204. for (int i = lag; i < 3000; ++i)
  5205. maxError = std::max (maxError, std::abs (out[(std::size_t) (2 * i)] - saw[(std::size_t) (i - lag)]));
  5206. CHECK (maxError == 0.0f);
  5207. }
  5208. }
  5209. TEST (vocodex_soundgoodizer_stage_limits_the_output)
  5210. {
  5211. // SG > 0: the vocoder's output (loud here: Wet 2000) goes through the Soundgoodizer approximation, whose
  5212. // master limiter keeps the peaks under −0.2 dBFS; its look-ahead is reported as latency
  5213. VocodexSpec spec;
  5214. spec.params[0] = 2000;
  5215. spec.params[1] = 250;
  5216. lynx::EffectSlot slot = lynx::makeEffectSlot (lynx::EffectKind::vocodex);
  5217. slot.state = spec.bytes();
  5218. auto fx = lynx::makeEffect (slot);
  5219. fx->prepare (48000.0);
  5220. CHECK (fx->latencySamples() == 72); // 1.5 ms at 48 kHz
  5221. const auto car = vocodexSaw (48000, 110.0, 48000.0);
  5222. std::vector<float> mod (48000), l (48000, 0.0f), r (48000, 0.0f);
  5223. for (std::size_t i = 0; i < mod.size(); ++i)
  5224. mod[i] = 0.9f * (float) std::sin (0.07 * (double) i) * (float) std::sin (0.0003 * (double) i);
  5225. auto peak = 0.0f;
  5226. for (int done = 0; done < 48000; done += 512)
  5227. {
  5228. const int n = std::min (512, 48000 - done);
  5229. fx->setSidechain (mod.data() + done, mod.data() + done);
  5230. fx->setSidechain2 (car.data() + done, car.data() + done);
  5231. fx->process (l.data() + done, r.data() + done, n, slot.params, 120.0);
  5232. }
  5233. for (std::size_t i = 0; i < l.size(); ++i)
  5234. peak = std::max ({ peak, std::abs (l[i]), std::abs (r[i]) });
  5235. CHECK (peak > 0.5f && peak <= 0.9775f);
  5236. }
  5237. TEST (vocodex_tail_bypass_and_noise)
  5238. {
  5239. // both inputs silent for longer than 0.5 s + hold + release: the own input passes unchanged
  5240. VocodexSpec spec;
  5241. const auto s = lynx::vocodex::parseState (spec.bytes());
  5242. CHECK (s.has_value());
  5243. lynx::vocodex::Engine engine;
  5244. engine.prepare (*s, 44100.0, 512, false);
  5245. std::vector<float> zero (1024, 0.0f), own (1024), out (1024);
  5246. for (std::size_t i = 0; i < own.size(); ++i)
  5247. own[i] = 0.25f * (float) std::sin (0.01 * (double) i);
  5248. for (int b = 0; b < 80; ++b)
  5249. engine.process (own.data(), zero.data(), zero.data(), out.data(), 512);
  5250. CHECK (out == own);
  5251. // carrier noise: the IPP-compatible generator restarts from the same seed after a Flush
  5252. spec.params[6] = 9000;
  5253. const auto noisy = lynx::vocodex::parseState (spec.bytes());
  5254. lynx::vocodex::Engine a;
  5255. a.prepare (*noisy, 44100.0, 512, false);
  5256. std::vector<float> mod (1024), first (1024), second (1024);
  5257. for (std::size_t i = 0; i < mod.size(); ++i)
  5258. mod[i] = 0.3f * (float) std::sin (0.05 * (double) i);
  5259. a.flush();
  5260. a.process (own.data(), mod.data(), zero.data(), first.data(), 512);
  5261. a.flush();
  5262. a.process (own.data(), mod.data(), zero.data(), second.data(), 512);
  5263. CHECK (first == second);
  5264. auto energy = 0.0;
  5265. for (auto v : first)
  5266. energy += (double) v * v;
  5267. CHECK (energy > 1e-6 && std::isfinite (energy));
  5268. }
  5269. TEST (synth_spectral_oscillator)
  5270. {
  5271. // 1/n spectrum = saw: same harmonic proportions and same level as LYNX's saw
  5272. lynx::SynthSettings saw;
  5273. saw.osc[0] = { lynx::Waveform::saw, 0, 0.0f, 1.0f };
  5274. saw.cutoff = 20000.0f;
  5275. auto spectral = saw;
  5276. spectral.osc[0].wave = lynx::Waveform::spectral;
  5277. for (int n = 1; n <= lynx::SynthSettings::spectrumSize; ++n)
  5278. spectral.spectrum[(std::size_t) n - 1] = 1.0f / (float) n;
  5279. const auto a = renderSynthNote (saw, 57, 24000), b = renderSynthNote (spectral, 57, 24000); // 220 Hz
  5280. for (const auto h : { 1, 2, 3, 5 })
  5281. {
  5282. const auto ea = goertzel (a, 220.0 * h, 4800, 24000), eb = goertzel (b, 220.0 * h, 4800, 24000);
  5283. CHECK (std::abs (10.0 * std::log10 (eb / ea)) < 0.5); // within 0.5 dB
  5284. }
  5285. // odd only: no 2nd harmonic
  5286. auto odd = spectral;
  5287. for (int n = 2; n <= lynx::SynthSettings::spectrumSize; n += 2)
  5288. odd.spectrum[(std::size_t) n - 1] = 0.0f;
  5289. const auto c = renderSynthNote (odd, 57, 24000);
  5290. CHECK (goertzel (c, 440.0, 4800, 24000) < 1e-4 * goertzel (c, 220.0, 4800, 24000));
  5291. // high note: the band-limited tables don't pass Nyquist (no aliasing below the fundamental)
  5292. const auto d = renderSynthNote (spectral, 105, 24000); // 3520 Hz
  5293. CHECK (goertzel (d, 1000.0, 4800, 24000) < 1e-3 * goertzel (d, 3520.0, 4800, 24000));
  5294. }
  5295. TEST (compressor_sidechain_ducks_and_orders_mixer)
  5296. {
  5297. // the detector listens to the side input: quiet signal on the track, loud kick on the sidechain -> reduction
  5298. auto slot = lynx::makeEffectSlot (lynx::EffectKind::compressor);
  5299. slot.params[0] = 0.5f; // threshold
  5300. slot.params[1] = 1.0f; // high ratio
  5301. slot.params[4] = 0.0f;
  5302. auto run = [&] (bool withSidechain) {
  5303. auto fx = lynx::makeEffect (lynx::EffectKind::compressor);
  5304. fx->prepare (48000.0);
  5305. std::vector<float> l (4800, 0.1f), r (4800, 0.1f), kick (4800, 1.0f);
  5306. if (withSidechain)
  5307. fx->setSidechain (kick.data(), kick.data());
  5308. fx->process (l.data(), r.data(), 4800, slot.params, 120.0);
  5309. return l.back();
  5310. };
  5311. const auto alone = run (false), ducked = run (true);
  5312. CHECK (ducked < 0.5f * alone);
  5313. // order: track 5 listens to 7 via sidechain -> 7 comes before 5
  5314. auto song = lynx::Song::makeDefault();
  5315. while (song.mixer.size() < 8)
  5316. song.mixer.push_back ({});
  5317. auto comp = lynx::makeEffectSlot (lynx::EffectKind::compressor);
  5318. comp.sidechain = 7;
  5319. song.mixer[5].effects.push_back (comp);
  5320. const auto order = song.mixerOrder();
  5321. const auto at = [&] (int t) { return std::find (order.begin(), order.end(), t) - order.begin(); };
  5322. CHECK (at (7) < at (5));
  5323. }
  5324. TEST (pitch_correction_pulls_to_allowed_note)
  5325. {
  5326. auto run = [] (const lynx::EffectParams& p, double hz) {
  5327. auto fx = lynx::makeEffect (lynx::EffectKind::pitchCorrect);
  5328. fx->prepare (48000.0);
  5329. std::vector<float> l (48000 * 2), r;
  5330. for (std::size_t i = 0; i < l.size(); ++i)
  5331. l[i] = 0.5f * (float) std::sin (2.0 * 3.141592653589793 * hz * (double) i / 48000.0);
  5332. r = l;
  5333. fx->process (l.data(), r.data(), (int) l.size(), p, 120.0);
  5334. // frequency from zero crossings in the last second
  5335. int crossings = 0;
  5336. for (std::size_t i = 48000 + 1; i < l.size(); ++i)
  5337. crossings += (l[i - 1] < 0.0f) != (l[i] < 0.0f);
  5338. return crossings / 2.0;
  5339. };
  5340. auto slot = lynx::makeEffectSlot (lynx::EffectKind::pitchCorrect); // chromatic, instant, A 440
  5341. CHECK (std::abs (run (slot.params, 452.0) - 440.0) < 4.0);
  5342. for (int k = 0; k < 12; ++k)
  5343. slot.params[(std::size_t) (5 + k)] = k == 0 ? 1.0f : 0.0f; // only C
  5344. CHECK (std::abs (run (slot.params, 452.0) - 523.25) < 5.0); // C5 (523 Hz) is closer than C4 (262)
  5345. slot.params[2] = 1.0f; // turn everything off: passes unchanged
  5346. CHECK (std::abs (run (slot.params, 452.0) - 452.0) < 4.0);
  5347. }
  5348. TEST (pitch_correction_bypass_is_a_pure_delay)
  5349. {
  5350. // FL's Pitcher with Bypass All still runs its shifter: the plain path is an exact 9-sample delay, the formant
  5351. // path (256-Hann overlap-add) an exact 257-sample delay, and Gender changes nothing without a shift
  5352. // (REA_rodada30 §2.4/2.5); both are reported as latency
  5353. std::vector<float> in (48000);
  5354. for (std::size_t i = 0; i < in.size(); ++i)
  5355. in[i] = 0.5f * (float) std::sin (2.0 * 3.141592653589793 * 440.0 * (double) i / 48000.0)
  5356. + 0.2f * (float) std::sin (2.0 * 3.141592653589793 * 1234.5 * (double) i / 48000.0);
  5357. auto run = [&] (bool formant, float gender, int& latency) {
  5358. auto fx = lynx::makeEffect (lynx::EffectKind::pitchCorrect);
  5359. fx->prepare (48000.0);
  5360. auto slot = lynx::makeEffectSlot (lynx::EffectKind::pitchCorrect);
  5361. slot.params[2] = 1.0f;
  5362. slot.params[29] = formant ? 1.0f : 0.0f;
  5363. slot.params[30] = gender;
  5364. auto l = in, r = in;
  5365. for (std::size_t i = 0; i < l.size(); i += 480)
  5366. fx->process (l.data() + i, r.data() + i, 480, slot.params, 120.0);
  5367. latency = fx->latencySamples();
  5368. return l;
  5369. };
  5370. int latency = 0;
  5371. auto plain = run (false, 0.5f, latency);
  5372. CHECK (latency == 9);
  5373. auto worst = 0.0f;
  5374. for (std::size_t i = 4000; i < in.size(); ++i)
  5375. worst = std::max (worst, std::abs (plain[i] - in[i - 9]));
  5376. CHECK (worst < 1e-5f);
  5377. auto formant = run (true, 0.8f, latency);
  5378. CHECK (latency == 257);
  5379. worst = 0.0f;
  5380. for (std::size_t i = 4000; i < in.size(); ++i)
  5381. worst = std::max (worst, std::abs (formant[i] - in[i - 257]));
  5382. CHECK (worst < 1e-5f);
  5383. }
  5384. TEST (pitch_correction_formant_path)
  5385. {
  5386. // Formant on: PSOLA keeps the correction (output pitch = grain spacing) while Gender resamples the grains:
  5387. // the spectrum of a saw moves up with Gender > 0.5 and down with Gender < 0.5
  5388. auto run = [] (float gender) {
  5389. auto fx = lynx::makeEffect (lynx::EffectKind::pitchCorrect);
  5390. fx->prepare (48000.0);
  5391. auto slot = lynx::makeEffectSlot (lynx::EffectKind::pitchCorrect); // chromatic, instant, A 440
  5392. slot.params[29] = 1.0f;
  5393. slot.params[30] = gender;
  5394. std::vector<float> l (48000 * 2), r;
  5395. for (std::size_t i = 0; i < l.size(); ++i)
  5396. l[i] = 0.5f * (float) (2.0 * std::fmod (452.0 * (double) i / 48000.0, 1.0) - 1.0); // saw
  5397. r = l;
  5398. fx->process (l.data(), r.data(), (int) l.size(), slot.params, 120.0);
  5399. l.erase (l.begin(), l.begin() + 48000);
  5400. return l;
  5401. };
  5402. // period by autocorrelation (lags 60…160 = 300…800 Hz)
  5403. auto pitch = [] (const std::vector<float>& x) {
  5404. auto best = 0.0, bestLag = 0.0;
  5405. for (int lag = 60; lag <= 160; ++lag)
  5406. {
  5407. auto sum = 0.0;
  5408. for (std::size_t i = 0; i + (std::size_t) lag < x.size(); ++i)
  5409. sum += (double) x[i] * x[i + (std::size_t) lag];
  5410. if (sum > best)
  5411. {
  5412. best = sum;
  5413. bestLag = lag;
  5414. }
  5415. }
  5416. return 48000.0 / bestLag;
  5417. };
  5418. // brightness: energy of the first difference relative to the energy
  5419. auto brightness = [] (const std::vector<float>& x) {
  5420. auto e = 0.0, d = 0.0;
  5421. for (std::size_t i = 1; i < x.size(); ++i)
  5422. {
  5423. e += (double) x[i] * x[i];
  5424. d += (double) (x[i] - x[i - 1]) * (x[i] - x[i - 1]);
  5425. }
  5426. return d / e;
  5427. };
  5428. const auto neutral = run (0.5f), up = run (0.8f), down = run (0.3f);
  5429. CHECK (std::abs (pitch (neutral) - 440.0) < 5.0); // 452 Hz pulled to A
  5430. CHECK (std::abs (pitch (up) - 440.0) < 5.0); // Gender does not move the pitch
  5431. CHECK (brightness (up) > 1.5 * brightness (neutral));
  5432. CHECK (brightness (down) < 0.7 * brightness (neutral));
  5433. }
  5434. TEST (parallel_container_inner_links_modulate)
  5435. {
  5436. // one branch: utility (gain) + a control-only auto-pan LFO (1 beat); the link maps the LFO 0..1 onto the
  5437. // utility gain −24 dB..0 dB, so the level must swing; without the link it stays put
  5438. auto container = lynx::makeEffectSlot (lynx::EffectKind::parallel);
  5439. auto gain = lynx::makeEffectSlot (lynx::EffectKind::utility);
  5440. auto lfo = lynx::makeEffectSlot (lynx::EffectKind::autoPan);
  5441. lfo.params[0] = 1.0f / 64.0f;
  5442. lfo.params[4] = 1.0f; // control only: audio passes unchanged
  5443. container.branches.push_back ({ { gain, lfo }, 1.0f });
  5444. lynx::EffectLink link;
  5445. link.source = 1;
  5446. link.param = 0;
  5447. for (int i = 0; i <= 32; ++i)
  5448. link.curve.push_back (0.5f * (float) i / 32.0f);
  5449. auto levels = [&] (bool linked) {
  5450. auto slot = container;
  5451. if (linked)
  5452. slot.links.push_back (link);
  5453. auto fx = lynx::makeParallelEffect (slot);
  5454. fx->prepare (48000.0);
  5455. float lo = 1e9f, hi = 0.0f;
  5456. for (int block = 0; block < 94; ++block) // ~1 beat at 120 BPM in 256-sample blocks
  5457. {
  5458. std::vector<float> l (256, 1.0f), r (256, 1.0f);
  5459. fx->setSongPosition (block * 256.0 / 48000.0 * 2.0 * 960.0); // the engine positions every block
  5460. fx->process (l.data(), r.data(), 256, slot.params, 120.0);
  5461. lo = std::min (lo, std::abs (l[128]));
  5462. hi = std::max (hi, std::abs (l[128]));
  5463. }
  5464. return std::pair { lo, hi };
  5465. };
  5466. const auto [lo, hi] = levels (true);
  5467. CHECK (hi > 0.8f && lo < 0.12f);
  5468. const auto [lo0, hi0] = levels (false);
  5469. CHECK (std::abs (hi0 - lo0) < 1e-4f);
  5470. }
  5471. TEST (synth_spectrum_decays_per_harmonic)
  5472. {
  5473. // 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
  5474. lynx::SynthSettings s;
  5475. s.osc[0] = { lynx::Waveform::spectral, 0, 0.0f, 1.0f };
  5476. s.cutoff = 20000.0f;
  5477. s.decay = 0.0f;
  5478. s.sustain = 1.0f;
  5479. s.spectrum[0] = 1.0f;
  5480. s.spectrum[2] = 1.0f;
  5481. s.spectrumDecay[2] = 0.2f;
  5482. const auto x = renderSynthNote (s, 57, 48000); // 220 Hz, 48 kHz, 1 s
  5483. // equal 2400-sample windows (Goertzel power grows with the window): 10…60 ms and 500…550 ms
  5484. const auto early1 = goertzel (x, 220.0, 480, 2880), early3 = goertzel (x, 660.0, 480, 2880);
  5485. const auto late1 = goertzel (x, 220.0, 24000, 26400), late3 = goertzel (x, 660.0, 24000, 26400);
  5486. CHECK (early3 > 0.05 * early1); // ≈ −9 dB on average over 10…60 ms
  5487. CHECK (late3 < 1e-4 * late1);
  5488. CHECK (std::abs (10.0 * std::log10 (late1 / early1)) < 1.0); // the 1st holds
  5489. // without per-harmonic decay the spectrum stays as it is
  5490. s.spectrumDecay[2] = 0.0f;
  5491. const auto y = renderSynthNote (s, 57, 48000);
  5492. CHECK (std::abs (10.0 * std::log10 (goertzel (y, 660.0, 24000, 26400) / goertzel (y, 660.0, 480, 2880))) < 1.0);
  5493. }
  5494. TEST (worker_pool_runs_each_index_once_per_round)
  5495. {
  5496. // rounds of alternating sizes (a stalled worker must never run an index of a later round), each index
  5497. // exactly once, and nothing running after parallelFor returns
  5498. lynx::WorkerPool pool (3);
  5499. std::vector<std::atomic<int>> hits (64);
  5500. std::atomic<int> round { 0 }, outside { 0 }, wrongRound { 0 };
  5501. std::atomic<bool> open { false };
  5502. int failures = 0;
  5503. for (int r = 1; r <= 20000; ++r)
  5504. {
  5505. const auto n = (r % 3 == 0) ? 64 : (r % 3 == 1 ? 2 : 9);
  5506. for (int i = 0; i < n; ++i)
  5507. hits[(std::size_t) i].store (0);
  5508. round.store (r);
  5509. open.store (true);
  5510. auto fn = [&, r] (int i) {
  5511. if (! open.load())
  5512. outside.fetch_add (1);
  5513. if (round.load() != r)
  5514. wrongRound.fetch_add (1);
  5515. hits[(std::size_t) i].fetch_add (1);
  5516. };
  5517. pool.parallelFor (n, fn);
  5518. open.store (false);
  5519. for (int i = 0; i < n; ++i)
  5520. failures += hits[(std::size_t) i].load() != 1;
  5521. }
  5522. CHECK (failures == 0);
  5523. CHECK (outside.load() == 0);
  5524. CHECK (wrongRound.load() == 0);
  5525. }
  5526. TEST (ladder_filter_follows_toxic_law)
  5527. {
  5528. // the 4-pole ladder: −24 dB/oct far above the cutoff (vs −12 for the SVF), resonance raises the corner, and
  5529. // the input saturation keeps it bounded even at full resonance
  5530. auto level = [] (bool ladder, float res, double hz) {
  5531. lynx::SynthSettings s;
  5532. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  5533. s.cutoff = 500.0f;
  5534. s.resonance = res;
  5535. s.ladder = ladder;
  5536. const auto key = (int) std::lround (69.0 + 12.0 * std::log2 (hz / 440.0));
  5537. const auto x = renderSynthNote (s, key, 48000);
  5538. double e = 0.0, peak = 0.0;
  5539. for (std::size_t i = 24000; i < 48000; ++i)
  5540. e += (double) x[i] * x[i], peak = std::max (peak, (double) std::abs (x[i]));
  5541. return std::pair { std::sqrt (e / 24000.0), peak };
  5542. };
  5543. 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
  5544. const auto svfHigh = level (false, 0.0f, 3520.0).first / level (false, 0.0f, 110.0).first;
  5545. CHECK (20.0 * std::log10 (high / low) < -55.0); // ≈ 24 dB/oct over ~2.8 octaves
  5546. CHECK (20.0 * std::log10 (svfHigh) > -45.0); // the 2-pole SVF falls much less
  5547. const auto corner0 = level (true, 0.0f, 523.25).first, corner1 = level (true, 0.6f, 523.25).first;
  5548. CHECK (corner1 > 1.5 * corner0); // resonance boosts near the cutoff
  5549. const auto loud = level (true, 1.0f, 523.25);
  5550. CHECK (std::isfinite (loud.first) && loud.second < 20.0); // self-oscillation stays bounded
  5551. }
  5552. TEST (synth_spectrum_settles_on_target)
  5553. {
  5554. // ALT DECAY-like morph: harmonic 3 starts at 1 and settles on 0.25 (−12 dB) instead of fading out
  5555. lynx::SynthSettings s;
  5556. s.osc[0] = { lynx::Waveform::spectral, 0, 0.0f, 1.0f };
  5557. s.cutoff = 20000.0f;
  5558. s.decay = 0.0f;
  5559. s.sustain = 1.0f;
  5560. s.spectrum[0] = 1.0f;
  5561. s.spectrum[2] = 1.0f;
  5562. s.spectrumDecay[2] = 0.1f;
  5563. s.spectrumTarget[2] = 0.25f;
  5564. const auto x = renderSynthNote (s, 57, 48000);
  5565. const auto ratio = goertzel (x, 660.0, 24000, 26400) / goertzel (x, 220.0, 24000, 26400);
  5566. CHECK (std::abs (10.0 * std::log10 (ratio) - 20.0 * std::log10 (0.25)) < 1.0);
  5567. }
  5568. TEST (kepler_chorus_is_stereo_and_keeps_level)
  5569. {
  5570. // chorus I on a sine: L and R differ (opposite LFO phases), the level stays close to the dry one
  5571. lynx::SynthSettings s;
  5572. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  5573. s.cutoff = 20000.0f;
  5574. auto dry = s;
  5575. s.chorus = 1;
  5576. auto render = [] (const lynx::SynthSettings& set) {
  5577. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  5578. inst->prepare (48000.0);
  5579. lynx::ChannelDef c;
  5580. c.synth = set;
  5581. inst->configure (c, 120.0);
  5582. inst->noteOn (69, 1.0f);
  5583. std::vector<float> l (96000), r (96000);
  5584. inst->render (l.data(), r.data(), 96000, 1.0f, 1.0f);
  5585. return std::pair { l, r };
  5586. };
  5587. const auto [l, r] = render (s);
  5588. const auto [dl, dr] = render (dry);
  5589. double diff = 0.0, e = 0.0, ed = 0.0;
  5590. for (std::size_t i = 48000; i < 96000; ++i)
  5591. diff += std::abs (l[i] - r[i]), e += (double) l[i] * l[i], ed += (double) dl[i] * dl[i];
  5592. CHECK (diff / 48000.0 > 1e-3);
  5593. CHECK (std::abs (10.0 * std::log10 (e / ed)) < 3.0);
  5594. }
  5595. TEST (fl_pan_law_matches_love_philter_dll)
  5596. {
  5597. // values printed by the installation's Love Philter pan routine for vol 0.8 (REA_rodada27 §3.1, lppan.txt)
  5598. struct Row { double pan, ll, rr, rl, lr; };
  5599. const Row rows[] = { { -1.5, 0.239782482, -0.432956904, 0.805467963, 0.0 }, { -0.5, 0.805467963, 0.432956904, 0.239782482, 0.0 },
  5600. { 0.0, 0.8, 0.8, 0.0, 0.0 }, { 0.75, 0.220719516, 0.707889318, 0.0, 0.401742548 },
  5601. { 1.0, 0.0, 0.565685451, 0.0, 0.565685451 } };
  5602. for (const auto& row : rows)
  5603. {
  5604. float ll, rl, lr, rr;
  5605. lynx::flPanMatrix (row.pan, ll, rl, lr, rr);
  5606. CHECK (std::abs (0.8 * ll - row.ll) < 1e-6 && std::abs (0.8 * rr - row.rr) < 1e-6);
  5607. CHECK (std::abs (0.8 * rl - row.rl) < 1e-6 && std::abs (0.8 * lr - row.lr) < 1e-6);
  5608. }
  5609. }
  5610. TEST (effector_units_match_fl_dll_impulse_responses)
  5611. {
  5612. // impulse responses of the installation's Effector engine (REA_rodada27 §2, eu_<kind>_<X>_<Y>.txt; LFO off,
  5613. // wet 1, blocks of 256): samples 1, 10, 100 and 1000
  5614. struct Case { int kind; float x, y; double v[4]; };
  5615. const Case cases[] = { { 3, 0.5f, 0.5f, { -0.603055418, 0.159798339, -0.0055043716, -1.06241259e-06 } },
  5616. { 4, 0.2f, 0.5f, { 4.68885949e-26, 4.20032622e-19, 0.000487731799, 2.27715846e-09 } },
  5617. { 4, 0.8f, 0.3f, { -0.293783396, -0.0306414738, -0.00068128563, 1.358577e-15 } } };
  5618. for (const auto& c : cases)
  5619. {
  5620. auto fx = lynx::effector::make();
  5621. fx->prepare (44100.0);
  5622. lynx::EffectParams p {};
  5623. p[lynx::effector::type] = c.kind / 11.0f;
  5624. p[lynx::effector::wetMix] = 1.0f;
  5625. p[lynx::effector::paramX] = c.x;
  5626. p[lynx::effector::paramY] = c.y;
  5627. p[lynx::effector::modX] = p[lynx::effector::modY] = 0.5f;
  5628. p[lynx::effector::modRate] = 0.5f;
  5629. p[lynx::effector::inputLevel] = 1.0f;
  5630. p[lynx::effector::outputGain] = 0.5f;
  5631. std::vector<float> l (1024, 0.0f), r (1024, 0.0f);
  5632. l[0] = r[0] = 1.0f;
  5633. for (int d = 0; d < 1024; d += 256)
  5634. fx->process (l.data() + d, r.data() + d, 256, p, 120.0);
  5635. const int at[4] { 1, 10, 100, 1000 };
  5636. for (int k = 0; k < 4; ++k)
  5637. CHECK (std::abs (l[(std::size_t) at[k]] - c.v[k]) < 2e-7 + 1e-5 * std::abs (c.v[k]));
  5638. }
  5639. }
  5640. TEST (harmless_stereo_tremolo_and_vibrato)
  5641. {
  5642. // tremolo d = 1: each side swings between 0 and 1.25 at 5 Hz, L and R in anti-phase; vibrato modulates the pitch
  5643. lynx::SynthSettings s;
  5644. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  5645. s.cutoff = 20000.0f;
  5646. s.stereoTremolo = 1.0f;
  5647. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  5648. inst->prepare (48000.0);
  5649. lynx::ChannelDef c;
  5650. c.synth = s;
  5651. inst->configure (c, 120.0);
  5652. inst->noteOn (69, 1.0f);
  5653. std::vector<float> l (48000), r (48000);
  5654. inst->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  5655. 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; };
  5656. // θ = 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
  5657. CHECK (envelope (l, 19200) > 4.0f * envelope (r, 19200));
  5658. CHECK (envelope (r, 24000) > 4.0f * envelope (l, 24000));
  5659. // vibrato 100 cents: zero crossings vary in spacing; without it they are regular
  5660. auto crossingsSpread = [] (float cents) {
  5661. lynx::SynthSettings v;
  5662. v.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  5663. v.cutoff = 20000.0f;
  5664. v.vibratoCents = cents;
  5665. const auto x = renderSynthNote (v, 69, 48000);
  5666. std::vector<int> zc;
  5667. for (int i = 24000; i < 48000; ++i)
  5668. if (x[(std::size_t) i - 1] < 0.0f && x[(std::size_t) i] >= 0.0f)
  5669. zc.push_back (i);
  5670. int lo = 1 << 30, hi = 0;
  5671. for (std::size_t k = 1; k < zc.size(); ++k)
  5672. lo = std::min (lo, zc[k] - zc[k - 1]), hi = std::max (hi, zc[k] - zc[k - 1]);
  5673. return hi - lo;
  5674. };
  5675. CHECK (crossingsSpread (0.0f) <= 1);
  5676. CHECK (crossingsSpread (100.0f) >= 4);
  5677. }
  5678. TEST (physical_models_sound_and_end)
  5679. {
  5680. // Sakura: a plucked string with default-ish parameters rings and fades after the release; Drumpad: a hit decays
  5681. for (const auto kind : { lynx::InstrumentKind::sakura, lynx::InstrumentKind::drumpad })
  5682. {
  5683. lynx::ChannelDef c;
  5684. c.instrument = kind;
  5685. if (kind == lynx::InstrumentKind::sakura)
  5686. {
  5687. c.modelParams.assign (146, 0.5f);
  5688. c.modelParams[111] = 3.0f; // both strings at the note
  5689. c.modelParams[113] = 0.5f; // octave ×1
  5690. c.modelParams[6] = c.modelParams[11] = 0.99f; // long decay
  5691. c.modelParams[31] = 0.0f; // noise exciter
  5692. }
  5693. else
  5694. {
  5695. c.modelParams.assign (38, 0.5f);
  5696. c.modelParams[0] = 1.0f; // retrigger noise
  5697. c.modelParams[30] = c.modelParams[31] = c.modelParams[32] = c.modelParams[33] = 0.0f; // no velocity morph
  5698. }
  5699. auto inst = lynx::makeInstrument (kind);
  5700. inst->prepare (48000.0);
  5701. inst->configure (c, 120.0);
  5702. inst->noteOn (60, 0.8f);
  5703. std::vector<float> l (48000), r (48000);
  5704. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  5705. inst->noteOff (60);
  5706. inst->render (l.data() + 24000, r.data() + 24000, 24000, 1.0f, 1.0f);
  5707. double early = 0.0;
  5708. for (int i = 0; i < 12000; ++i)
  5709. early += (double) l[(std::size_t) i] * l[(std::size_t) i];
  5710. CHECK (early > 1e-6);
  5711. CHECK (std::all_of (l.begin(), l.end(), [] (float v) { return std::isfinite (v); }));
  5712. std::vector<float> tail (480000), tailR (480000);
  5713. inst->render (tail.data(), tailR.data(), 480000, 1.0f, 1.0f); // 10 s later the voice has ended
  5714. CHECK (inst->idle());
  5715. }
  5716. }
  5717. TEST (squeeze_matches_fl_model)
  5718. {
  5719. // Fruity Squeeze: Steps quantises, Mix 0 passes the input dry ×Volume/127; a silent block is left untouched
  5720. auto slot = lynx::makeEffectSlot (lynx::EffectKind::squeeze);
  5721. slot.params[1] = 0.0f; // mix 0: dry only
  5722. auto fx = lynx::makeEffect (lynx::EffectKind::squeeze);
  5723. fx->prepare (44100.0);
  5724. std::vector<float> l (512, 0.3f), r (512, -0.2f);
  5725. fx->process (l.data(), r.data(), 512, slot.params, 120.0);
  5726. CHECK (std::abs (l[100] - 0.3f) < 1e-6f && std::abs (r[100] + 0.2f) < 1e-6f); // Volume 127/127
  5727. slot.params[1] = 1.0f; // wet only
  5728. slot.params[2] = 32000.0f / 32768.0f; // 32768^(1 − 32000/32768) ≈ 1.27 levels per unit → heavy quantisation
  5729. std::vector<float> a (512), b (512);
  5730. for (int i = 0; i < 512; ++i)
  5731. a[(std::size_t) i] = b[(std::size_t) i] = 0.4f * (float) std::sin (i * 0.05);
  5732. fx->process (a.data(), b.data(), 512, slot.params, 120.0);
  5733. const auto levels = std::pow (32768.0f, 1.0f - 32000.0f / 32768.0f);
  5734. for (int i = 0; i < 512; i += 37)
  5735. CHECK (std::abs (a[(std::size_t) i] * levels - std::nearbyint (a[(std::size_t) i] * levels)) < 1e-3f);
  5736. std::vector<float> z (512, 0.0f), z2 (512, 0.0f);
  5737. fx->process (z.data(), z2.data(), 512, slot.params, 120.0);
  5738. CHECK (z[10] == 0.0f);
  5739. }
  5740. TEST (sakura_matrix_and_effects)
  5741. {
  5742. // REA_rodada29 §1: velocity → level follows 10^(2m)·0.05 (vel 1 vs 0.5 → ×10 in amplitude); the delay leaves
  5743. // an echo after the note has ended and keeps the instrument from going idle until its tail is silent
  5744. auto base = [] {
  5745. lynx::ChannelDef c;
  5746. c.instrument = lynx::InstrumentKind::sakura;
  5747. c.modelParams.assign (146, 0.0f);
  5748. const std::pair<int, float> values[] { { 0, 0.375f }, { 1, 0.5f }, { 3, 0.5f }, { 4, 1.0f }, { 6, 0.95f }, { 9, 0.3f },
  5749. { 11, 0.95f }, { 14, 0.3f }, { 18, 0.5f }, { 19, 0.5f }, { 27, 0.5f }, { 28, 1.0f },
  5750. { 29, 0.7f }, { 31, 1.0f }, { 32, 0.5f }, { 111, 3.0f }, { 113, 0.5f } };
  5751. for (const auto& [i, v] : values)
  5752. c.modelParams[(std::size_t) i] = v;
  5753. return c;
  5754. };
  5755. auto render = [] (const lynx::ChannelDef& c, float velocity, int held, int total) {
  5756. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sakura);
  5757. inst->prepare (48000.0);
  5758. inst->configure (c, 120.0);
  5759. inst->noteOn (60, velocity);
  5760. std::vector<float> l ((std::size_t) total), r ((std::size_t) total);
  5761. for (int s = 0; s < total; s += 256)
  5762. {
  5763. if (s == held)
  5764. inst->noteOff (60);
  5765. inst->render (l.data() + s, r.data() + s, std::min (256, total - s), 1.0f, 1.0f);
  5766. }
  5767. return std::make_pair (l, std::move (inst));
  5768. };
  5769. auto energy = [] (const std::vector<float>& x, int from, int to) {
  5770. double e = 0.0;
  5771. for (int i = from; i < to; ++i)
  5772. e += (double) x[(std::size_t) i] * x[(std::size_t) i];
  5773. return e;
  5774. };
  5775. auto c = base();
  5776. c.modelParams[79] = 6.0f; // slot 1: velocity → level, amount 1
  5777. c.modelParams[80] = 1.0f;
  5778. c.modelParams[82] = 1.0f;
  5779. const auto loud = energy (render (c, 1.0f, 24064, 24064).first, 0, 24064);
  5780. const auto soft = energy (render (c, 0.5f, 24064, 24064).first, 0, 24064);
  5781. CHECK (loud > 1e-6 && std::abs (loud / soft - 100.0) < 1.0);
  5782. auto d = base();
  5783. auto [dry, dryInst] = render (d, 0.8f, 4864, 72000);
  5784. d.modelParams[63] = 1.0f; // delay on: time 0.5 → ≈ 0.52 s, wet 1, no feedback: one echo
  5785. d.modelParams[64] = 0.5f;
  5786. d.modelParams[69] = 1.0f;
  5787. auto [wet, wetInst] = render (d, 0.8f, 4864, 72000);
  5788. CHECK (energy (wet, 26000, 40000) > 100.0 * energy (dry, 26000, 40000) + 1e-9); // the note ends near 0.2 s
  5789. CHECK (dryInst->idle() || energy (dry, 70000, 72000) < 1e-12);
  5790. CHECK (! wetInst->idle()); // the echo tail has not been silent for 3 s yet
  5791. }
  5792. TEST (drumsynth_live_engine)
  5793. {
  5794. // REA_rodada30 §1: key → patch slot, state parsing, the engine against our reference model (no DLL: synthesised
  5795. // sources only, noise from the fallback seed), voice modes, patch level/pan
  5796. CHECK (lynx::drumSynthKeyToSlot (48) == 0 && lynx::drumSynthKeyToSlot (71) == 23 && lynx::drumSynthKeyToSlot (0) == 24);
  5797. CHECK (lynx::drumSynthKeyToSlot (47) == 71 && lynx::drumSynthKeyToSlot (72) == 72 && lynx::drumSynthKeyToSlot (119) == 119);
  5798. CHECK (lynx::drumSynthKeyToSlot (120) == -1);
  5799. // a version 3 state: 120 names, 120 × 38 ints (send track −1 becomes 0 below version 4), flags
  5800. std::vector<std::uint8_t> blob;
  5801. auto put = [&] (std::uint32_t v) { for (int k = 0; k < 4; ++k) blob.push_back ((std::uint8_t) (v >> (8 * k))); };
  5802. put (3);
  5803. put (66);
  5804. for (int i = 0; i < 120; ++i)
  5805. blob.push_back (2), blob.push_back ('a'), blob.push_back ((std::uint8_t) ('0' + i % 10));
  5806. for (int i = 0; i < 120 * 38; ++i)
  5807. put ((std::uint32_t) (i % 38 == 36 ? -1 : i % 38 == 4 ? 300 : 0));
  5808. put (0);
  5809. const auto parsed = lynx::drumSynthLiveParams (blob);
  5810. CHECK (parsed && (int) parsed->size() == lynx::drumSynthParamCount);
  5811. CHECK (parsed && (*parsed)[36] == 0.0f && (*parsed)[38 * 7 + 4] == 300.0f && (*parsed)[(std::size_t) lynx::drumSynthEditorKeyIndex] == 66.0f);
  5812. blob.resize (500);
  5813. CHECK (! lynx::drumSynthLiveParams (blob));
  5814. // patch on key 60 (slot 12): tone-mode Osc1 with sweep and click, noise-band Osc2, ring, 2 retriggers
  5815. 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,
  5816. 0, 0, 0, 0, 0, 0, 30, -1, 0, 0, 64 };
  5817. lynx::ChannelDef c;
  5818. c.instrument = lynx::InstrumentKind::drumsynth;
  5819. c.modelParams.assign ((std::size_t) lynx::drumSynthParamCount, 0.0f);
  5820. for (int s = 0; s < 120; ++s)
  5821. c.modelParams[(std::size_t) (38 * s + 15)] = c.modelParams[(std::size_t) (38 * s + 34)] = -1.0f;
  5822. for (int i = 0; i < 38; ++i)
  5823. c.modelParams[(std::size_t) (38 * 12 + i)] = (float) patch[i];
  5824. auto render = [] (const lynx::ChannelDef& def, std::vector<int> keys, int total, float gl = 1.0f, float gr = 1.0f) {
  5825. auto inst = lynx::makeInstrument (lynx::InstrumentKind::drumsynth);
  5826. inst->configure (def, 120.0);
  5827. inst->prepare (48000.0);
  5828. std::vector<float> l ((std::size_t) total), r ((std::size_t) total);
  5829. for (int s = 0; s < total; s += 512)
  5830. {
  5831. for (std::size_t k = 0; k + 1 < keys.size(); k += 2)
  5832. if (keys[k + 1] == s)
  5833. inst->noteOn (keys[k], 100.0f / 128.0f);
  5834. inst->render (l.data() + s, r.data() + s, std::min (512, total - s), gl, gr);
  5835. }
  5836. return std::make_tuple (l, r, std::move (inst));
  5837. };
  5838. {
  5839. auto [l, r, inst] = render (c, { 60, 0 }, 9600);
  5840. // reference model (REA round 30 dsl_model.py, seed 0x56CE, FL velocity 100, V = 1, centre: × g(100)·cos(π/4))
  5841. const std::pair<int, float> golden[] { { 0, -0.0074092713f }, { 10, -0.13961405f }, { 100, -0.47290668f }, { 1000, -0.29188696f },
  5842. { 3000, -0.22130175f }, { 6000, -0.049537566f }, { 9599, 0.010392102f } };
  5843. for (const auto& [i, v] : golden)
  5844. CHECK (std::abs (l[(std::size_t) i] - v) < 2e-6f && std::abs (r[(std::size_t) i] - v) < 2e-6f);
  5845. std::vector<float> tail (48000 * 4), tailR (tail.size());
  5846. inst->render (tail.data(), tailR.data(), (int) tail.size(), 1.0f, 1.0f);
  5847. CHECK (inst->idle()); // the engine reported the voice finished
  5848. }
  5849. auto energy = [] (const std::vector<float>& x, int from, int to) {
  5850. double e = 0.0;
  5851. for (int i = from; i < to; ++i)
  5852. e += (double) x[(std::size_t) i] * x[(std::size_t) i];
  5853. return e;
  5854. };
  5855. // a key without a patch level (slot 0, level 0) and a key outside the 120 patches are silent
  5856. CHECK (energy (std::get<0> (render (c, { 48, 0, 125, 0 }, 4096)), 0, 4096) == 0.0);
  5857. // mono: a second hit on the same key cuts the first; poly: both ring together (Osc2 off: no noise, deterministic)
  5858. auto tone = c;
  5859. tone.modelParams[38 * 12 + 14] = 0.0f;
  5860. const auto single = std::get<0> (render (tone, { 60, 0 }, 8192));
  5861. const auto mono = std::get<0> (render (tone, { 60, 0, 60, 2048 }, 8192));
  5862. auto poly = tone;
  5863. poly.modelParams[38 * 12 + 24] = 1.0f;
  5864. const auto both = std::get<0> (render (poly, { 60, 0, 60, 2048 }, 8192));
  5865. double monoDiff = 0.0, polyDiff = 0.0;
  5866. for (int i = 2048 + 300; i < 8192; ++i) // after the cut fade: mono = only the second hit, a copy of the first
  5867. 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]);
  5868. CHECK (monoDiff < 1e-3 && polyDiff > 1.0);
  5869. // patch pan +64 → right only; channel volume counts twice (FL applies Final.Vol in the engine and at the host)
  5870. auto right = c;
  5871. right.modelParams[38 * 12 + 1] = 64.0f;
  5872. const auto [pl, pr, pi] = render (right, { 60, 0 }, 4096);
  5873. CHECK (energy (pl, 0, 4096) < 1e-12 * energy (pr, 0, 4096) && energy (pr, 0, 4096) > 1.0);
  5874. const auto full = std::get<0> (render (tone, { 60, 0 }, 4096));
  5875. const auto half = std::get<0> (render (tone, { 60, 0 }, 4096, 0.5f, 0.5f));
  5876. CHECK (std::abs (half[100] - 0.25f * full[100]) < 1e-6f && std::abs (full[100]) > 0.01f);
  5877. }
  5878. TEST (kepler_lfo_bpm_sync)
  5879. {
  5880. // 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)
  5881. std::vector<std::uint8_t> state (0x21 + 34 * 4, 0);
  5882. auto putU32 = [&] (std::size_t o, std::uint32_t v) { std::memcpy (state.data() + o, &v, 4); };
  5883. putU32 (12, 9);
  5884. std::memcpy (state.data() + 16, "Kepler-1", 9);
  5885. putU32 (0x19, 4);
  5886. putU32 (0x1D, 34);
  5887. float k[34] {};
  5888. k[5] = 0.602085769f; // "Pads - Kepler" demo: n = 286
  5889. k[6] = 1.0f;
  5890. k[10] = 1.0f; // vibrato on
  5891. k[33] = 1.0f;
  5892. std::memcpy (state.data() + 0x21, k, sizeof k);
  5893. lynx::SynthSettings s;
  5894. float gain = 0.0f;
  5895. CHECK (lynx::synthFromKepler (state, s, gain));
  5896. CHECK (s.lfo[lynx::lfoPitch].sync && s.lfo[lynx::lfoPitch].secondsTiming);
  5897. CHECK (std::abs (s.lfo[lynx::lfoPitch].period - 286.0f / 192.0f) < 1e-6f);
  5898. k[5] = 0.0f; // slowest: 32 beats
  5899. std::memcpy (state.data() + 0x21, k, sizeof k);
  5900. CHECK (lynx::synthFromKepler (state, s, gain) && std::abs (s.lfo[lynx::lfoPitch].period - 32.0f) < 1e-6f);
  5901. k[6] = 0.0f; // free rate in seconds
  5902. std::memcpy (state.data() + 0x21, k, sizeof k);
  5903. CHECK (lynx::synthFromKepler (state, s, gain) && ! s.lfo[lynx::lfoPitch].sync);
  5904. }
  5905. namespace
  5906. {
  5907. // A Harmor state written from scratch (REA_rodada11 §4.1 layout, version 18): part A only — a decaying-harmonics
  5908. // timbre, low-pass + resonance, filter envelope, 3-voice unison, vibrato, pluck, tremolo, volume envelope with a
  5909. // velocity map — and the global block. Every other curve is neutral.
  5910. std::vector<std::uint8_t> harmorTestState (bool panLfo = true)
  5911. {
  5912. std::vector<std::uint8_t> b;
  5913. 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))); };
  5914. auto f64 = [&] (double v) { std::uint64_t u; std::memcpy (&u, &v, 8); for (int k = 0; k < 8; ++k) b.push_back ((std::uint8_t) (u >> (8 * k))); };
  5915. struct Pt { double dx, y, tension; int mode; };
  5916. auto curve = [&] (const std::vector<Pt>& pts, std::array<std::int32_t, 5> hdr) {
  5917. i32 (3), i32 (3), i32 ((std::int32_t) pts.size());
  5918. for (const auto& p : pts)
  5919. {
  5920. f64 (p.dx), f64 (p.y);
  5921. const auto t = (float) p.tension;
  5922. std::uint32_t u;
  5923. std::memcpy (&u, &t, 4);
  5924. i32 ((std::int32_t) u);
  5925. b.push_back ((std::uint8_t) p.mode), b.push_back (0), b.push_back (0), b.push_back (0);
  5926. }
  5927. for (auto h : hdr)
  5928. i32 (h);
  5929. };
  5930. const std::array<std::int32_t, 5> off { 0, 0, -1, -1, -1 }, on { 0, 1, -1, -1, -1 };
  5931. auto flat = [&] (double y, std::array<std::int32_t, 5> hdr = { 0, 0, -1, -1, -1 }) { curve ({ { 0, y, 0, 0 }, { 1, y, 0, 2 } }, hdr); };
  5932. i32 (18);
  5933. i32 (1 | 4);
  5934. std::vector<std::uint8_t> part;
  5935. std::swap (b, part);
  5936. std::array<std::int32_t, 386> p {};
  5937. const std::pair<int, int> values[] = { { 0, 500 }, { 3, 1000 }, { 9, 1024 }, { 11, 1000 }, { 12, 1000 }, { 17, 300 }, { 18, 4000 },
  5938. { 19, 500 }, { 20, 1000 }, { 24, 500 }, { 25, 500 }, { 28, 500 }, { 29, 256 }, { 30, -1 }, { 31, -1 }, { 33, -1 }, { 34, 3 },
  5939. { 35, 1 }, { 37, 192 }, { 38, 128 }, { 39, 500 }, { 40, 10000 }, { 41, 1 }, { 42, 10000 }, { 43, 1 }, { 45, 200 }, { 46, 500 },
  5940. { 47, 1 }, { 49, -140 }, { 50, 1200 }, { 51, 0 }, { 52, 5000 }, { 54, 500 }, { 56, 600 }, { 57, 300 }, { 59, 500 }, { 60, 600 },
  5941. { 64, 8192 }, { 66, 500 }, { 72, 600 }, { 74, 1000 }, { 75, 600 }, { 78, 5000 }, { 79, 500 }, { 80, 3000 } };
  5942. for (const auto& [i, v] : values)
  5943. p[(std::size_t) i] = v;
  5944. for (auto v : p)
  5945. i32 (v);
  5946. for (int i = 0; i < 12; ++i)
  5947. i32 (i); // module order
  5948. std::array<std::uint8_t, 0x4b> misc {};
  5949. auto put = [&] (int o, std::int32_t v) { std::memcpy (misc.data() + o, &v, 4); };
  5950. const float one = 1.0f;
  5951. put (0x08, 107), put (0x1c, 1), put (0x28, 200), std::memcpy (misc.data() + 0x30, &one, 4);
  5952. put (0x34, 0), put (0x38, 4), put (0x3c, 100), put (0x40, 108);
  5953. misc[0x44] = 1;
  5954. b.insert (b.end(), misc.begin(), misc.end());
  5955. static const int mode1[] = { 0, 2, 4, 5, 12, 13, 14, 15, 17, 18, 23, 24, 27, 28, 29, 30, 33, 36, 38, 39, 40, 41, 42 };
  5956. for (int k = 0; k < 43; ++k)
  5957. {
  5958. static const int mode2[] = { 2, 14, 23, 28, 30, 38, 39, 41, 42 }; // ×2 around 0.5: 1.0 is neutral
  5959. const bool centred = std::find (std::begin (mode1), std::end (mode1), k) != std::end (mode1);
  5960. const bool doubled = std::find (std::begin (mode2), std::end (mode2), k) != std::end (mode2);
  5961. const double neutral = centred && ! doubled ? 0.5 : 1.0;
  5962. i32 (3);
  5963. i32 (1065353216), i32 (1065353216), i32 (1065353216);
  5964. if (k == 1) // volume envelope: attack, decay to the sustain point, release
  5965. curve ({ { 0, 0, 0, 0 }, { 0.01, 1, 0.3, 0 }, { 0.3, 0.6, -0.4, 0 }, { 0.4, 0, 0.2, 0 } }, { 0, 1, 1, -1, 2 });
  5966. else if (k == 4) // filter-1 envelope
  5967. curve ({ { 0, 1, 0, 0 }, { 0.25, 0.2, -0.5, 0 } }, { 0, 1, -1, -1, -1 });
  5968. else
  5969. flat (neutral);
  5970. for (int a : { 128, 128, 0, 128 })
  5971. i32 (a);
  5972. if (k == 0 && panLfo) // pan LFO
  5973. flat (1.0, on);
  5974. else
  5975. flat (0.5);
  5976. for (int a : { k == 0 ? 40000 : 0, 0, 0, 0 })
  5977. i32 (a);
  5978. i32 (0);
  5979. for (int m = 2; m < 11; ++m)
  5980. if (k == 1 && m == 3)
  5981. curve ({ { 0, 0.2, 0, 0 }, { 1, 1, -0.3, 0 } }, off); // velocity → volume
  5982. else
  5983. flat (neutral);
  5984. }
  5985. for (int c = 0; c < 26; ++c)
  5986. if (c == 2 || c == 3)
  5987. curve ({ { 0, 0.25, 0, 0 }, { 0.006, 0.12, -0.46, 0 }, { 0.994, 0, 0, 0 } }, off); // timbres
  5988. else if (c == 14)
  5989. curve ({ { 0, 1, 0, 0 }, { 1, 0, 0, 0 } }, off); // pluck curve
  5990. else
  5991. flat (c == 0 || c == 17 ? 0.25 : (c == 5 ? 0.0 : (c == 6 || c == 10 || c == 11 || (c >= 18 && c <= 24) ? 1.0 : 0.5)));
  5992. std::swap (b, part);
  5993. i32 ((std::int32_t) part.size());
  5994. b.insert (b.end(), part.begin(), part.end());
  5995. std::array<std::int32_t, 53> g {};
  5996. g[0] = g[1] = g[2] = 256, g[10] = 500, g[11] = 1000, g[12] = 1000, g[15] = 1000;
  5997. for (auto v : g)
  5998. i32 (v);
  5999. for (int i = 0; i < 6; ++i)
  6000. i32 (i);
  6001. std::array<std::uint8_t, 0x3d> gm {};
  6002. const std::int32_t cr = 200, vr = 1;
  6003. std::memcpy (gm.data() + 12, &vr, 4);
  6004. std::memcpy (gm.data() + 24, &cr, 4);
  6005. b.insert (b.end(), gm.begin(), gm.end());
  6006. return b;
  6007. }
  6008. } // namespace
  6009. TEST (harmor_engine)
  6010. {
  6011. // REA_rodada34: state parsing, the additive engine against our reference model (hmodel.py), host levels, voice end
  6012. const auto blob = harmorTestState();
  6013. if (const char* dump = std::getenv ("LYNX_DUMP_HARMOR"))
  6014. std::ofstream (dump, std::ios::binary).write ((const char*) blob.data(), (std::streamsize) blob.size());
  6015. CHECK (lynx::harmorStateUsable (blob));
  6016. CHECK (lynx::harmorFallbacks (blob).size() == 1); // (only the harmonic-randomness note)
  6017. const auto at = lynx::harmorParamOffset (blob, 0, 52);
  6018. std::int32_t cutoff = 0;
  6019. CHECK (at > 0 && (std::memcpy (&cutoff, blob.data() + at, 4), cutoff == 5000));
  6020. CHECK (lynx::harmorParamOffset (blob, 1, 52) < 0 && lynx::harmorParamOffset (blob, -1, 12) > at);
  6021. auto broken = blob;
  6022. broken.resize (broken.size() / 2);
  6023. CHECK (! lynx::harmorStateUsable (broken));
  6024. auto old = blob;
  6025. old[0] = 15; // articulators and curves are stored from version 16
  6026. CHECK (! lynx::harmorStateUsable (old));
  6027. lynx::ChannelDef c;
  6028. c.instrument = lynx::InstrumentKind::harmor;
  6029. c.pluginState = blob;
  6030. auto render = [] (const lynx::ChannelDef& def, int total, float gl, float gr, int offAt) {
  6031. auto inst = lynx::makeInstrument (lynx::InstrumentKind::harmor);
  6032. inst->configure (def, 120.0);
  6033. inst->prepare (44100.0);
  6034. std::vector<float> l ((std::size_t) total), r ((std::size_t) total);
  6035. inst->noteOn (60, 0.78125f);
  6036. for (int s = 0; s < total; s += 512)
  6037. {
  6038. if (s == offAt)
  6039. inst->noteOff (60);
  6040. inst->render (l.data() + s, r.data() + s, std::min (512, total - s), gl, gr);
  6041. }
  6042. return std::make_tuple (l, r, std::move (inst));
  6043. };
  6044. {
  6045. // reference model (REA round 34 hmodel.py; C5 at FL velocity 100, Final.Vol 1, centre, released at 6144, the
  6046. // Mersenne Twister seeded like LYNX's)
  6047. auto [l, r, inst] = render (c, 8192, 1.0f, 1.0f, 6144);
  6048. const std::tuple<int, float, float> golden[] {
  6049. { 0, 0.0f, 0.0f }, { 100, 0.00947693f, 0.04249846f }, { 1000, 0.08140575f, -0.03251422f }, { 3000, 0.05928446f, -0.00247572f },
  6050. { 6000, 0.02997839f, 0.14549091f }, { 7000, -0.01121871f, 0.04197952f }, { 8191, 0.00314545f, 0.03857505f } };
  6051. for (const auto& [i, gl, gr] : golden)
  6052. CHECK (std::abs (l[(std::size_t) i] - gl) < 2e-6f && std::abs (r[(std::size_t) i] - gr) < 2e-6f);
  6053. // after the release the volume envelope ends, the record declicks and the instrument goes idle
  6054. std::vector<float> tail (44100), tailR (tail.size());
  6055. inst->render (tail.data(), tailR.data(), (int) tail.size(), 1.0f, 1.0f);
  6056. CHECK (inst->idle());
  6057. CHECK (std::abs (tail.back()) == 0.0f);
  6058. }
  6059. // the reference renderer gives the same samples as the instrument
  6060. {
  6061. const auto ref = lynx::harmor::renderReference (blob, { { 0, 60, 0.78125, 1.0, 0.0, 6144 } }, 44100.0, 8192);
  6062. const auto [l, r, inst] = render (c, 8192, 1.0f, 1.0f, 6144);
  6063. double worst = 0.0;
  6064. for (int i = 0; i < 8192; ++i)
  6065. worst = std::max ({ worst, (double) std::abs (ref[2 * (std::size_t) i] - l[(std::size_t) i]), (double) std::abs (ref[2 * (std::size_t) i + 1] - r[(std::size_t) i]) });
  6066. CHECK (worst == 0.0);
  6067. }
  6068. // FL's level law applied once: half the channel volume halves the output; full right pan silences the left side
  6069. const auto full = std::get<0> (render (c, 2048, 1.0f, 1.0f, -1));
  6070. const auto half = std::get<0> (render (c, 2048, 0.5f, 0.5f, -1));
  6071. CHECK (std::abs (half[1000] - 0.5f * full[1000]) < 1e-6f && std::abs (full[1000]) > 0.01f);
  6072. auto mono = c;
  6073. mono.pluginState = harmorTestState (false); // no pan LFO ...
  6074. const std::int32_t one = 1;
  6075. std::memcpy (mono.pluginState.data() + lynx::harmorParamOffset (mono.pluginState, 0, 34), &one, 4); // ... nor unison spread
  6076. const auto [pl, pr, pi] = render (mono, 2048, 0.0f, 1.41421356f, -1);
  6077. double el = 0.0, er = 0.0;
  6078. for (int i = 0; i < 2048; ++i)
  6079. el += (double) pl[(std::size_t) i] * pl[(std::size_t) i], er += (double) pr[(std::size_t) i] * pr[(std::size_t) i];
  6080. CHECK (el < 1e-10 * er && er > 1e-3);
  6081. }
  6082. // our own Maximus v7 state (layout REA_rodada8 §1.1): 7 globals, 4 × 13 band parameters, 8 envelopes (dx, y, tension, type)
  6083. static std::vector<std::uint8_t> maximusTestState (const std::array<int, 7>& g, const std::array<std::array<int, 13>, 4>& bands,
  6084. const std::array<std::vector<std::array<double, 4>>, 8>& envs, int oversampling)
  6085. {
  6086. std::vector<std::uint8_t> d;
  6087. auto put = [&] (const void* v, std::size_t n) { d.insert (d.end(), (const std::uint8_t*) v, (const std::uint8_t*) v + n); };
  6088. auto i32 = [&] (std::int32_t v) { put (&v, 4); };
  6089. i32 (7);
  6090. for (int copy = 0; copy < 2; ++copy)
  6091. {
  6092. for (auto v : g)
  6093. i32 (v);
  6094. for (const auto& b : bands)
  6095. for (auto v : b)
  6096. i32 (v);
  6097. }
  6098. d.resize (0x1fe, 0);
  6099. std::memcpy (d.data() + 0x1f4, &oversampling, 4);
  6100. for (const auto& e : envs)
  6101. {
  6102. i32 (3), i32 (2), i32 ((std::int32_t) e.size());
  6103. for (const auto& pt : e)
  6104. {
  6105. const double dx = pt[0], y = pt[1];
  6106. const float t = (float) pt[2];
  6107. put (&dx, 8), put (&y, 8), put (&t, 4);
  6108. const std::uint8_t flags[4] { (std::uint8_t) pt[3], 0, 0, 0 };
  6109. put (flags, 4);
  6110. }
  6111. i32 (0), i32 (-1), i32 (-1), i32 (-1), i32 (-1);
  6112. }
  6113. return d;
  6114. }
  6115. TEST (harmless_rack)
  6116. {
  6117. // REA_rodada36: Harmless's effects rack against our reference model (rack.py / maxmodel.py, which match the
  6118. // installation's Harmless_x64.dll and SG_x64.dll), 44.1 kHz, host blocks of 512
  6119. std::vector<float> inL (8192), inR (8192);
  6120. for (int i = 0; i < 4096; ++i)
  6121. {
  6122. 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));
  6123. inR[(std::size_t) i] = (float) (1.2 * std::sin (2.0 * 3.141592653589793 * 660.0 * i / 44100.0));
  6124. }
  6125. auto run = [&] (const std::array<int, 100>& p, int compType, std::shared_ptr<const lynx::hlfx::MaximusPreset> comp, int total, int voicesUntil) {
  6126. lynx::hlfx::Rack rack;
  6127. std::array<int, 7> t {};
  6128. t[3] = compType;
  6129. rack.prepare (p, t, 44100.0, 120.0, std::move (comp));
  6130. std::vector<float> l (inL.begin(), inL.begin() + total), r (inR.begin(), inR.begin() + total);
  6131. for (int s = 0; s < total; s += 512)
  6132. rack.process (l.data() + s, r.data() + s, std::min (512, total - s), s < voicesUntil);
  6133. return std::make_pair (l, r);
  6134. };
  6135. {
  6136. // chorus type 3 (mix 400), ping-pong delay type 2 (vol 600, feedback 500, 1/4 beat), reverb type 4 (vol 700)
  6137. std::array<int, 100> p {};
  6138. p[90] = 3, p[91] = 400, p[92] = 2, p[93] = 600, p[94] = 500, p[95] = 48, p[96] = 4, p[97] = 700;
  6139. const auto [l, r] = run (p, 0, nullptr, 8192, 4096);
  6140. const std::tuple<int, float, float> golden[] { { 0, 0.0f, 0.0f }, { 500, -0.25248247f, 0.15141529f }, { 3000, -0.65128994f, -0.64854866f },
  6141. { 5000, -0.54308629f, -0.36827448f }, { 6000, -0.98378551f, -0.72790027f },
  6142. { 8191, 0.50599128f, -0.43637198f } };
  6143. for (const auto& [i, gl, gr] : golden)
  6144. CHECK (std::abs (l[(std::size_t) i] - gl) < 2e-6f && std::abs (r[(std::size_t) i] - gr) < 2e-6f);
  6145. }
  6146. {
  6147. // the delay alone: an impulse comes back after round(time·fs·0.3125/bpm) samples × (11^0.6 − 1)/10, then × feedback
  6148. std::array<int, 100> p {};
  6149. p[92] = 1, p[93] = 600, p[94] = 500, p[95] = 48;
  6150. lynx::hlfx::Rack rack;
  6151. rack.prepare (p, {}, 44100.0, 120.0, nullptr);
  6152. std::vector<float> l (16384), r (16384);
  6153. l[0] = 1.0f;
  6154. for (int s = 0; s < 16384; s += 512)
  6155. rack.process (l.data() + s, r.data() + s, 512, s == 0);
  6156. const auto D = 5512; // 48·44100·0.3125/120 = 5512.5 → 5512 (round half to even)
  6157. const auto vol = (float) ((std::exp ((double) (600 * 0.001f) * (double) (float) std::log (11.0)) - 1.0) * (double) 0.1f);
  6158. CHECK (std::abs (l[(std::size_t) D] - vol) < 1e-7f && std::abs (l[(std::size_t) D - 1]) < 1e-12f);
  6159. // the feedback ramps from 0.5 toward 0.5: the second echo is vol·0.5
  6160. CHECK (std::abs (l[(std::size_t) (2 * D)] - vol * 0.5f) < 1e-7f && std::abs (r[(std::size_t) D]) < 1e-12f);
  6161. }
  6162. // the compressor: Maximus states of our own (no preset data), checked against SG_x64.dll by REA round 36
  6163. using Env = std::vector<std::array<double, 4>>;
  6164. const Env def { { 0.0, 0.0, 0.0, 0 }, { 0.5, 0.5, 0.0, 0 }, { 0.5, 0.5, 0.0, 0 } };
  6165. 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,
  6166. int sus = 2882) { return std::array<int, 13> { mode, pre, post, sep, sat, ceil, att, rel2, 2, 5000, 3, sus, 0 }; };
  6167. {
  6168. // master brickwall at −0.22 dB only (bands off / compression off)
  6169. const auto st = maximusTestState ({ 19800, 1, 48065, 1, 1115, 1000, -1 }, { band (3), band (1), band (3), band (0) },
  6170. { def, def, def, def, def, def, def, def }, 0);
  6171. const auto preset = lynx::hlfx::makeMaximusPreset (st);
  6172. CHECK (preset != nullptr);
  6173. std::array<int, 100> p {};
  6174. p[98] = 1000;
  6175. const auto [l, r] = run (p, 1, preset, 4096, 4096);
  6176. const std::tuple<int, float, float> golden[] { { 100, 0.02499794f, 0.88166064f }, { 1000, 0.56971455f, -0.62808162f },
  6177. { 2047, -0.27541649f, 0.70913559f }, { 3000, 0.32431602f, -0.37985173f },
  6178. { 4095, -0.12743534f, -0.15237498f } };
  6179. for (const auto& [i, gl, gr] : golden)
  6180. CHECK (std::abs (l[(std::size_t) i] - gl) < 2e-6f && std::abs (r[(std::size_t) i] - gr) < 2e-6f);
  6181. float peak = 0.0f;
  6182. for (int i = 2048; i < 4096; ++i)
  6183. peak = std::max ({ peak, std::abs (l[(std::size_t) i]), std::abs (r[(std::size_t) i]) });
  6184. CHECK (peak < 0.9751f);
  6185. }
  6186. {
  6187. // 24 dB crossovers, ×2 oversampling, low cut, stereo separation, saturation A, a knee with tension (type 7) and
  6188. // exponential tensions (type 0), release 2 on the master, band mix 600
  6189. const Env knee { { 0.0, 0.0, 0.0, 0 }, { 0.35, 0.35, 0.0, 0 }, { 0.65, 0.6, 0.36, 7 } };
  6190. const Env t0 { { 0.0, 0.0, 0.0, 0 }, { 0.5, 0.5, 0.14, 0 }, { 0.5, 0.5, 0.0, 0 } };
  6191. const Env m0 { { 0.0, 0.0, 0.0, 0 }, { 0.5, 0.5, 0.0, 0 }, { 0.5, 0.6, 0.085, 0 } };
  6192. const auto st = maximusTestState ({ 19800, 1, 48065, 1, 891, 600, 32768 },
  6193. { band (1, 1264, 1296, 500, -500, 1200), band (0, 1340, 1000, -348, 0, 1000, 1115, 0, 1570),
  6194. band (0, 1364, 1152, 0, 0, 1000, 1115, 0, 1186), band (0, 1000, 1000, 0, -196, 1000, 1115, 4464, 1538) },
  6195. { def, def, knee, def, t0, def, m0, def }, 1);
  6196. const auto preset = lynx::hlfx::makeMaximusPreset (st);
  6197. CHECK (preset != nullptr);
  6198. std::array<int, 100> p {};
  6199. p[98] = 600;
  6200. const auto [l, r] = run (p, 2, preset, 4096, 4096);
  6201. const std::tuple<int, float, float> golden[] { { 100, 0.0f, 0.0f }, { 1000, -0.46856275f, -0.63261062f },
  6202. { 2047, 0.20268074f, 0.5414567f }, { 3000, -0.25614089f, -0.49984524f },
  6203. { 4095, 0.10172816f, 0.0505573f } };
  6204. for (const auto& [i, gl, gr] : golden)
  6205. CHECK (std::abs (l[(std::size_t) i] - gl) < 2e-6f && std::abs (r[(std::size_t) i] - gr) < 2e-6f);
  6206. }
  6207. {
  6208. // an .fst wrapper around a state is found; unsupported states are rejected
  6209. const auto st = maximusTestState ({ 19800, 1, 48065, 1, 1115, 1000, -1 }, { band (3), band (1), band (3), band (0) },
  6210. { def, def, def, def, def, def, def, def }, 0);
  6211. std::vector<std::uint8_t> fst { 'F', 'L', 'h', 'd', 6, 0, 0, 0, 0, 0, 1, 0, 0x60, 0, 'F', 'L', 'd', 't' };
  6212. std::vector<std::uint8_t> body { 0xC9, 8, 'M', 'a', 'x', 'i', 'm', 'u', 's', 0, 0xD5 };
  6213. for (auto n = st.size(); ; n >>= 7)
  6214. {
  6215. body.push_back ((std::uint8_t) ((n & 0x7f) | (n >= 0x80 ? 0x80 : 0)));
  6216. if (n < 0x80)
  6217. break;
  6218. }
  6219. body.insert (body.end(), st.begin(), st.end());
  6220. const auto len = (std::uint32_t) body.size();
  6221. for (int k = 0; k < 4; ++k)
  6222. fst.push_back ((std::uint8_t) (len >> (8 * k)));
  6223. fst.insert (fst.end(), body.begin(), body.end());
  6224. const auto found = lynx::hlfx::maximusStateFromFst (fst);
  6225. CHECK (found && *found == st);
  6226. auto rms = st;
  6227. rms[4 + 4 * (7 + 13 * 3 + 12)] = 1; // RMS detector on the master (decoded in REA_rodada38: Harmor's preset 2)
  6228. CHECK (lynx::hlfx::makeMaximusPreset (rms) != nullptr);
  6229. }
  6230. }
  6231. // ---- Sytrus (REA_rodada31) -------------------------------------------------------------------------------------------
  6232. // A Sytrus state built from scratch (version 25 layout, our own values — no FL preset data), zlib "stored" blocks.
  6233. namespace
  6234. {
  6235. struct SytrusTestPatch
  6236. {
  6237. std::vector<std::int32_t> main = std::vector<std::int32_t> (240, 0); // 962-byte main block as ints (+ mute bytes)
  6238. struct Op
  6239. {
  6240. int p[10] { 0, 256, 0, 0, 0, 0, 0, 0, 0, 0 };
  6241. int ratio = 20000, offset = 0, noise = 0;
  6242. std::vector<float> amps { 1.0f };
  6243. std::uint8_t flags[8] {};
  6244. int env1[3] { -1, -1, -1 }; // volume envelope: on (≠ −1 → on), decay point, sustain point
  6245. std::vector<std::pair<double, double>> env1pts;
  6246. } ops[6];
  6247. struct Filt
  6248. {
  6249. int p[10] { 0, 0, 128, 0, 128, 0, 0, 128, 128, 0 };
  6250. int type = 3;
  6251. } filts[3];
  6252. std::array<std::array<std::uint8_t, 23>, 3> delays {};
  6253. std::array<std::int32_t, 9> reverb { 19, 221, 0, 50, 80, 30, 221, 2, 0 };
  6254. bool reverbOn = false;
  6255. int eqmode = 0;
  6256. SytrusTestPatch()
  6257. {
  6258. main[0] = 128, main[1] = 128;
  6259. for (int i = 0; i < 8; ++i)
  6260. main[(std::size_t) (165 + i)] = (i % 4 == 2) ? 0 : 128;
  6261. main[173] = 1, main[175] = 128, main[188] = 128, main[189] = -1, main[190] = main[191] = 256;
  6262. }
  6263. void cell (int layer, int row, int col, int v) { main[(std::size_t) (3 + layer * 81 + row * 9 + col)] = v; }
  6264. std::vector<std::uint8_t> blob() const
  6265. {
  6266. std::vector<std::uint8_t> b;
  6267. 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))); };
  6268. auto f32 = [&] (float v) { std::int32_t x; std::memcpy (&x, &v, 4); i32 (x); };
  6269. 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))); };
  6270. // point lists: kind 1 envelope, 2 LFO, 3 map / shaper curve; format version 3
  6271. auto env = [&] (int kind, const std::vector<std::pair<double, double>>& pts, int on, int decay, int sus) {
  6272. i32 (kind), i32 (3), i32 ((std::int32_t) pts.size());
  6273. for (const auto& [dt, y] : pts)
  6274. f64 (dt), f64 (y), f32 (0.0f), i32 (0);
  6275. i32 (0), i32 (on), i32 (decay), i32 (-1), i32 (sus);
  6276. };
  6277. for (int i = 0; i < 240; ++i)
  6278. if (4 * i + 4 <= 0x320)
  6279. i32 (main[(std::size_t) i]);
  6280. b.resize (962, 0); // mute bytes: none muted
  6281. i32 (0); // global declick amount
  6282. b.push_back (0), b.push_back (0), b.push_back (0); // OSC grouping, DC stage, GIBBS OFF
  6283. for (int k = 0; k < 9; ++k)
  6284. b.push_back (k == 7 ? 1 : 0); // flag group (release multiplier on, as Default.fst)
  6285. for (const auto& d : delays)
  6286. b.insert (b.end(), d.begin(), d.end());
  6287. for (auto v : reverb)
  6288. i32 (v);
  6289. b.push_back (reverbOn ? 1 : 0), b.push_back (0);
  6290. i32 (eqmode);
  6291. for (int k = 0; k < 3; ++k)
  6292. i32 (0), i32 (30000), i32 (20000), i32 (k);
  6293. b.push_back (0); // no info text
  6294. for (int u = 0; u < 10; ++u)
  6295. {
  6296. const int narts = u < 6 ? 6 : (u < 9 ? 8 : 2);
  6297. for (int j = 0; j < 10; ++j)
  6298. i32 (u < 6 ? ops[u].p[j] : (u < 9 ? filts[u - 6].p[j] : 0));
  6299. if (u < 6)
  6300. {
  6301. const auto& o = ops[u];
  6302. const auto at = b.size();
  6303. b.resize (at + 0x828, 0);
  6304. auto put = [&] (std::size_t off, const void* src, std::size_t n) { std::memcpy (b.data() + at + off, src, n); };
  6305. put (0, &o.ratio, 4), put (4, &o.offset, 4), put (8, &o.noise, 4);
  6306. put (0xc, o.amps.data(), 4 * o.amps.size());
  6307. const std::int32_t shape[5] { 0, 0, 0, 0, 128 };
  6308. put (0x80c, shape, sizeof shape);
  6309. put (0x820, o.flags, 8);
  6310. }
  6311. else if (u < 9)
  6312. {
  6313. const auto at = b.size();
  6314. b.resize (at + 0x30, 0);
  6315. std::memcpy (b.data() + at + 0x2c, &filts[u - 6].type, 4);
  6316. env (3, { { 0.0, 0.0 }, { 1.0, 1.0 } }, 0, -1, -1);
  6317. b.push_back (0);
  6318. }
  6319. for (int k = 0; k < narts; ++k)
  6320. {
  6321. const bool add = k == 0 || k == 3 || (u >= 6 && u <= 8 && (k == 2 || k == 3)) || (u < 6 && k == 4);
  6322. const double neutral = add ? 0.5 : 1.0;
  6323. i32 (3), i32 (0), f32 (1.0f), f32 (1.0f);
  6324. if (u < 6 && k == 1 && ops[u].env1[0] != -1)
  6325. env (1, ops[u].env1pts, -1, ops[u].env1[1], ops[u].env1[2]);
  6326. else
  6327. env (1, { { 0.0, 0.0 }, { 1.0, 1.0 } }, 0, -1, -1);
  6328. i32 (128), i32 (128), i32 (0), i32 (128);
  6329. env (2, { { 0.0, 1.0 }, { 1.0, 1.0 } }, 0, -1, -1);
  6330. i32 (40000), i32 (0), i32 (0), i32 (0), i32 (0);
  6331. for (int m = 0; m < 6; ++m)
  6332. env (3, { { 0.0, neutral }, { 1.0, neutral } }, 0, -1, -1);
  6333. }
  6334. }
  6335. b.push_back (0), b.push_back (0);
  6336. // zlib with stored blocks
  6337. std::vector<std::uint8_t> z { 0x78, 0x01 };
  6338. for (std::size_t at = 0; at < b.size(); at += 65535)
  6339. {
  6340. const auto n = std::min<std::size_t> (65535, b.size() - at);
  6341. z.push_back (at + n >= b.size() ? 1 : 0);
  6342. z.push_back ((std::uint8_t) n), z.push_back ((std::uint8_t) (n >> 8));
  6343. z.push_back ((std::uint8_t) ~n), z.push_back ((std::uint8_t) (~n >> 8));
  6344. z.insert (z.end(), b.begin() + (std::ptrdiff_t) at, b.begin() + (std::ptrdiff_t) (at + n));
  6345. }
  6346. std::uint32_t a = 1, c = 0;
  6347. for (auto x : b)
  6348. a = (a + x) % 65521, c = (c + a) % 65521;
  6349. for (int k = 3; k >= 0; --k)
  6350. z.push_back ((std::uint8_t) (((c << 16) | a) >> (8 * k)));
  6351. std::vector<std::uint8_t> out { 25, 0, 0, 0 };
  6352. out.insert (out.end(), z.begin(), z.end());
  6353. return out;
  6354. }
  6355. };
  6356. // renders like FL's Gen_Render calls: notes start/release at the block that contains them
  6357. std::pair<std::vector<float>, std::vector<float>> sytrusRender (const std::vector<std::uint8_t>& blob, bool renderMode, int n,
  6358. std::vector<std::array<int, 3>> notes, double fs = 44100.0)
  6359. {
  6360. lynx::sytrus::Engine e;
  6361. e.setTempo (120.0);
  6362. e.prepare (fs, renderMode, 512);
  6363. e.setPatch (lynx::sytrus::parsePatch (blob));
  6364. std::vector<float> l ((std::size_t) n), r ((std::size_t) n);
  6365. for (int n0 = 0; n0 < n; n0 += 512)
  6366. {
  6367. for (std::size_t k = 0; k < notes.size(); ++k)
  6368. {
  6369. if (notes[k][1] >= n0 && notes[k][1] < n0 + 512)
  6370. {
  6371. lynx::sytrus::NoteParams p;
  6372. p.key = (float) notes[k][0];
  6373. p.id = (std::int64_t) k + 1;
  6374. e.noteOn (p);
  6375. }
  6376. if (notes[k][2] >= n0 && notes[k][2] < n0 + 512)
  6377. e.release ((std::int64_t) k + 1);
  6378. }
  6379. e.render (l.data() + n0, r.data() + n0, std::min (512, n - n0), 1.0f, 0.0f);
  6380. }
  6381. return { l, r };
  6382. }
  6383. } // namespace
  6384. TEST (sytrus_engine_sine)
  6385. {
  6386. // one sine operator, ratio 1, OUT 256, no envelopes: C5 = 523.2511 Hz at 0.7071 (centre of the pan law, §6.1)
  6387. SytrusTestPatch t;
  6388. t.cell (0, 0, 8, 256);
  6389. const auto blob = t.blob();
  6390. CHECK (lynx::sytrus::stateUsable (blob));
  6391. CHECK (lynx::sytrus::parsePatch (blob) != nullptr);
  6392. auto broken = blob;
  6393. broken.resize (broken.size() / 2);
  6394. CHECK (! lynx::sytrus::stateUsable (broken));
  6395. const auto [l, r] = sytrusRender (blob, false, 8192, { { 60, 0, 4096 } });
  6396. double worst = 0.0;
  6397. for (int k = 0; k < 4000; ++k)
  6398. 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)));
  6399. CHECK (worst < 2e-5);
  6400. CHECK (l == r);
  6401. // 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
  6402. // 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)
  6403. int last = 0;
  6404. for (int k = 0; k < 8192; ++k)
  6405. if (l[(std::size_t) k] != 0.0f)
  6406. last = k;
  6407. CHECK (last == 4895);
  6408. // key 69 = 880 Hz; 48 kHz
  6409. const auto [l2, r2] = sytrusRender (blob, false, 4096, { { 69, 0, -1 } }, 48000.0);
  6410. worst = 0.0;
  6411. for (int k = 0; k < 4000; ++k)
  6412. 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)));
  6413. CHECK (worst < 5e-5);
  6414. (void) r2;
  6415. }
  6416. TEST (sytrus_engine_reference)
  6417. {
  6418. // FM 2→1, Vanilla LP filter, volume envelope, unison 3, delay and reverb, 2× oversampling with the 8-sample
  6419. // envelope tick (render settings): against our Python reference model of REA_rodada31 (sytmodel.render)
  6420. SytrusTestPatch t;
  6421. t.main[195] = 0, t.main[196] = 1, t.main[193] = 0, t.main[194] = 1;
  6422. t.main[173] = 3, t.main[174] = 64, t.main[176] = 100;
  6423. t.ops[1].ratio = 40000;
  6424. t.cell (0, 0, 1, 128); // op 2 → op 1 FM
  6425. t.cell (0, 0, 8, 128);
  6426. t.cell (0, 6, 0, 256); // op 1 → filter 1
  6427. t.cell (0, 6, 8, 256);
  6428. t.cell (0, 0, 7, 200); // FX send
  6429. t.filts[0].p[0] = 1, t.filts[0].p[2] = 180, t.filts[0].p[3] = 60;
  6430. t.ops[0].env1[0] = 0, t.ops[0].env1[1] = 1, t.ops[0].env1[2] = 2;
  6431. t.ops[0].env1pts = { { 0.0, 0.0 }, { 0.05, 1.0 }, { 0.1, 0.6 }, { 0.2, 0.0 } };
  6432. const std::int32_t d0[5] { 40, 100, 50, 100, 0 };
  6433. std::memcpy (t.delays[0].data(), d0, 20);
  6434. t.delays[0][22] = 1;
  6435. t.reverb = { 19, 221, 10, 50, 80, 30, 100, 2, 100 };
  6436. t.reverbOn = true;
  6437. const auto blob = t.blob();
  6438. const auto [l, r] = sytrusRender (blob, true, 12000, { { 60, 0, 6000 } });
  6439. // reference values (model render_mode=True, 44.1 kHz, block 512, key 60, velocity 0.78125, release at 6000); the same
  6440. // state rendered by FL's own Sytrus DLL in render mode differs from this by −136 dB (EXEC, REA round 31 harness)
  6441. const std::array<std::pair<int, float>, 8> golden { { { 100, -0.00235529384f }, { 777, -0.175126165f }, { 2000, 0.30976975f }, { 4321, -0.0213534199f },
  6442. { 6100, 0.202372357f }, { 7000, 0.249530748f }, { 9000, 0.0307101421f }, { 11999, 0.176390275f } } };
  6443. for (const auto& [i, v] : golden)
  6444. CHECK (std::abs (l[(std::size_t) i] - v) < 1e-6f);
  6445. const std::array<std::pair<int, float>, 3> goldenR { { { 777, -0.166890964f }, { 4321, -0.212358952f }, { 9000, -0.0251909085f } } };
  6446. for (const auto& [i, v] : goldenR)
  6447. CHECK (std::abs (r[(std::size_t) i] - v) < 1e-6f);
  6448. }
  6449. TEST (sytrus_instrument)
  6450. {
  6451. // the LYNX instrument: state in ChannelDef::pluginState, channel volume/pan recovered from the rack gains
  6452. SytrusTestPatch t;
  6453. t.cell (0, 0, 8, 256);
  6454. lynx::ChannelDef c;
  6455. c.instrument = lynx::InstrumentKind::sytrus;
  6456. c.pluginState = t.blob();
  6457. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sytrus);
  6458. inst->prepare (44100.0);
  6459. inst->configure (c, 120.0);
  6460. CHECK (inst->idle());
  6461. std::vector<float> l (4096), r (4096);
  6462. inst->noteOn (60, 100.0f / 128.0f);
  6463. // 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
  6464. inst->render (l.data(), r.data(), 4096, 0.5f, 0.5f);
  6465. double peak = 0.0;
  6466. for (int k = 1000; k < 4096; ++k)
  6467. peak = std::max (peak, (double) std::abs (l[(std::size_t) k]));
  6468. CHECK (std::abs (peak - 0.5 * 0.70710678) < 1e-3); // Final.Vol 0.5 × the plugin's centre pan law
  6469. CHECK (! inst->idle());
  6470. inst->noteOff (60);
  6471. std::vector<float> tail (44100 * 3), tailR (tail.size());
  6472. inst->render (tail.data(), tailR.data(), (int) tail.size(), 0.5f, 0.5f);
  6473. CHECK (inst->idle());
  6474. CHECK (tail.back() == 0.0f);
  6475. }
  6476. TEST (harmor_effects_rack)
  6477. {
  6478. // REA_rodada38: the rack runs in the state's unit order and the records' FX send joins it at unit 4 — with the FX
  6479. // amount at 1000 every record output bypasses a reverb placed before unit 4 (EXEC: −600 dB vs the rack off)
  6480. auto blob = harmorTestState (false);
  6481. auto set = [&] (std::vector<std::uint8_t>& st, int part, int index, std::int32_t v) {
  6482. std::memcpy (st.data() + lynx::harmorParamOffset (st, part, index), &v, 4);
  6483. };
  6484. set (blob, 0, 10, 1000); // all to the FX send
  6485. auto render = [] (const std::vector<std::uint8_t>& st) {
  6486. return lynx::harmor::renderReference (st, { { 0, 60, 0.8, 1.0, 0.0, 6000 } }, 44100.0, 12000);
  6487. };
  6488. const auto dry = render (blob);
  6489. auto rev = blob;
  6490. set (rev, -1, 22, 1); // reverb on: room 50, diffusion 100, decay 2^3·0.1 s, high cut / damping off, wet 0.8
  6491. set (rev, -1, 24, 1050), set (rev, -1, 26, 50), set (rev, -1, 27, 100), set (rev, -1, 28, 300), set (rev, -1, 29, 1050);
  6492. set (rev, -1, 30, 2), set (rev, -1, 31, 800);
  6493. const auto bypassed = render (rev);
  6494. double eb = 0.0, db = 0.0;
  6495. for (std::size_t i = 0; i < dry.size(); ++i)
  6496. eb += (double) (bypassed[i] - dry[i]) * (bypassed[i] - dry[i]), db += (double) dry[i] * dry[i];
  6497. CHECK (eb < 1e-12 * db && db > 1e-3); // (float rounding of the rack's buffers only)
  6498. auto after = rev;
  6499. const std::int32_t order[6] { 0, 1, 2, 4, 3, 5 }; // the join before the reverb
  6500. for (int k = 0; k < 6; ++k)
  6501. set (after, -1, 53 + k, order[k]);
  6502. const auto wet = render (after);
  6503. double e = 0.0, d = 0.0;
  6504. bool finite = true;
  6505. for (std::size_t i = 0; i < wet.size(); ++i)
  6506. e += (double) (wet[i] - dry[i]) * (wet[i] - dry[i]), d += (double) dry[i] * dry[i], finite = finite && std::isfinite (wet[i]);
  6507. CHECK (finite && e > 1e-4 * d && d > 1e-3);
  6508. // a distortion (type 6) and a delay on the dry path change the sound, stay finite, and the instrument ends quiet
  6509. auto dist = harmorTestState (false);
  6510. {
  6511. const auto at = lynx::harmorParamOffset (dist, -1, 0) + 0xd4 + 0x18 + 48; // global misc +48: distortion type
  6512. const std::int32_t six = 6;
  6513. std::memcpy (dist.data() + at, &six, 4);
  6514. }
  6515. set (dist, -1, 17, 600), set (dist, -1, 19, 1000), set (dist, -1, 21, 1100);
  6516. set (dist, -1, 39, 1), set (dist, -1, 40, 2), set (dist, -1, 41, 400), set (dist, -1, 42, 96), set (dist, -1, 44, 800);
  6517. set (dist, -1, 47, 1050);
  6518. lynx::ChannelDef c;
  6519. c.instrument = lynx::InstrumentKind::harmor;
  6520. c.pluginState = dist;
  6521. auto inst = lynx::makeInstrument (lynx::InstrumentKind::harmor);
  6522. inst->configure (c, 120.0);
  6523. inst->prepare (44100.0);
  6524. std::vector<float> l (44100 * 4), r (l.size());
  6525. inst->noteOn (60, 0.8f);
  6526. double energy = 0.0;
  6527. for (int s = 0; s < (int) l.size(); s += 512)
  6528. {
  6529. if (s == 8192)
  6530. inst->noteOff (60);
  6531. inst->render (l.data() + s, r.data() + s, 512, 1.0f, 1.0f);
  6532. }
  6533. for (std::size_t i = 0; i < l.size(); ++i)
  6534. finite = finite && std::isfinite (l[i]) && std::isfinite (r[i]), energy += (double) l[i] * l[i];
  6535. CHECK (finite && energy > 1.0);
  6536. std::vector<float> tail (44100 * 6), tailR (tail.size());
  6537. for (int s = 0; s < (int) tail.size(); s += 512)
  6538. inst->render (tail.data() + s, tailR.data() + s, 512, 1.0f, 1.0f);
  6539. CHECK (inst->idle());
  6540. }
  6541. TEST (harmless_engine)
  6542. {
  6543. // REA_rodada32: state parsing, the additive engine against our reference model (hlmodel.py), host levels, voice end
  6544. std::vector<std::uint8_t> blob;
  6545. 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))); };
  6546. std::array<std::int32_t, 100> p {}; // the reference's clean patch: Saw, open filter, no modulation
  6547. for (int i = 11; i < 23; ++i)
  6548. p[(std::size_t) i] = 1000;
  6549. 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;
  6550. 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;
  6551. // + resonance, pluck, 3-voice unison, tremolo, LFO on pitch
  6552. 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;
  6553. put (12);
  6554. for (auto v : p)
  6555. put (v);
  6556. for (int i = 0; i < 7; ++i)
  6557. put (0);
  6558. put (524); // Custom colour table: 524 × (amplitude, phase)
  6559. for (int i = 0; i < 1048; ++i)
  6560. {
  6561. const auto f = i < 524 ? 1.0f / (float) (i + 1) : 0.25f;
  6562. std::uint32_t bits = 0;
  6563. std::memcpy (&bits, &f, 4);
  6564. put ((std::int32_t) bits);
  6565. }
  6566. const auto parsed = lynx::harmlessParams (blob);
  6567. CHECK (parsed && (int) parsed->size() == lynx::harmlessParamCount);
  6568. CHECK (parsed && (*parsed)[54] == 3500.0f && (*parsed)[99] == 0.0f && (*parsed)[lynx::harmlessCustomFlagIndex] == 1.0f);
  6569. CHECK (parsed && (*parsed)[lynx::harmlessCustomIndex + 1] == 0.5f && (*parsed)[lynx::harmlessCustomIndex + 524] == 0.25f);
  6570. auto old = blob;
  6571. old[0] = 3; // versions below 4 are not Harmless states we know
  6572. CHECK (! lynx::harmlessParams (old));
  6573. old = blob;
  6574. old.resize (300);
  6575. CHECK (! lynx::harmlessParams (old));
  6576. lynx::ChannelDef c;
  6577. c.instrument = lynx::InstrumentKind::harmless;
  6578. c.modelParams = *parsed;
  6579. c.modelParams[lynx::harmlessCustomFlagIndex] = 0.0f; // colour 0 (Saw): the custom table is not read
  6580. auto render = [] (const lynx::ChannelDef& def, int total, float gl, float gr, int offAt) {
  6581. auto inst = lynx::makeInstrument (lynx::InstrumentKind::harmless);
  6582. inst->configure (def, 120.0);
  6583. inst->prepare (44100.0);
  6584. std::vector<float> l ((std::size_t) total), r ((std::size_t) total);
  6585. inst->noteOn (60, 0.78125f);
  6586. for (int s = 0; s < total; s += 512)
  6587. {
  6588. if (s == offAt)
  6589. inst->noteOff (60);
  6590. inst->render (l.data() + s, r.data() + s, std::min (512, total - s), gl, gr);
  6591. }
  6592. return std::make_tuple (l, r, std::move (inst));
  6593. };
  6594. {
  6595. // reference model (REA round 32 hlmodel.py, C5 at FL velocity 100, channel volume 1, centre, released at 6144)
  6596. auto [l, r, inst] = render (c, 8192, 1.0f, 1.0f, 6144);
  6597. const std::tuple<int, float, float> golden[] {
  6598. { 0, 0.0f, 0.0f }, { 10, -0.02220994f, -0.06232700f }, { 100, 0.40623373f, 0.17308202f }, { 1000, -0.04091963f, -0.26821208f },
  6599. { 3000, 0.14519004f, 0.11027778f }, { 6000, 0.50411958f, 0.27901855f }, { 8191, 0.02117692f, -0.01466602f } };
  6600. for (const auto& [i, gl, gr] : golden)
  6601. CHECK (std::abs (l[(std::size_t) i] - gl) < 2e-6f && std::abs (r[(std::size_t) i] - gr) < 2e-6f);
  6602. // after the release the record fades out (below 1e-4, then 30 ms) and the instrument goes idle
  6603. std::vector<float> tail (44100), tailR (tail.size());
  6604. inst->render (tail.data(), tailR.data(), (int) tail.size(), 1.0f, 1.0f);
  6605. CHECK (inst->idle());
  6606. }
  6607. // FL's level law applied once: half the channel volume halves the output; full right pan silences the left side
  6608. const auto full = std::get<0> (render (c, 2048, 1.0f, 1.0f, -1));
  6609. const auto half = std::get<0> (render (c, 2048, 0.5f, 0.5f, -1));
  6610. CHECK (std::abs (half[100] - 0.5f * full[100]) < 1e-6f && std::abs (full[100]) > 0.1f);
  6611. auto mono = c;
  6612. mono.modelParams[25] = 0.0f; // no tremolo, no unison pan spread
  6613. mono.modelParams[65] = 1.0f;
  6614. const auto [pl, pr, pi] = render (mono, 2048, 0.0f, 1.41421356f, -1);
  6615. double el = 0.0, er = 0.0;
  6616. for (int i = 0; i < 2048; ++i)
  6617. el += (double) pl[(std::size_t) i] * pl[(std::size_t) i], er += (double) pr[(std::size_t) i] * pr[(std::size_t) i];
  6618. CHECK (el < 1e-10 * er && er > 1.0);
  6619. }
  6620. TEST (startup_sound)
  6621. {
  6622. // the splash's sound: the right length, finite, at its peak level, quiet before the whoosh swells,
  6623. // a landing "pop" at impactTime and a chime ringing after it
  6624. using namespace lynx::startup;
  6625. const auto sound = makeSound (48000.0);
  6626. CHECK (sound.left.size() == (std::size_t) (soundLength * 48000.0) && sound.right.size() == sound.left.size());
  6627. float peak = 0.0f;
  6628. bool finite = true;
  6629. for (std::size_t i = 0; i < sound.left.size(); ++i)
  6630. {
  6631. finite = finite && std::isfinite (sound.left[i]) && std::isfinite (sound.right[i]);
  6632. peak = std::max ({ peak, std::abs (sound.left[i]), std::abs (sound.right[i]) });
  6633. }
  6634. CHECK (finite && std::abs (peak - peakLevel) < 1.0e-4f);
  6635. auto rms = [&sound] (double from, double to) {
  6636. double e = 0.0;
  6637. const auto a = (std::size_t) (from * 48000.0), b = (std::size_t) (to * 48000.0);
  6638. for (auto i = a; i < b; ++i)
  6639. e += (double) sound.left[i] * sound.left[i];
  6640. return std::sqrt (e / (double) (b - a));
  6641. };
  6642. CHECK (rms (0.0, 0.05) < 0.2 * rms (impactTime - 0.05, impactTime)); // the whoosh swells
  6643. CHECK (rms (impactTime, impactTime + 0.05) > rms (impactTime - 0.05, impactTime)); // the landing
  6644. CHECK (rms (0.8, 1.0) > 0.005 && rms (soundLength - 0.02, soundLength) < rms (0.8, 1.0)); // chime rings, tail fades
  6645. CHECK (makeSound (48000.0).left == sound.left); // the same sound on every start
  6646. }
  6647. namespace
  6648. {
  6649. // little-endian byte writer for the state builders below
  6650. struct Bytes
  6651. {
  6652. std::vector<std::uint8_t> b;
  6653. void raw (const char* s, std::size_t n) { b.insert (b.end(), s, s + n); }
  6654. void i32 (std::int32_t v) { b.insert (b.end(), reinterpret_cast<const std::uint8_t*> (&v), reinterpret_cast<const std::uint8_t*> (&v) + 4); }
  6655. void f32 (float v) { b.insert (b.end(), reinterpret_cast<const std::uint8_t*> (&v), reinterpret_cast<const std::uint8_t*> (&v) + 4); }
  6656. void zeros (std::size_t n) { b.insert (b.end(), n, 0); }
  6657. void bytes (const std::vector<std::uint8_t>& o) { b.insert (b.end(), o.begin(), o.end()); }
  6658. };
  6659. // A GMS state written from scratch (REA_rodada12 §1.1 layout, "Syn4"): oscillator waves that don't exist (silent
  6660. // tables, so the result does not depend on an FL installation), noise through the ladder with envelope and LFO,
  6661. // unison, slide, distortion, delay, reverb and the output EQ.
  6662. std::vector<std::uint8_t> gmsTestState()
  6663. {
  6664. std::array<float, 212> P {};
  6665. for (int i : { 1, 2, 44, 55, 56, 57, 58, 59, 60, 207, 208, 209, 210, 211 })
  6666. P[(std::size_t) i] = 0.5f;
  6667. P[0] = 0.75f, P[4] = 0.1f, P[5] = 0.4f, P[6] = 0.6f, P[7] = 0.3f, P[8] = 0.8f;
  6668. P[10] = 0.2f, P[11] = 1.0f, P[12] = 0.45f, P[13] = 0.55f, P[16] = 0.6f, P[20] = 0.2f, P[22] = 0.5f;
  6669. P[28] = 0.5f, P[34] = 0.4f, P[41] = 0.2f, P[42] = 0.6f, P[43] = 0.5f, P[45] = 0.8f, P[199] = 1.0f, P[198] = 0.8f, P[200] = 1.0f;
  6670. P[147] = 1.0f, P[117] = 0.3f, P[127] = 0.6f; // distortion
  6671. P[153] = 1.0f, P[123] = 0.5f, P[133] = 0.4f, P[143] = 0.4f; // delay (1/2 beat)
  6672. P[154] = 1.0f, P[124] = 0.6f, P[134] = 0.5f; // reverb
  6673. P[206] = 1.0f, P[207] = 0.7f, P[211] = 0.3f; // output EQ
  6674. Bytes preset;
  6675. preset.raw ("4nyS", 4);
  6676. for (const char* path : { "NoSuchDir\\NoWave A.wav", "NoSuchDir\\NoWave B.wav", "NoSuchDir\\NoWave C.wav", "", "", "", "" })
  6677. {
  6678. const auto n = std::strlen (path);
  6679. preset.raw (path, n);
  6680. preset.zeros (512 - n);
  6681. }
  6682. preset.i32 (0), preset.i32 (0), preset.i32 (0);
  6683. for (auto v : P)
  6684. preset.f32 (v);
  6685. preset.raw ("LYNX test", 9);
  6686. preset.zeros (512 - 9);
  6687. Bytes s;
  6688. s.raw ("SSLF", 4);
  6689. s.i32 ((std::int32_t) preset.b.size());
  6690. s.bytes (preset.b);
  6691. return s.b;
  6692. }
  6693. // A Morphine state written from scratch (REA_rodada16 §3 / REA_rodada39 §2.2 layout): generators A and B with a few
  6694. // frames each (A loops, PWM on A), C and D silent, a morph line A→B, four envelopes (Eg1 → pitch and velocity →
  6695. // amplitude through the matrix), the master ADSR and every plugin effect on.
  6696. std::vector<std::uint8_t> morphineTestState()
  6697. {
  6698. auto mbp = [] (int seed) {
  6699. Bytes b;
  6700. b.raw ("0PBM", 4);
  6701. for (int a = 0; a < 3; ++a)
  6702. for (int byte = 0; byte < 16; ++byte)
  6703. {
  6704. b.b.push_back (0xff);
  6705. for (int bit = 0; bit < 8; ++bit)
  6706. {
  6707. const auto k = byte * 8 + bit;
  6708. const float v = a == 0 ? std::cbrt (1.0f / (float) (k + 1 + seed * (k % 3))) * (k < 40 ? 1.0f : 0.2f)
  6709. : a == 1 ? 0.1f * (float) ((k * 7 + seed) % 11 - 5) / 5.0f
  6710. : 0.02f * (float) ((k * 5 + seed) % 7 - 3);
  6711. b.f32 (v);
  6712. }
  6713. }
  6714. return b.b;
  6715. };
  6716. auto msp = [&] (int frames, int seed, int loopMode) {
  6717. Bytes b;
  6718. b.raw ("0PSM", 4);
  6719. b.i32 (frames);
  6720. for (int f = 0; f < frames; ++f)
  6721. {
  6722. const auto m = mbp (seed + f);
  6723. b.i32 (20 + 7 * f), b.f32 (1.0f - 0.2f * (float) f), b.i32 ((std::int32_t) m.size());
  6724. b.bytes (m);
  6725. }
  6726. b.i32 (0x424);
  6727. b.i32 (10), b.i32 (40), b.i32 (0), b.i32 (loopMode);
  6728. b.f32 (0.45f), b.f32 (0.6f), b.f32 (0.5f), b.i32 (0);
  6729. for (int k = 0; k < 128; ++k)
  6730. b.f32 (0.3f);
  6731. for (int k = 0; k < 128; ++k)
  6732. b.f32 (1.0f);
  6733. return b.b;
  6734. };
  6735. auto mvc = [&] (int frames, int seed, int pwmMode) {
  6736. Bytes z;
  6737. z.raw ("0HZM", 4);
  6738. z.i32 (1);
  6739. const auto s = msp (frames, seed, 1);
  6740. z.i32 (128), z.f32 (frames > 1 ? 0.9f : 0.0f), z.i32 ((std::int32_t) s.size());
  6741. z.bytes (s);
  6742. Bytes b;
  6743. b.raw ("0CVM", 4);
  6744. b.i32 ((std::int32_t) z.b.size());
  6745. b.bytes (z.b);
  6746. b.i32 (28), b.f32 (0.4f), b.i32 (pwmMode), b.f32 (0.3f), b.i32 (0), b.f32 (0.5f), b.f32 (0.6f);
  6747. return b.b;
  6748. };
  6749. Bytes p;
  6750. p.raw ("0roM", 4);
  6751. p.raw ("0RPM", 4);
  6752. for (const auto& g : { mvc (3, 1, 2), mvc (2, 7, 0), mvc (1, 3, 0), mvc (1, 5, 0) })
  6753. {
  6754. p.i32 ((std::int32_t) g.size());
  6755. p.bytes (g);
  6756. }
  6757. {
  6758. Bytes m;
  6759. m.raw ("0LMM", 4);
  6760. m.i32 (2), m.i32 (12);
  6761. m.f32 (0.0f), m.f32 (1.0f), m.i32 (60);
  6762. m.f32 (1.0f), m.f32 (1.0f), m.i32 (60);
  6763. m.i32 (0x54), m.i32 (0), m.i32 (0), m.i32 (0), m.i32 (0);
  6764. for (float v : { 1.0f, 0.8f, 0.0f, 0.0f, 0.5f, 0.4f, 0.5f, 0.5f })
  6765. m.f32 (v);
  6766. for (int k = 0; k < 4; ++k)
  6767. m.i32 (0);
  6768. m.f32 (0.5f), m.f32 (0.5f), m.f32 (0.5f), m.i32 (0);
  6769. p.i32 ((std::int32_t) m.b.size());
  6770. p.bytes (m.b);
  6771. }
  6772. {
  6773. Bytes d;
  6774. d.raw ("0DMM", 4);
  6775. d.i32 (4);
  6776. for (int e = 0; e < 4; ++e)
  6777. {
  6778. Bytes g;
  6779. g.raw ("0GEM", 4);
  6780. g.i32 (3), g.i32 (8);
  6781. g.f32 (0.0f), g.i32 (10), g.f32 (1.0f), g.i32 (40 + 10 * e), g.f32 (0.3f), g.i32 (50);
  6782. g.i32 (0x2c), g.i32 (0), g.i32 (0), g.i32 (0), g.f32 (0.5f), g.i32 (0), g.f32 (0.45f), g.i32 (0), g.f32 (0.5f), g.f32 (0.6f),
  6783. g.i32 (e == 0 ? 1 : 0);
  6784. d.i32 ((std::int32_t) g.b.size());
  6785. d.bytes (g.b);
  6786. }
  6787. d.i32 (0x94);
  6788. const int src[12] = { 5, 2 }, dst[12] = { 3, 1 };
  6789. const float amt[12] = { 0.56f, 0.7f };
  6790. for (int k = 0; k < 12; ++k)
  6791. d.i32 (src[k]);
  6792. for (int k = 0; k < 12; ++k)
  6793. d.i32 (dst[k]);
  6794. for (int k = 0; k < 12; ++k)
  6795. d.f32 (amt[k]);
  6796. p.i32 ((std::int32_t) d.b.size());
  6797. p.bytes (d.b);
  6798. }
  6799. {
  6800. const float A[40] = { 0.5f, 0.0f, 0.0f, -1.0f, 0.2f, 0.5f, 0.55f, 0.1f, 0.17f, 0.2f, // master … velocity curve, ADSR A
  6801. 0.5f, 0.7f, 0.4f, 0.5f, 0.5f, 0.3f, 1.0f, 0.4f, 0.6f, 0.3f, // D S R, chorus, delay …
  6802. 0.4f, 0.3f, 1.0f, 0.5f, 0.5f, 0.4f, 1.0f, 0.6f, 0.4f, 0.5f, // … delay, reverb, EQ …
  6803. 0.5f, 0.5f, 0.55f, 0.5f, 0.45f, 1.0f, 0.0f, 0.5f, 1.0f, 0.0f }; // EQ on, noise (muted)
  6804. Bytes g;
  6805. g.i32 (0x5c4);
  6806. for (auto v : A)
  6807. g.f32 (v);
  6808. g.zeros (0x5c4 - g.b.size());
  6809. p.bytes (g.b);
  6810. }
  6811. Bytes s;
  6812. s.raw ("SSLF", 4);
  6813. s.i32 ((std::int32_t) p.b.size());
  6814. s.bytes (p.b);
  6815. return s.b;
  6816. }
  6817. void dumpIfAsked (const char* var, const std::vector<std::uint8_t>& blob)
  6818. {
  6819. if (const char* path = std::getenv (var))
  6820. {
  6821. std::ofstream out (path, std::ios::binary);
  6822. out.write (reinterpret_cast<const char*> (blob.data()), (std::streamsize) blob.size());
  6823. }
  6824. }
  6825. } // namespace
  6826. TEST (gms_engine)
  6827. {
  6828. const auto blob = gmsTestState();
  6829. dumpIfAsked ("LYNX_DUMP_GMS", blob);
  6830. CHECK (lynx::gmsStateUsable (blob));
  6831. CHECK (lynx::gmsWaveNames (blob) == std::vector<std::string> ({ "NoWave A", "NoWave B", "NoWave C" }));
  6832. CHECK (lynx::gmsParamOffset (blob, 12) == 8 + 4 + 7 * 512 + 12 + 4 * 12 && lynx::gmsParamOffset (blob, 212) < 0);
  6833. auto broken = blob;
  6834. broken[8] = 'X';
  6835. CHECK (! lynx::gmsStateUsable (broken));
  6836. CHECK (! lynx::gmsStateUsable (std::vector<std::uint8_t> (blob.begin(), blob.begin() + 2000)));
  6837. // golden samples of our round-39 model (gmsmodel.GmsPlugin, waves missing → silent tables, tempo 140, 44.1 kHz,
  6838. // host blocks of 512): C5 vel 100 0–30000, E5 vel 80 11025–40000, G5 vel 110 22050–52000 (Init.Vol law A)
  6839. auto iv = [] (double vel) { return (std::pow (11.0, vel / 100.0) - 1.0) / 10.0; };
  6840. const std::vector<lynx::gms::RefNote> notes = { { 0, 60, (float) iv (100), 1.0, 0.0, 0.0, 30000 },
  6841. { 11025, 64, (float) iv (80), 1.0, 0.0, 0.0, 40000 },
  6842. { 22050, 67, (float) iv (110), 1.0, 0.0, 0.0, 52000 } };
  6843. const auto y = lynx::gms::renderReference (blob, notes, 44100.0, 66150, "");
  6844. CHECK (y.size() == 2 * 66150u);
  6845. static const struct { int i; float l, r; } golden[] = { { 100, 0.0298744496f, 0.0198248848f }, { 5000, 0.0669416264f, 0.0666475743f }, { 15000, -0.005992427f, 0.013085857f }, { 25000, 0.0102018276f, 0.0130400788f }, { 35000, -0.0679694712f, -0.0050432696f }, { 45000, -0.0161557719f, 0.154340729f }, { 55000, -0.00719845621f, 0.0182181317f }, { 66000, 0.0389953516f, 0.0104107196f } };
  6846. for (const auto& g : golden)
  6847. CHECK (std::abs (y[2 * (std::size_t) g.i] - g.l) < 1e-6f && std::abs (y[2 * (std::size_t) g.i + 1] - g.r) < 1e-6f);
  6848. double e = 0.0;
  6849. for (auto v : y)
  6850. e += (double) v * v;
  6851. CHECK (std::abs (std::sqrt (e / (double) y.size()) - 0.0790270452795) < 1e-6);
  6852. // the instrument: same engine behind LYNX's channel gains (V = 1, centre → law A), velocity → Init.Vol
  6853. lynx::ChannelDef c;
  6854. c.instrument = lynx::InstrumentKind::gms;
  6855. c.pluginState = blob;
  6856. auto inst = lynx::makeInstrument (lynx::InstrumentKind::gms);
  6857. inst->configure (c, 140.0);
  6858. inst->prepare (44100.0);
  6859. std::vector<float> l (8192, 0.0f), r (8192, 0.0f);
  6860. for (int b = 0; b < 16; ++b)
  6861. {
  6862. if (b == 0)
  6863. inst->noteOn (60, 0.78125f);
  6864. if (b == 10)
  6865. inst->noteOff (60);
  6866. inst->render (l.data() + 512 * b, r.data() + 512 * b, 512, 1.0f, 1.0f);
  6867. }
  6868. const auto ref = lynx::gms::renderReference (blob, { { 0, 60, (std::pow (11.0, 1.28 * 0.78125) - 1.0) / 10.0, 1.0, 0.0, 0.0, 5120 } }, 44100.0, 8192, "");
  6869. double diff = 0.0, energy = 0.0;
  6870. for (int i = 0; i < 8192; ++i)
  6871. {
  6872. diff = std::max ({ diff, (double) std::abs (l[(std::size_t) i] - ref[2 * (std::size_t) i]), (double) std::abs (r[(std::size_t) i] - ref[2 * (std::size_t) i + 1]) });
  6873. energy += (double) l[(std::size_t) i] * l[(std::size_t) i];
  6874. }
  6875. CHECK (diff == 0.0 && energy > 1e-3);
  6876. }
  6877. TEST (morphine_engine)
  6878. {
  6879. const auto blob = morphineTestState();
  6880. dumpIfAsked ("LYNX_DUMP_MORPHINE", blob);
  6881. CHECK (lynx::morphineStateUsable (blob));
  6882. CHECK (lynx::morphineNoiseName (blob).empty());
  6883. const auto at = lynx::morphineParamOffset (blob, 9);
  6884. CHECK (at > 0);
  6885. float a9 = 0.0f;
  6886. std::memcpy (&a9, blob.data() + at, 4);
  6887. CHECK (a9 == 0.2f && lynx::morphineParamOffset (blob, 40) < 0);
  6888. auto broken = blob;
  6889. broken[12] = 'X'; // the MPR0 tag
  6890. CHECK (! lynx::morphineStateUsable (broken));
  6891. CHECK (! lynx::morphineStateUsable (std::vector<std::uint8_t> (blob.begin(), blob.end() - 10)));
  6892. // golden samples of our round-39 model (mormodel.Synth, tempo 120, 44.1 kHz, host blocks of 512): keys 60/64/67,
  6893. // Init.Vol 1.0/0.5/2.0, note-offs at 30000/50000/70000
  6894. const std::vector<lynx::morphine::RefNote> notes = { { 0, 60, 1.0, 1.0, 0.0, 0.0, 30000 },
  6895. { 11025, 64, 0.5, 1.0, 0.0, 0.0, 50000 },
  6896. { 22050, 67, 2.0, 1.0, 0.0, 0.0, 70000 } };
  6897. const auto y = lynx::morphine::renderReference (blob, notes, 44100.0, 80000, "");
  6898. CHECK (y.size() == 2 * 80000u);
  6899. static const struct { int i; float l, r; } golden[] = { { 100, 0.00094500737f, 0.00085531926f }, { 5000, 0.0311509669f, -0.11552836f }, { 15000, 0.0843918771f, 0.0369227529f }, { 25000, 0.60864079f, 1.03062224f }, { 35000, -0.346013308f, 0.135865599f }, { 45000, -0.0373920798f, -0.13064307f }, { 60000, -0.138871655f, -0.163586512f }, { 75000, 0.0251323506f, -0.00735046482f } };
  6900. for (const auto& g : golden)
  6901. CHECK (std::abs (y[2 * (std::size_t) g.i] - g.l) < 1e-6f && std::abs (y[2 * (std::size_t) g.i + 1] - g.r) < 1e-6f);
  6902. double e = 0.0;
  6903. for (auto v : y)
  6904. e += (double) v * v;
  6905. CHECK (std::abs (std::sqrt (e / (double) y.size()) - 0.18467099041) < 1e-6);
  6906. // the instrument: same engine behind LYNX's channel gains
  6907. lynx::ChannelDef c;
  6908. c.instrument = lynx::InstrumentKind::morphine;
  6909. c.pluginState = blob;
  6910. auto inst = lynx::makeInstrument (lynx::InstrumentKind::morphine);
  6911. inst->configure (c, 120.0);
  6912. inst->prepare (44100.0);
  6913. std::vector<float> l (8192, 0.0f), r (8192, 0.0f);
  6914. for (int b = 0; b < 16; ++b)
  6915. {
  6916. if (b == 0)
  6917. inst->noteOn (60, 0.78125f);
  6918. if (b == 10)
  6919. inst->noteOff (60);
  6920. inst->render (l.data() + 512 * b, r.data() + 512 * b, 512, 1.0f, 1.0f);
  6921. }
  6922. const auto ref = lynx::morphine::renderReference (blob, { { 0, 60, (std::pow (11.0, 1.28 * 0.78125) - 1.0) / 10.0, 1.0, 0.0, 0.0, 5120 } }, 44100.0, 8192, "");
  6923. double diff = 0.0, energy = 0.0;
  6924. for (int i = 0; i < 8192; ++i)
  6925. {
  6926. diff = std::max ({ diff, (double) std::abs (l[(std::size_t) i] - ref[2 * (std::size_t) i]), (double) std::abs (r[(std::size_t) i] - ref[2 * (std::size_t) i + 1]) });
  6927. energy += (double) l[(std::size_t) i] * l[(std::size_t) i];
  6928. }
  6929. CHECK (diff == 0.0 && energy > 1e-3);
  6930. }