tests.cpp 414 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605
  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/PoiZone.h"
  31. #include "core/MiniSynth.h"
  32. #include "core/Harmless.h"
  33. #include "core/Harmor.h"
  34. #include "core/Morphine.h"
  35. #include "core/Ogun.h"
  36. #include "core/Dx10.h"
  37. #include "core/Kepler.h"
  38. #include "core/HarmlessFx.h"
  39. #include "core/MaximusFx.h"
  40. #include "core/LiveEventQueue.h"
  41. #include "core/RackRenderer.h"
  42. #include "core/Scheduler.h"
  43. #include "core/SnapshotExchange.h"
  44. #include "core/SoftClip.h"
  45. #include "core/Slicer.h"
  46. #include "core/SytrusEngine.h"
  47. #include "core/Templates.h"
  48. #include "core/Vocodex.h"
  49. #include "core/TimeStretch.h"
  50. #include "core/WorkerPool.h"
  51. #include "core/Song.h"
  52. #include "core/NoteEdit.h"
  53. #include "core/Recorder.h"
  54. #include "core/KeyMap.h"
  55. #include "core/RackOps.h"
  56. #include "core/ValueMath.h"
  57. #include "core/Workspace.h"
  58. #include "core/StartupSound.h"
  59. #include "flp/Flp.h"
  60. #include "ui/I18nData.h"
  61. namespace
  62. {
  63. int failures = 0;
  64. int checks = 0;
  65. std::vector<std::pair<const char*, std::function<void()>>>& registry()
  66. {
  67. static std::vector<std::pair<const char*, std::function<void()>>> r;
  68. return r;
  69. }
  70. struct Register
  71. {
  72. Register (const char* name, std::function<void()> fn) { registry().emplace_back (name, std::move (fn)); }
  73. };
  74. #define TEST(name) \
  75. static void name(); \
  76. static Register reg_##name (#name, name); \
  77. static void name()
  78. #define CHECK(cond) \
  79. do \
  80. { \
  81. ++checks; \
  82. if (! (cond)) \
  83. { \
  84. ++failures; \
  85. std::printf (" FAILED %s:%d: %s\n", __FILE__, __LINE__, #cond); \
  86. } \
  87. } while (false)
  88. std::string realFlpDir;
  89. // --- helpers for building synthetic .flp files -----------------------------
  90. struct FlpBuilder
  91. {
  92. std::vector<std::uint8_t> bytes;
  93. FlpBuilder (std::uint16_t ppq = 96)
  94. {
  95. put ("FLhd");
  96. u32 (6);
  97. u16 (0);
  98. u16 (1);
  99. u16 (ppq);
  100. put ("FLdt");
  101. u32 (0); // size is not used by the reader
  102. }
  103. void put (const char* s) { bytes.insert (bytes.end(), s, s + std::strlen (s)); }
  104. void u8 (std::uint8_t v) { bytes.push_back (v); }
  105. void u16 (std::uint16_t v) { u8 ((std::uint8_t) v); u8 ((std::uint8_t) (v >> 8)); }
  106. void u32 (std::uint32_t v) { u16 ((std::uint16_t) v); u16 ((std::uint16_t) (v >> 16)); }
  107. void varint (std::size_t n)
  108. {
  109. do
  110. {
  111. auto b = (std::uint8_t) (n & 0x7F);
  112. n >>= 7;
  113. u8 (n ? (std::uint8_t) (b | 0x80) : b);
  114. } while (n);
  115. }
  116. void data (std::uint8_t id, const std::vector<std::uint8_t>& payload)
  117. {
  118. u8 (id);
  119. varint (payload.size());
  120. bytes.insert (bytes.end(), payload.begin(), payload.end());
  121. }
  122. void ascii (std::uint8_t id, const std::string& s)
  123. {
  124. std::vector<std::uint8_t> p (s.begin(), s.end());
  125. p.push_back (0);
  126. data (id, p);
  127. }
  128. void utf16 (std::uint8_t id, const std::u16string& s)
  129. {
  130. std::vector<std::uint8_t> p;
  131. for (auto c : s)
  132. {
  133. p.push_back ((std::uint8_t) c);
  134. p.push_back ((std::uint8_t) (c >> 8));
  135. }
  136. p.push_back (0);
  137. p.push_back (0);
  138. data (id, p);
  139. }
  140. };
  141. std::vector<std::uint8_t> noteRecord (std::uint32_t pos, std::uint16_t channel, std::uint32_t len, std::uint16_t key,
  142. std::uint8_t velocity)
  143. {
  144. std::vector<std::uint8_t> r (24, 0);
  145. std::memcpy (&r[0], &pos, 4);
  146. std::memcpy (&r[6], &channel, 2);
  147. std::memcpy (&r[8], &len, 4);
  148. std::memcpy (&r[12], &key, 2);
  149. r[16] = 120;
  150. r[20] = 64;
  151. r[21] = velocity;
  152. return r;
  153. }
  154. } // namespace
  155. // ---------------------------------------------------------------------------
  156. // FLP
  157. TEST (flp_rejects_garbage)
  158. {
  159. std::vector<std::uint8_t> junk (64, 0x41);
  160. bool threw = false;
  161. try { flp::EventReader r (junk); } catch (const flp::Error&) { threw = true; }
  162. CHECK (threw);
  163. }
  164. TEST (flp_reads_size_classes_varint_and_extended_ids)
  165. {
  166. FlpBuilder b;
  167. b.u8 (0x15); b.u8 (2); // u8
  168. b.u8 (0x40); b.u16 (513); // u16
  169. b.u8 (0x9C); b.u32 (128500); // u32
  170. b.data (0xD5, std::vector<std::uint8_t> (300, 7)); // 2-byte varint
  171. b.u8 (0xAC); b.u32 (0xC0000100); b.varint (3); b.u8 (1); b.u8 (2); b.u8 (3); // extended ID
  172. flp::EventReader r (b.bytes);
  173. flp::Event e;
  174. CHECK (r.header().ppq == 96);
  175. CHECK (r.next (e) && e.id == 0x15 && e.value == 2);
  176. CHECK (r.next (e) && e.id == 0x40 && e.value == 513);
  177. CHECK (r.next (e) && e.id == 0x9C && e.value == 128500);
  178. CHECK (r.next (e) && e.id == 0xD5 && e.data.size() == 300 && e.data[299] == 7);
  179. CHECK (r.next (e) && e.id == 0xC0000100 && e.isData() && e.data.size() == 3 && e.data[2] == 3);
  180. CHECK (! r.next (e));
  181. }
  182. TEST (flp_truncated_file_throws)
  183. {
  184. FlpBuilder b;
  185. b.u8 (0x9C); b.u8 (1); // u32 with only 1 byte
  186. flp::EventReader r (b.bytes);
  187. flp::Event e;
  188. bool threw = false;
  189. try { r.next (e); } catch (const flp::Error&) { threw = true; }
  190. CHECK (threw);
  191. }
  192. TEST (flp_version_numbers)
  193. {
  194. CHECK (flp::parseVersionNumber ("25.2.5.5319") == 25002005u);
  195. CHECK (flp::parseVersionNumber ("20.99.3000.3031") == 20102000u);
  196. CHECK (flp::parseVersionNumber ("11.0.3") == 11000003u);
  197. }
  198. TEST (flp_playlist_record_size_by_version)
  199. {
  200. CHECK (flp::playlistRecordSize (12009003, 64) == 32);
  201. CHECK (flp::playlistRecordSize (21000000, 120) == 60);
  202. CHECK (flp::playlistRecordSize (25002005, 160) == 80);
  203. CHECK (flp::playlistRecordSize (25002005, 60) == 60); // size doesn't match the version -> tries the others
  204. CHECK (flp::playlistRecordSize (25002005, 7) == 0);
  205. }
  206. TEST (flp_parses_project_model)
  207. {
  208. FlpBuilder b (96);
  209. b.ascii (0xC7, "25.2.5.5319");
  210. b.u8 (0x9C); b.u32 (174500);
  211. b.utf16 (0xC2, u"Título");
  212. b.u8 (0x41); b.u16 (3);
  213. b.u8 (0x96); b.u32 (0x00A14547); // BGR in the file
  214. auto notes = noteRecord (96, 1, 48, 64, 100);
  215. auto n2 = noteRecord (0, 0, 0, 60, 128);
  216. notes.insert (notes.end(), n2.begin(), n2.end());
  217. b.data (0xE0, notes);
  218. b.u8 (0x40); b.u16 (0);
  219. b.u8 (0x15); b.u8 (0);
  220. b.utf16 (0xCB, u"Kick");
  221. {
  222. std::vector<std::uint8_t> levels (24, 0);
  223. const std::int32_t lv[] = { 3200, 12800, -150 };
  224. std::memcpy (levels.data(), lv, sizeof (lv));
  225. b.data (0xDB, levels);
  226. }
  227. b.u8 (0x68); b.u16 (5);
  228. b.u8 (0x40); b.u16 (1);
  229. b.u8 (0x15); b.u8 (2);
  230. b.utf16 (0xC9, u"FLEX");
  231. b.utf16 (0xCB, u"Lead");
  232. b.u8 (0x63); b.u16 (0);
  233. std::vector<std::uint8_t> item (80, 0);
  234. std::uint32_t pos = 384, len = 768;
  235. std::uint16_t base = 20480, idx = 20480 + 3, rv = 499 - 2;
  236. std::memcpy (&item[0], &pos, 4);
  237. std::memcpy (&item[4], &base, 2);
  238. std::memcpy (&item[6], &idx, 2);
  239. std::memcpy (&item[8], &len, 4);
  240. std::memcpy (&item[12], &rv, 2);
  241. b.data (0xE9, item);
  242. b.utf16 (0xCC, u"Drums");
  243. b.data (0xEC, std::vector<std::uint8_t> (12, 0));
  244. b.data (0xEC, std::vector<std::uint8_t> (12, 0));
  245. const auto p = flp::parseProject (b.bytes);
  246. CHECK (p.version == "25.2.5.5319");
  247. CHECK (std::abs (p.tempo - 174.5) < 1e-9);
  248. CHECK (p.title == "Título");
  249. CHECK (p.channels.size() == 2);
  250. CHECK (p.channels[0].name == "Kick" && p.channels[0].mixerTrack == 5);
  251. CHECK (p.channels[0].hasLevels && p.channels[0].pan == 3200 && p.channels[0].volume == 12800 && p.channels[0].pitchCents == -150);
  252. CHECK (p.channels[1].type == flp::ChannelType::instrument && p.channels[1].pluginName == "FLEX");
  253. CHECK (p.patterns.size() == 1 && p.patterns[0].index == 3);
  254. CHECK (p.patterns[0].colour && *p.patterns[0].colour == 0x4745A1);
  255. CHECK (p.patterns[0].notes.size() == 2 && p.patterns[0].notes[0].position == 0); // sorted
  256. CHECK (p.patterns[0].notes[1].key == 64 && p.patterns[0].notes[1].length == 48);
  257. CHECK (p.arrangements.size() == 1 && p.arrangements[0].items.size() == 1);
  258. const auto& it = p.arrangements[0].items[0];
  259. CHECK (it.kind == flp::PlaylistItem::Kind::pattern && it.index == 3 && it.track == 2 && it.position == 384);
  260. CHECK (p.mixer.size() == 2 && p.mixer[0].name == "Drums" && p.mixer[1].name.empty());
  261. CHECK (p.warnings.empty());
  262. }
  263. TEST (flp_fuzz_corrupted_files_do_not_crash)
  264. {
  265. if (realFlpDir.empty())
  266. return;
  267. // some real .flp files, corrupted in various ways: the parser may reject them (flp::Error), but
  268. // must never hang, read past the buffer or produce a Song with invalid indices
  269. std::vector<std::vector<std::uint8_t>> sources;
  270. for (auto& entry : std::filesystem::recursive_directory_iterator (realFlpDir))
  271. if (entry.path().extension() == ".flp" && sources.size() < 6 && std::filesystem::file_size (entry.path()) < 3'000'000)
  272. {
  273. std::ifstream in (entry.path(), std::ios::binary);
  274. sources.emplace_back ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  275. }
  276. std::uint32_t seed = 2024;
  277. auto rnd = [&] (std::uint32_t n) { seed = seed * 1664525u + 1013904223u; return n == 0 ? 0u : (seed >> 8) % n; };
  278. int parsed = 0, rejected = 0;
  279. for (int round = 0; round < 240 && ! sources.empty(); ++round)
  280. {
  281. auto bytes = sources[(std::size_t) rnd ((std::uint32_t) sources.size())];
  282. switch (round % 4)
  283. {
  284. case 0: bytes.resize (rnd ((std::uint32_t) bytes.size())); break; // truncated
  285. 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;
  286. case 2: // absurd event size
  287. for (int k = 0; k < 5; ++k)
  288. bytes[(std::size_t) rnd ((std::uint32_t) bytes.size())] = 0xFF;
  289. break;
  290. default: // shuffled block
  291. {
  292. const auto a = rnd ((std::uint32_t) bytes.size()), b = rnd ((std::uint32_t) bytes.size());
  293. std::reverse (bytes.begin() + std::min (a, b), bytes.begin() + std::max (a, b));
  294. break;
  295. }
  296. }
  297. try
  298. {
  299. const auto project = flp::parseProject (bytes);
  300. const auto song = lynx::importFlp (project);
  301. ++parsed;
  302. for (const auto& p : song.patterns)
  303. for (const auto& n : p.notes)
  304. CHECK (n.channel >= 0 && n.channel < (int) song.channels.size());
  305. for (const auto& c : song.playlist)
  306. CHECK (c.kind != lynx::ClipKind::pattern || (c.pattern >= 0 && c.pattern < (int) song.patterns.size()));
  307. }
  308. catch (const flp::Error&)
  309. {
  310. ++rejected;
  311. }
  312. }
  313. std::printf (" fuzz: %d imported, %d rejected\n", parsed, rejected);
  314. CHECK (parsed + rejected == 240);
  315. }
  316. TEST (plugin_state_decoders_survive_garbage)
  317. {
  318. // random blobs (varied sizes, including valid headers followed by garbage)
  319. std::uint32_t seed = 77;
  320. auto rnd = [&] { seed = seed * 1664525u + 1013904223u; return seed >> 8; };
  321. const char* plugins[] = { "Fruity Parametric EQ 2", "Fruity Limiter", "Fruity Reeverb 2", "Fruity Delay 2", "Fruity Delay 3",
  322. "Fruity Compressor", "Fruity Balance", "Fruity PanOMatic", "Fruity Stereo Shaper", "Fruity Phase Inverter" };
  323. int decoded = 0;
  324. for (int round = 0; round < 3000; ++round)
  325. {
  326. std::vector<std::uint8_t> blob ((std::size_t) (rnd() % 600));
  327. for (auto& b : blob)
  328. b = (std::uint8_t) rnd();
  329. if (blob.size() >= 4 && round % 3 == 0) // versions the readers accept
  330. {
  331. const std::uint32_t versions[] = { 8, 10001, 10000, 12, 14, 6, 1 };
  332. const auto v = versions[rnd() % 7];
  333. std::memcpy (blob.data(), &v, 4);
  334. }
  335. if (auto fx = lynx::effectFromFl (plugins[rnd() % 10], blob))
  336. {
  337. ++decoded;
  338. for (auto v : fx->params)
  339. CHECK (std::isfinite (v) && v >= 0.0f && v <= 1.0f);
  340. }
  341. lynx::SynthSettings synth;
  342. if (lynx::synthFrom3xOsc (blob, synth))
  343. for (const auto& o : synth.osc)
  344. CHECK (std::isfinite (o.level) && o.level >= 0.0f && o.level <= 1.0f);
  345. float harmlessGain = 1.0f;
  346. if (lynx::synthFromHarmless (blob, 120.0, synth, harmlessGain))
  347. CHECK (std::isfinite (harmlessGain) && std::isfinite (synth.cutoff) && std::isfinite (synth.attack));
  348. if (lynx::synthFromFruitKick (blob, synth))
  349. CHECK (std::isfinite (synth.decay) && std::isfinite (synth.pitchEnv.amount));
  350. if (lynx::synthFromGms (blob, 120.0, synth, harmlessGain) || lynx::synthFromHarmor (blob, synth, harmlessGain) || lynx::synthFromOgun (blob, synth, harmlessGain)
  351. || lynx::synthFromSakura (blob, synth) || lynx::synthFromKepler (blob, synth, harmlessGain))
  352. CHECK (std::isfinite (synth.cutoff) && std::isfinite (synth.attack) && std::isfinite (harmlessGain));
  353. if (auto sound = lynx::drumSynthLiveSound (blob))
  354. CHECK (sound->size() < 256);
  355. if (auto wave = lynx::waveTravellerSample (blob))
  356. CHECK (! wave->first.empty() && wave->second >= 0 && wave->second <= 127);
  357. lynx::synthFromBooBass (blob, synth);
  358. lynx::gmsStateUsable (blob); // (the exact engines' parsers reject garbage without crashing)
  359. lynx::morphineStateUsable (blob);
  360. lynx::poizoneStateUsable (blob);
  361. if (lynx::synthFromPoiZone (blob, synth, harmlessGain) || lynx::synthFromBassDrum (blob, synth, harmlessGain) || lynx::synthFromToxic (blob, synth, harmlessGain)
  362. || lynx::synthFromMorphine (blob, synth, harmlessGain))
  363. CHECK (std::isfinite (synth.cutoff) && std::isfinite (harmlessGain));
  364. if (auto patch = lynx::drumpadPatchName (blob))
  365. CHECK (patch->size() <= 0x30 && std::isfinite (lynx::drumToneForName (*patch).decay));
  366. if (auto flex = lynx::flexPresetName (blob))
  367. CHECK ((! flex->first.empty() || ! flex->second.empty()) && flex->second.size() <= 1024);
  368. if (lynx::synthFromSytrus (blob, 120.0, synth, harmlessGain))
  369. CHECK (std::isfinite (synth.cutoff) && std::isfinite (synth.attack));
  370. if (lynx::synthFromDX10 (blob, synth))
  371. CHECK (std::isfinite (synth.decay) && std::isfinite (synth.release) && std::isfinite (synth.osc[1].level));
  372. if (blob.size() >= 4 && round % 5 == 0) // MiniSynth header followed by garbage
  373. {
  374. std::memcpy (blob.data(), "SSLF", 4);
  375. if (blob.size() > 220)
  376. {
  377. std::memcpy (blob.data() + 40, "DATA", 4);
  378. std::memcpy (blob.data() + 48, "0rev", 4);
  379. }
  380. }
  381. if (lynx::synthFromMiniSynth (blob, 120.0, synth))
  382. CHECK (std::isfinite (synth.cutoff) && std::isfinite (synth.decay) && std::isfinite (synth.attack));
  383. if (lynx::miniSynthStateUsable (blob)) // the exact engine's parser and a short render with silent tables
  384. {
  385. const auto params = lynx::miniSynthParams (blob);
  386. CHECK (params.size() == 43u && std::all_of (params.begin(), params.end(), [] (float v) { return v >= 0.0f && v <= 1.0f; }));
  387. const auto y = lynx::minisynth::renderReference (blob, { { 0, 60, 1.0, 1.0, 0.0, 0.0, 64 } }, 44100.0, 128, "");
  388. CHECK (y.size() == 256u && std::all_of (y.begin(), y.end(), [] (float v) { return std::isfinite (v); }));
  389. }
  390. lynx::ForeignPlugin foreign;
  391. lynx::parseFlWrapper (blob, foreign);
  392. std::vector<std::uint8_t> component, controller;
  393. lynx::splitFlVst3State (blob, component, controller);
  394. }
  395. CHECK (decoded == 3000); // every known name yields an effect (default when the blob is unusable)
  396. }
  397. TEST (inflate_zlib)
  398. {
  399. // fixed Huffman with back-references
  400. const std::uint8_t fixed[] = { 0x78, 0xda, 0x4b, 0x4c, 0x4a, 0x4e, 0xc4, 0x86, 0x22, 0x00, 0x7c, 0x69, 0x09, 0x89 };
  401. const auto a = lynx::inflateZlib (fixed, sizeof (fixed));
  402. CHECK (a && std::string (a->begin(), a->end()) == "abcabcabcabcabcabcabcabcX");
  403. // stored (uncompressed) block
  404. const std::uint8_t stored[] = { 0x78, 0x01, 0x01, 0x03, 0x00, 0xfc, 0xff, 'L', 'Y', 'N', 0x00, 0x00, 0x00, 0x00 };
  405. const auto b = lynx::inflateZlib (stored, sizeof (stored));
  406. CHECK (b && std::string (b->begin(), b->end()) == "LYN");
  407. // truncated, bad header and size limit
  408. CHECK (! lynx::inflateZlib (fixed, 6));
  409. const std::uint8_t bad[] = { 0x12, 0x34, 0x00 };
  410. CHECK (! lynx::inflateZlib (bad, sizeof (bad)));
  411. CHECK (! lynx::inflateZlib (fixed, sizeof (fixed), false, 10));
  412. }
  413. TEST (fl_round15_effects_convert_known_values)
  414. {
  415. auto blob = [] (std::vector<std::int32_t> words) {
  416. std::vector<std::uint8_t> b (words.size() * 4);
  417. std::memcpy (b.data(), words.data(), b.size());
  418. return b;
  419. };
  420. // Frequency Shifter "+800 Hz": frequency 51542 in the 20 kHz range, 100% wet
  421. const auto fs = lynx::effectFromFl ("Frequency Shifter", blob ({ 4, 10000, 0, 51542, 0, 10000, 10000, 5000, 10000, 0, 5000, 0, 0 }));
  422. CHECK (fs && fs->kind == lynx::EffectKind::freqShift);
  423. if (fs)
  424. {
  425. const auto x = (fs->params[0] - 0.5) * 2.0;
  426. CHECK (std::abs (2000.0 * x * std::abs (x) - 800.0) < 10.0);
  427. CHECK (std::abs (fs->params[1] - 1.0f) < 1e-4f);
  428. }
  429. // Emphasis: input 0.0625 (= +1.5 dB) and ceiling 0.9308 (≈ −1.6 dB) -> limiter
  430. const auto em = lynx::effectFromFl ("Emphasis", blob ({ 8, 0, 0, 2, 1, 0, 0, 625, 10000, 10000, 9308, 0, 2, 7, 0 }));
  431. CHECK (em && em->kind == lynx::EffectKind::limiter && em->enabled);
  432. if (em)
  433. {
  434. CHECK (std::abs (em->params[1] * 24.0f - 1.5f) < 0.05f);
  435. CHECK (std::abs (em->params[0] * 12.0f - 12.0f + 1.6f) < 0.1f);
  436. }
  437. // Pitch Shifter +12 st, mix 100%
  438. 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 }));
  439. CHECK (ps && ps->kind == lynx::EffectKind::pitchShift && std::abs (ps->params[0] - (0.5f + 12.0f / 48.0f)) < 1e-4f);
  440. }
  441. TEST (frequency_shifter_moves_spectrum_by_hz)
  442. {
  443. auto fx = lynx::makeEffect (lynx::EffectKind::freqShift);
  444. fx->prepare (48000.0);
  445. auto slot = lynx::makeEffectSlot (lynx::EffectKind::freqShift);
  446. // +200 Hz: x·|x|·2000 = 200 -> x = sqrt(0.1)
  447. slot.params[0] = (float) (0.5 + std::sqrt (0.1) / 2.0);
  448. std::vector<float> l (48000), r (48000);
  449. for (int i = 0; i < 48000; ++i)
  450. l[(std::size_t) i] = r[(std::size_t) i] = (float) std::sin (2.0 * 3.141592653589793 * 1000.0 * i / 48000.0);
  451. for (int done = 0; done < 48000; done += 480)
  452. fx->process (l.data() + done, r.data() + done, 480, slot.params, 120.0);
  453. auto energy = [&] (double f) {
  454. const auto w = 2.0 * 3.141592653589793 * f / 48000.0, k = 2.0 * std::cos (w);
  455. double s1 = 0.0, s2 = 0.0;
  456. for (int i = 9600; i < 48000; ++i)
  457. {
  458. const auto s0 = l[(std::size_t) i] + k * s1 - s2;
  459. s2 = s1;
  460. s1 = s0;
  461. }
  462. return s1 * s1 + s2 * s2 - k * s1 * s2;
  463. };
  464. // the energy moves to 1200 Hz; little remains at 1000 and almost nothing at the image (800)
  465. CHECK (energy (1200.0) > 50.0 * energy (1000.0));
  466. CHECK (energy (1200.0) > 50.0 * energy (800.0));
  467. }
  468. TEST (pitch_shift_moves_frequency_keeps_length)
  469. {
  470. auto fx = lynx::makeEffect (lynx::EffectKind::pitchShift);
  471. fx->prepare (48000.0);
  472. auto slot = lynx::makeEffectSlot (lynx::EffectKind::pitchShift);
  473. auto crossingsAfter = [&] (float semitoneParam) {
  474. fx->reset();
  475. slot.params[0] = semitoneParam;
  476. std::vector<float> l (48000), r (48000);
  477. for (int i = 0; i < 48000; ++i)
  478. l[(std::size_t) i] = r[(std::size_t) i] = (float) std::sin (2.0 * 3.141592653589793 * 220.0 * i / 48000.0);
  479. for (int done = 0; done < 48000; done += 512)
  480. fx->process (l.data() + done, r.data() + done, std::min (512, 48000 - done), slot.params, 120.0);
  481. int crossings = 0;
  482. for (int i = 9600; i < 48000; ++i)
  483. crossings += (l[(std::size_t) i - 1] < 0.0f) != (l[(std::size_t) i] < 0.0f);
  484. for (auto v : l)
  485. CHECK (std::isfinite (v) && std::abs (v) < 1.6f);
  486. return crossings / 0.8 / 2.0; // cycles per second
  487. };
  488. CHECK (std::abs (crossingsAfter (0.5f) - 220.0) < 8.0); // 0 st
  489. CHECK (std::abs (crossingsAfter (0.5f + 12.0f / 48.0f) - 440.0) < 25.0); // +12 st
  490. CHECK (std::abs (crossingsAfter (0.5f - 12.0f / 48.0f) - 110.0) < 12.0); // −12 st
  491. }
  492. TEST (volume_gate_follows_bar_position)
  493. {
  494. auto fx = lynx::makeEffect (lynx::EffectKind::volumeGate);
  495. fx->prepare (48000.0);
  496. auto slot = lynx::makeEffectSlot (lynx::EffectKind::volumeGate);
  497. for (int i = 0; i < 32; ++i)
  498. slot.params[(std::size_t) i] = i < 16 ? 1.0f : 0.0f; // first two beats open, two closed
  499. slot.params[33] = slot.params[34] = 0.0f; // no smoothing
  500. // 120 BPM: one beat = 0.5 s = 24000 samples; the 4-beat bar starts at tick 0
  501. std::vector<float> l (96000, 1.0f), r (96000, 1.0f);
  502. fx->setSongPosition (0.0);
  503. for (int done = 0; done < 96000; done += 512)
  504. fx->process (l.data() + done, r.data() + done, std::min (512, 96000 - done), slot.params, 120.0);
  505. CHECK (l[10000] > 0.99f && l[40000] > 0.99f); // beats 1 and 2
  506. CHECK (l[60000] < 0.01f && l[90000] < 0.01f); // beats 3 and 4
  507. // starting mid-bar (beat 3): already closed
  508. std::vector<float> l2 (4800, 1.0f), r2 (4800, 1.0f);
  509. fx->reset();
  510. fx->setSongPosition (2.0 * lynx::ppq);
  511. fx->process (l2.data(), r2.data(), 4800, slot.params, 120.0);
  512. CHECK (l2[4000] < 0.01f);
  513. // mix 0: transparent
  514. slot.params[32] = 0.0f;
  515. std::vector<float> l3 (4800, 1.0f), r3 (4800, 1.0f);
  516. fx->setSongPosition (2.0 * lynx::ppq);
  517. fx->process (l3.data(), r3.data(), 4800, slot.params, 120.0);
  518. CHECK (l3[4000] > 0.99f);
  519. }
  520. TEST (patcher_branch_heads_follow_rea)
  521. {
  522. auto words = [] (std::vector<std::int32_t> v) {
  523. std::vector<std::uint8_t> b (v.size() * 4);
  524. std::memcpy (b.data(), v.data(), b.size());
  525. return b;
  526. };
  527. // Frequency Splitter, 2 bands, destinations 1/2/3, slope combo 3 (24 dB/oct), high send −6 dB
  528. std::vector<std::int32_t> fs (18, 0);
  529. fs[0] = 4;
  530. fs[1] = 32768;
  531. fs[3] = 3;
  532. fs[6] = 0;
  533. fs[11] = -600;
  534. fs[15] = 1;
  535. fs[16] = 2;
  536. fs[17] = 3;
  537. const auto split = words (fs);
  538. const auto low = lynx::patcherBranchHead ("Frequency Splitter", split, 1);
  539. CHECK (low.valid && low.slot && low.note.empty());
  540. if (low.slot)
  541. {
  542. // low band = just the Crossover low-pass, combo 3 (24 dB/oct)
  543. CHECK (low.slot->kind == lynx::EffectKind::crossover && low.slot->params[0] == 0.0f && low.slot->params[3] == 1.0f);
  544. CHECK (std::lround (low.slot->params[5] * 7.0f) == 3);
  545. }
  546. const auto mid = lynx::patcherBranchHead ("Frequency Splitter", split, 2);
  547. CHECK (mid.valid && mid.gain == 0.0f); // with 2 bands the mid is silent
  548. const auto high = lynx::patcherBranchHead ("Frequency Splitter", split, 3);
  549. CHECK (high.valid && std::abs (high.gain - std::pow (10.0f, -6.0f / 20.0f)) < 1e-4f);
  550. CHECK (! lynx::patcherBranchHead ("Frequency Splitter", split, 7).valid);
  551. // Stereo Shaper with identity matrix: the difference (destination 4) is zero
  552. const auto shaper = words ({ 3, 0, 12800, 12800, 0, 0, 0, 4, 0 });
  553. const auto diff = lynx::patcherBranchHead ("Fruity Stereo Shaper", shaper, 4);
  554. 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);
  555. CHECK (! lynx::patcherBranchHead ("Fruity Stereo Shaper", shaper, 2).valid);
  556. }
  557. TEST (parallel_container_sums_branches)
  558. {
  559. // two branches: dry with gain 0.5 and a utility that flips phase (matrix −1) with gain 0.5 -> silence
  560. auto slot = lynx::makeEffectSlot (lynx::EffectKind::parallel);
  561. lynx::EffectBranch dry;
  562. dry.gain = 0.5f;
  563. lynx::EffectBranch inverted;
  564. inverted.gain = 0.5f;
  565. auto flip = lynx::makeEffectSlot (lynx::EffectKind::utility);
  566. flip.params[2] = flip.params[5] = 0.25f; // (−1 + 2)/4
  567. inverted.chain.push_back (flip);
  568. slot.branches = { dry, inverted };
  569. auto fx = lynx::makeParallelEffect (slot);
  570. fx->prepare (48000.0);
  571. std::vector<float> l (9000, 0.8f), r (9000, -0.4f);
  572. fx->process (l.data(), r.data(), 9000, slot.params, 120.0);
  573. CHECK (std::abs (l[100]) < 1e-5f && std::abs (r[8999]) < 1e-5f);
  574. // only the dry branch with gain 2: doubles
  575. slot.branches = { lynx::EffectBranch { {}, 2.0f } };
  576. auto doubler = lynx::makeParallelEffect (slot);
  577. doubler->prepare (48000.0);
  578. std::fill (l.begin(), l.end(), 0.25f);
  579. doubler->process (l.data(), r.data(), 9000, slot.params, 120.0);
  580. CHECK (std::abs (l[5000] - 0.5f) < 1e-6f);
  581. }
  582. TEST (fl_controller_constant_outputs)
  583. {
  584. std::vector<std::int32_t> xy { 2, 32768, 0, 65536, 0, 16384, 0, 65536, 0, 1024, 256 };
  585. std::vector<std::uint8_t> blob (xy.size() * 4 + 8, 0);
  586. std::memcpy (blob.data(), xy.data(), xy.size() * 4);
  587. CHECK (std::abs (lynx::controllerConstantOutput ("Fruity X-Y Controller", blob, 0).value_or (-1.0f) - 0.5f) < 1e-4f);
  588. CHECK (std::abs (lynx::controllerConstantOutput ("Fruity X-Y Controller", blob, 1).value_or (-1.0f) - 0.25f) < 1e-4f);
  589. // Control Surface: version + group { 0x836: value 0.75, -, output 2 }
  590. std::vector<std::uint8_t> cs (4, 0);
  591. cs[0] = 1;
  592. auto chunk = [] (std::vector<std::uint8_t>& out, std::uint32_t id, const std::vector<std::uint8_t>& body) {
  593. const auto size = (std::uint64_t) body.size();
  594. out.insert (out.end(), reinterpret_cast<const std::uint8_t*> (&id), reinterpret_cast<const std::uint8_t*> (&id) + 4);
  595. out.insert (out.end(), reinterpret_cast<const std::uint8_t*> (&size), reinterpret_cast<const std::uint8_t*> (&size) + 8);
  596. out.insert (out.end(), body.begin(), body.end());
  597. };
  598. std::vector<std::uint8_t> value (12, 0);
  599. const float v = 0.75f;
  600. const std::int32_t out = 2;
  601. std::memcpy (value.data(), &v, 4);
  602. std::memcpy (value.data() + 8, &out, 4);
  603. std::vector<std::uint8_t> group;
  604. chunk (group, 0x836, value);
  605. chunk (cs, 0, group);
  606. CHECK (std::abs (lynx::controllerConstantOutput ("Control Surface", cs, 2).value_or (-1.0f) - 0.75f) < 1e-6f);
  607. CHECK (! lynx::controllerConstantOutput ("Control Surface", cs, 0).has_value());
  608. }
  609. TEST (flp_midi_out_notes_reach_wrapper_on_same_port)
  610. {
  611. auto record = [] (std::vector<std::uint8_t>& out, std::uint32_t id, std::vector<std::uint8_t> body) {
  612. const auto size = (std::uint64_t) body.size();
  613. out.insert (out.end(), reinterpret_cast<const std::uint8_t*> (&id), reinterpret_cast<const std::uint8_t*> (&id) + 4);
  614. out.insert (out.end(), reinterpret_cast<const std::uint8_t*> (&size), reinterpret_cast<const std::uint8_t*> (&size) + 8);
  615. out.insert (out.end(), body.begin(), body.end());
  616. };
  617. auto i32s = [] (std::vector<std::int32_t> v) {
  618. std::vector<std::uint8_t> b (v.size() * 4);
  619. std::memcpy (b.data(), v.data(), b.size());
  620. return b;
  621. };
  622. flp::Project p;
  623. flp::Channel midiOut;
  624. midiOut.index = 0;
  625. midiOut.type = flp::ChannelType::native;
  626. midiOut.pluginName = "MIDI Out";
  627. midiOut.pluginState = i32s ({ 7, 0, -1, -1, -1, 0, 3, 0 }); // channel 1, port 3 (@24)
  628. flp::Channel wrapper;
  629. wrapper.index = 1;
  630. wrapper.type = flp::ChannelType::native;
  631. wrapper.pluginName = "Fruity Wrapper";
  632. wrapper.pluginState = i32s ({ 9 });
  633. record (wrapper.pluginState, 0x32, i32s ({ 7 })); // VST3
  634. record (wrapper.pluginState, 0x01, i32s ({ 3, -1, 0, 0, 0 })); // input port 3
  635. p.channels = { midiOut, wrapper };
  636. flp::Pattern pattern;
  637. pattern.index = 1;
  638. flp::Note note;
  639. note.channel = 0;
  640. note.key = 64;
  641. note.length = 96;
  642. pattern.notes.push_back (note);
  643. p.patterns.push_back (pattern);
  644. const auto song = lynx::importFlp (p);
  645. CHECK (song.channels.size() == 2 && song.channels[0].muted);
  646. CHECK (song.channels[1].plugin.foreign.midiInPort == 3);
  647. int toWrapper = 0;
  648. for (const auto& pat : song.patterns)
  649. for (const auto& n : pat.notes)
  650. toWrapper += n.channel == 1 && n.key == 64;
  651. CHECK (toWrapper == 1);
  652. }
  653. TEST (flp_effect_automation_follows_slots_and_params)
  654. {
  655. // track 1: slot 0 with an effect that has no equivalent (dropped), slot 2 with Parametric EQ 2
  656. flp::Project p;
  657. flp::MixerInsert insert;
  658. insert.index = 1;
  659. insert.slots.push_back ({ 0, "Some Unknown FX", {} });
  660. insert.slots.push_back ({ 2, "Fruity Parametric EQ 2", {} });
  661. p.mixer.push_back (insert);
  662. auto clip = [&] (int index, std::uint32_t target) {
  663. flp::Channel c;
  664. c.index = index;
  665. c.type = flp::ChannelType::automationClip;
  666. c.automation = { { 0.0, 0.0 }, { 96.0, 1.0 } };
  667. p.channels.push_back (c);
  668. p.automationLinks.push_back ({ index, { target } });
  669. };
  670. 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; };
  671. clip (0, mixer (1, 2, 0x8000 + 7)); // EQ band 1 frequency
  672. clip (1, mixer (1, 2, 0x1F01)); // EQ slot mix
  673. clip (2, mixer (1, 0, 0x8000)); // parameter of the dropped effect
  674. clip (3, mixer (1, 2, 0x8000 + 21)); // band type: no equivalent
  675. const auto song = lynx::importFlp (p);
  676. CHECK (song.automations.size() == 4);
  677. CHECK (song.mixer[1].effects.size() == 1 && song.mixer[1].effects[0].kind == lynx::EffectKind::parametricEq);
  678. const auto& freq = song.automations[0];
  679. CHECK (freq.target.kind == lynx::AutomationTargetKind::effectParam && freq.target.index == 1 && freq.target.slot == 0);
  680. CHECK (freq.target.param == lynx::peq::param (0, 1));
  681. // FL's 0..1 (20 Hz..20 kHz) becomes our frequency scale
  682. CHECK (std::abs (freq.points.front().value - lynx::peq::hzValue (20.0)) < 1e-4f);
  683. CHECK (std::abs (freq.points.back().value - lynx::peq::hzValue (20000.0)) < 1e-4f);
  684. CHECK (song.automations[1].target.kind == lynx::AutomationTargetKind::effectMix && song.automations[1].target.slot == 0);
  685. CHECK (song.automations[2].target.kind == lynx::AutomationTargetKind::none);
  686. CHECK (song.automations[3].target.kind == lynx::AutomationTargetKind::none);
  687. // the automated mix is read/written through the target
  688. auto copy = song;
  689. CHECK (copy.setTargetValue (song.automations[1].target, 0.25f) && std::abs (copy.mixer[1].effects[0].mix - 0.25f) < 1e-6f);
  690. CHECK (std::abs (copy.targetValue (song.automations[1].target) - 0.25f) < 1e-6f);
  691. }
  692. TEST (flp_real_files)
  693. {
  694. if (realFlpDir.empty())
  695. {
  696. std::printf (" (skipped: pass a folder with .flp files as argument)\n");
  697. return;
  698. }
  699. int files = 0, withNotes = 0, withPlaylist = 0, automations = 0, automationsWithTarget = 0, sends = 0;
  700. int threeOsc = 0, threeOscDecoded = 0, wrapped = 0, wrappedParsed = 0, markers = 0, signatures = 0, trackEqs = 0;
  701. int harmless = 0, harmlessDecoded = 0, harmlessParsed = 0, harmlessKind = 0, sytrus = 0, sytrusDecoded = 0, sytrusEngine = 0, sytrusRendered = 0,
  702. sytrusSounding = 0;
  703. int harmor = 0, harmorUsable = 0, harmorKind = 0, harmorSounding = 0;
  704. int gms = 0, gmsUsable = 0, gmsKind = 0, gmsSounding = 0, morphine = 0, morphineUsable = 0, morphineKind = 0, morphineSounding = 0, demoGoldens = 0;
  705. int ogun = 0, ogunUsable = 0, ogunKind = 0, ogunSounding = 0;
  706. int poizone = 0, poizoneUsable = 0, poizoneKind = 0, poizoneSounding = 0, poizoneGoldens = 0;
  707. int miniSynth = 0, miniSynthUsable = 0, miniSynthKind = 0, miniSynthSounding = 0, miniSynthGoldens = 0;
  708. int dx10 = 0, dx10Usable = 0, dx10Kind = 0, dx10Sounding = 0;
  709. int kepler = 0, keplerUsable = 0, keplerKind = 0, keplerSounding = 0;
  710. std::map<std::string, std::pair<int, int>> generators; // GMS/Ogun/Autogun/Sakura/DrumSynth: channels, decoded
  711. int ogunTrumpet = 0; // Ogun channels whose spectrum matches the REA "Trumpet" reference
  712. int peqSlots = 0, peqShaped = 0, reverbs = 0, reverbsDryless = 0, reverbsLowCut = 0;
  713. int dwChannels = 0, dwZones = 0, fpcKits = 0, padChannels = 0, padNotes = 0;
  714. int harmlessCompWanted = 0, harmlessCompLoaded = 0; // Harmless rack compressors / presets read from the installation
  715. int maximusSlots = 0, maximusExact = 0, sgzSlots = 0, sgzExact = 0, vocodexSlots = 0, vocodexWithData = 0; // REA_rodada40
  716. // import with the installation's samples (realFlpDir is ...\Data): for DirectWave/FPC
  717. lynx::FlpImportOptions withFiles;
  718. const auto flRoot = std::filesystem::path (realFlpDir).parent_path().string();
  719. withFiles.roots = { flRoot, realFlpDir, "" };
  720. withFiles.fileExists = [] (const std::string& path) {
  721. auto local = path;
  722. std::replace (local.begin(), local.end(), '\\', '/');
  723. return std::filesystem::exists (local);
  724. };
  725. withFiles.readFile = [] (const std::string& path) {
  726. auto local = path;
  727. std::replace (local.begin(), local.end(), '\\', '/');
  728. std::ifstream in (local, std::ios::binary);
  729. return std::vector<std::uint8_t> ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  730. };
  731. int embeddedSaved = 0;
  732. withFiles.saveEmbedded = [&embeddedSaved] (const std::vector<std::uint8_t>& wav, const std::string&) {
  733. ++embeddedSaved;
  734. return wav.size() > 44 ? std::string ("embutido.wav") : std::string();
  735. };
  736. int slicedChannels = 0, flKeysChannels = 0;
  737. for (auto& entry : std::filesystem::recursive_directory_iterator (realFlpDir))
  738. {
  739. if (entry.path().extension() != ".flp")
  740. continue;
  741. std::ifstream in (entry.path(), std::ios::binary);
  742. std::vector<std::uint8_t> bytes ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  743. ++files;
  744. try
  745. {
  746. const auto p = flp::parseProject (bytes);
  747. CHECK (! p.version.empty());
  748. CHECK (p.tempo > 10.0 && p.tempo < 1000.0);
  749. const auto song = lynx::importFlp (p);
  750. CHECK (! song.patterns.empty());
  751. {
  752. const auto full = lynx::importFlp (p, withFiles);
  753. bool hasFpc = false;
  754. for (const auto& c : p.channels)
  755. hasFpc = hasFpc || c.pluginName == "FPC";
  756. // GMS and Morphine (REA_rodada39): every state plays on the exact engine (GMS with its waves from the
  757. // installation) and sounds; two demo channels match golden samples of our round-39 models
  758. for (const auto& c : p.channels)
  759. {
  760. if (c.pluginName == "GMS")
  761. ++gms, gmsUsable += lynx::gmsStateUsable (c.pluginState) ? 1 : 0;
  762. if (c.pluginName == "Morphine")
  763. ++morphine, morphineUsable += lynx::morphineStateUsable (c.pluginState) ? 1 : 0;
  764. }
  765. // Kepler: every state in the demos plays on the exact engine (REA_rodada46) when the engine DLL is installed
  766. for (const auto& c : p.channels)
  767. if (c.pluginName == "Kepler")
  768. {
  769. ++kepler;
  770. keplerUsable += lynx::keplerStateUsable (c.pluginState) ? 1 : 0;
  771. }
  772. for (const auto& c : full.channels)
  773. if (c.instrument == lynx::InstrumentKind::kepler)
  774. {
  775. ++keplerKind;
  776. const auto y = lynx::kepler::renderReference (c.pluginState, c.samplePath, { { 0, 60, 1.0, 0.0, 0.0, 6000 }, { 2000, 67, 0.6, 0.0, 0.0, 8000 } },
  777. 44100.0, 11025);
  778. double e = 0.0;
  779. bool finite = ! y.empty();
  780. for (auto v : y)
  781. finite = finite && std::isfinite (v), e += (double) v * v;
  782. CHECK (finite);
  783. keplerSounding += e > 1e-6 ? 1 : 0;
  784. }
  785. const auto file = entry.path().filename().string();
  786. for (const auto& c : full.channels)
  787. {
  788. const auto isGms = c.instrument == lynx::InstrumentKind::gms, isMorphine = c.instrument == lynx::InstrumentKind::morphine;
  789. if (! isGms && ! isMorphine)
  790. continue;
  791. (isGms ? gmsKind : morphineKind)++;
  792. auto iv = [] (double vel) { return (std::pow (11.0, vel / 100.0) - 1.0) / 10.0; };
  793. const auto golden = (isGms && c.name == "GMS" && file.find ("Song For You") != std::string::npos)
  794. || (isMorphine && c.name == "Morphine" && file.find ("SHINE") != std::string::npos);
  795. std::vector<float> y;
  796. if (isGms)
  797. y = lynx::gms::renderReference (c.pluginState,
  798. { { 0, 60, (float) iv (100), 1.0, 0.0, 0.0, 30000 }, { 11025, 64, (float) iv (80), 1.0, 0.0, 0.0, 40000 },
  799. { 22050, 67, (float) iv (110), 1.0, 0.0, 0.0, 52000 }, { 60000, 48, (float) iv (127), 1.0, 0.0, 0.0, 70000 } },
  800. 44100.0, golden ? 88200 : 22050, c.samplePath);
  801. else
  802. 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 } },
  803. 44100.0, golden ? 100000 : 22050, c.samplePath);
  804. double e = 0.0;
  805. bool finite = ! y.empty();
  806. for (auto v : y)
  807. finite = finite && std::isfinite (v), e += (double) v * v;
  808. CHECK (finite);
  809. (isGms ? gmsSounding : morphineSounding) += e > 1e-6 ? 1 : 0;
  810. if (golden && ! y.empty())
  811. {
  812. // our model, same events (GMS: tempo 140; Morphine: tempo 120), state as saved, 44.1 kHz
  813. const auto rms = std::sqrt (e / (double) y.size());
  814. CHECK (std::abs (rms - (isGms ? 0.213602668574 : 0.0673606448152)) < 1e-5);
  815. 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 } },
  816. 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 } };
  817. for (const auto& g : isGms ? std::vector (std::begin (gmsAt), std::end (gmsAt)) : std::vector (std::begin (morAt), std::end (morAt)))
  818. 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);
  819. ++demoGoldens;
  820. }
  821. }
  822. // MiniSynth (REA_rodada41): every state plays on the exact engine (tables from the installation's
  823. // oscdata.dat) and sounds; two demo channels match golden samples of our round-41 model (bit-identical to
  824. // renders of the installation's DLL for these states)
  825. for (const auto& c : p.channels)
  826. if (c.pluginName == "MiniSynth")
  827. ++miniSynth, miniSynthUsable += lynx::miniSynthStateUsable (c.pluginState) ? 1 : 0;
  828. for (const auto& c : full.channels)
  829. {
  830. if (c.instrument != lynx::InstrumentKind::minisynth)
  831. continue;
  832. ++miniSynthKind;
  833. auto iv = [] (double vel) { return (std::pow (11.0, vel / 100.0) - 1.0) / 10.0; };
  834. const auto exo = file.find ("Exoplanet") != std::string::npos;
  835. const auto golden = exo && (c.name == "Main Lead 1" || c.name == "Riser");
  836. const auto y = lynx::minisynth::renderReference (c.pluginState,
  837. { { 0, 60, iv (100), 1.0, 0.0, 0.0, 30000 }, { 11025, 64, iv (80), 1.0, 0.0, 0.0, 40000 },
  838. { 22050, 67, iv (110), 1.0, 0.0, 0.0, 52000 }, { 60000, 48, iv (127), 1.0, 0.0, 0.0, 70000 } },
  839. 44100.0, golden ? 88200 : 22050, c.samplePath);
  840. double e = 0.0;
  841. bool finite = ! y.empty();
  842. for (auto v : y)
  843. finite = finite && std::isfinite (v), e += (double) v * v;
  844. CHECK (finite);
  845. miniSynthSounding += e > 1e-6 ? 1 : 0;
  846. if (golden && ! y.empty())
  847. {
  848. // our model, same events, tempo 120, state as saved, 44.1 kHz, host blocks of 512, L = R = Final.Vol
  849. const auto lead = c.name == "Main Lead 1";
  850. CHECK (std::abs (std::sqrt (e / (double) y.size()) - (lead ? 0.177495801753 : 0.19006567413)) < 1e-9);
  851. static const struct { int i; float v; } leadAt[] = { { 2000, -0.113459975f }, { 15000, -0.00234968495f }, { 30000, 0.13985157f }, { 50000, -0.267063439f }, { 65000, -0.244418889f }, { 80000, -0.0162940286f } },
  852. riserAt[] = { { 2000, -0.0603227727f }, { 15000, 0.112200871f }, { 30000, 0.0453962795f }, { 50000, 0.234380022f }, { 65000, -0.164545432f }, { 80000, -0.000485120923f } };
  853. for (const auto& g : lead ? std::vector (std::begin (leadAt), std::end (leadAt)) : std::vector (std::begin (riserAt), std::end (riserAt)))
  854. CHECK (y[2 * (std::size_t) g.i] == g.v && y[2 * (std::size_t) g.i + 1] == g.v);
  855. ++miniSynthGoldens;
  856. }
  857. }
  858. // PoiZone (REA_rodada44): every state plays on the exact engine and sounds; the demo channel matches golden
  859. // samples of our round-44 model
  860. for (const auto& c : p.channels)
  861. if (c.pluginName == "PoiZone")
  862. ++poizone, poizoneUsable += lynx::poizoneStateUsable (c.pluginState) ? 1 : 0;
  863. for (const auto& c : full.channels)
  864. {
  865. if (c.instrument != lynx::InstrumentKind::poizone)
  866. continue;
  867. ++poizoneKind;
  868. auto iv = [] (double vel) { return (std::pow (11.0, vel / 100.0) - 1.0) / 10.0; };
  869. const auto golden = c.name == "PoiZone" && file.find ("NIGHT TERROR") != std::string::npos;
  870. const auto y = lynx::poizone::renderReference (c.pluginState,
  871. { { 0, 60, iv (100), 1.0, 0.0, 0.0, 30000 }, { 11025, 64, iv (80), 1.0, 0.0, 0.0, 40000 },
  872. { 22050, 67, iv (110), 1.0, 0.0, 0.0, 52000 }, { 60000, 48, iv (127), 1.0, 0.0, 0.0, 70000 } },
  873. 44100.0, golden ? 88200 : 22050);
  874. double e = 0.0;
  875. bool finite = ! y.empty();
  876. for (auto v : y)
  877. finite = finite && std::isfinite (v), e += (double) v * v;
  878. CHECK (finite);
  879. poizoneSounding += e > 1e-6 ? 1 : 0;
  880. if (golden && ! y.empty())
  881. {
  882. // our model, same events, tempo 120, state as saved, 44.1 kHz, L = R = Final.Vol
  883. CHECK (std::abs (std::sqrt (e / (double) y.size()) - 0.018975758213507415) < 1e-7);
  884. static const struct { int i; float l, r; } at[] = { { 2000, -0.0030244605f, -0.0031888473f }, { 15000, 0.002743553f, -0.013375883f }, { 30000, 0.031268276f, 0.04751329f }, { 50000, 0.049796376f, 0.035944063f }, { 65000, -0.0014251951f, -0.01722545f }, { 80000, 0.01474628f, 0.000680499f } };
  885. for (const auto& g : at)
  886. CHECK (std::abs (y[2 * (std::size_t) g.i] - g.l) < 1e-7f && std::abs (y[2 * (std::size_t) g.i + 1] - g.r) < 1e-7f);
  887. ++poizoneGoldens;
  888. }
  889. }
  890. for (const auto& c : full.channels)
  891. {
  892. if (c.instrument == lynx::InstrumentKind::harmless && c.modelParams.size() >= (std::size_t) lynx::harmlessParamCount
  893. && c.modelParams[(std::size_t) lynx::harmlessComboIndex + 3] > 0.5f)
  894. {
  895. ++harmlessCompWanted;
  896. harmlessCompLoaded += c.modelParams.size() > (std::size_t) lynx::harmlessCompIndex + 1000 ? 1 : 0;
  897. }
  898. flKeysChannels += c.zones.size() == 30 && c.zones.front().path.find ("CHANGPIANO") != std::string::npos ? 1 : 0;
  899. if (c.sampler.slices.size() >= 4)
  900. {
  901. ++slicedChannels;
  902. CHECK (std::is_sorted (c.sampler.slices.begin(), c.sampler.slices.end()));
  903. CHECK (c.sampler.slices.back() < 1.0f);
  904. }
  905. if (! c.zones.empty() && c.name.find (" - ") == std::string::npos)
  906. {
  907. ++dwChannels;
  908. dwZones += (int) c.zones.size();
  909. }
  910. padChannels += c.name.find (" - ") != std::string::npos && c.instrument == lynx::InstrumentKind::sampler ? 1 : 0;
  911. }
  912. fpcKits += hasFpc;
  913. // Maximus / Soundgoodizer become the exact engine (REA_rodada40); Vocodex carries SG.dat (and its
  914. // carrier's Sytrus preset) read from the installation
  915. for (const auto& insert : p.mixer)
  916. for (const auto& slot : insert.slots)
  917. {
  918. maximusSlots += slot.plugin == "Maximus";
  919. sgzSlots += slot.plugin == "Soundgoodizer";
  920. vocodexSlots += slot.plugin == "Vocodex";
  921. }
  922. for (const auto& t : full.mixer)
  923. for (const auto& fx : t.effects)
  924. {
  925. if (fx.kind == lynx::EffectKind::maximus)
  926. {
  927. const auto blob = lynx::maximusfx::unpack (fx.state);
  928. CHECK (blob && lynx::maximusfx::presetOf (*blob) != nullptr);
  929. if (blob)
  930. (blob->build == lynx::hlfx::MaximusBuild::soundgoodizer ? sgzExact : maximusExact) += 1;
  931. }
  932. if (fx.kind == lynx::EffectKind::vocodex)
  933. vocodexWithData += ! lynx::vocodex::splitInstallData (fx.state).second.sgDat.empty();
  934. }
  935. for (const auto& pat : full.patterns)
  936. for (const auto& n : pat.notes)
  937. {
  938. CHECK (n.channel >= 0 && n.channel < (int) full.channels.size());
  939. padNotes += full.channels[(std::size_t) n.channel].name.find (" - ") != std::string::npos ? 1 : 0;
  940. }
  941. }
  942. const auto peqDefaults = lynx::makeEffectSlot (lynx::EffectKind::parametricEq).params;
  943. for (const auto& t : song.mixer)
  944. for (const auto& fx : t.effects)
  945. {
  946. if (fx.kind == lynx::EffectKind::parametricEq)
  947. {
  948. ++peqSlots;
  949. peqShaped += fx.params != peqDefaults;
  950. for (double hz : { 50.0, 1000.0, 10000.0 })
  951. CHECK (std::isfinite (lynx::peq::responseDb (fx.params, 48000.0, hz)));
  952. }
  953. if (fx.kind == lynx::EffectKind::reverb)
  954. {
  955. ++reverbs;
  956. reverbsDryless += fx.params[4] < 0.01f;
  957. reverbsLowCut += fx.params[5] > 0.0f;
  958. }
  959. }
  960. for (const auto& t : song.mixer)
  961. if (t.eq.active())
  962. {
  963. ++trackEqs;
  964. for (std::size_t b = 0; b < 3; ++b)
  965. CHECK (t.eq.hz[b] >= 10.0f && t.eq.hz[b] <= 16000.0f && std::abs (t.eq.gainDb[b]) <= 18.0f);
  966. }
  967. for (const auto& a : song.arrangements)
  968. for (const auto& m : a.markers)
  969. {
  970. ++markers;
  971. signatures += m.isSignature();
  972. CHECK (m.tick >= 0);
  973. }
  974. // Fruity Wrapper (channels and mixer slots): every blob in the demos is read
  975. auto countWrapper = [&] (const std::string& plugin, const std::vector<std::uint8_t>& state) {
  976. if (plugin != "Fruity Wrapper")
  977. return;
  978. ++wrapped;
  979. lynx::ForeignPlugin f;
  980. wrappedParsed += lynx::parseFlWrapper (state, f) && f.format != lynx::ForeignPlugin::Format::none && ! f.name.empty();
  981. };
  982. for (const auto& c : p.channels)
  983. countWrapper (c.pluginName, c.pluginState);
  984. for (const auto& insert : p.mixer)
  985. for (const auto& slot : insert.slots)
  986. countWrapper (slot.plugin, slot.state);
  987. // Harmless: every state in the demos becomes a synth, with finite values
  988. for (const auto& c : p.channels)
  989. if (c.pluginName == "Harmless")
  990. {
  991. ++harmless;
  992. lynx::SynthSettings hs;
  993. float g = 1.0f;
  994. if (lynx::synthFromHarmless (c.pluginState, 128.0, hs, g))
  995. {
  996. ++harmlessDecoded;
  997. CHECK (std::isfinite (g) && hs.cutoff >= 20.0f && hs.cutoff <= 20000.0f && std::isfinite (hs.decay) && std::isfinite (hs.release));
  998. }
  999. if (const auto hp = lynx::harmlessParams (c.pluginState))
  1000. harmlessParsed += (int) hp->size() == lynx::harmlessParamCount ? 1 : 0;
  1001. }
  1002. for (const auto& c : song.channels)
  1003. harmlessKind += c.instrument == lynx::InstrumentKind::harmless ? 1 : 0;
  1004. // Harmor: every state in the demos plays on the exact engine (REA_rodada34) and sounds, with finite samples
  1005. for (const auto& c : p.channels)
  1006. if (c.pluginName == "Harmor")
  1007. {
  1008. ++harmor;
  1009. harmorUsable += lynx::harmorStateUsable (c.pluginState) ? 1 : 0;
  1010. }
  1011. for (const auto& c : song.channels)
  1012. if (c.instrument == lynx::InstrumentKind::harmor)
  1013. {
  1014. ++harmorKind;
  1015. 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);
  1016. double e = 0.0;
  1017. bool finite = ! y.empty();
  1018. for (auto v : y)
  1019. finite = finite && std::isfinite (v), e += (double) v * v;
  1020. CHECK (finite);
  1021. harmorSounding += e > 1e-6 ? 1 : 0;
  1022. }
  1023. // Ogun: every state in the demos plays on the exact engine (REA_rodada37) and sounds, with finite samples
  1024. for (const auto& c : p.channels)
  1025. if (c.pluginName == "Ogun")
  1026. {
  1027. ++ogun;
  1028. ogunUsable += lynx::ogunStateUsable (c.pluginState) ? 1 : 0;
  1029. }
  1030. for (const auto& c : song.channels)
  1031. if (c.instrument == lynx::InstrumentKind::ogun)
  1032. {
  1033. ++ogunKind;
  1034. const auto y = lynx::ogun::renderReference (c.pluginState, { { 0, 60, 0.8, 1.0, 0.0, 0.0, 0.0, 0.0, 0.5, 6000 },
  1035. { 2000, 67, 0.6, 1.0, 0.0, 0.0, 0.0, 0.0, 0.5, 8000 } }, 44100.0, 11025);
  1036. double e = 0.0;
  1037. bool finite = ! y.empty();
  1038. for (auto v : y)
  1039. finite = finite && std::isfinite (v), e += (double) v * v;
  1040. CHECK (finite);
  1041. ogunSounding += e > 1e-6 ? 1 : 0;
  1042. }
  1043. // Fruity DX10: every state plays on the exact engine when its channel processor is neutral (REA_rodada42)
  1044. for (const auto& c : p.channels)
  1045. if (c.pluginName == "Fruity DX10" || c.pluginName == "DX10")
  1046. ++dx10, dx10Usable += lynx::dx10StateUsable (c.pluginState) ? 1 : 0;
  1047. for (const auto& c : song.channels)
  1048. if (c.instrument == lynx::InstrumentKind::dx10)
  1049. {
  1050. ++dx10Kind;
  1051. const auto y = lynx::dx10::renderReference (c.pluginState, { { 0, 60, 1.0, 1.0, 0.0, 0.0, 6000 }, { 2000, 67, 0.6, 1.0, 0.0, 0.0, 8000 } },
  1052. 44100.0, 11025);
  1053. double e = 0.0;
  1054. bool finite = ! y.empty();
  1055. for (auto v : y)
  1056. finite = finite && std::isfinite (v), e += (double) v * v;
  1057. CHECK (finite);
  1058. dx10Sounding += e > 1e-6 ? 1 : 0;
  1059. }
  1060. // Sytrus: every state in the demos (zlib + 10 units) decodes, with finite values
  1061. for (const auto& c : p.channels)
  1062. if (c.pluginName == "Sytrus")
  1063. {
  1064. ++sytrus;
  1065. lynx::SynthSettings ss;
  1066. float g = 1.0f;
  1067. // the Sytrus engine (REA_rodada31) reads every demo state; the first 24 play a short note (render settings)
  1068. if (lynx::sytrus::stateUsable (c.pluginState))
  1069. {
  1070. ++sytrusEngine;
  1071. if (sytrusRendered < 24)
  1072. {
  1073. ++sytrusRendered;
  1074. lynx::sytrus::Engine e;
  1075. e.prepare (44100.0, true, 512);
  1076. e.setPatch (lynx::sytrus::parsePatch (c.pluginState));
  1077. lynx::sytrus::NoteParams note;
  1078. e.noteOn (note);
  1079. std::vector<float> l (8192), r (8192);
  1080. e.render (l.data(), r.data(), 8192, 0.551f, 0.0f);
  1081. bool finite = true;
  1082. double energy = 0.0;
  1083. for (std::size_t k = 0; k < l.size(); ++k)
  1084. finite = finite && std::isfinite (l[k]) && std::isfinite (r[k]), energy += (double) l[k] * l[k];
  1085. CHECK (finite);
  1086. sytrusSounding += energy > 1e-6;
  1087. }
  1088. }
  1089. if (lynx::synthFromSytrus (c.pluginState, 128.0, ss, g))
  1090. {
  1091. ++sytrusDecoded;
  1092. CHECK (std::isfinite (g) && ss.cutoff >= 20.0f && ss.cutoff <= 20000.0f && std::isfinite (ss.attack) && std::isfinite (ss.decay)
  1093. && std::isfinite (ss.release) && ss.sustain >= 0.0f && ss.sustain <= 1.0f && std::isfinite (ss.filterEnv.amount));
  1094. for (const auto& o : ss.osc)
  1095. CHECK (o.level >= 0.0f && o.level <= 1.0f && o.octave >= -3 && o.octave <= 3);
  1096. }
  1097. }
  1098. // round 12 generators
  1099. for (const auto& c : p.channels)
  1100. {
  1101. lynx::SynthSettings gs;
  1102. float g = 1.0f;
  1103. int decoded = -1;
  1104. if (c.pluginName == "Harmor")
  1105. {
  1106. decoded = lynx::synthFromHarmor (c.pluginState, gs, g);
  1107. if (decoded)
  1108. {
  1109. // REA_rodada25 §4: most resonant settings stay below Q ≈ 3, a few saturate
  1110. CHECK (gs.resonance >= 0.0f && gs.resonance <= 1.0f);
  1111. static int resonant = 0, strong = 0, total = 0;
  1112. resonant += gs.resonance > 0.0f;
  1113. strong += gs.resonance > 0.9f;
  1114. if (++total % 50 == 0)
  1115. std::printf (" Harmor resonance: %d with a peak, %d with Q > ~5 (of %d)\n", resonant, strong, total);
  1116. }
  1117. static int saw = 0, square = 0, other = 0, total = 0;
  1118. if (decoded && std::any_of (gs.osc.begin(), gs.osc.end(), [] (const lynx::SynthOscillator& o) { return o.wave == lynx::Waveform::spectral; }))
  1119. {
  1120. auto isSaw = true, isSquare = true;
  1121. for (int n = 1; n <= 16; ++n)
  1122. {
  1123. isSaw = isSaw && std::abs (gs.spectrum[(std::size_t) n - 1] - 1.0f / n) < 1e-3f;
  1124. isSquare = isSquare && std::abs (gs.spectrum[(std::size_t) n - 1] - (n % 2 == 1 ? 1.1535f / n : 0.0f)) < 2e-3f;
  1125. }
  1126. ++(isSaw ? saw : isSquare ? square : other);
  1127. if (++total % 20 == 0 || total == 100)
  1128. std::printf (" Harmor spectrum: %d saw, %d square, %d other (of %d)\n", saw, square, other, total);
  1129. }
  1130. }
  1131. else if (c.pluginName == "GMS")
  1132. decoded = lynx::synthFromGms (c.pluginState, 128.0, gs, g);
  1133. else if (c.pluginName == "Ogun" || c.pluginName == "Autogun")
  1134. {
  1135. decoded = lynx::synthFromOgun (c.pluginState, gs, g);
  1136. // REA_rodada24 §1.9: the "Trumpet" preset (richness 7, no seeds) has partials 0.9087, 0.8610,
  1137. // 0.8151… at the fixed seed-3 phases 0.919, 0.380, 0.130
  1138. if (decoded && gs.osc[0].wave == lynx::Waveform::spectral)
  1139. {
  1140. CHECK (std::all_of (gs.spectrum.begin(), gs.spectrum.end(), [] (float a) { return std::isfinite (a) && a >= 0.0f; }));
  1141. static constexpr float trumpet[3] { 0.9087f, 0.8610f, 0.8151f }, phases[3] { 0.919f, 0.380f, 0.130f };
  1142. auto match = true;
  1143. for (std::size_t k = 0; k < 3; ++k)
  1144. match = match && std::abs (gs.spectrum[k] * 2.0f / 3.14159265f - trumpet[k]) < 1e-3f && std::abs (gs.spectrumPhase[k] - phases[k]) < 1e-3f;
  1145. ogunTrumpet += match ? 1 : 0;
  1146. }
  1147. }
  1148. else if (c.pluginName == "Sakura")
  1149. decoded = lynx::synthFromSakura (c.pluginState, gs);
  1150. else if (c.pluginName == "Kepler")
  1151. decoded = lynx::synthFromKepler (c.pluginState, gs, g);
  1152. else if (c.pluginName == "Wave Traveller")
  1153. decoded = lynx::waveTravellerSample (c.pluginState).has_value() ? 2 : 0;
  1154. else if (c.pluginName == "PoiZone")
  1155. decoded = lynx::synthFromPoiZone (c.pluginState, gs, g);
  1156. else if (c.pluginName == "BassDrum")
  1157. decoded = lynx::synthFromBassDrum (c.pluginState, gs, g);
  1158. else if (c.pluginName == "Toxic Biohazard")
  1159. decoded = lynx::synthFromToxic (c.pluginState, gs, g);
  1160. else if (c.pluginName == "Morphine")
  1161. decoded = lynx::synthFromMorphine (c.pluginState, gs, g);
  1162. else if (c.pluginName == "BooBass")
  1163. decoded = lynx::synthFromBooBass (c.pluginState, gs);
  1164. else if (c.pluginName == "Drumpad" || c.pluginName == "DrumPad")
  1165. decoded = lynx::drumpadPatchName (c.pluginState).has_value() ? 2 : 0;
  1166. else if (c.pluginName == "Fruity Envelope Controller" && c.pluginState.size() >= 4 && c.pluginState[2] >= 6) // v >= 6
  1167. decoded = lynx::parseEnvelopeController (c.pluginState).has_value() ? 2 : 0;
  1168. else if (c.pluginName == "FLEX")
  1169. decoded = lynx::flexPresetName (c.pluginState).has_value() ? 2 : 0;
  1170. else if (c.pluginName == "Fruity DrumSynth Live")
  1171. decoded = lynx::drumSynthLiveParams (c.pluginState).has_value() ? 2 : 0;
  1172. if (decoded < 0)
  1173. continue;
  1174. auto& counter = generators[c.pluginName];
  1175. ++counter.first;
  1176. counter.second += decoded != 0;
  1177. if (decoded == 1 && c.pluginName != "Fruity DrumSynth Live")
  1178. {
  1179. CHECK (std::isfinite (g) && g >= 0.0f && gs.cutoff >= 20.0f && gs.cutoff <= 20000.0f && gs.sustain >= 0.0f && gs.sustain <= 1.0f);
  1180. 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));
  1181. for (const auto& o : gs.osc)
  1182. CHECK (o.level >= 0.0f && o.level <= 4.0f && std::isfinite (o.detune) && std::isfinite (o.pan));
  1183. }
  1184. }
  1185. // 3x Osc: every state in the demos decodes, with levels summing to at most 1
  1186. for (const auto& c : p.channels)
  1187. if (c.pluginName == "3x Osc")
  1188. {
  1189. ++threeOsc;
  1190. lynx::SynthSettings s;
  1191. if (lynx::synthFrom3xOsc (c.pluginState, s))
  1192. {
  1193. ++threeOscDecoded;
  1194. // with AM, osc 3 is the modulation depth and is left out of the sum
  1195. const auto sum = s.osc[0].level + s.osc[1].level + (s.am ? 0.0f : s.osc[2].level);
  1196. CHECK (sum <= 1.001f && s.osc[2].level <= 1.0f);
  1197. for (const auto& o : s.osc)
  1198. CHECK (o.octave >= -2 && o.octave <= 2 && std::abs (o.semitones) <= 11 && std::abs (o.pan) <= 1.0f);
  1199. }
  1200. }
  1201. for (auto& pat : p.patterns)
  1202. if (! pat.notes.empty())
  1203. {
  1204. ++withNotes;
  1205. break;
  1206. }
  1207. for (auto& a : p.arrangements)
  1208. for (auto& item : a.items)
  1209. CHECK (item.track >= 0 && item.track < 500);
  1210. for (auto& clip : song.playlist)
  1211. {
  1212. CHECK (clip.pattern >= 0 && clip.pattern < (int) song.patterns.size());
  1213. CHECK (clip.length > 0 && clip.offset >= 0);
  1214. if (clip.kind == lynx::ClipKind::automation)
  1215. CHECK (clip.automation >= 0 && clip.automation < (int) song.automations.size());
  1216. }
  1217. for (auto& a : song.automations)
  1218. {
  1219. ++automations;
  1220. automationsWithTarget += a.target.kind != lynx::AutomationTargetKind::none;
  1221. CHECK (a.isLive() || ! a.points.empty());
  1222. for (std::size_t i = 1; i < a.points.size(); ++i)
  1223. CHECK (a.points[i].tick >= a.points[i - 1].tick);
  1224. }
  1225. // imported routing has no cycles and valid destinations
  1226. CHECK (song.mixerOrder().size() + 1 == song.mixer.size());
  1227. for (auto& t : song.mixer)
  1228. for (auto& s : t.sends)
  1229. {
  1230. ++sends;
  1231. CHECK (s.target > 0 && s.target < (int) song.mixer.size());
  1232. }
  1233. if (! song.playlist.empty())
  1234. ++withPlaylist;
  1235. }
  1236. catch (const flp::Error& e)
  1237. {
  1238. ++failures;
  1239. std::printf (" FAILED %s: %s\n", entry.path().string().c_str(), e.what());
  1240. }
  1241. }
  1242. CHECK (threeOscDecoded == threeOsc);
  1243. std::printf (" Harmless: %d channels, %d decoded\n", harmless, harmlessDecoded);
  1244. std::printf (" Sytrus: %d channels, %d decoded, %d by the engine (%d of %d rendered sound)\n", sytrus, sytrusDecoded, sytrusEngine,
  1245. sytrusSounding, sytrusRendered);
  1246. CHECK (sytrusEngine == sytrus);
  1247. CHECK (sytrusSounding >= sytrusRendered * 3 / 4);
  1248. for (const auto& [name, counter] : generators)
  1249. {
  1250. std::printf (" %s: %d channels, %d decoded\n", name.c_str(), counter.first, counter.second);
  1251. CHECK (counter.second == counter.first);
  1252. }
  1253. std::printf (" Ogun spectra matching the Trumpet reference: %d\n", ogunTrumpet);
  1254. CHECK (ogunTrumpet >= 1);
  1255. // demo Gross Beat: the volume slot becomes the gate (those using an envelope slot get steps < 1)
  1256. {
  1257. int vocodexes = 0, vocodexSides = 0;
  1258. int lovePhilterLinks[4] {}; // live links: cutoff, resonance; inside containers: cutoff, resonance
  1259. int embeddedZones = 0, lovePhilters = 0, lovePhiltersRead = 0, lovePhiltersConverted = 0, gates = 0, shaped = 0, effectors = 0, patchers = 0, serial = 0, parallel = 0, generatorPatchers = 0;
  1260. for (const auto& entry : std::filesystem::recursive_directory_iterator (std::filesystem::path (realFlpDir) / "Demo projects"))
  1261. if (entry.path().extension() == ".flp")
  1262. {
  1263. std::ifstream in (entry.path(), std::ios::binary);
  1264. const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1265. try
  1266. {
  1267. const auto project = flp::parseProject (file);
  1268. for (const auto& insert : project.mixer)
  1269. for (const auto& slot : insert.slots)
  1270. if (slot.plugin == "Gross Beat")
  1271. {
  1272. const auto fx = lynx::effectFromFl (slot.plugin, slot.state);
  1273. CHECK (fx && fx->kind == lynx::EffectKind::volumeGate);
  1274. ++gates;
  1275. if (fx && std::any_of (fx->params.begin(), fx->params.begin() + 32, [] (float v) { return v < 0.99f; }))
  1276. ++shaped;
  1277. }
  1278. else if (slot.plugin == "Fruity Love Philter")
  1279. {
  1280. ++lovePhilters;
  1281. lovePhiltersRead += lynx::parseLovePhilter (slot.state).has_value();
  1282. if (const auto conv = lynx::lovePhilterEffects (slot.state))
  1283. {
  1284. ++lovePhiltersConverted;
  1285. CHECK (! conv->slots.empty());
  1286. for (const auto& fx : conv->slots)
  1287. for (auto v : fx.params)
  1288. CHECK (std::isfinite (v) && v >= 0.0f && v <= 1.0f);
  1289. for (const auto& fx : conv->slots)
  1290. for (const auto& link : fx.links)
  1291. {
  1292. const auto& chain = fx.branches[(std::size_t) link.branch].chain;
  1293. CHECK (link.source < (int) chain.size() && chain[(std::size_t) link.target].kind == lynx::EffectKind::parametricEq);
  1294. lovePhilterLinks[2 + (link.param == lynx::peq::param (0, 3) ? 1 : 0)]++;
  1295. }
  1296. for (const auto& link : conv->links)
  1297. {
  1298. lovePhilterLinks[link.param == lynx::peq::param (0, 3) ? 1 : 0]++;
  1299. CHECK (link.curve.size() == 33);
  1300. for (auto v : link.curve)
  1301. CHECK (std::isfinite (v) && v >= 0.0f && v <= 1.0f);
  1302. }
  1303. }
  1304. }
  1305. else if (slot.plugin == "Vocodex")
  1306. {
  1307. const auto v = lynx::vocodexEffect (slot.state);
  1308. CHECK (v.has_value());
  1309. vocodexes += v.has_value();
  1310. vocodexSides += v && (v->modIn > 0 || v->carIn > 0);
  1311. }
  1312. else if (slot.plugin == "Effector")
  1313. effectors += lynx::effectFromFl (slot.plugin, slot.state).has_value();
  1314. else if (slot.plugin == "Patcher")
  1315. {
  1316. const auto graph = lynx::parsePatcher (slot.state);
  1317. CHECK (graph.has_value());
  1318. ++patchers;
  1319. if (graph && ! graph->serialChain.empty())
  1320. ++serial;
  1321. if (graph && graph->serialChain.empty() && graph->audio)
  1322. ++parallel;
  1323. }
  1324. for (const auto& c : project.channels)
  1325. if (c.pluginName == "DirectWave")
  1326. if (const auto program = lynx::directWaveProgram (c.pluginState))
  1327. for (const auto& wav : program->embeddedWav)
  1328. if (! wav.empty())
  1329. {
  1330. ++embeddedZones;
  1331. CHECK (wav.size() > 44 && std::memcmp (wav.data(), "RIFF", 4) == 0);
  1332. }
  1333. for (const auto& c : project.channels)
  1334. if (c.pluginName == "Patcher")
  1335. {
  1336. const auto graph = lynx::parsePatcher (c.pluginState);
  1337. CHECK (graph.has_value());
  1338. generatorPatchers += graph && graph->mainGenerator >= 0;
  1339. }
  1340. }
  1341. catch (const flp::Error&) {}
  1342. }
  1343. std::printf (" Gross Beat: %d slots, %d with gate; Effector: %d converted; Love Philter: %d, %d read\n", gates, shaped, effectors,
  1344. lovePhilters, lovePhiltersRead);
  1345. CHECK (lovePhiltersRead == lovePhilters && lovePhiltersConverted == lovePhilters);
  1346. std::printf (" Vocodex: %d converted, %d with side inputs\n", vocodexes, vocodexSides);
  1347. CHECK (vocodexes >= 9);
  1348. std::printf (" Love Philter live links: %d cutoff, %d resonance; in multi-unit containers: %d cutoff, %d resonance\n",
  1349. lovePhilterLinks[0], lovePhilterLinks[1], lovePhilterLinks[2], lovePhilterLinks[3]);
  1350. CHECK (lovePhilterLinks[2] + lovePhilterLinks[3] > 0);
  1351. std::printf (" DirectWave: %d zones with embedded audio\n", embeddedZones);
  1352. CHECK (embeddedZones == 12);
  1353. std::printf (" Patcher: %d in the mixer (%d serial, %d reduced to serial/parallel), %d as instrument with generator\n", patchers, serial,
  1354. parallel, generatorPatchers);
  1355. CHECK (gates == 0 || shaped > 0);
  1356. }
  1357. // Envelope Controller "Basic Sidechain" (Future House): drops on the note and returns to ~1 within ~1/3 s
  1358. {
  1359. const auto path = std::filesystem::path (realFlpDir) / "Demo projects" / "Demo songs" / "Asher Postman - Future House.flp";
  1360. if (std::filesystem::exists (path))
  1361. {
  1362. std::ifstream in (path, std::ios::binary);
  1363. const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1364. const auto song = lynx::importFlp (flp::parseProject (file));
  1365. const lynx::ChannelDef* controller = nullptr;
  1366. for (const auto& c : song.channels)
  1367. if (c.instrument == lynx::InstrumentKind::controller)
  1368. controller = &c;
  1369. CHECK (controller != nullptr);
  1370. if (controller != nullptr)
  1371. {
  1372. auto inst = lynx::makeInstrument (lynx::InstrumentKind::controller);
  1373. inst->prepare (48000.0);
  1374. inst->configure (*controller, song.bpm);
  1375. std::vector<float> l (480), r (480);
  1376. inst->render (l.data(), r.data(), 480, 1.0f, 1.0f);
  1377. inst->noteOn (60, 1.0f);
  1378. inst->render (l.data(), r.data(), 480, 1.0f, 1.0f); // 10 ms
  1379. const auto ducked = inst->controlOutput (0);
  1380. for (int i = 0; i < 100; ++i) // +1 s
  1381. inst->render (l.data(), r.data(), 480, 1.0f, 1.0f);
  1382. const auto recovered = inst->controlOutput (0);
  1383. std::printf (" Envelope Controller (Basic Sidechain): %.2f on the note, %.2f after 1 s\n", ducked, recovered);
  1384. CHECK (ducked < 0.3f && recovered > 0.9f);
  1385. }
  1386. }
  1387. }
  1388. // mutation fuzz: real states with flipped and truncated bytes must not crash the readers
  1389. {
  1390. std::map<std::string, std::vector<std::uint8_t>> samples; // one real blob per plugin
  1391. for (const auto& entry : std::filesystem::recursive_directory_iterator (std::filesystem::path (realFlpDir) / "Demo projects"))
  1392. {
  1393. if (entry.path().extension() != ".flp")
  1394. continue;
  1395. std::ifstream in (entry.path(), std::ios::binary);
  1396. const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1397. try
  1398. {
  1399. const auto project = flp::parseProject (file);
  1400. for (const auto& c : project.channels)
  1401. if (! c.pluginState.empty())
  1402. samples.emplace (c.pluginName, c.pluginState);
  1403. for (const auto& insert : project.mixer)
  1404. for (const auto& slot : insert.slots)
  1405. if (! slot.state.empty())
  1406. samples.emplace (slot.plugin, slot.state);
  1407. }
  1408. catch (const flp::Error&) {}
  1409. }
  1410. std::uint32_t seed = 12345;
  1411. auto rnd = [&seed] { seed = seed * 1664525u + 1013904223u; return seed >> 8; };
  1412. int mutations = 0;
  1413. for (const auto& [name, original] : samples)
  1414. for (int round = 0; round < 40; ++round)
  1415. {
  1416. auto blob = original;
  1417. if (round % 4 == 3 && ! blob.empty())
  1418. blob.resize (rnd() % blob.size()); // truncated
  1419. else
  1420. for (int k = 0; k < 1 + (int) (rnd() % 8) && ! blob.empty(); ++k)
  1421. blob[rnd() % blob.size()] = (std::uint8_t) rnd();
  1422. ++mutations;
  1423. lynx::SynthSettings synth;
  1424. float gain = 1.0f;
  1425. lynx::synthFromSytrus (blob, 120.0, synth, gain);
  1426. lynx::synthFromHarmor (blob, synth, gain);
  1427. lynx::synthFromGms (blob, 120.0, synth, gain);
  1428. lynx::synthFromOgun (blob, synth, gain);
  1429. lynx::synthFromMorphine (blob, synth, gain);
  1430. lynx::synthFromKepler (blob, synth, gain);
  1431. lynx::synthFromPoiZone (blob, synth, gain);
  1432. lynx::synthFromToxic (blob, synth, gain);
  1433. lynx::synthFromBassDrum (blob, synth, gain);
  1434. lynx::synthFromHarmless (blob, 120.0, synth, gain);
  1435. lynx::harmlessParams (blob);
  1436. if (lynx::harmorStateUsable (blob))
  1437. lynx::harmorFallbacks (blob);
  1438. lynx::parseEnvelopeController (blob);
  1439. lynx::parseKeyboardController (blob);
  1440. lynx::parseLovePhilter (blob);
  1441. lynx::parsePatcher (blob);
  1442. lynx::effectFromFl (name, blob);
  1443. lynx::fpcPads (blob);
  1444. lynx::directWaveProgram (blob);
  1445. CHECK (std::isfinite (gain) && std::isfinite (synth.cutoff));
  1446. }
  1447. std::printf (" mutation fuzz: %d blobs from %d plugins\n", mutations, (int) samples.size());
  1448. }
  1449. // WavPack (.wv) samples from FL packs: all decode, with finite, non-silent audio
  1450. {
  1451. int files = 0, decoded = 0, audible = 0;
  1452. double seconds = 0.0;
  1453. for (const auto& entry : std::filesystem::recursive_directory_iterator (std::filesystem::path (realFlpDir) / "Patches" / "Packs"))
  1454. if (entry.path().extension() == ".wv")
  1455. {
  1456. std::ifstream in (entry.path(), std::ios::binary);
  1457. const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1458. ++files;
  1459. lynx::DecodedAudio audio;
  1460. if (! lynx::decodeWavPack (file.data(), file.size(), audio))
  1461. continue;
  1462. ++decoded;
  1463. float peak = 0.0f;
  1464. bool finite = true;
  1465. for (const auto& ch : audio.channels)
  1466. for (auto v : ch)
  1467. {
  1468. finite = finite && std::isfinite (v);
  1469. peak = std::max (peak, std::abs (v));
  1470. }
  1471. CHECK (finite && peak <= 4.0f);
  1472. audible += peak > 1e-4f;
  1473. seconds += (double) audio.channels[0].size() / audio.sampleRate;
  1474. }
  1475. std::printf (" WavPack: %d .wv files, %d decoded, %d audible, %.0f s of audio\n", files, decoded, audible, seconds);
  1476. CHECK (decoded == files);
  1477. }
  1478. // native GMS presets (.gmsynth = the contents of 0xD5 without the "SSLF")
  1479. int gmsPresets = 0, gmsDecoded = 0;
  1480. const auto gmsFolder = std::filesystem::path (realFlpDir) / "Patches" / "Plugin presets" / "Generators" / "GMS";
  1481. if (std::filesystem::exists (gmsFolder))
  1482. for (const auto& entry : std::filesystem::recursive_directory_iterator (gmsFolder))
  1483. if (entry.path().extension() == ".gmsynth")
  1484. {
  1485. std::ifstream in (entry.path(), std::ios::binary);
  1486. std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1487. std::vector<std::uint8_t> blob { 'S', 'S', 'L', 'F' };
  1488. const auto n = (std::uint32_t) file.size();
  1489. blob.insert (blob.end(), reinterpret_cast<const std::uint8_t*> (&n), reinterpret_cast<const std::uint8_t*> (&n) + 4);
  1490. blob.insert (blob.end(), file.begin(), file.end());
  1491. lynx::SynthSettings gs;
  1492. float g = 1.0f;
  1493. ++gmsPresets;
  1494. if (lynx::synthFromGms (blob, 120.0, gs, g))
  1495. {
  1496. ++gmsDecoded;
  1497. CHECK (std::isfinite (g) && gs.cutoff >= 20.0f && std::isfinite (gs.pitchEnv.amount) && std::isfinite (gs.lfo[lynx::lfoPitch].period));
  1498. }
  1499. }
  1500. std::printf (" GMS presets: %d, %d decoded\n", gmsPresets, gmsDecoded);
  1501. // the synth's "FL presets" button: Sytrus/Harmor .fst and .gmsynth become synth settings
  1502. int presetFiles = 0, presetsRead = 0;
  1503. for (const auto* name : { "Sytrus", "Harmor", "GMS", "Harmless", "Ogun", "Sakura", "Fruit Kick", "Fruity DX10", "MiniSynth", "Kepler",
  1504. "PoiZone", "Toxic Biohazard", "BassDrum" })
  1505. {
  1506. const auto folder = std::filesystem::path (realFlpDir) / "Patches" / "Plugin presets" / "Generators" / name;
  1507. if (! std::filesystem::exists (folder))
  1508. continue;
  1509. for (const auto& entry : std::filesystem::recursive_directory_iterator (folder))
  1510. if (entry.path().extension() == ".fst" || entry.path().extension() == ".gmsynth")
  1511. {
  1512. std::ifstream in (entry.path(), std::ios::binary);
  1513. const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1514. ++presetFiles;
  1515. presetsRead += lynx::synthFromFlPreset (file).has_value();
  1516. }
  1517. }
  1518. std::printf (" FL synth presets: %d files, %d read\n", presetFiles, presetsRead);
  1519. CHECK (presetsRead >= presetFiles * 95 / 100);
  1520. CHECK (gmsDecoded == gmsPresets);
  1521. CHECK (sytrusDecoded == sytrus);
  1522. CHECK (harmlessDecoded == harmless && harmless > 100);
  1523. std::printf (" Harmless: %d states parsed for the engine, %d channels imported as Harmless\n", harmlessParsed, harmlessKind);
  1524. CHECK (harmlessParsed == harmless && harmlessKind >= harmless);
  1525. std::printf (" Harmor: %d channels, %d states usable by the engine, %d imported as Harmor (%d sounding)\n", harmor, harmorUsable, harmorKind, harmorSounding);
  1526. CHECK (harmorUsable == harmor && harmor > 90 && harmorKind >= harmor && harmorSounding >= harmorKind * 9 / 10);
  1527. 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",
  1528. gms, gmsUsable, gmsKind, gmsSounding, morphine, morphineUsable, morphineKind, morphineSounding, demoGoldens);
  1529. CHECK (gmsUsable == gms && gms >= 9 && gmsKind == gms && gmsSounding == gmsKind);
  1530. std::printf (" MiniSynth channels: %d, %d usable, %d on the exact engine, %d sounding, %d golden\n", miniSynth, miniSynthUsable, miniSynthKind,
  1531. miniSynthSounding, miniSynthGoldens);
  1532. CHECK (miniSynthUsable == miniSynth && miniSynth >= 12 && miniSynthKind == miniSynth && miniSynthSounding == miniSynthKind && miniSynthGoldens == 2);
  1533. CHECK (morphineUsable == morphine && morphine >= 7 && morphineKind == morphine && morphineSounding == morphineKind && demoGoldens == 2);
  1534. std::printf (" PoiZone: %d channels, %d usable, %d imported as PoiZone (%d sounding), %d demo golden\n", poizone, poizoneUsable, poizoneKind,
  1535. poizoneSounding, poizoneGoldens);
  1536. CHECK (poizoneUsable == poizone && poizone >= 2 && poizoneKind == poizone && poizoneSounding == poizoneKind && poizoneGoldens == 1);
  1537. std::printf (" Ogun: %d channels, %d states usable by the engine, %d imported as Ogun (%d sounding)\n", ogun, ogunUsable, ogunKind, ogunSounding);
  1538. CHECK (ogunUsable == ogun && ogun >= 20 && ogunKind >= ogun && ogunSounding >= ogunKind * 9 / 10);
  1539. std::printf (" Fruity DX10: %d channels, %d states usable by the engine, %d imported as DX10 (%d sounding)\n", dx10, dx10Usable, dx10Kind, dx10Sounding);
  1540. CHECK (dx10Usable == dx10 && dx10 >= 12 && dx10Kind == dx10 && dx10Sounding == dx10Kind);
  1541. std::printf (" Kepler: %d channels, %d states usable by the engine, %d imported as Kepler (%d sounding)\n", kepler, keplerUsable, keplerKind, keplerSounding);
  1542. CHECK (keplerUsable == kepler && kepler >= 4 && keplerSounding == keplerKind && (keplerKind == 0 || keplerKind == kepler));
  1543. std::printf (" Harmless rack compressor: %d of %d presets read from the installation\n", harmlessCompLoaded, harmlessCompWanted);
  1544. CHECK (harmlessCompLoaded == harmlessCompWanted && harmlessCompWanted > 100);
  1545. std::printf (" Maximus: %d of %d slots on the exact engine; Soundgoodizer: %d of %d; Vocodex with SG.dat: %d of %d\n", maximusExact,
  1546. maximusSlots, sgzExact, sgzSlots, vocodexWithData, vocodexSlots);
  1547. // REA_rodada40 §6: in Demo projects the 4 states left on the approximation use the Frequency Splitter linear-phase
  1548. // option; the other Data folders add states with options not decoded
  1549. CHECK (maximusSlots - maximusExact <= 16 && maximusExact >= 97 && sgzExact == sgzSlots && sgzSlots > 90);
  1550. CHECK (vocodexWithData == vocodexSlots && vocodexSlots >= 10);
  1551. // 3x Osc channel presets shipped with FL (.fst): all become synth settings
  1552. int presets = 0, presetsDecoded = 0;
  1553. const auto presetDir = std::filesystem::path (realFlpDir) / "Patches" / "Channel presets" / "3x Osc";
  1554. if (std::filesystem::is_directory (presetDir))
  1555. for (auto& entry : std::filesystem::directory_iterator (presetDir))
  1556. if (entry.path().extension() == ".fst")
  1557. {
  1558. ++presets;
  1559. std::ifstream in (entry.path(), std::ios::binary);
  1560. std::vector<std::uint8_t> bytes ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  1561. if (auto synth = lynx::synthFromFlPreset (bytes))
  1562. {
  1563. ++presetsDecoded;
  1564. CHECK (synth->osc[0].level + synth->osc[1].level + (synth->am ? 0.0f : synth->osc[2].level) <= 1.001f);
  1565. }
  1566. }
  1567. std::printf (" %d 3x Osc presets, %d read\n", presets, presetsDecoded);
  1568. CHECK (presetsDecoded == presets);
  1569. // FL effect presets that become built-in effects
  1570. int fxPresets = 0, fxDecoded = 0;
  1571. for (auto kind : { lynx::EffectKind::parametricEq, lynx::EffectKind::limiter, lynx::EffectKind::reverb, lynx::EffectKind::delay,
  1572. lynx::EffectKind::utility })
  1573. for (const auto& plugin : lynx::flPluginsForEffect (kind))
  1574. {
  1575. const auto dir = std::filesystem::path (realFlpDir) / "Patches" / "Plugin presets" / "Effects" / plugin;
  1576. if (! std::filesystem::is_directory (dir))
  1577. continue;
  1578. for (auto& entry : std::filesystem::recursive_directory_iterator (dir))
  1579. if (entry.path().extension() == ".fst")
  1580. {
  1581. ++fxPresets;
  1582. std::ifstream in (entry.path(), std::ios::binary);
  1583. std::vector<std::uint8_t> bytes ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  1584. fxDecoded += lynx::effectFromFlPreset (bytes).has_value();
  1585. }
  1586. }
  1587. std::printf (" %d FL effect presets, %d read\n", fxPresets, fxDecoded);
  1588. CHECK (fxDecoded == fxPresets);
  1589. CHECK (wrappedParsed == wrapped);
  1590. std::printf (" %d plugins in Fruity Wrapper, %d read\n", wrapped, wrappedParsed);
  1591. std::printf (" %d markers, %d time signature changes, %d tracks with EQ\n", markers, signatures, trackEqs);
  1592. std::printf (" %d parametric EQs (%d with FL settings), %d reverbs (%d without dry)\n", peqSlots, peqShaped, reverbs, reverbsDryless);
  1593. std::printf (" DirectWave: %d channels, %d zones; FPC: %d projects, %d pad channels, %d pad notes\n", dwChannels, dwZones, fpcKits,
  1594. padChannels, padNotes);
  1595. CHECK (dwZones > 1000 && padChannels > 250 && padNotes > 500);
  1596. std::printf (" sliced channels (Slicer/Slicex): %d; embedded WAVs saved: %d\n", slicedChannels, embeddedSaved);
  1597. CHECK (slicedChannels >= 25 && embeddedSaved >= 10); // without decoding Ogg here, some loops have no duration
  1598. std::printf (" FL Keys (Grand Piano, 30 zones): %d channels\n", flKeysChannels);
  1599. CHECK (flKeysChannels >= 8);
  1600. CHECK (peqSlots > 1000 && peqShaped > 900 && reverbsDryless > 20 && reverbsLowCut > 250);
  1601. CHECK (markers > 300 && signatures > 60);
  1602. std::printf (" %d 3x Osc channels, %d decoded\n", threeOsc, threeOscDecoded);
  1603. std::printf (" %d .flp files read, %d with notes, %d with playlist, %d automations (%d with target), %d sends\n",
  1604. files, withNotes, withPlaylist, automations, automationsWithTarget, sends);
  1605. CHECK (files > 0);
  1606. CHECK (automations > 0 && sends > 0);
  1607. }
  1608. // ---------------------------------------------------------------------------
  1609. // Sequencer
  1610. TEST (pattern_toggle_step_and_length)
  1611. {
  1612. lynx::Pattern p;
  1613. CHECK (! p.hasStep (0, 4));
  1614. p.toggleStep (0, 4);
  1615. CHECK (p.hasStep (0, 4));
  1616. CHECK (p.notes.size() == 1 && p.notes[0].start == 4 * lynx::ticksPerStep);
  1617. CHECK (p.effectiveLength (4) == 4 * lynx::ppq); // one bar
  1618. p.toggleStep (1, 20); // second bar
  1619. CHECK (p.effectiveLength (4) == 8 * lynx::ppq);
  1620. p.toggleStep (0, 4);
  1621. CHECK (! p.hasStep (0, 4) && p.notes.size() == 1);
  1622. }
  1623. TEST (scheduler_places_events_at_exact_samples)
  1624. {
  1625. lynx::Pattern p;
  1626. p.toggleStep (0, 0);
  1627. p.toggleStep (0, 4); // tick 960 = 1 beat
  1628. const double sr = 48000.0, bpm = 120.0; // 1 beat = 0.5 s = 24000 samples
  1629. const auto tps = lynx::ticksPerSample (bpm, sr);
  1630. lynx::EventBuffer ev;
  1631. lynx::schedulePatternLoop (p, p.effectiveLength (4), 23900.0 * tps, 512, tps, ev);
  1632. // the beat-2 note starts at sample 24000 -> offset 100 in this block
  1633. int ons = 0;
  1634. for (auto& e : ev)
  1635. if (e.type == lynx::NoteEvent::Type::on)
  1636. {
  1637. ++ons;
  1638. CHECK (e.sampleOffset == 100);
  1639. }
  1640. CHECK (ons == 1);
  1641. }
  1642. TEST (scheduler_wraps_the_loop)
  1643. {
  1644. lynx::Pattern p;
  1645. p.toggleStep (2, 0);
  1646. const auto len = p.effectiveLength (4); // 3840 ticks
  1647. const double sr = 48000.0;
  1648. const auto tps = lynx::ticksPerSample (120.0, sr);
  1649. lynx::EventBuffer ev;
  1650. // block that crosses the loop end: starts 10 samples before
  1651. const auto start = (double) len - 10.0 * tps;
  1652. lynx::schedulePatternLoop (p, len, start, 64, tps, ev);
  1653. bool found = false;
  1654. for (auto& e : ev)
  1655. if (e.type == lynx::NoteEvent::Type::on && e.channel == 2)
  1656. {
  1657. found = true;
  1658. CHECK (e.sampleOffset == 10);
  1659. }
  1660. CHECK (found);
  1661. }
  1662. TEST (scheduler_off_before_on_at_same_sample)
  1663. {
  1664. lynx::Pattern p;
  1665. lynx::Note a;
  1666. a.start = 0; a.length = 240; a.channel = 0;
  1667. lynx::Note b = a;
  1668. b.start = 240;
  1669. p.notes = { a, b };
  1670. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  1671. lynx::EventBuffer ev;
  1672. lynx::schedulePatternLoop (p, p.effectiveLength (4), 200.0, 4000, tps, ev);
  1673. CHECK (ev.size() >= 2);
  1674. CHECK (ev[0].type == lynx::NoteEvent::Type::off);
  1675. CHECK (ev[1].type == lynx::NoteEvent::Type::on);
  1676. CHECK (ev[0].sampleOffset == ev[1].sampleOffset);
  1677. }
  1678. TEST (snapshot_exchange_hands_over_and_recycles)
  1679. {
  1680. struct Counted
  1681. {
  1682. int value;
  1683. int* alive;
  1684. Counted (int v, int* a) : value (v), alive (a) { ++*alive; }
  1685. ~Counted() { --*alive; }
  1686. };
  1687. int alive = 0;
  1688. {
  1689. lynx::SnapshotExchange<Counted> x;
  1690. CHECK (x.acquire() == nullptr);
  1691. x.publish (std::make_unique<Counted> (1, &alive));
  1692. CHECK (x.acquire()->value == 1);
  1693. x.publish (std::make_unique<Counted> (2, &alive));
  1694. x.publish (std::make_unique<Counted> (3, &alive)); // 2 was never read: freed immediately
  1695. CHECK (alive == 2);
  1696. CHECK (x.acquire()->value == 3);
  1697. CHECK (alive == 2); // 1 was returned, but only the UI frees it
  1698. x.collectGarbage();
  1699. CHECK (alive == 1);
  1700. // without collection, the return slots fill up and the audio side holds on to the current one
  1701. for (int i = 0; i < 20; ++i)
  1702. {
  1703. x.publish (std::make_unique<Counted> (10 + i, &alive));
  1704. CHECK (x.acquire() != nullptr);
  1705. }
  1706. }
  1707. CHECK (alive == 0);
  1708. }
  1709. TEST (rack_renderer_makes_sound_and_reuses_instruments)
  1710. {
  1711. auto song = lynx::Song::makeDefault();
  1712. song.bpm = 120.0;
  1713. const double sr = 48000.0;
  1714. auto state = lynx::RackState::build (song, nullptr, sr);
  1715. lynx::RackRenderer r;
  1716. r.prepare (sr);
  1717. std::vector<float> l (512), rr (512);
  1718. double tick = 0.0;
  1719. float peak = 0.0f;
  1720. int kicks = 0;
  1721. for (int block = 0; block < 93; ++block) // 47616 samples: just before 1 s
  1722. {
  1723. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  1724. for (auto& e : r.lastEvents())
  1725. if (e.type == lynx::NoteEvent::Type::on && e.channel == 0)
  1726. ++kicks;
  1727. for (int i = 0; i < 512; ++i)
  1728. {
  1729. CHECK (std::isfinite (l[(std::size_t) i]));
  1730. peak = std::max (peak, std::abs (l[(std::size_t) i]));
  1731. }
  1732. tick += 512 * lynx::ticksPerSample (song.bpm, sr);
  1733. }
  1734. CHECK (peak > 0.1f && peak < 4.0f);
  1735. CHECK (kicks == 2); // 120 BPM: beats at 0 and 0.5 s
  1736. // editing the song keeps the instruments of channels whose type didn't change
  1737. song.channels[4].instrument = lynx::InstrumentKind::kick;
  1738. auto next = lynx::RackState::build (song, state.get(), sr);
  1739. CHECK (next->instruments[0] == state->instruments[0]);
  1740. CHECK (next->instruments[4] != state->instruments[4]);
  1741. // stopping silences the synth and triggers no new notes
  1742. r.process (next.get(), false, tick, 512, l.data(), rr.data());
  1743. CHECK (r.lastEvents().size() == 0);
  1744. }
  1745. TEST (flp_import_maps_channels_and_rescales)
  1746. {
  1747. flp::Project p;
  1748. p.header.ppq = 96;
  1749. p.tempo = 150.0;
  1750. p.channels = { { 0, flp::ChannelType::sampler, "Kick 808", "", "", 1 },
  1751. { 1, flp::ChannelType::audioClip, "Vocal", "", "", 2 },
  1752. { 2, flp::ChannelType::instrument, "Lead", "FLEX", "", 3 } };
  1753. flp::Pattern pat;
  1754. pat.index = 1;
  1755. flp::Note n;
  1756. n.position = 96;
  1757. n.length = 0;
  1758. n.channel = 2;
  1759. n.key = 72;
  1760. n.velocity = 64;
  1761. pat.notes.push_back (n);
  1762. p.patterns.push_back (pat);
  1763. const auto s = lynx::importFlp (p);
  1764. CHECK (s.bpm == 150.0);
  1765. CHECK (s.channels.size() == 3); // audio clip channels stay in the rack, as in FL
  1766. CHECK (s.channels[0].instrument == lynx::InstrumentKind::kick);
  1767. CHECK (s.channels[1].instrument == lynx::InstrumentKind::audioClip);
  1768. CHECK (s.channels[2].instrument == lynx::InstrumentKind::synth);
  1769. CHECK (s.patterns.size() == 1);
  1770. CHECK (s.patterns[0].notes[0].start == lynx::ppq); // 96 @ PPQ 96 = 1 beat
  1771. CHECK (s.patterns[0].notes[0].channel == 2);
  1772. CHECK (s.patterns[0].notes[0].length == lynx::ticksPerStep); // step note
  1773. CHECK (std::abs (s.patterns[0].notes[0].velocity - 0.5f) < 1e-6f);
  1774. }
  1775. TEST (live_queue_is_fifo_and_bounded)
  1776. {
  1777. lynx::LiveEventQueue q;
  1778. lynx::NoteEvent e;
  1779. CHECK (! q.pop (e));
  1780. for (int i = 0; i < 10; ++i)
  1781. {
  1782. lynx::NoteEvent in;
  1783. in.key = i;
  1784. CHECK (q.push (in));
  1785. }
  1786. for (int i = 0; i < 10; ++i)
  1787. CHECK (q.pop (e) && e.key == i);
  1788. int pushed = 0;
  1789. while (q.push (e))
  1790. ++pushed;
  1791. CHECK (pushed == (int) lynx::LiveEventQueue::capacity - 1); // one slot stays free to tell full from empty
  1792. }
  1793. TEST (sampler_plays_pitched_one_shot)
  1794. {
  1795. // 1000-frame ramp sample: the position can be measured from the amplitude
  1796. auto data = std::make_shared<lynx::SampleData>();
  1797. data->sampleRate = 48000.0;
  1798. for (int i = 0; i < 1000; ++i)
  1799. data->left.push_back (1.0f);
  1800. auto sampler = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  1801. sampler->prepare (48000.0);
  1802. std::vector<float> l (2048, 0.0f), r (2048, 0.0f);
  1803. sampler->noteOn (60, 1.0f);
  1804. sampler->noteOff (60); // one-shot: noteOff doesn't cut
  1805. sampler->render (l.data(), r.data(), 2048, 1.0f, 1.0f);
  1806. int sounding = 0;
  1807. for (auto s : l)
  1808. sounding += s > 0.5f;
  1809. CHECK (sounding >= 995 && sounding <= 1000); // plays the whole sample at the original pitch
  1810. std::fill (l.begin(), l.end(), 0.0f);
  1811. sampler->noteOn (72, 1.0f); // one octave up: half the duration
  1812. sampler->render (l.data(), r.data(), 2048, 1.0f, 1.0f);
  1813. sounding = 0;
  1814. for (auto s : l)
  1815. sounding += s > 0.5f;
  1816. CHECK (sounding >= 495 && sounding <= 500);
  1817. CHECK (r[10] > 0.5f); // mono goes to both sides
  1818. auto silent = lynx::makeInstrument (lynx::InstrumentKind::sampler, nullptr);
  1819. silent->prepare (48000.0);
  1820. silent->noteOn (60, 1.0f);
  1821. std::fill (l.begin(), l.end(), 0.0f);
  1822. silent->render (l.data(), r.data(), 64, 1.0f, 1.0f);
  1823. CHECK (l[0] == 0.0f);
  1824. }
  1825. TEST (rack_live_notes_and_sample_provider)
  1826. {
  1827. lynx::Song song;
  1828. lynx::ChannelDef c;
  1829. c.name = "Smp";
  1830. c.instrument = lynx::InstrumentKind::sampler;
  1831. c.samplePath = "a.wav";
  1832. song.channels.push_back (c);
  1833. song.patterns.emplace_back();
  1834. int loads = 0;
  1835. auto provider = [&] (const std::string& path) -> std::shared_ptr<const lynx::SampleData> {
  1836. ++loads;
  1837. CHECK (path == "a.wav");
  1838. auto d = std::make_shared<lynx::SampleData>();
  1839. d->left.assign (4800, 0.5f);
  1840. return d;
  1841. };
  1842. auto state = lynx::RackState::build (song, nullptr, 48000.0, provider);
  1843. CHECK (loads == 1);
  1844. lynx::RackRenderer renderer;
  1845. renderer.prepare (48000.0);
  1846. lynx::LiveEventQueue live;
  1847. lynx::NoteEvent on;
  1848. on.channel = 0;
  1849. on.velocity = 1.0f;
  1850. live.push (on);
  1851. std::vector<float> l (256), r (256);
  1852. renderer.process (state.get(), false, 0.0, 256, l.data(), r.data(), &live); // stopped, but the live note plays
  1853. CHECK (l[0] > 0.1f);
  1854. // same sample: reused; different sample: reloaded
  1855. auto same = lynx::RackState::build (song, state.get(), 48000.0, provider);
  1856. CHECK (loads == 1 && same->instruments[0] == state->instruments[0]);
  1857. song.channels[0].samplePath = "b.wav";
  1858. auto other = lynx::RackState::build (song, state.get(), 48000.0, [&] (const std::string&) { ++loads; return nullptr; });
  1859. CHECK (loads == 2 && other->instruments[0] != state->instruments[0]);
  1860. }
  1861. TEST (flp_paths_resolve_and_samplers_import)
  1862. {
  1863. lynx::FlPathRoots roots { "C:\\FL", "C:\\FL\\Data", "D:\\User" };
  1864. CHECK (lynx::resolveFlPath ("%FLStudioFactoryData%\\Data\\x.wav", roots) == "C:\\FL\\Data\\x.wav");
  1865. CHECK (lynx::resolveFlPath ("%FLStudioData%\\Patches\\y.wav", roots) == "C:\\FL\\Data\\Patches\\y.wav");
  1866. CHECK (lynx::resolveFlPath ("%FLStudioUserData%\\z.wav", roots) == "D:\\User\\z.wav");
  1867. CHECK (lynx::resolveFlPath ("E:\\abs.wav", roots) == "E:\\abs.wav");
  1868. CHECK (lynx::resolveFlPath ("%FLStudioUserData%\\z.wav", {}) == "");
  1869. flp::Project p;
  1870. p.channels = { { 0, flp::ChannelType::sampler, "Kick", "", "%FLStudioData%\\k.wav", 1 },
  1871. { 1, flp::ChannelType::sampler, "Hat", "", "%FLStudioData%\\missing.wav", 1 } };
  1872. lynx::FlpImportOptions options;
  1873. options.roots = roots;
  1874. options.fileExists = [] (const std::string& path) { return path == "C:\\FL\\Data\\k.wav"; };
  1875. const auto s = lynx::importFlp (p, options);
  1876. CHECK (s.channels[0].instrument == lynx::InstrumentKind::sampler);
  1877. CHECK (s.channels[0].samplePath == "C:\\FL\\Data\\k.wav");
  1878. CHECK (s.channels[1].instrument == lynx::InstrumentKind::hat); // no file: built-in instrument
  1879. }
  1880. TEST (soft_clip_is_transparent_below_knee_and_bounded)
  1881. {
  1882. float s[] = { 0.5f, -0.89f, 1.5f, -3.0f, 0.95f };
  1883. lynx::softClip (s, 5);
  1884. CHECK (s[0] == 0.5f && s[1] == -0.89f);
  1885. CHECK (s[2] > 0.9f && s[2] <= 1.0f);
  1886. CHECK (s[3] < -0.9f && s[3] >= -1.0f);
  1887. CHECK (s[4] > 0.9f && s[4] < 0.95f);
  1888. }
  1889. TEST (song_scheduler_plays_clips_with_offset_and_cut)
  1890. {
  1891. lynx::Song s;
  1892. s.channels.resize (1);
  1893. auto& p = s.patterns.emplace_back();
  1894. for (int step : { 0, 4, 8, 12 }) // one note per beat
  1895. p.toggleStep (0, step);
  1896. // clip at bar 2 playing only the second half of the pattern (beats 3 and 4)
  1897. lynx::Clip c;
  1898. c.pattern = 0;
  1899. c.start = 4 * lynx::ppq;
  1900. c.length = 2 * lynx::ppq;
  1901. c.offset = 2 * lynx::ppq;
  1902. s.playlist.push_back (c);
  1903. CHECK (s.songLength() == 8 * lynx::ppq);
  1904. const double sr = 48000.0;
  1905. const auto tps = lynx::ticksPerSample (120.0, sr); // 1 beat = 24000 samples
  1906. lynx::EventBuffer ev;
  1907. // whole song in a single block (8 beats = 192000 samples)
  1908. lynx::scheduleSong (s, 0.0, 192000, tps, ev);
  1909. std::vector<int> ons;
  1910. for (auto& e : ev)
  1911. if (e.type == lynx::NoteEvent::Type::on)
  1912. ons.push_back (e.sampleOffset);
  1913. CHECK (ons.size() == 2);
  1914. CHECK (ons.size() == 2 && ons[0] == 4 * 24000 && ons[1] == 5 * 24000);
  1915. // crossing the loop: bar 1 is empty, so nothing at the start of the second pass
  1916. ev.clear();
  1917. lynx::scheduleSong (s, 8.0 * lynx::ppq - 100 * tps, 200, tps, ev);
  1918. CHECK (ev.size() == 0);
  1919. // a note longer than the clip is cut at the clip end
  1920. p.notes[3].length = 4 * lynx::ppq;
  1921. ev.clear();
  1922. lynx::scheduleSong (s, 0.0, 192000, tps, ev);
  1923. int lastOff = -1;
  1924. for (auto& e : ev)
  1925. if (e.type == lynx::NoteEvent::Type::off)
  1926. lastOff = std::max (lastOff, e.sampleOffset);
  1927. CHECK (lastOff == 6 * 24000);
  1928. }
  1929. TEST (remove_pattern_fixes_clips)
  1930. {
  1931. lynx::Song s;
  1932. s.patterns.resize (3);
  1933. s.currentPattern = 2;
  1934. s.playlist = { { 0, 0, 0, 100, 0 }, { 1, 0, 100, 100, 0 }, { 2, 1, 0, 100, 0 } };
  1935. s.removePattern (1);
  1936. CHECK (s.patterns.size() == 2);
  1937. CHECK (s.playlist.size() == 2 && s.playlist[1].pattern == 1);
  1938. CHECK (s.currentPattern == 1);
  1939. }
  1940. TEST (flp_import_3x_osc_state_and_channel_filter)
  1941. {
  1942. // new 3x Osc patch (version 14): osc 2 mix 64 coarse -12, osc 3 mix 32 coarse -24
  1943. std::vector<std::uint8_t> blob (460, 0);
  1944. auto put = [&] (std::size_t off, std::int32_t v) {
  1945. for (int b = 0; b < 4; ++b)
  1946. blob[off + (std::size_t) b] = (std::uint8_t) ((std::uint32_t) v >> (8 * b));
  1947. };
  1948. put (0x00, 14);
  1949. put (0x08, 3); // osc 1 saw
  1950. put (0x10, 7); // osc 1 fine +7
  1951. put (0x04, -32); // osc 1 pan -0.5
  1952. put (0x1C, 64); // osc 2 mix
  1953. put (0x28, -12); // osc 2 coarse
  1954. put (0x38, 32); // osc 3 mix
  1955. put (0x40, 2); // osc 3 square
  1956. put (0x44, -19); // osc 3 coarse: -1 octave and -7 semitones
  1957. lynx::SynthSettings s;
  1958. CHECK (lynx::synthFrom3xOsc (blob, s));
  1959. 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);
  1960. CHECK (s.osc[0].wave == lynx::Waveform::saw && s.osc[0].detune == 7.0f && s.osc[0].pan == -0.5f);
  1961. CHECK (s.osc[1].wave == lynx::Waveform::sine && s.osc[1].octave == -1 && s.osc[1].semitones == 0);
  1962. CHECK (s.osc[2].wave == lynx::Waveform::square && s.osc[2].octave == -1 && s.osc[2].semitones == -7);
  1963. CHECK (! lynx::synthFrom3xOsc (std::vector<std::uint8_t> (40, 0), s));
  1964. // channel filter: open by default; LP with Mod X 128 ~ 2.71 kHz; Fast LP with Mod X 128 ~ 280 Hz
  1965. float hz = 0.0f, res = 1.0f;
  1966. int mode = -1;
  1967. lynx::synthFilterFromChannel (256, 0, 0, hz, res, mode);
  1968. CHECK (hz >= 19999.0f && res == 0.0f);
  1969. lynx::synthFilterFromChannel (128, 0, 1, hz, res, mode);
  1970. CHECK (std::abs (hz - 2710.0f) < 30.0f && res == 0.0f);
  1971. lynx::synthFilterFromChannel (128, 0, 0, hz, res, mode);
  1972. CHECK (hz > 240.0f && hz < 320.0f);
  1973. lynx::synthFilterFromChannel (128, 256, 1, hz, res, mode);
  1974. CHECK (res > 0.8f);
  1975. CHECK (mode == 0);
  1976. lynx::synthFilterFromChannel (64, 0, 3, hz, res, mode); // high-pass at ~840 Hz
  1977. CHECK (mode == 2 && std::abs (hz - 840.0f) < 40.0f);
  1978. lynx::synthFilterFromChannel (128, 0, 2, hz, res, mode); // band-pass
  1979. CHECK (mode == 1);
  1980. }
  1981. TEST (synth_pitch_and_filter_envelopes)
  1982. {
  1983. auto render = [] (const lynx::SynthSettings& s, int frames) {
  1984. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  1985. inst->prepare (48000.0);
  1986. lynx::ChannelDef c;
  1987. c.synth = s;
  1988. inst->configure (c, 120.0);
  1989. inst->noteOn (45, 1.0f); // A2 = 110 Hz
  1990. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  1991. inst->render (l.data(), r.data(), frames, 1.0f, 1.0f);
  1992. return l;
  1993. };
  1994. auto crossings = [] (const std::vector<float>& b, int from, int to) {
  1995. int n = 0;
  1996. for (int i = from + 1; i < to; ++i)
  1997. n += (b[(std::size_t) i - 1] < 0.0f) != (b[(std::size_t) i] < 0.0f);
  1998. return n;
  1999. };
  2000. // 3x Osc "kick": sine with a +24 st pitch envelope falling fast
  2001. lynx::SynthSettings kick;
  2002. kick.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  2003. kick.cutoff = 20000.0f;
  2004. kick.pitchEnv = { 24.0f, 0.0f, 0.0f, 0.05f, 0.0f, 0.05f };
  2005. const auto k = render (kick, 48000);
  2006. const auto early = crossings (k, 0, 2400); // first 50 ms: well above 110 Hz
  2007. const auto late = crossings (k, 24000, 48000); // then back to 110 Hz (~110 crossings in 0.5 s)
  2008. CHECK (early > 20); // +24 st ramp over 50 ms: ~2.2x the average frequency (11 crossings without envelope)
  2009. CHECK (std::abs (late - 110) < 4);
  2010. // cutoff envelope: saw closed at 200 Hz opens +5 octaves on attack and closes again
  2011. lynx::SynthSettings pluck;
  2012. pluck.cutoff = 200.0f;
  2013. pluck.filterEnv = { 5.0f, 0.0f, 0.0f, 0.1f, 0.0f, 0.1f };
  2014. const auto p = render (pluck, 48000);
  2015. auto hf = [&] (int from, int to) { // energy of the difference (highs)
  2016. double e = 0.0;
  2017. for (int i = from + 1; i < to; ++i)
  2018. e += std::pow ((double) p[(std::size_t) i] - p[(std::size_t) i - 1], 2.0);
  2019. return e;
  2020. };
  2021. CHECK (hf (0, 2400) > 4.0 * hf (40000, 42400));
  2022. // Toxic Biohazard's envelope (REA_rodada33 §2): exponential towards 5 clipped at 1, so the cutoff is still near
  2023. // its base early in the attack, fully open at A = 0.2 s and back down after the exponential decay
  2024. lynx::SynthSettings toxic = pluck;
  2025. toxic.filterEnv = { 5.0f, 0.2f, 0.0f, 0.1f, 0.0f, 0.1f, 1 };
  2026. const auto t = render (toxic, 48000);
  2027. auto thf = [&] (int from, int to) {
  2028. double e = 0.0;
  2029. for (int i = from + 1; i < to; ++i)
  2030. e += std::pow ((double) t[(std::size_t) i] - t[(std::size_t) i - 1], 2.0);
  2031. return e;
  2032. };
  2033. CHECK (thf (9000, 9600) > 4.0 * thf (300, 900));
  2034. CHECK (thf (9000, 9600) > 4.0 * thf (40000, 40600));
  2035. }
  2036. TEST (synth_mono_reuses_the_sounding_voice)
  2037. {
  2038. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  2039. inst->prepare (48000.0);
  2040. lynx::ChannelDef c;
  2041. c.synth.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  2042. c.synth.cutoff = 20000.0f;
  2043. c.synth.mono = true;
  2044. inst->configure (c, 120.0);
  2045. std::vector<float> l (48000), r (48000);
  2046. inst->noteOn (57, 1.0f);
  2047. inst->render (l.data(), r.data(), 4800, 1.0f, 1.0f);
  2048. inst->noteOn (69, 1.0f); // A4 takes over the A3 voice: only one note sounding
  2049. inst->render (l.data() + 4800, r.data() + 4800, 43200, 1.0f, 1.0f);
  2050. int crossings = 0;
  2051. float peak = 0.0f;
  2052. for (std::size_t i = 24001; i < 48000; ++i)
  2053. {
  2054. crossings += (l[i - 1] < 0.0f) != (l[i] < 0.0f);
  2055. peak = std::max (peak, std::abs (l[i]));
  2056. }
  2057. CHECK (std::abs (crossings - 440) < 4); // 0.5 s of 440 Hz, without the A3 underneath
  2058. CHECK (peak < 0.35f); // one voice (0.3 level), not two summed
  2059. // no click on the handover: the jump between neighbouring samples stays sine-sized
  2060. float jump = 0.0f;
  2061. for (std::size_t i = 4790; i < 4810; ++i)
  2062. jump = std::max (jump, std::abs (l[i] - l[i - 1]));
  2063. CHECK (jump < 0.05f);
  2064. }
  2065. TEST (synth_porta_glides_and_am_modulates)
  2066. {
  2067. auto make = [] (const lynx::SynthSettings& s) {
  2068. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  2069. inst->prepare (48000.0);
  2070. lynx::ChannelDef c;
  2071. c.synth = s;
  2072. inst->configure (c, 120.0);
  2073. return inst;
  2074. };
  2075. auto crossings = [] (const std::vector<float>& b, std::size_t from, std::size_t to) {
  2076. int n = 0;
  2077. for (auto i = from + 1; i < to; ++i)
  2078. n += (b[i - 1] < 0.0f) != (b[i] < 0.0f);
  2079. return n;
  2080. };
  2081. // mono + 1-beat porta (0.5 s at 120 BPM): from A3 to A4, halfway ~E4 (329.6 Hz)
  2082. lynx::SynthSettings s;
  2083. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  2084. s.cutoff = 20000.0f;
  2085. s.mono = true;
  2086. s.porta = true;
  2087. s.portaBeats = 1.0f;
  2088. auto inst = make (s);
  2089. std::vector<float> l (96000), r (96000);
  2090. inst->noteOn (57, 1.0f);
  2091. inst->render (l.data(), r.data(), 4800, 1.0f, 1.0f);
  2092. inst->noteOn (69, 1.0f);
  2093. inst->render (l.data() + 4800, r.data() + 4800, 91200, 1.0f, 1.0f);
  2094. const auto middle = crossings (l, 4800 + 12000 - 2400, 4800 + 12000 + 2400); // 0.1 s around 0.25 s
  2095. CHECK (std::abs (middle - 66) < 6); // ~330 Hz * 0.1 s * 2
  2096. CHECK (std::abs (crossings (l, 48000, 96000) - 880) < 4); // reached A4 (1 s = 880 crossings)
  2097. // AM: osc 3 at level 1.0, slow sine, modulates osc 1 (the average level drops, the sum doesn't gain osc 3)
  2098. lynx::SynthSettings am;
  2099. am.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  2100. am.osc[2] = { lynx::Waveform::sine, -3, 0.0f, 1.0f };
  2101. am.cutoff = 20000.0f;
  2102. am.am = true;
  2103. auto modulated = make (am);
  2104. modulated->noteOn (69, 1.0f);
  2105. std::fill (l.begin(), l.end(), 0.0f);
  2106. modulated->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  2107. float peak = 0.0f;
  2108. for (std::size_t i = 4800; i < 48000; ++i)
  2109. peak = std::max (peak, std::abs (l[i]));
  2110. CHECK (peak > 0.45f && peak < 0.65f); // 0.3 · (1 + 1) at most: (1 − o3) goes up to 2
  2111. }
  2112. TEST (channel_lfo_vibrato_and_tremolo)
  2113. {
  2114. auto render = [] (const lynx::SynthSettings& s) {
  2115. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  2116. inst->prepare (48000.0);
  2117. lynx::ChannelDef c;
  2118. c.synth = s;
  2119. inst->configure (c, 120.0);
  2120. inst->noteOn (69, 1.0f);
  2121. std::vector<float> l (48000), r (48000);
  2122. inst->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  2123. return l;
  2124. };
  2125. lynx::SynthSettings s;
  2126. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  2127. s.cutoff = 20000.0f;
  2128. // tremolo: 100% volume LFO at 4 Hz (0.25 s period) -> the amplitude envelope goes from ~0 to ~2x
  2129. auto tremolo = s;
  2130. tremolo.lfo[lynx::lfoVolume] = { 1.0f, 0.25f, false, 0, 0.0f, 0.0f };
  2131. const auto t = render (tremolo);
  2132. float lowest = 1.0f, highest = 0.0f;
  2133. for (std::size_t w = 4800; w + 480 <= 48000; w += 480) // 10 ms windows (4.4 cycles of 440 Hz)
  2134. {
  2135. float peak = 0.0f;
  2136. for (auto i = w; i < w + 480; ++i)
  2137. peak = std::max (peak, std::abs (t[i]));
  2138. lowest = std::min (lowest, peak);
  2139. highest = std::max (highest, peak);
  2140. }
  2141. CHECK (lowest < 0.08f && highest > 0.5f);
  2142. // synced vibrato: ±1 semitone, 1-beat period (0.5 s at 120 BPM); the average stays at 440 Hz
  2143. auto vibrato = s;
  2144. vibrato.lfo[lynx::lfoPitch] = { 1.0f, 1.0f, true, 0, 0.0f, 0.0f };
  2145. const auto v = render (vibrato);
  2146. int crossings = 0;
  2147. for (std::size_t i = 1; i < 48000; ++i)
  2148. crossings += (v[i - 1] < 0.0f) != (v[i] < 0.0f);
  2149. CHECK (std::abs (crossings - 880) < 12);
  2150. int firstQuarter = 0; // first quarter of the cycle: rising sine -> higher than 440
  2151. for (std::size_t i = 1; i < 6000; ++i)
  2152. firstQuarter += (v[i - 1] < 0.0f) != (v[i] < 0.0f);
  2153. CHECK (firstQuarter > 112);
  2154. }
  2155. TEST (sampler_porta_glides_from_previous_note)
  2156. {
  2157. auto data = std::make_shared<lynx::SampleData>();
  2158. data->sampleRate = 48000.0;
  2159. data->left.resize (96000);
  2160. for (std::size_t i = 0; i < data->left.size(); ++i)
  2161. data->left[i] = 0.5f * (float) std::sin (6.283185307 * 220.0 * (double) i / 48000.0);
  2162. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  2163. inst->prepare (48000.0);
  2164. lynx::ChannelDef c;
  2165. c.sampler.cut = true;
  2166. c.sampler.porta = true;
  2167. c.sampler.portaBeats = 1.0f; // 0.5 s at 120 BPM
  2168. inst->configure (c, 120.0);
  2169. std::vector<float> l (24000), r (24000);
  2170. inst->noteOn (60, 1.0f);
  2171. inst->render (l.data(), r.data(), 2400, 1.0f, 1.0f);
  2172. inst->noteOn (72, 1.0f); // one octave up: starts at 220 Hz and rises
  2173. std::fill (l.begin(), l.end(), 0.0f);
  2174. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  2175. auto crossings = [&] (std::size_t from, std::size_t to) {
  2176. int n = 0;
  2177. for (auto i = from + 1; i < to; ++i)
  2178. n += (l[i - 1] < 0.0f) != (l[i] < 0.0f);
  2179. return n;
  2180. };
  2181. const auto start = crossings (600, 2400); // 37.5 ms still near 220 Hz: ~17 crossings (440 Hz would give 33)
  2182. const auto end = crossings (21600, 24000); // 50 ms at the end of the glide: near 440 Hz (~44; 220 Hz would give 22)
  2183. CHECK (start < 22);
  2184. CHECK (end > 36);
  2185. }
  2186. TEST (zoned_sampler_picks_zone_by_key_and_velocity)
  2187. {
  2188. auto sine = [] (double hz, float amp) {
  2189. auto d = std::make_shared<lynx::SampleData>();
  2190. d->sampleRate = 48000.0;
  2191. d->left.resize (48000);
  2192. for (std::size_t i = 0; i < d->left.size(); ++i)
  2193. d->left[i] = amp * (float) std::sin (6.283185307 * hz * (double) i / 48000.0);
  2194. return d;
  2195. };
  2196. // lows: 220 Hz sine recorded as A3 (57), up to key 69; highs: 880 Hz as A5 (81)
  2197. // hard layer on the highs: same tuning, louder
  2198. std::vector<lynx::LoadedZone> zones {
  2199. { { "graves.wav", 57, 0, 69, 0, 127, 0.0f, 1.0f }, sine (220.0, 0.5f) },
  2200. { { "agudos.wav", 81, 70, 127, 0, 99, 0.0f, 1.0f }, sine (880.0, 0.25f) },
  2201. { { "agudos forte.wav", 81, 70, 127, 100, 127, 0.0f, 1.0f }, sine (880.0, 0.9f) },
  2202. };
  2203. auto inst = lynx::makeZonedSampler (zones);
  2204. inst->prepare (48000.0);
  2205. inst->configure (lynx::ChannelDef {}, 120.0);
  2206. auto play = [&] (int key, float velocity) {
  2207. inst->allNotesOff();
  2208. std::vector<float> l (24000), r (24000);
  2209. inst->render (l.data(), r.data(), 2000, 1.0f, 1.0f); // let the old voices die out
  2210. std::fill (l.begin(), l.end(), 0.0f);
  2211. inst->noteOn (key, velocity);
  2212. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  2213. int crossings = 0;
  2214. float peak = 0.0f;
  2215. for (std::size_t i = 1; i < 24000; ++i)
  2216. {
  2217. crossings += (l[i - 1] < 0.0f) != (l[i] < 0.0f);
  2218. peak = std::max (peak, std::abs (l[i]));
  2219. }
  2220. return std::pair { crossings, peak };
  2221. };
  2222. const auto low = play (69, 0.5f); // A4 from root A3: 440 Hz -> 440 crossings in 0.5 s
  2223. CHECK (std::abs (low.first - 440) < 4);
  2224. const auto soft = play (81, 0.5f); // high zone at the root: 880 Hz
  2225. CHECK (std::abs (soft.first - 880) < 6);
  2226. const auto hard = play (81, 0.95f); // high velocity: hard layer
  2227. CHECK (hard.second > soft.second * 2.0f);
  2228. // overlapping layers round-robin: two identical zones at different levels, notes alternate
  2229. auto rr = lynx::makeZonedSampler ({ { { "a.wav", 60 }, sine (440.0, 0.2f) }, { { "b.wav", 60 }, sine (440.0, 0.8f) } });
  2230. rr->prepare (48000.0);
  2231. rr->configure (lynx::ChannelDef {}, 120.0);
  2232. float peaks[2] {};
  2233. for (int k = 0; k < 2; ++k)
  2234. {
  2235. rr->allNotesOff();
  2236. std::vector<float> l (4800), r (4800);
  2237. rr->render (l.data(), r.data(), 2000, 1.0f, 1.0f);
  2238. std::fill (l.begin(), l.end(), 0.0f);
  2239. rr->noteOn (60, 1.0f);
  2240. rr->render (l.data(), r.data(), 4800, 1.0f, 1.0f);
  2241. for (auto v : l)
  2242. peaks[k] = std::max (peaks[k], std::abs (v));
  2243. }
  2244. CHECK (std::abs (peaks[0] - peaks[1]) > 0.3f);
  2245. }
  2246. TEST (zoned_sampler_loops_while_held)
  2247. {
  2248. // 0.1 s sample with a loop in the middle: holding the note it keeps sounding well past the end of the file;
  2249. // on release, it leaves the loop and ends
  2250. auto data = std::make_shared<lynx::SampleData>();
  2251. data->sampleRate = 48000.0;
  2252. data->left.resize (4800);
  2253. for (std::size_t i = 0; i < data->left.size(); ++i)
  2254. data->left[i] = 0.5f * (float) std::sin (6.283185307 * 480.0 * (double) i / 48000.0); // 100 frames per cycle
  2255. lynx::SampleZone zone { "loop.wav", 60 };
  2256. zone.loopStart = 1000;
  2257. zone.loopEnd = 3000;
  2258. zone.loopMode = 2;
  2259. auto inst = lynx::makeZonedSampler ({ { zone, data } });
  2260. inst->prepare (48000.0);
  2261. lynx::ChannelDef c;
  2262. c.sampler.release = 0.01f;
  2263. inst->configure (c, 120.0);
  2264. inst->noteOn (60, 1.0f);
  2265. std::vector<float> l (48000), r (48000);
  2266. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f); // 0.5 s held
  2267. float held = 0.0f;
  2268. for (std::size_t i = 20000; i < 24000; ++i)
  2269. held = std::max (held, std::abs (l[i]));
  2270. CHECK (held > 0.3f);
  2271. inst->noteOff (60);
  2272. inst->render (l.data() + 24000, r.data() + 24000, 24000, 1.0f, 1.0f);
  2273. float after = 0.0f;
  2274. for (std::size_t i = 40000; i < 48000; ++i)
  2275. after = std::max (after, std::abs (l[i]));
  2276. CHECK (after == 0.0f);
  2277. }
  2278. TEST (global_lfo_follows_song_position)
  2279. {
  2280. // global volume LFO (1-beat period): a note mid-cycle starts mid-wave; the
  2281. // same note with a per-note LFO starts at phase 0
  2282. auto first = [] (bool global, double songTicks) {
  2283. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  2284. inst->prepare (48000.0);
  2285. lynx::ChannelDef c;
  2286. c.synth.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  2287. c.synth.cutoff = 20000.0f;
  2288. c.synth.lfo[lynx::lfoVolume] = { 1.0f, 1.0f, true, 2, 0.0f, 0.0f, global }; // pulse: +1 in the first half
  2289. inst->configure (c, 120.0);
  2290. inst->setSongPosition (songTicks);
  2291. inst->noteOn (69, 1.0f);
  2292. std::vector<float> l (4800), r (4800);
  2293. inst->render (l.data(), r.data(), 4800, 1.0f, 1.0f);
  2294. float peak = 0.0f;
  2295. for (std::size_t i = 2400; i < 4800; ++i)
  2296. peak = std::max (peak, std::abs (l[i]));
  2297. return peak;
  2298. };
  2299. // mid-cycle (phase 0.6) the pulse is at −1: volume ~0; per note (phase 0) it is at +1: ~2x
  2300. const auto globalLate = first (true, 0.6 * lynx::ppq);
  2301. const auto perNote = first (false, 0.6 * lynx::ppq);
  2302. CHECK (globalLate < 0.05f);
  2303. CHECK (perNote > 0.4f);
  2304. }
  2305. TEST (sampler_channel_filter_darkens_and_bypasses_when_open)
  2306. {
  2307. // white noise in the sampler: with a 300 Hz cutoff the energy drops a lot; open passes unchanged
  2308. auto data = std::make_shared<lynx::SampleData>();
  2309. data->sampleRate = 48000.0;
  2310. data->left.resize (48000);
  2311. std::uint32_t seed = 7;
  2312. for (auto& v : data->left)
  2313. {
  2314. seed = seed * 1664525u + 1013904223u;
  2315. v = ((float) (seed >> 8) / 16777216.0f - 0.5f);
  2316. }
  2317. data->right = data->left;
  2318. auto energy = [&] (float cutoff) {
  2319. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  2320. inst->prepare (48000.0);
  2321. lynx::ChannelDef c;
  2322. c.sampler.cutoff = cutoff;
  2323. inst->configure (c, 120.0);
  2324. inst->noteOn (60, 1.0f);
  2325. std::vector<float> l (24000), r (24000);
  2326. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  2327. double e = 0.0;
  2328. for (auto v : l)
  2329. e += (double) v * v;
  2330. return e;
  2331. };
  2332. const auto open = energy (20000.0f), dark = energy (300.0f);
  2333. {
  2334. // high-pass at 10 kHz: also removes most of the noise energy, but from the other side
  2335. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  2336. inst->prepare (48000.0);
  2337. lynx::ChannelDef hp;
  2338. hp.sampler.cutoff = 10000.0f;
  2339. hp.sampler.filterType = 2;
  2340. inst->configure (hp, 120.0);
  2341. inst->noteOn (60, 1.0f);
  2342. std::vector<float> l (24000), r (24000);
  2343. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  2344. double e = 0.0, lowE = 0.0;
  2345. float lp = 0.0f;
  2346. for (auto v : l)
  2347. {
  2348. e += (double) v * v;
  2349. lp += 0.01f * (v - lp); // crude low-pass: almost nothing should remain below
  2350. lowE += (double) lp * lp;
  2351. }
  2352. CHECK (e > 10.0 && e < 0.7 * energy (20000.0f));
  2353. CHECK (lowE < e * 0.01);
  2354. }
  2355. CHECK (open > 100.0);
  2356. CHECK (dark < open * 0.05);
  2357. // +12 st pitch envelope with sustain 1: the sample runs at double speed
  2358. // and ends in half the time (1 s of sample -> 0.5 s)
  2359. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  2360. inst->prepare (48000.0);
  2361. lynx::ChannelDef c;
  2362. c.sampler.pitchEnv = { 12.0f, 0.0f, 0.0f, 0.1f, 1.0f, 0.1f };
  2363. inst->configure (c, 120.0);
  2364. inst->noteOn (60, 1.0f);
  2365. std::vector<float> l (48000), r (48000);
  2366. inst->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  2367. float tail = 0.0f, body = 0.0f;
  2368. for (std::size_t i = 20000; i < 23000; ++i)
  2369. body = std::max (body, std::abs (l[i]));
  2370. for (std::size_t i = 25000; i < 48000; ++i)
  2371. tail = std::max (tail, std::abs (l[i]));
  2372. CHECK (body > 0.1f);
  2373. CHECK (tail == 0.0f);
  2374. }
  2375. TEST (synth_oscillator_pan_and_semitones)
  2376. {
  2377. auto render = [] (lynx::SynthSettings s, std::vector<float>& l, std::vector<float>& r) {
  2378. auto synth = lynx::makeInstrument (lynx::InstrumentKind::synth);
  2379. synth->prepare (48000.0);
  2380. lynx::ChannelDef c;
  2381. c.synth = s;
  2382. synth->configure (c, 120.0);
  2383. synth->noteOn (69, 1.0f);
  2384. l.assign (24000, 0.0f);
  2385. r.assign (24000, 0.0f);
  2386. synth->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  2387. };
  2388. lynx::SynthSettings s;
  2389. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f, 7, 1.0f }; // a fifth up, fully right
  2390. s.cutoff = 20000.0f;
  2391. std::vector<float> l, r;
  2392. render (s, l, r);
  2393. float peakL = 0.0f, peakR = 0.0f;
  2394. int crossings = 0;
  2395. for (std::size_t i = 4800; i < 24000; ++i)
  2396. {
  2397. peakL = std::max (peakL, std::abs (l[i]));
  2398. peakR = std::max (peakR, std::abs (r[i]));
  2399. crossings += (r[i - 1] < 0.0f) != (r[i] < 0.0f);
  2400. }
  2401. CHECK (peakL < 1e-4f && peakR > 0.1f);
  2402. // 440 * 2^(7/12) = 659.3 Hz; 0.4 s = 263.7 cycles = ~527 crossings
  2403. CHECK (std::abs (crossings - 527) < 6);
  2404. }
  2405. TEST (fl_wrapper_state_parses_records_and_vst3_state)
  2406. {
  2407. // Fruity Wrapper blob (version 12): VST3 generator type, class ID, name, path and state
  2408. std::vector<std::uint8_t> blob;
  2409. 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))); };
  2410. auto record = [&] (std::vector<std::uint8_t>& b, std::uint32_t id, const std::vector<std::uint8_t>& payload) {
  2411. u32 (b, id);
  2412. u32 (b, (std::uint32_t) payload.size());
  2413. u32 (b, 0);
  2414. b.insert (b.end(), payload.begin(), payload.end());
  2415. };
  2416. auto bytes = [] (const std::string& s) { return std::vector<std::uint8_t> (s.begin(), s.end()); };
  2417. std::vector<std::uint8_t> vst3State;
  2418. u32 (vst3State, 1);
  2419. record (vst3State, 1, std::vector<std::uint8_t> (64, 0));
  2420. record (vst3State, 3, bytes ("COMPONENTE"));
  2421. record (vst3State, 2, bytes ("CONTROLADOR"));
  2422. // record 4: 3 slots → ParamIDs 700, −1 (empty), 0xFFFFFF01
  2423. std::vector<std::uint8_t> slots;
  2424. for (auto v : { 3u, 700u, 0xFFFFFFFFu, 0xFFFFFF01u })
  2425. u32 (slots, v);
  2426. record (vst3State, 4, slots);
  2427. u32 (blob, 12);
  2428. record (blob, 0x01, std::vector<std::uint8_t> (20, 0xFF));
  2429. record (blob, 0x32, { 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });
  2430. std::vector<std::uint8_t> cid;
  2431. for (int i = 0; i < 16; ++i)
  2432. cid.push_back ((std::uint8_t) (0xA0 + i));
  2433. record (blob, 0x34, cid);
  2434. record (blob, 0x36, bytes ("Surge XT"));
  2435. record (blob, 0x37, bytes ("C:/Program Files/Common Files/VST3/Surge XT.vst3"));
  2436. record (blob, 0x35, vst3State);
  2437. lynx::ForeignPlugin p;
  2438. CHECK (lynx::parseFlWrapper (blob, p));
  2439. CHECK (p.format == lynx::ForeignPlugin::Format::vst3);
  2440. CHECK (p.hasClassId && p.classId[0] == 0xA0 && p.classId[15] == 0xAF);
  2441. CHECK (p.name == "Surge XT" && p.path.find ("Surge XT.vst3") != std::string::npos);
  2442. std::vector<std::uint8_t> component, controller;
  2443. CHECK (lynx::splitFlVst3State (p.state, component, controller));
  2444. CHECK (component == bytes ("COMPONENTE") && controller == bytes ("CONTROLADOR"));
  2445. const auto saved = lynx::flVst3ParamSlots (p.state);
  2446. CHECK (saved == (std::vector<std::int32_t> { 700, -1, (std::int32_t) 0xFFFFFF01u }));
  2447. // FL's slot assignment: saved slots keep their ParamID wherever it now sits; the empty slot stays empty;
  2448. // a vanished ParamID (0xFFFFFF01) leaves its slot dead; parameters without a slot get slots 3, 4… in list order
  2449. const auto positions = lynx::flVst3SlotPositions (saved, { 5u, 700u, 9u });
  2450. CHECK (positions == (std::vector<int> { 1, -1, -1, 0, 2 }));
  2451. CHECK (lynx::flVst3SlotPositions ({}, { 5u, 6u }) == (std::vector<int> { 0, 1 })); // new instance: slot = position
  2452. // version out of range or no type: not a usable wrapper
  2453. blob[0] = 13;
  2454. CHECK (! lynx::parseFlWrapper (blob, p));
  2455. CHECK (! lynx::parseFlWrapper ({ 12, 0, 0, 0 }, p));
  2456. }
  2457. TEST (schedule_index_matches_full_scan)
  2458. {
  2459. // random song (long notes, swing, clips with offset); indexed scheduling must yield
  2460. // exactly the same events as the full scan, including in the block that wraps around
  2461. lynx::Song s = lynx::Song::makeDefault();
  2462. s.swing = 0.6f;
  2463. std::uint32_t seed = 12345;
  2464. auto rnd = [&] (int n) { seed = seed * 1664525u + 1013904223u; return (int) ((seed >> 8) % (std::uint32_t) n); };
  2465. s.patterns.resize (3);
  2466. for (auto& p : s.patterns)
  2467. {
  2468. p.notes.clear();
  2469. for (int i = 0; i < 60; ++i)
  2470. {
  2471. lynx::Note n;
  2472. n.start = rnd (16 * lynx::ppq);
  2473. n.length = rnd (5) == 0 ? rnd (12 * lynx::ppq) + 1 : rnd (lynx::ppq) + 1;
  2474. n.channel = rnd (4);
  2475. n.key = 40 + rnd (40);
  2476. n.slide = rnd (20) == 0;
  2477. p.notes.push_back (n);
  2478. }
  2479. p.sortNotes();
  2480. }
  2481. s.playlist.clear();
  2482. for (int i = 0; i < 12; ++i)
  2483. {
  2484. lynx::Clip c;
  2485. c.pattern = rnd (3);
  2486. c.track = rnd (4);
  2487. c.start = rnd (40) * lynx::ppq;
  2488. c.length = (rnd (12) + 1) * lynx::ppq;
  2489. c.offset = rnd (4) * lynx::ppq;
  2490. s.playlist.push_back (c);
  2491. }
  2492. s.mode = lynx::PlayMode::song;
  2493. const auto index = lynx::makeScheduleIndex (s);
  2494. const auto tps = lynx::ticksPerSample (140.0, 48000.0);
  2495. const auto loop = (double) s.songLength();
  2496. int mismatches = 0, events = 0;
  2497. for (int block = 0; block < 400; ++block)
  2498. {
  2499. const auto start = block == 0 ? loop - 100.0 * tps : (double) rnd ((int) loop * 2);
  2500. const auto samples = 64 + rnd (24000); // up to ~1 beat per block
  2501. lynx::EventBuffer a, b;
  2502. lynx::scheduleSong (s, start, samples, tps, a, false, nullptr);
  2503. lynx::scheduleSong (s, start, samples, tps, b, false, &index);
  2504. events += a.size();
  2505. if (a.size() != b.size())
  2506. {
  2507. ++mismatches;
  2508. continue;
  2509. }
  2510. for (int i = 0; i < a.size(); ++i)
  2511. {
  2512. const auto& x = *(a.begin() + i);
  2513. const auto& y = *(b.begin() + i);
  2514. mismatches += x.sampleOffset != y.sampleOffset || x.type != y.type || x.key != y.key || x.channel != y.channel;
  2515. }
  2516. }
  2517. CHECK (events > 500);
  2518. CHECK (mismatches == 0);
  2519. }
  2520. TEST (mixer_track_eq_defaults_and_boost)
  2521. {
  2522. // FL defaults: 90 Hz, 1.5 kHz and 8 kHz; peak Q 0.632; shelf slope 0.607
  2523. lynx::TrackEq eq;
  2524. CHECK (std::abs (lynx::TrackEq::peakQ (eq.width[1]) - 0.632) < 0.01);
  2525. CHECK (std::abs (lynx::TrackEq::shelfSlope (eq.width[0]) - 0.607) < 0.01);
  2526. CHECK (! eq.active());
  2527. // +12 dB peak at 1.5 kHz on a track: a 1.5 kHz sine rises ~4x
  2528. lynx::Song song = lynx::Song::makeDefault();
  2529. song.mixer[1].eq.gainDb[1] = 12.0f;
  2530. for (auto& c : song.channels)
  2531. c.mixerTrack = 1;
  2532. song.channels[4].instrument = lynx::InstrumentKind::synth;
  2533. song.channels[4].synth = {};
  2534. song.channels[4].synth.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  2535. song.channels[4].synth.cutoff = 20000.0f;
  2536. auto render = [] (const lynx::Song& s) {
  2537. auto state = lynx::RackState::build (s, nullptr, 48000.0);
  2538. lynx::RackRenderer renderer;
  2539. renderer.prepare (48000.0);
  2540. lynx::LiveEventQueue live;
  2541. lynx::NoteEvent on; // 1.5 kHz ~ key 90.6: use 91 (1568 Hz), still within the wide peak
  2542. on.channel = 4;
  2543. on.key = 91;
  2544. on.velocity = 1.0f;
  2545. live.push (on);
  2546. std::vector<float> l (24000), r (24000);
  2547. for (int pos = 0; pos < 24000; pos += 480)
  2548. renderer.process (state.get(), false, 0.0, 480, l.data() + pos, r.data() + pos, pos == 0 ? &live : nullptr);
  2549. float peak = 0.0f;
  2550. for (std::size_t i = 12000; i < 24000; ++i)
  2551. peak = std::max (peak, std::abs (l[i]));
  2552. return peak;
  2553. };
  2554. const auto boosted = render (song);
  2555. song.mixer[1].eq.gainDb[1] = 0.0f;
  2556. const auto flat = render (song);
  2557. CHECK (flat > 0.01f);
  2558. CHECK (boosted / flat > 3.0f && boosted / flat < 4.2f);
  2559. }
  2560. TEST (bars_follow_time_signature_markers)
  2561. {
  2562. lynx::Song song;
  2563. song.beatsPerBar = 4;
  2564. const auto bar4 = (std::int64_t) lynx::ppq * 4;
  2565. auto bars = song.barsBetween (0, bar4 * 3);
  2566. CHECK (bars.size() == 3 && bars[2].tick == bar4 * 2 && bars[2].number == 3);
  2567. // 7/4 from bar 3, and 3/4 in the middle of a 7 bar (cuts and restarts)
  2568. song.addMarker ({ bar4 * 2, "Verso", 7, 4 });
  2569. song.addMarker ({ bar4, "Nome só", 0, 4 });
  2570. const auto seven = (std::int64_t) lynx::ppq * 7;
  2571. song.addMarker ({ bar4 * 2 + seven + lynx::ppq * 2, "", 3, 4 });
  2572. bars = song.barsBetween (0, bar4 * 2 + seven * 2);
  2573. CHECK (bars.size() >= 5);
  2574. CHECK (bars[1].length == bar4 && bars[2].tick == bar4 * 2 && bars[2].length == seven);
  2575. CHECK (bars[3].length == lynx::ppq * 2); // cut short by the change
  2576. CHECK (bars[4].length == lynx::ppq * 3 && bars[4].number == 5);
  2577. CHECK (song.markers()[0].name == "Nome só"); // sorted by tick
  2578. // from far away: starts at the right bar without losing the numbering
  2579. const auto far = song.barsBetween (lynx::ppq * 3000, lynx::ppq * 3001);
  2580. CHECK (far.size() == 1 && far[0].length == lynx::ppq * 3);
  2581. CHECK (song.barAt (lynx::ppq * 3000).number == far[0].number);
  2582. CHECK ((lynx::ppq * 3000 - far[0].tick) < far[0].length);
  2583. }
  2584. TEST (split_drum_channel_moves_notes_to_pads)
  2585. {
  2586. lynx::Song song = lynx::Song::makeDefault();
  2587. const auto channels = (int) song.channels.size();
  2588. song.patterns[0].notes.clear();
  2589. song.patterns[0].notes.push_back ({ 0, 240, 1, 36, 0.9f }); // kit kick (channel 1)
  2590. song.patterns[0].notes.push_back ({ 240, 240, 1, 38, 0.8f }); // snare
  2591. song.patterns[0].notes.push_back ({ 480, 240, 1, 50, 0.8f }); // key without a pad: dropped
  2592. song.patterns[0].notes.push_back ({ 480, 240, 3, 60, 0.8f }); // other channel: shifts by 1 position
  2593. lynx::Automation a;
  2594. a.target = { lynx::AutomationTargetKind::channelVolume, 3, 0, 0 };
  2595. song.automations.push_back (a);
  2596. std::vector<lynx::DrumPad> pads (2);
  2597. pads[0].name = "Kick";
  2598. pads[0].key = 36;
  2599. pads[0].layers = { { "kick.wav" } };
  2600. pads[1].name = "Snare";
  2601. pads[1].key = 38;
  2602. pads[1].layers = { { "snare soft.wav", 60, 0, 127, 0, 90 }, { "snare hard.wav", 60, 0, 127, 91, 127 } };
  2603. pads[1].cutGroup = 2;
  2604. pads[1].cutBy = 2;
  2605. lynx::splitDrumChannel (song, 1, pads);
  2606. CHECK ((int) song.channels.size() == channels + 1);
  2607. CHECK (song.channels[1].samplePath == "kick.wav" && song.channels[1].instrument == lynx::InstrumentKind::sampler);
  2608. CHECK (song.channels[2].zones.size() == 2 && song.channels[2].cutGroup == song.channels[2].cutBy && song.channels[2].cutGroup != 0);
  2609. const auto& notes = song.patterns[0].notes;
  2610. CHECK (notes.size() == 3);
  2611. CHECK (notes[0].channel == 1 && notes[0].key == 60);
  2612. CHECK (notes[1].channel == 2 && notes[1].key == 60);
  2613. CHECK (notes[2].channel == 4); // the old channel 3
  2614. CHECK (song.automations[0].target.index == 4);
  2615. }
  2616. TEST (flp_import_brings_playlist)
  2617. {
  2618. flp::Project p;
  2619. p.header.ppq = 96;
  2620. p.channels = { { 0, flp::ChannelType::sampler, "Kick", "", "", 1 } };
  2621. flp::Pattern empty;
  2622. empty.index = 1;
  2623. flp::Pattern full;
  2624. full.index = 2;
  2625. flp::Note n;
  2626. n.channel = 0;
  2627. full.notes.push_back (n);
  2628. p.patterns = { empty, full };
  2629. flp::Arrangement a;
  2630. flp::PlaylistItem item;
  2631. item.kind = flp::PlaylistItem::Kind::pattern;
  2632. item.index = 2;
  2633. item.position = 384;
  2634. item.length = 192;
  2635. item.track = 3;
  2636. item.patternStartTick = 96;
  2637. a.items.push_back (item);
  2638. item.index = 1; // empty pattern: discarded
  2639. a.items.push_back (item);
  2640. item.kind = flp::PlaylistItem::Kind::channelClip; // audio: not supported yet
  2641. a.items.push_back (item);
  2642. p.arrangements.push_back (a);
  2643. const auto s = lynx::importFlp (p);
  2644. CHECK (s.mode == lynx::PlayMode::song);
  2645. CHECK (s.playlist.size() == 1);
  2646. CHECK (s.playlist[0].pattern == 0 && s.playlist[0].track == 3);
  2647. CHECK (s.playlist[0].start == 4 * lynx::ppq && s.playlist[0].length == 2 * lynx::ppq && s.playlist[0].offset == lynx::ppq);
  2648. }
  2649. TEST (rack_releases_notes_on_position_jump)
  2650. {
  2651. lynx::Song s;
  2652. lynx::ChannelDef c;
  2653. c.instrument = lynx::InstrumentKind::synth;
  2654. s.channels.push_back (c);
  2655. auto& p = s.patterns.emplace_back();
  2656. lynx::Note n;
  2657. n.start = 0;
  2658. n.length = 4 * lynx::ppq; // long note
  2659. p.notes.push_back (n);
  2660. s.bpm = 120.0;
  2661. auto state = lynx::RackState::build (s, nullptr, 48000.0);
  2662. lynx::RackRenderer r;
  2663. r.prepare (48000.0);
  2664. std::vector<float> l (512), rr (512);
  2665. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  2666. double tick = 0.0;
  2667. for (int i = 0; i < 20; ++i, tick += 512 * tps)
  2668. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  2669. // jump to tick 2000 (mid-note, no new "on"): the synth must go silent
  2670. for (int i = 0; i < 40; ++i)
  2671. r.process (state.get(), true, 2000.0 + i * 512 * tps, 512, l.data(), rr.data());
  2672. float tail = 0.0f;
  2673. for (auto v : l)
  2674. tail = std::max (tail, std::abs (v));
  2675. CHECK (tail < 0.001f);
  2676. }
  2677. namespace
  2678. {
  2679. // Two samplers with a constant 0.5 signal on different inserts; returns the output peak.
  2680. float juce_db (float gain)
  2681. {
  2682. return 20.0f * std::log10 (gain);
  2683. }
  2684. float renderMixerCase (const std::function<void (lynx::Song&)>& tweak, lynx::MeterBank* meters = nullptr)
  2685. {
  2686. lynx::Song s;
  2687. s.mixer = lynx::Song::defaultMixer (4);
  2688. for (int i = 0; i < 2; ++i)
  2689. {
  2690. lynx::ChannelDef c;
  2691. c.instrument = lynx::InstrumentKind::sampler;
  2692. c.samplePath = "dc";
  2693. c.volume = 1.0f;
  2694. c.mixerTrack = i + 1;
  2695. s.channels.push_back (c);
  2696. }
  2697. s.patterns.emplace_back();
  2698. tweak (s);
  2699. auto provider = [] (const std::string&) {
  2700. auto d = std::make_shared<lynx::SampleData>();
  2701. d->left.assign (48000, 0.5f);
  2702. return std::shared_ptr<const lynx::SampleData> (d);
  2703. };
  2704. auto state = lynx::RackState::build (s, nullptr, 48000.0, provider);
  2705. lynx::RackRenderer r;
  2706. r.prepare (48000.0, 256);
  2707. lynx::LiveEventQueue live;
  2708. for (int ch = 0; ch < 2; ++ch)
  2709. {
  2710. lynx::NoteEvent on;
  2711. on.channel = ch;
  2712. on.velocity = 1.0f;
  2713. live.push (on);
  2714. }
  2715. std::vector<float> l (1000), rr (1000); // larger than the mixer block: tests the chunking
  2716. r.process (state.get(), false, 0.0, 1000, l.data(), rr.data(), &live, meters);
  2717. return std::max (std::abs (l[999]), std::abs (rr[999]));
  2718. }
  2719. } // namespace
  2720. TEST (mixer_routes_mutes_solos_and_meters)
  2721. {
  2722. // two 0.5 channels summed on the Master at 0 dB
  2723. CHECK (std::abs (renderMixerCase ([] (lynx::Song&) {}) - 1.0f) < 1e-4f);
  2724. // insert 1 muted: only channel 2 remains
  2725. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.mixer[1].muted = true; }) - 0.5f) < 1e-4f);
  2726. // solo on insert 2: same
  2727. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.mixer[2].solo = true; }) - 0.5f) < 1e-4f);
  2728. // FL fader curve: 0.8 = 0 dB, max ≈ +5.6 dB, half travel ≈ -12.7 dB
  2729. CHECK (std::abs (lynx::faderGain (0.8f) - 1.0f) < 1e-5f);
  2730. CHECK (std::abs (juce_db (lynx::faderGain (1.0f)) - 5.59f) < 0.05f);
  2731. CHECK (lynx::faderGain (0.0f) == 0.0f);
  2732. // Master fader at max
  2733. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.mixer[0].volume = 1.0f; }) - lynx::faderGain (1.0f)) < 1e-4f);
  2734. // both channels on the same insert, insert fader at 0.4
  2735. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) {
  2736. s.channels[1].mixerTrack = 1;
  2737. s.mixer[1].volume = 0.4f;
  2738. }) - lynx::faderGain (0.4f)) < 1e-4f);
  2739. // a route outside the mixer falls to the last existing insert, without crashing
  2740. CHECK (renderMixerCase ([] (lynx::Song& s) { s.channels[0].mixerTrack = 100; }) > 0.9f);
  2741. // no mixer: everything straight to the output at 0 dB
  2742. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.mixer.clear(); }) - 1.0f) < 1e-4f);
  2743. lynx::MeterBank meters;
  2744. renderMixerCase ([] (lynx::Song&) {}, &meters);
  2745. CHECK (std::abs (meters.takePeak (1, 0) - 0.5f) < 1e-4f);
  2746. CHECK (std::abs (meters.takePeak (0, 1) - 1.0f) < 1e-4f);
  2747. CHECK (meters.takePeak (1, 0) == 0.0f); // reading resets
  2748. CHECK (meters.takePeak (3, 0) == 0.0f); // insert with no channel
  2749. }
  2750. TEST (next_free_insert_and_flp_mixer_import)
  2751. {
  2752. auto s = lynx::Song::makeDefault();
  2753. CHECK (s.mixer.size() == 17 && s.mixer[0].name == "Master");
  2754. CHECK (s.nextFreeInsert() == 6); // the 5 default channels take 1..5
  2755. flp::Project p;
  2756. p.channels = { { 0, flp::ChannelType::sampler, "Kick", "", "", 30 } };
  2757. p.mixer = { { 0, "" }, { 30, "Drums" } };
  2758. const auto song = lynx::importFlp (p);
  2759. CHECK (song.channels[0].mixerTrack == 30);
  2760. CHECK (song.mixer.size() == 31);
  2761. CHECK (song.mixer[30].name == "Drums" && song.mixer[0].name == "Master");
  2762. }
  2763. namespace
  2764. {
  2765. float runEffectOnSine (lynx::EffectKind kind, const std::function<void (lynx::EffectSlot&)>& tweak, double hz, float amp,
  2766. int frames = 48000)
  2767. {
  2768. auto fx = lynx::makeEffect (kind);
  2769. fx->prepare (48000.0);
  2770. auto slot = lynx::makeEffectSlot (kind);
  2771. tweak (slot);
  2772. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  2773. for (int i = 0; i < frames; ++i)
  2774. l[(std::size_t) i] = r[(std::size_t) i] = amp * (float) std::sin (6.283185307 * hz * i / 48000.0);
  2775. for (int i = 0; i < frames; i += 480)
  2776. fx->process (l.data() + i, r.data() + i, std::min (480, frames - i), slot.params, 120.0);
  2777. float peak = 0.0f;
  2778. for (int i = frames / 2; i < frames; ++i) // second half: already settled
  2779. {
  2780. CHECK (std::isfinite (l[(std::size_t) i]));
  2781. peak = std::max (peak, std::abs (l[(std::size_t) i]));
  2782. }
  2783. return peak;
  2784. }
  2785. } // namespace
  2786. TEST (parametric_eq_bands_and_response)
  2787. {
  2788. // default: transparent
  2789. auto slot = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  2790. CHECK (std::abs (lynx::peq::responseDb (slot.params, 48000.0, 1000.0)) < 0.01);
  2791. CHECK (std::abs (runEffectOnSine (lynx::EffectKind::parametricEq, [] (auto&) {}, 1000.0, 0.5f) - 0.5f) < 0.005f);
  2792. // +12 dB peak at 1 kHz on band 4: the response and the signal agree
  2793. auto boost = [] (lynx::EffectSlot& s) {
  2794. s.params[(std::size_t) lynx::peq::param (3, 1)] = lynx::peq::hzValue (1000.0);
  2795. s.params[(std::size_t) lynx::peq::param (3, 2)] = lynx::peq::gainValue (12.0);
  2796. };
  2797. boost (slot);
  2798. CHECK (std::abs (lynx::peq::responseDb (slot.params, 48000.0, 1000.0) - 12.0) < 0.2);
  2799. CHECK (std::abs (lynx::peq::responseDb (slot.params, 48000.0, 100.0)) < 1.0);
  2800. const auto peak = runEffectOnSine (lynx::EffectKind::parametricEq, boost, 1000.0, 0.1f);
  2801. CHECK (std::abs (peak - 0.1f * std::pow (10.0f, 12.0f / 20.0f)) < 0.01f);
  2802. // low cut at 48 dB/oct at 200 Hz: 50 Hz (2 octaves below) drops ~96 dB; 2 kHz passes
  2803. auto cut = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  2804. cut.params[(std::size_t) lynx::peq::param (0, 0)] = lynx::peq::typeValue (lynx::peq::BandType::lowCut);
  2805. cut.params[(std::size_t) lynx::peq::param (0, 1)] = lynx::peq::hzValue (200.0);
  2806. cut.params[(std::size_t) lynx::peq::param (0, 3)] = lynx::peq::qValue (0.70710678); // Butterworth
  2807. cut.params[(std::size_t) (lynx::peq::slopeParam + 0)] = 1.0f;
  2808. CHECK (lynx::peq::responseDb (cut.params, 48000.0, 50.0) < -80.0);
  2809. CHECK (std::abs (lynx::peq::responseDb (cut.params, 48000.0, 200.0) + 3.0) < 0.5); // -3 dB at the cutoff (Butterworth)
  2810. CHECK (std::abs (lynx::peq::responseDb (cut.params, 48000.0, 2000.0)) < 0.1);
  2811. // round-trip conversions
  2812. CHECK (std::abs (lynx::peq::hz (lynx::peq::hzValue (440.0)) - 440.0) < 0.5);
  2813. CHECK (std::abs (lynx::peq::q (lynx::peq::qValue (2.5)) - 2.5) < 0.01);
  2814. CHECK (lynx::peq::type (lynx::peq::typeValue (lynx::peq::BandType::notch)) == lynx::peq::BandType::notch);
  2815. }
  2816. TEST (fl_parametric_eq2_state_maps_to_bands)
  2817. {
  2818. // v8 blob: band 1 low cut at 100 Hz "Steep 8", band 4 peak +6 dB at 1 kHz, output −3 dB
  2819. std::vector<std::uint8_t> blob (354, 0);
  2820. auto put = [&] (std::size_t off, std::int32_t v) { std::memcpy (blob.data() + off, &v, 4); };
  2821. put (0, 8);
  2822. auto param = [&] (int i, std::int32_t v) { put (4 + 4 * (std::size_t) i, v); };
  2823. auto hzRaw = [] (double hz) { return (std::int32_t) std::lround (std::log (hz / 20.0) / std::log (1000.0) * 65536.0); };
  2824. for (int b = 0; b < 7; ++b)
  2825. param (21 + b, 0); // all off
  2826. param (21 + 0, 3); // high pass (= low cut)
  2827. param (7 + 0, hzRaw (100.0));
  2828. param (14 + 0, 40124); // default width -> Q ~0.68
  2829. param (28 + 0, -3); // Steep 8 -> 4 biquads
  2830. param (21 + 3, 6); // peaking
  2831. param (7 + 3, hzRaw (1000.0));
  2832. param (3, 600); // +6 dB
  2833. param (14 + 3, 25412);
  2834. param (35, -300); // main level −3 dB
  2835. put (0x13E, 0x7F);
  2836. const auto slot = lynx::effectFromFl ("Fruity Parametric EQ 2", blob);
  2837. CHECK (slot.has_value() && slot->kind == lynx::EffectKind::parametricEq);
  2838. const auto& p = slot->params;
  2839. CHECK (lynx::peq::type (p[(std::size_t) lynx::peq::param (0, 0)]) == lynx::peq::BandType::lowCut);
  2840. CHECK (lynx::peq::slopeStages (p[(std::size_t) lynx::peq::slopeParam]) == 4);
  2841. CHECK (lynx::peq::type (p[(std::size_t) lynx::peq::param (3, 0)]) == lynx::peq::BandType::peak);
  2842. CHECK (lynx::peq::type (p[(std::size_t) lynx::peq::param (1, 0)]) == lynx::peq::BandType::off);
  2843. CHECK (std::abs (lynx::peq::responseDb (p, 48000.0, 1000.0) - 3.0) < 0.3); // +6 from the peak −3 from the output
  2844. CHECK (lynx::peq::responseDb (p, 48000.0, 30.0) < -40.0); // 48 dB/oct below 100 Hz
  2845. CHECK (std::abs (lynx::peq::responseDb (p, 48000.0, 8000.0) + 3.0) < 0.3);
  2846. // a band muted by the mask doesn't sound
  2847. put (0x13E, 0x7F & ~(1 << 3));
  2848. const auto muted = lynx::effectFromFl ("Fruity Parametric EQ 2", blob);
  2849. CHECK (lynx::peq::type (muted->params[(std::size_t) lynx::peq::param (3, 0)]) == lynx::peq::BandType::off);
  2850. }
  2851. TEST (reverb_low_cut_and_predelay)
  2852. {
  2853. // impulse: with 100 ms predelay the wet only starts later; with a 3 kHz low cut a
  2854. // 100 Hz sine barely enters the reverb
  2855. auto run = [] (const std::function<void (lynx::EffectSlot&)>& tweak, double hz, bool impulse) {
  2856. auto fx = lynx::makeEffect (lynx::EffectKind::reverb);
  2857. fx->prepare (48000.0);
  2858. auto slot = lynx::makeEffectSlot (lynx::EffectKind::reverb);
  2859. slot.params[4] = 0.0f; // wet only
  2860. slot.params[3] = 1.0f;
  2861. tweak (slot);
  2862. std::vector<float> l (48000), r (48000);
  2863. for (int i = 0; i < 48000; ++i)
  2864. 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);
  2865. for (int i = 0; i < 48000; i += 480)
  2866. fx->process (l.data() + i, r.data() + i, 480, slot.params, 120.0);
  2867. return l;
  2868. };
  2869. const auto delayed = run ([] (auto& s) { s.params[7] = 0.1f; }, 0.0, true);
  2870. float early = 0.0f, later = 0.0f;
  2871. for (std::size_t i = 0; i < 4800; ++i)
  2872. early = std::max (early, std::abs (delayed[i]));
  2873. for (std::size_t i = 4800; i < 24000; ++i)
  2874. later = std::max (later, std::abs (delayed[i]));
  2875. CHECK (early == 0.0f && later > 0.0f);
  2876. 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; };
  2877. const auto open = energy (run ([] (auto&) {}, 100.0, false));
  2878. const auto cut = energy (run ([] (auto& s) { s.params[5] = 1.0f; }, 100.0, false));
  2879. CHECK (cut < open * 0.01);
  2880. }
  2881. TEST (utility_effect_and_fl_stereo_tools)
  2882. {
  2883. // transparent by default; balance fully right silences the left
  2884. CHECK (std::abs (runEffectOnSine (lynx::EffectKind::utility, [] (auto&) {}, 440.0, 0.5f) - 0.5f) < 0.001f);
  2885. CHECK (runEffectOnSine (lynx::EffectKind::utility, [] (auto& s) { s.params[1] = 1.0f; }, 440.0, 0.5f) < 0.001f);
  2886. // Stereo Shaper in "mono": each output = 0.5 L + 0.5 R
  2887. std::vector<std::uint8_t> blob (36, 0);
  2888. auto put = [&] (std::size_t off, std::int32_t v) { std::memcpy (blob.data() + off, &v, 4); };
  2889. put (4, 6400); put (8, 6400); put (12, 6400); put (16, 6400);
  2890. const auto slot = lynx::effectFromFl ("Fruity Stereo Shaper", blob);
  2891. CHECK (slot && slot->kind == lynx::EffectKind::utility);
  2892. auto fx = lynx::makeEffect (lynx::EffectKind::utility);
  2893. float l = 1.0f, r = 0.0f;
  2894. fx->process (&l, &r, 1, slot->params, 120.0);
  2895. CHECK (std::abs (l - 0.5f) < 1e-4f && std::abs (r - 0.5f) < 1e-4f);
  2896. // Balance: volume 256 = 0 dB, pan −128 = fully left
  2897. std::vector<std::uint8_t> bal (8, 0);
  2898. std::int32_t pan = -128, vol = 256;
  2899. std::memcpy (bal.data(), &pan, 4);
  2900. std::memcpy (bal.data() + 4, &vol, 4);
  2901. const auto b = lynx::effectFromFl ("Fruity Balance", bal);
  2902. l = 0.5f; r = 0.5f;
  2903. fx->process (&l, &r, 1, b->params, 120.0);
  2904. CHECK (std::abs (l - 0.5f) < 1e-3f && std::abs (r) < 1e-4f);
  2905. }
  2906. TEST (effects_eq_compressor_behave)
  2907. {
  2908. // EQ at default is transparent
  2909. CHECK (std::abs (runEffectOnSine (lynx::EffectKind::eq, [] (auto&) {}, 1000.0, 0.5f) - 0.5f) < 0.01f);
  2910. // +18 dB on the lows: 60 Hz rises a lot, 5 kHz barely
  2911. CHECK (runEffectOnSine (lynx::EffectKind::eq, [] (auto& s) { s.params[0] = 1.0f; }, 60.0, 0.05f) > 0.3f);
  2912. CHECK (runEffectOnSine (lynx::EffectKind::eq, [] (auto& s) { s.params[0] = 1.0f; }, 5000.0, 0.05f) < 0.06f);
  2913. // compressor: threshold -20 dB, ratio 20:1 flattens a 0 dBFS signal to near the threshold
  2914. const auto squashed = runEffectOnSine (lynx::EffectKind::compressor, [] (auto& s) {
  2915. s.params[0] = 40.0f / 60.0f;
  2916. s.params[1] = 1.0f;
  2917. }, 200.0, 1.0f);
  2918. CHECK (squashed < 0.2f && squashed > 0.05f);
  2919. // a signal below the threshold passes intact
  2920. CHECK (std::abs (runEffectOnSine (lynx::EffectKind::compressor, [] (auto& s) { s.params[0] = 1.0f; }, 200.0, 0.3f) - 0.3f) < 0.01f);
  2921. }
  2922. TEST (effects_delay_echoes_on_tempo_and_reverb_has_tail)
  2923. {
  2924. auto delay = lynx::makeEffect (lynx::EffectKind::delay);
  2925. delay->prepare (48000.0);
  2926. auto slot = lynx::makeEffectSlot (lynx::EffectKind::delay);
  2927. slot.params[0] = 3.5f / 8.0f; // index 3 = 1/4 = 0.5 s at 120 BPM
  2928. slot.params[1] = 0.0f; // no feedback: a single echo
  2929. slot.params[2] = 1.0f;
  2930. slot.params[4] = 0.0f; // no damping
  2931. std::vector<float> l (48000, 0.0f), r (48000, 0.0f);
  2932. l[0] = r[0] = 1.0f;
  2933. delay->process (l.data(), r.data(), 48000, slot.params, 120.0);
  2934. CHECK (std::abs (l[24000] - 1.0f) < 1e-4f);
  2935. CHECK (std::abs (l[12000]) < 1e-6f);
  2936. auto reverb = lynx::makeEffect (lynx::EffectKind::reverb);
  2937. reverb->prepare (48000.0);
  2938. auto rs = lynx::makeEffectSlot (lynx::EffectKind::reverb);
  2939. rs.params[3] = 1.0f;
  2940. std::fill (l.begin(), l.end(), 0.0f);
  2941. std::fill (r.begin(), r.end(), 0.0f);
  2942. l[0] = r[0] = 1.0f;
  2943. reverb->process (l.data(), r.data(), 48000, rs.params, 120.0);
  2944. float tail = 0.0f;
  2945. for (int i = 4800; i < 9600; ++i) // between 100 and 200 ms after the impulse
  2946. tail = std::max (tail, std::abs (l[(std::size_t) i]));
  2947. CHECK (tail > 1e-4f && tail < 1.0f);
  2948. CHECK (lynx::formatEffectParam (lynx::EffectKind::delay, 0, slot.params[0], 120.0) == "1/4 (500 ms)");
  2949. }
  2950. TEST (rack_runs_insert_effects_and_reuses_them)
  2951. {
  2952. // an insert with EQ at -inf doesn't exist; we use the EQ output at -18 dB to see the effect act
  2953. const auto quiet = renderMixerCase ([] (lynx::Song& s) {
  2954. auto eq = lynx::makeEffectSlot (lynx::EffectKind::eq);
  2955. eq.params[4] = 0.0f; // output -18 dB
  2956. s.mixer[1].effects.push_back (eq);
  2957. });
  2958. CHECK (quiet > 0.55f && quiet < 0.6f); // 0.5 from channel 2 + 0.5 * 0.126 from channel 1
  2959. const auto bypassed = renderMixerCase ([] (lynx::Song& s) {
  2960. auto eq = lynx::makeEffectSlot (lynx::EffectKind::eq);
  2961. eq.params[4] = 0.0f;
  2962. eq.enabled = false;
  2963. s.mixer[1].effects.push_back (eq);
  2964. });
  2965. CHECK (std::abs (bypassed - 1.0f) < 1e-4f);
  2966. auto s = lynx::Song::makeDefault();
  2967. s.mixer[2].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::reverb));
  2968. auto a = lynx::RackState::build (s, nullptr, 48000.0);
  2969. s.mixer[2].effects[0].params[0] = 0.9f; // turning a knob doesn't recreate the effect
  2970. auto b = lynx::RackState::build (s, a.get(), 48000.0);
  2971. CHECK (b->effects[2][0] == a->effects[2][0]);
  2972. s.mixer[2].effects[0] = lynx::makeEffectSlot (lynx::EffectKind::delay);
  2973. auto c = lynx::RackState::build (s, b.get(), 48000.0);
  2974. CHECK (c->effects[2][0] != b->effects[2][0]);
  2975. }
  2976. TEST (audio_clips_trigger_cut_and_resume)
  2977. {
  2978. lynx::Song s;
  2979. s.bpm = 120.0; // 1 beat = 0.5 s = 24000 samples at 48 kHz
  2980. lynx::ChannelDef c;
  2981. c.instrument = lynx::InstrumentKind::audioClip;
  2982. c.samplePath = "ramp";
  2983. c.volume = 1.0f;
  2984. s.channels.push_back (c);
  2985. s.patterns.emplace_back();
  2986. lynx::Clip clip;
  2987. clip.kind = lynx::ClipKind::audio;
  2988. clip.channel = 0;
  2989. clip.start = lynx::ppq; // starts at beat 2
  2990. clip.length = 2 * lynx::ppq; // lasts 2 beats
  2991. clip.offset = lynx::ppq; // skips the first beat of the audio
  2992. s.playlist.push_back (clip);
  2993. s.mode = lynx::PlayMode::song;
  2994. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  2995. lynx::EventBuffer ev;
  2996. lynx::scheduleSong (s, 0.0, 4 * 24000, tps, ev);
  2997. CHECK (ev.size() == 2);
  2998. CHECK (ev[0].type == lynx::NoteEvent::Type::on && ev[0].sampleOffset == 24000 && std::abs (ev[0].startSeconds - 0.5) < 1e-9);
  2999. CHECK (ev[1].type == lynx::NoteEvent::Type::off && ev[1].sampleOffset == 3 * 24000);
  3000. // seek to the middle of the clip (beat 2.5): with resume, starts at the block's first sample
  3001. ev.clear();
  3002. lynx::scheduleSong (s, 1.5 * lynx::ppq, 256, tps, ev, true);
  3003. CHECK (ev.size() == 1 && ev[0].sampleOffset == 0 && std::abs (ev[0].startSeconds - 0.75) < 1e-9);
  3004. ev.clear();
  3005. lynx::scheduleSong (s, 1.5 * lynx::ppq, 256, tps, ev, false);
  3006. CHECK (ev.size() == 0);
  3007. // sample whose value = position in seconds: lets us check where playback started
  3008. auto provider = [] (const std::string&) {
  3009. auto d = std::make_shared<lynx::SampleData>();
  3010. d->sampleRate = 48000.0;
  3011. for (int i = 0; i < 48000 * 3; ++i)
  3012. d->left.push_back ((float) i / 48000.0f);
  3013. return std::shared_ptr<const lynx::SampleData> (d);
  3014. };
  3015. auto state = lynx::RackState::build (s, nullptr, 48000.0, provider);
  3016. lynx::RackRenderer r;
  3017. r.prepare (48000.0, 512);
  3018. std::vector<float> l (256), rr (256);
  3019. // first block already playing mid-clip
  3020. r.process (state.get(), true, 1.5 * lynx::ppq, 256, l.data(), rr.data());
  3021. CHECK (std::abs (l[0] - 0.75f) < 0.001f);
  3022. // the clip ends at beat 3: after the short fade, silence (the sample would still have audio)
  3023. double tick = 3.0 * lynx::ppq - 10 * tps;
  3024. r.process (state.get(), false, tick, 256, l.data(), rr.data()); // stops (fade)
  3025. for (int i = 0; i < 4; ++i)
  3026. r.process (state.get(), false, tick, 256, l.data(), rr.data());
  3027. CHECK (std::abs (l[255]) < 1e-6f);
  3028. }
  3029. TEST (remove_channel_fixes_notes_and_audio_clips)
  3030. {
  3031. lynx::Song s;
  3032. s.channels.resize (3);
  3033. s.patterns.resize (1);
  3034. s.patterns[0].notes = { { 0, 240, 0, 60, 1.0f }, { 0, 240, 1, 60, 1.0f }, { 0, 240, 2, 60, 1.0f } };
  3035. lynx::Clip a;
  3036. a.kind = lynx::ClipKind::audio;
  3037. a.channel = 1;
  3038. a.length = 100;
  3039. lynx::Clip b = a;
  3040. b.channel = 2;
  3041. s.playlist = { a, b };
  3042. s.removeChannel (1);
  3043. CHECK (s.channels.size() == 2);
  3044. CHECK (s.patterns[0].notes.size() == 2 && s.patterns[0].notes[1].channel == 1);
  3045. CHECK (s.playlist.size() == 1 && s.playlist[0].channel == 1);
  3046. }
  3047. TEST (flp_import_audio_clips_with_offsets)
  3048. {
  3049. flp::Project p;
  3050. p.header.ppq = 96;
  3051. p.tempo = 120.0;
  3052. p.channels = { { 0, flp::ChannelType::audioClip, "Vocal", "", "%FLStudioData%\\v.wav", 2 },
  3053. { 1, flp::ChannelType::audioClip, "Loop", "", "%FLStudioData%\\l.wav", 3 } };
  3054. flp::Arrangement arr;
  3055. flp::PlaylistItem beats; // offset in beats: end - start = duration in beats
  3056. beats.kind = flp::PlaylistItem::Kind::channelClip;
  3057. beats.index = 0;
  3058. beats.position = 192;
  3059. beats.length = 384; // 4 beats
  3060. beats.startOffset = 2.0f;
  3061. beats.endOffset = 6.0f;
  3062. flp::PlaylistItem ms = beats; // offset in ms: 4 beats at 120 BPM = 2000 ms
  3063. ms.index = 1;
  3064. ms.startOffset = 500.0f;
  3065. ms.endOffset = 2500.0f;
  3066. arr.items = { beats, ms };
  3067. p.arrangements.push_back (arr);
  3068. lynx::FlpImportOptions options;
  3069. options.roots = { "C:\\FL", "C:\\FL\\Data", "" };
  3070. options.fileExists = [] (const std::string&) { return true; };
  3071. const auto s = lynx::importFlp (p, options);
  3072. CHECK (s.channels.size() == 2 && s.channels[0].instrument == lynx::InstrumentKind::audioClip);
  3073. CHECK (s.channels[0].samplePath == "C:\\FL\\Data\\v.wav");
  3074. CHECK (s.playlist.size() == 2);
  3075. CHECK (s.playlist[0].kind == lynx::ClipKind::audio && s.playlist[0].start == 2 * lynx::ppq);
  3076. CHECK (s.playlist[0].offset == 2 * lynx::ppq);
  3077. CHECK (s.playlist[1].offset == lynx::ppq); // 500 ms at 120 BPM = 1 beat
  3078. CHECK (s.mode == lynx::PlayMode::song);
  3079. }
  3080. TEST (plugin_factories_create_reuse_and_fallback)
  3081. {
  3082. lynx::Song s;
  3083. s.mixer = lynx::Song::defaultMixer (2);
  3084. lynx::ChannelDef c;
  3085. c.instrument = lynx::InstrumentKind::plugin;
  3086. c.plugin.id = "VST3-Synth-123";
  3087. c.mixerTrack = 1;
  3088. s.channels.push_back (c);
  3089. lynx::ChannelDef missing = c;
  3090. missing.plugin.id = "VST3-Ausente-0";
  3091. s.channels.push_back (missing);
  3092. lynx::EffectSlot fx;
  3093. fx.kind = lynx::EffectKind::plugin;
  3094. fx.plugin.id = "VST3-Reverb-9";
  3095. s.mixer[1].effects.push_back (fx);
  3096. s.patterns.emplace_back();
  3097. int instrumentsMade = 0, effectsMade = 0;
  3098. lynx::RackState::Factories f;
  3099. f.pluginInstruments = [&] (const lynx::PluginRef& ref, double) -> std::shared_ptr<lynx::Instrument> {
  3100. if (ref.id != "VST3-Synth-123")
  3101. return nullptr;
  3102. ++instrumentsMade;
  3103. auto synth = lynx::makeInstrument (lynx::InstrumentKind::synth);
  3104. synth->prepare (48000.0);
  3105. return synth;
  3106. };
  3107. f.pluginEffects = [&] (const lynx::PluginRef&, double) -> std::shared_ptr<lynx::Effect> {
  3108. ++effectsMade;
  3109. auto eq = lynx::makeEffect (lynx::EffectKind::eq);
  3110. eq->prepare (48000.0);
  3111. return eq;
  3112. };
  3113. auto a = lynx::RackState::build (s, nullptr, 48000.0, f);
  3114. CHECK (instrumentsMade == 1 && effectsMade == 1);
  3115. CHECK (a->instruments.size() == 2 && a->instruments[1] != nullptr); // missing: muted, but it exists
  3116. // changing the saved state doesn't recreate; swapping the plugin does
  3117. s.channels[0].plugin.state = "abc";
  3118. auto b = lynx::RackState::build (s, a.get(), 48000.0, f);
  3119. CHECK (instrumentsMade == 1 && b->instruments[0] == a->instruments[0] && b->effects[1][0] == a->effects[1][0]);
  3120. s.mixer[1].effects[0].plugin.id = "VST3-Outro-1";
  3121. auto c2 = lynx::RackState::build (s, b.get(), 48000.0, f);
  3122. CHECK (effectsMade == 2);
  3123. // rendering with a missing plugin and a plugin slot breaks nothing
  3124. lynx::RackRenderer r;
  3125. r.prepare (48000.0, 256);
  3126. lynx::LiveEventQueue live;
  3127. lynx::NoteEvent on;
  3128. on.channel = 0;
  3129. on.velocity = 1.0f;
  3130. live.push (on);
  3131. on.channel = 1;
  3132. live.push (on);
  3133. std::vector<float> l (256), rr (256);
  3134. r.process (c2.get(), false, 0.0, 256, l.data(), rr.data(), &live);
  3135. float peak = 0.0f;
  3136. for (auto v : l)
  3137. {
  3138. CHECK (std::isfinite (v));
  3139. peak = std::max (peak, std::abs (v));
  3140. }
  3141. CHECK (peak > 0.0f);
  3142. }
  3143. TEST (export_song_adds_silent_tail_and_never_restarts)
  3144. {
  3145. auto s = lynx::Song::makeDefault();
  3146. s.playlist.clear();
  3147. std::int64_t length = 0;
  3148. auto pat = lynx::makeExportSong (s, true, lynx::ppq * 8, length); // empty Playlist: uses the pattern
  3149. CHECK (length == lynx::ppq * 4);
  3150. CHECK (pat.mode == lynx::PlayMode::song && pat.playlist.size() == 2);
  3151. CHECK (pat.songLength() >= length + lynx::ppq * 8);
  3152. // no new notes after the song ends, only silence until the end of the tail
  3153. lynx::EventBuffer events;
  3154. const auto tps = lynx::ticksPerSample (pat.bpm, 48000.0);
  3155. int onsAfterEnd = 0, onsBefore = 0;
  3156. for (double tick = 0.0; tick < (double) (length + lynx::ppq * 8); tick += 512 * tps)
  3157. {
  3158. events.clear();
  3159. lynx::scheduleSong (pat, tick, 512, tps, events);
  3160. for (const auto& e : events)
  3161. if (e.type == lynx::NoteEvent::Type::on)
  3162. (tick + e.sampleOffset * tps >= (double) length ? onsAfterEnd : onsBefore)++;
  3163. }
  3164. CHECK (onsBefore == (int) s.patterns[0].notes.size());
  3165. CHECK (onsAfterEnd == 0);
  3166. // with Playlist: the end is the last clip's, without rounding
  3167. s.playlist.push_back ({ 0, 0, lynx::ppq * 2, lynx::ppq * 3, 0 });
  3168. auto song = lynx::makeExportSong (s, true, 0, length);
  3169. CHECK (length == lynx::ppq * 5 && song.playlist.size() == 1);
  3170. song = lynx::makeExportSong (s, false, 0, length);
  3171. CHECK (length == lynx::ppq * 4 && song.playlist[0].start == 0);
  3172. }
  3173. TEST (note_edit_selection_operations)
  3174. {
  3175. namespace ne = lynx::noteedit;
  3176. lynx::Pattern p;
  3177. p.notes = { { 0, 240, 0, 60 }, { 480, 240, 0, 64 }, { 960, 480, 1, 67 } };
  3178. // sorting keeps the indices in step
  3179. p.notes[0].start = 1200;
  3180. std::vector<int> tracked { 0, 2 };
  3181. ne::sortTracking (p, tracked);
  3182. CHECK (p.notes[2].start == 1200 && p.notes[(std::size_t) tracked[0]].start == 1200);
  3183. CHECK (p.notes[(std::size_t) tracked[1]].key == 67);
  3184. // group move respects the limits
  3185. std::int64_t dt = -5000;
  3186. int dk = 100;
  3187. ne::move (p, { 0, 1 }, dt, dk);
  3188. CHECK (dt == -480 && dk == 127 - 67 && p.notes[0].start == 0 && p.notes[1].key == 127);
  3189. // duplicate: right after the selection, rounded to the grid
  3190. lynx::Pattern q;
  3191. q.notes = { { 0, 240, 0, 60 }, { 240, 300, 0, 62 } }; // 540-tick selection
  3192. const auto added = ne::duplicate (q, { 0, 1 }, 960);
  3193. CHECK (added.size() == 2 && q.notes[(std::size_t) added[0]].start == 960 && q.notes[(std::size_t) added[1]].start == 1200);
  3194. // paste onto another channel with an offset
  3195. const auto pasted = ne::paste (q, ne::copy (q, { 1 }), 100, 3);
  3196. CHECK (pasted.size() == 1 && q.notes.back().channel == 3 && q.notes.back().start == 340);
  3197. // quantize rounds to the nearest
  3198. q.notes[0].start = 130;
  3199. q.notes[1].start = 100;
  3200. ne::quantize (q, { 0, 1 }, 240);
  3201. CHECK (q.notes[0].start == 240 && q.notes[1].start == 0);
  3202. // remove several (order and duplicates don't matter)
  3203. const auto before = q.notes.size();
  3204. ne::remove (q, { 1, 0, 1 });
  3205. CHECK (q.notes.size() == before - 2);
  3206. }
  3207. TEST (note_edit_quick_operations)
  3208. {
  3209. namespace ne = lynx::noteedit;
  3210. const std::int64_t step = lynx::ticksPerStep, bar = lynx::ppq * 4;
  3211. // split: only strictly inside; the tail is appended and does not slide again
  3212. lynx::Pattern p;
  3213. p.notes = { { 0, 4 * step, 0, 60 } };
  3214. p.notes[0].slide = true;
  3215. CHECK (ne::split (p, 0, 0) == -1 && ne::split (p, 0, 4 * step) == -1);
  3216. CHECK (ne::split (p, 0, step) == 1 && p.notes[0].length == step && p.notes[1].start == step && p.notes[1].length == 3 * step
  3217. && ! p.notes[1].slide);
  3218. // chop to grid: a 2.5-step note from half a step becomes 3 pieces cut on the step lines
  3219. lynx::Pattern c;
  3220. c.notes = { { step / 2, step * 5 / 2, 0, 60 }, { 0, step, 1, 50 } };
  3221. const auto pieces = ne::chop (c, { 0, 1 }, step);
  3222. CHECK (pieces.size() == 4 && c.notes.size() == 4);
  3223. CHECK (c.notes[0].length == step / 2 && c.notes[2].start == step && c.notes[2].length == step && c.notes[3].start == 2 * step
  3224. && c.notes[3].length == step);
  3225. // join: touching and overlapping notes of the same key and channel merge; others stay
  3226. lynx::Pattern j;
  3227. j.notes = { { 0, step, 0, 60 }, { step, step, 0, 60 }, { step * 3 / 2, step * 2, 0, 60 }, { 5 * step, step, 0, 60 },
  3228. { step, step, 0, 62 }, { step, step, 1, 60 } };
  3229. CHECK (ne::join (j, { 0, 1, 2, 3, 4, 5 }) == 2 && j.notes.size() == 4);
  3230. CHECK (j.notes[0].start == 0 && j.notes[0].length == step * 7 / 2);
  3231. // legato: each note reaches the next start (a chord ends together); the last keeps its length
  3232. lynx::Pattern l;
  3233. l.notes = { { 0, 10, 0, 60 }, { 0, 10, 0, 64 }, { step, 10, 0, 62 }, { 3 * step, 10, 0, 65 }, { step, 10, 1, 40 } };
  3234. ne::legato (l, { 0, 1, 2, 3, 4 });
  3235. CHECK (l.notes[0].length == step && l.notes[1].length == step && l.notes[2].length == 2 * step && l.notes[3].length == 10
  3236. && l.notes[4].length == 10);
  3237. // shrink to grid and full quantise (start and end)
  3238. ne::shrinkToGrid (l, { 3 }, step / 2);
  3239. CHECK (l.notes[3].length == step / 2);
  3240. lynx::Pattern q;
  3241. q.notes = { { 10, step - 30, 0, 60 }, { step + 100, 20, 0, 60 } };
  3242. ne::quantizeFull (q, { 0, 1 }, step);
  3243. CHECK (q.notes[0].start == 0 && q.notes[0].length == step && q.notes[1].start == step && q.notes[1].length == step);
  3244. // rotate inside the bar, wrapping
  3245. lynx::Pattern r;
  3246. r.notes = { { 0, step, 0, 60 }, { bar - step, step, 0, 62 } };
  3247. ne::rotate (r, { 0, 1 }, step, bar, 1);
  3248. CHECK (r.notes[0].start == step && r.notes[1].start == 0);
  3249. ne::rotate (r, { 0, 1 }, step, bar, -2);
  3250. CHECK (r.notes[0].start == bar - step && r.notes[1].start == bar - 2 * step);
  3251. r.notes.push_back ({ bar + step, step, 0, 64 }); // alone in the second bar: wraps inside that bar
  3252. ne::rotate (r, { 2 }, step, bar, -2);
  3253. CHECK (r.notes[2].start == 2 * bar - step);
  3254. }
  3255. TEST (note_edit_grid_and_time_text)
  3256. {
  3257. namespace ne = lynx::noteedit;
  3258. const std::int64_t step = lynx::ticksPerStep, bar = lynx::ppq * 4;
  3259. CHECK (ne::snapDown (250.0, step) == step && ne::snapDown (-1.0, step) == -step && ne::snapDown (17.9, 1) == 17);
  3260. CHECK (ne::snapNearest (1000.0, { 400, 1100, 980 }, 50.0, step) == 980);
  3261. CHECK (ne::snapNearest (1000.0, { 400 }, 50.0, step) == 960); // too far: falls back to the grid
  3262. // screen grid: 24 px per step shows steps; zoomed out it climbs to beats, bars and bar multiples
  3263. CHECK (ne::screenStep (24.0 / step, bar) == step);
  3264. CHECK (ne::screenStep (96.0 / bar, bar) == lynx::ppq);
  3265. CHECK (ne::screenStep (8.0 / bar, bar) == 2 * bar);
  3266. CHECK (ne::screenStep (200.0 / step, bar) == step / 4);
  3267. CHECK (ne::formatTime (0, 4) == "1:1:0" && ne::formatTime (bar + 5 * step + 7, 4) == "2:6:7");
  3268. CHECK (ne::formatTime (step * 2, 4, true) == "0:2:0");
  3269. std::int64_t t = 0;
  3270. CHECK (ne::parseTime ("2:6:7", 4, t) && t == bar + 5 * step + 7);
  3271. CHECK (ne::parseTime ("3", 4, t) && t == 2 * bar);
  3272. CHECK (ne::parseTime ("0:2:0", 4, t, true) && t == 2 * step);
  3273. CHECK (! ne::parseTime ("0:1:0", 4, t) && ! ne::parseTime ("1:17:0", 4, t) && ! ne::parseTime ("1:1:240", 4, t)
  3274. && ! ne::parseTime ("a", 4, t) && ! ne::parseTime ("", 4, t));
  3275. CHECK (ne::parseTime ("1:12:0", 3, t) && ! ne::parseTime ("1:13:0", 3, t)); // 3/4: 12 steps per bar
  3276. }
  3277. TEST (playlist_clip_edges_and_time_selection)
  3278. {
  3279. namespace ne = lynx::noteedit;
  3280. const std::int64_t beat = lynx::ppq;
  3281. // left-edge trim: content stays in place, cannot reveal what is before the content's start
  3282. lynx::Clip c { 0, 0, 4 * beat, 4 * beat, beat };
  3283. ne::trimStart (c, 5 * beat, beat);
  3284. CHECK (c.start == 5 * beat && c.offset == 2 * beat && c.length == 3 * beat);
  3285. ne::trimStart (c, 0, beat);
  3286. CHECK (c.start == 3 * beat && c.offset == 0 && c.length == 5 * beat);
  3287. ne::trimStart (c, 100 * beat, beat);
  3288. CHECK (c.length == beat && c.end() == 8 * beat);
  3289. // slip moves the content, not the clip
  3290. lynx::Clip s { 0, 0, 0, 2 * beat, beat };
  3291. ne::slip (s, beat / 2);
  3292. CHECK (s.offset == beat / 2 && s.start == 0 && s.length == 2 * beat);
  3293. ne::slip (s, beat);
  3294. CHECK (s.offset == 0);
  3295. ne::slip (s, -3 * beat);
  3296. CHECK (s.offset == 3 * beat);
  3297. // insert / delete time across all tracks, markers included
  3298. std::vector<lynx::Clip> clips { { 0, 0, 0, 2 * beat, 0 }, { 0, 1, 4 * beat, 2 * beat, 0 }, { 0, 2, beat, 6 * beat, 0 } };
  3299. std::vector<lynx::Marker> markers { { 5 * beat, "A" }, { beat / 2, "B" } };
  3300. ne::insertTime (clips, markers, 2 * beat, 4 * beat);
  3301. CHECK (clips[0].start == 0 && clips[1].start == 8 * beat && clips[2].start == beat && markers[0].tick == 9 * beat
  3302. && markers[1].tick == beat / 2);
  3303. std::vector<lynx::Clip> d { { 0, 0, 0, 2 * beat, 0 }, // before: kept
  3304. { 0, 1, 3 * beat, beat, 0 }, // inside: deleted
  3305. { 0, 2, beat, 6 * beat, 0 }, // spans the cut: head + tail
  3306. { 0, 3, 3 * beat, 4 * beat, 0 }, // tail outside: trimmed and moved
  3307. { 0, 4, 8 * beat, beat, 0 } }; // after: moved left
  3308. std::vector<lynx::Marker> dm { { 3 * beat, "in" }, { 9 * beat, "after" } };
  3309. ne::deleteTime (d, dm, 2 * beat, 5 * beat);
  3310. CHECK (d.size() == 5);
  3311. CHECK (d[1].track == 2 && d[1].start == beat && d[1].length == beat);
  3312. CHECK (d[2].track == 2 && d[2].start == 2 * beat && d[2].offset == 4 * beat && d[2].length == 2 * beat);
  3313. CHECK (d[3].track == 3 && d[3].start == 2 * beat && d[3].offset == 2 * beat && d[3].length == 2 * beat);
  3314. CHECK (d[4].start == 5 * beat && dm.size() == 1 && dm[0].tick == 6 * beat);
  3315. // time selection: overlapping clips; Ctrl+B repeats what starts inside it after itself
  3316. std::vector<lynx::Clip> r { { 0, 0, 0, beat, 0 }, { 0, 1, beat, 2 * beat, 0 }, { 0, 0, 4 * beat, beat, 0 } };
  3317. CHECK ((ne::clipsInTime (r, beat / 2, 2 * beat) == std::vector<int> { 0, 1 }));
  3318. const auto added = ne::repeatTime (r, 0, 4 * beat, {});
  3319. CHECK (added.size() == 2 && r[3].start == 4 * beat && r[4].start == 5 * beat && r[4].track == 1);
  3320. CHECK (ne::repeatTime (r, 0, 2 * beat, { 2 }).size() == 1 && r.back().start == 6 * beat);
  3321. }
  3322. TEST (recorder_builds_notes_in_pattern_and_song_mode)
  3323. {
  3324. auto song = lynx::Song::makeDefault();
  3325. const auto loop = song.patterns[0].effectiveLength (4); // 1 bar = 3840
  3326. lynx::NoteRecorder r;
  3327. r.add (song, { 100.0, 4, 60, 0.5f, true }); // no take: ignored
  3328. CHECK (r.takeFinished().empty());
  3329. r.begin (loop);
  3330. r.add (song, { 4000.0, 4, 60, 0.5f, true }); // second loop pass
  3331. r.add (song, { 4480.0, 4, 60, 0.0f, false });
  3332. r.add (song, { 5000.0, 4, 64, 0.9f, true }); // held until stop
  3333. r.end (song, 5240.0);
  3334. const auto notes = r.takeFinished();
  3335. CHECK (notes.size() == 2);
  3336. CHECK (notes[0].start == 4000 - 3840 && notes[0].length == 480 && notes[0].velocity == 0.5f && notes[0].channel == 4);
  3337. CHECK (notes[1].key == 64 && notes[1].start == 5000 - 3840 && notes[1].length == 240);
  3338. // song mode: position inside the current pattern's clip (with offset)
  3339. song.mode = lynx::PlayMode::song;
  3340. song.playlist = { { 0, 0, 7680, 3840, 960 } };
  3341. CHECK (lynx::patternPositionForTick (song, 7680.0 + 100.0, loop) == 1060);
  3342. CHECK (lynx::patternPositionForTick (song, 100.0, loop) == 100); // outside the clip: like loop
  3343. }
  3344. TEST (automation_curve_and_playback)
  3345. {
  3346. lynx::Automation a;
  3347. a.points = { { 0, 0.0f }, { 960, 1.0f }, { 1920, 0.5f, 0.0f } };
  3348. CHECK (a.valueAt (-10.0) == 0.0f && a.valueAt (480.0) == 0.5f && a.valueAt (5000.0) == 0.5f);
  3349. CHECK (a.length() == 1920);
  3350. a.points[0].tension = 1.0f; // curve: starts slow
  3351. CHECK (a.valueAt (480.0) < 0.2f && a.valueAt (480.0) > 0.0f);
  3352. // automated Master: silence in the first bar, sound in the second, and the last value
  3353. // keeps applying after the automation clip ends
  3354. auto song = lynx::Song::makeDefault();
  3355. song.bpm = 120.0;
  3356. song.mode = lynx::PlayMode::song;
  3357. const auto bar = (std::int64_t) lynx::ppq * 4;
  3358. for (int b = 0; b < 3; ++b)
  3359. song.playlist.push_back ({ 0, 0, bar * b, bar, 0 });
  3360. lynx::Automation master;
  3361. master.target = { lynx::AutomationTargetKind::mixerVolume, 0 };
  3362. master.points = { { 0, 0.0f }, { bar - 1, 0.0f }, { bar, 0.8f } };
  3363. song.automations.push_back (master);
  3364. lynx::Clip ac;
  3365. ac.kind = lynx::ClipKind::automation;
  3366. ac.automation = 0;
  3367. ac.track = 1;
  3368. ac.length = bar + bar / 2;
  3369. song.playlist.push_back (ac);
  3370. const double sr = 48000.0;
  3371. auto state = lynx::RackState::build (song, nullptr, sr);
  3372. CHECK (state->hasAutomation && state->mixerVolumeAuto[0] == 0 && state->automationClips[0].size() == 1);
  3373. lynx::RackRenderer r;
  3374. r.prepare (sr, 512);
  3375. std::vector<float> l (512), rr (512);
  3376. const auto tps = lynx::ticksPerSample (song.bpm, sr);
  3377. float peakBar1 = 0.0f, peakBar2 = 0.0f, peakBar3 = 0.0f;
  3378. for (double tick = 0.0; tick < (double) (bar * 3); tick += 512 * tps)
  3379. {
  3380. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  3381. auto& peak = tick < (double) bar - 512 * tps ? peakBar1 : tick < (double) bar * 2 ? peakBar2 : peakBar3;
  3382. for (auto v : l)
  3383. peak = std::max (peak, std::abs (v));
  3384. }
  3385. CHECK (peakBar1 < 1.0e-6f);
  3386. CHECK (peakBar2 > 0.05f);
  3387. CHECK (peakBar3 > 0.05f); // after the clip: keeps the last value
  3388. // target removed: automation disappears from the tables
  3389. song.removeChannel (0);
  3390. song.automations[0].target = { lynx::AutomationTargetKind::channelVolume, 0 };
  3391. song.removeChannel (0);
  3392. CHECK (song.automations[0].target.kind == lynx::AutomationTargetKind::none);
  3393. song.removeAutomation (0);
  3394. CHECK (song.automations.empty() && song.playlist.size() == 3);
  3395. }
  3396. TEST (mixer_sends_between_inserts)
  3397. {
  3398. // insert 1 goes only to 3; 3 goes to the Master: same sum (0.5 + 0.5)
  3399. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.setRoute (1, 3, true); s.setRoute (1, 0, false); }) - 1.0f) < 1e-4f);
  3400. // send at 50% and muted destination
  3401. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.setRoute (1, 3, true, 0.5f); s.setRoute (1, 0, false); }) - 0.75f) < 1e-4f);
  3402. 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);
  3403. // going to the Master and to 3: the signal doubles
  3404. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.setRoute (1, 3, true); }) - 1.5f) < 1e-4f);
  3405. // solo on 3 lets what reaches it sound (insert 1), but not 2
  3406. 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);
  3407. // solo on 1 lets the path to the Master (3) sound
  3408. 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);
  3409. // order and cycles
  3410. auto song = lynx::Song::makeDefault();
  3411. song.setRoute (4, 2, true);
  3412. song.setRoute (2, 1, true);
  3413. CHECK (! song.canRoute (1, 4) && ! song.canRoute (1, 2) && song.canRoute (1, 5));
  3414. song.setRoute (1, 4, true); // ignored: would create a cycle
  3415. CHECK (! song.routes (1, 4));
  3416. const auto order = song.mixerOrder();
  3417. const auto pos = [&] (int t) { return std::find (order.begin(), order.end(), t) - order.begin(); };
  3418. CHECK ((int) order.size() == (int) song.mixer.size() - 1);
  3419. CHECK (pos (4) < pos (2) && pos (2) < pos (1));
  3420. song.setRoute (4, 2, false);
  3421. CHECK (! song.routes (4, 2) && song.routes (4, 0));
  3422. }
  3423. namespace
  3424. {
  3425. // Test effect: delays the signal by `latency` samples and reports that latency (like a lookahead plugin).
  3426. class LatentEffect final : public lynx::Effect
  3427. {
  3428. public:
  3429. explicit LatentEffect (int samples) : latency (samples), line (samples) {}
  3430. void prepare (double) noexcept override {}
  3431. void reset() noexcept override {}
  3432. void process (float* l, float* r, int n, const lynx::EffectParams&, double) noexcept override { line.process (l, r, n); }
  3433. int latencySamples() const noexcept override { return latency; }
  3434. private:
  3435. int latency;
  3436. lynx::DelayLine line;
  3437. };
  3438. } // namespace
  3439. TEST (delay_line_mix_into_matches_process_and_drains_tail)
  3440. {
  3441. // mixInto = process over source*level, added to the destination; in stretches that cross the ring
  3442. lynx::DelayLine a (37), b (37);
  3443. std::vector<float> sl (300), sr (300), dl (300, 0.5f), dr (300, -0.5f), xl (300), xr (300);
  3444. for (int i = 0; i < 300; ++i)
  3445. {
  3446. sl[(std::size_t) i] = (float) std::sin (i * 0.1);
  3447. sr[(std::size_t) i] = (float) std::cos (i * 0.07);
  3448. }
  3449. for (int start = 0; start < 300; start += 100)
  3450. {
  3451. b.mixInto (sl.data() + start, sr.data() + start, 0.25f, dl.data() + start, dr.data() + start, 100);
  3452. for (int i = start; i < start + 100; ++i)
  3453. {
  3454. xl[(std::size_t) i] = sl[(std::size_t) i] * 0.25f;
  3455. xr[(std::size_t) i] = sr[(std::size_t) i] * 0.25f;
  3456. }
  3457. a.process (xl.data() + start, xr.data() + start, 100);
  3458. }
  3459. float worst = 0.0f;
  3460. for (int i = 0; i < 300; ++i)
  3461. worst = std::max ({ worst, std::abs (dl[(std::size_t) i] - 0.5f - xl[(std::size_t) i]),
  3462. std::abs (dr[(std::size_t) i] + 0.5f - xr[(std::size_t) i]) });
  3463. CHECK (worst < 1e-6f);
  3464. // silenced source: the tail still in the line comes out, then nothing remains
  3465. std::vector<float> tl (64, 0.0f), tr (64, 0.0f);
  3466. b.mixInto (nullptr, nullptr, 1.0f, tl.data(), tr.data(), 64);
  3467. CHECK (std::abs (tl[0] - sl[263] * 0.25f) < 1e-6f);
  3468. std::vector<float> zl (64, 0.0f), zr (64, 0.0f);
  3469. b.mixInto (nullptr, nullptr, 1.0f, zl.data(), zr.data(), 64);
  3470. CHECK (*std::max_element (zl.begin(), zl.end()) == 0.0f && *std::min_element (zl.begin(), zl.end()) == 0.0f);
  3471. }
  3472. TEST (limiter_lookahead_holds_ceiling_on_bursts)
  3473. {
  3474. // short bursts over a low floor: the sliding maximum must see each peak before it leaves
  3475. auto fx = lynx::makeEffect (lynx::EffectKind::limiter);
  3476. fx->prepare (48000.0);
  3477. auto slot = lynx::makeEffectSlot (lynx::EffectKind::limiter);
  3478. slot.params[2] = 0.0f; // 10 ms release
  3479. std::vector<float> l (48000), r (48000);
  3480. std::uint32_t seed = 1;
  3481. for (int i = 0; i < 48000; ++i)
  3482. {
  3483. seed = seed * 1664525u + 1013904223u;
  3484. const auto noise = ((float) (seed >> 8) / 16777216.0f - 0.5f) * 0.1f;
  3485. l[(std::size_t) i] = noise + ((i % 9973) < 3 ? 3.0f : 0.0f);
  3486. r[(std::size_t) i] = -noise;
  3487. }
  3488. for (int i = 0; i < 48000; i += 333)
  3489. fx->process (l.data() + i, r.data() + i, std::min (333, 48000 - i), slot.params, 120.0);
  3490. float peak = 0.0f, quiet = 0.0f;
  3491. for (int i = 0; i < 48000; ++i)
  3492. peak = std::max (peak, std::abs (l[(std::size_t) i]));
  3493. for (int i = 9973 * 2 + 2000; i < 9973 * 2 + 2400; ++i) // 40 ms after the burst the gain has already recovered
  3494. quiet = std::max (quiet, std::abs (r[(std::size_t) i]));
  3495. const auto ceiling = 1.0f; // the default ceiling is at 0 dBFS or below
  3496. CHECK (peak <= ceiling + 1e-5f);
  3497. CHECK (quiet > 0.03f);
  3498. }
  3499. TEST (pdc_aligns_paths_through_latent_effects)
  3500. {
  3501. // plan: channel 0 -> insert 1 (effect of 100) -> insert 3; channel 1 -> insert 2 -> Master
  3502. lynx::Song s;
  3503. s.mixer = lynx::Song::defaultMixer (4);
  3504. s.channels.resize (3);
  3505. s.channels[0].mixerTrack = 1;
  3506. s.channels[1].mixerTrack = 2;
  3507. s.channels[2].mixerTrack = 3;
  3508. s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::eq));
  3509. s.setRoute (1, 3, true);
  3510. s.setRoute (1, 0, false);
  3511. auto plan = lynx::computePdc (s, { 0, 0, 30 }, { {}, { 100 } });
  3512. CHECK (plan.inAlign[1] == 0 && plan.outLat[1] == 100);
  3513. CHECK (plan.inAlign[3] == 100 && plan.channelDelay[2] == 70); // instrument of 30 on insert 3
  3514. CHECK (plan.sendDelay[1][1] == 0); // the slowest path isn't delayed
  3515. CHECK (plan.sendDelay[2][0] == 100 && plan.sendDelay[3][0] == 0 && plan.total == 100);
  3516. // bypass zeroes the slot's latency
  3517. s.mixer[1].effects[0].enabled = false;
  3518. CHECK (lynx::computePdc (s, { 0, 0, 30 }, { {}, { 100 } }).total == 30);
  3519. // rendered: two impulses played together come out together
  3520. lynx::Song r;
  3521. r.mixer = lynx::Song::defaultMixer (2);
  3522. for (int i = 0; i < 2; ++i)
  3523. {
  3524. lynx::ChannelDef c;
  3525. c.instrument = lynx::InstrumentKind::sampler;
  3526. c.samplePath = "impulso";
  3527. c.volume = 1.0f;
  3528. c.mixerTrack = i + 1;
  3529. r.channels.push_back (c);
  3530. }
  3531. r.patterns.emplace_back();
  3532. lynx::EffectSlot fx;
  3533. fx.kind = lynx::EffectKind::plugin;
  3534. fx.plugin.id = "latente";
  3535. r.mixer[1].effects.push_back (fx);
  3536. lynx::RackState::Factories f;
  3537. f.samples = [] (const std::string&) {
  3538. auto d = std::make_shared<lynx::SampleData>();
  3539. d->left.assign (64, 0.0f);
  3540. d->left[0] = 1.0f;
  3541. return std::shared_ptr<const lynx::SampleData> (d);
  3542. };
  3543. f.pluginEffects = [] (const lynx::PluginRef&, double) -> std::shared_ptr<lynx::Effect> { return std::make_shared<LatentEffect> (100); };
  3544. auto state = lynx::RackState::build (r, nullptr, 48000.0, f);
  3545. CHECK (state->pdc.total == 100 && state->sendDelays[2][0] != nullptr && state->sendDelays[2][0]->length() == 100);
  3546. lynx::RackRenderer renderer;
  3547. renderer.prepare (48000.0, 256);
  3548. lynx::LiveEventQueue live;
  3549. for (int ch = 0; ch < 2; ++ch)
  3550. {
  3551. lynx::NoteEvent on;
  3552. on.channel = ch;
  3553. on.key = 60;
  3554. on.velocity = 1.0f;
  3555. live.push (on);
  3556. }
  3557. std::vector<float> l (256), rr (256);
  3558. renderer.process (state.get(), false, 0.0, 256, l.data(), rr.data(), &live);
  3559. int first = -1;
  3560. for (int i = 0; i < 256 && first < 0; ++i)
  3561. if (std::abs (l[(std::size_t) i]) > 0.01f)
  3562. first = i;
  3563. CHECK (first == 100 && std::abs (l[100] - 2.0f) < 1e-3f); // both impulses arrive together, summed
  3564. // editing without changing latencies reuses the lines
  3565. r.channels[0].volume = 0.5f;
  3566. auto next = lynx::RackState::build (r, state.get(), 48000.0, f);
  3567. CHECK (next->sendDelays[2][0] == state->sendDelays[2][0]);
  3568. }
  3569. TEST (mixer_mute_fades_instead_of_clicking)
  3570. {
  3571. lynx::Song s;
  3572. s.mixer = lynx::Song::defaultMixer (2);
  3573. lynx::ChannelDef c;
  3574. c.instrument = lynx::InstrumentKind::sampler;
  3575. c.samplePath = "dc";
  3576. c.volume = 1.0f;
  3577. c.mixerTrack = 1;
  3578. s.channels.push_back (c);
  3579. s.patterns.emplace_back();
  3580. auto provider = [] (const std::string&) {
  3581. auto d = std::make_shared<lynx::SampleData>();
  3582. d->left.assign (48000, 0.5f);
  3583. return std::shared_ptr<const lynx::SampleData> (d);
  3584. };
  3585. auto on = lynx::RackState::build (s, nullptr, 48000.0, provider);
  3586. s.mixer[1].muted = true;
  3587. auto off = lynx::RackState::build (s, on.get(), 48000.0, provider);
  3588. lynx::RackRenderer r;
  3589. r.prepare (48000.0, 256);
  3590. lynx::LiveEventQueue live;
  3591. lynx::NoteEvent note;
  3592. note.velocity = 1.0f;
  3593. live.push (note);
  3594. std::vector<float> l (256), rr (256);
  3595. r.process (on.get(), false, 0.0, 256, l.data(), rr.data(), &live);
  3596. CHECK (std::abs (l[255] - 0.5f) < 1e-3f);
  3597. r.process (off.get(), false, 0.0, 256, l.data(), rr.data());
  3598. CHECK (l[0] > 0.45f && l[128] > 0.2f && l[128] < 0.3f && std::abs (l[255]) < 1e-6f); // ramp down to zero
  3599. r.process (off.get(), false, 0.0, 256, l.data(), rr.data());
  3600. CHECK (std::abs (l[0]) < 1e-9f);
  3601. }
  3602. TEST (dither_quantizes_to_lsb_grid_with_small_error)
  3603. {
  3604. lynx::Dither d (16);
  3605. std::vector<float> x (4800);
  3606. for (std::size_t i = 0; i < x.size(); ++i)
  3607. x[i] = 0.25f * std::sin ((float) i * 0.05f);
  3608. auto y = x;
  3609. d.process (y.data(), (int) y.size(), 0);
  3610. double errorSum = 0.0;
  3611. bool onGrid = true;
  3612. for (std::size_t i = 0; i < x.size(); ++i)
  3613. {
  3614. const auto steps = y[i] * 32768.0f;
  3615. onGrid = onGrid && std::abs (steps - std::round (steps)) < 1e-3f;
  3616. errorSum += std::abs (y[i] - x[i]);
  3617. }
  3618. CHECK (onGrid);
  3619. CHECK (errorSum / (double) x.size() < 4.0 / 32768.0); // a few LSBs of noise on average
  3620. }
  3621. TEST (parallel_rendering_matches_sequential)
  3622. {
  3623. // 32 channels (worth parallelizing), inserts with chained sends
  3624. auto song = lynx::Song::makeDefault();
  3625. song.mixer = lynx::Song::defaultMixer (16);
  3626. for (int i = 5; i < 32; ++i)
  3627. {
  3628. lynx::ChannelDef c;
  3629. c.instrument = i % 2 ? lynx::InstrumentKind::synth : lynx::InstrumentKind::hat;
  3630. c.mixerTrack = 1 + i % 12;
  3631. c.volume = 0.3f;
  3632. song.channels.push_back (c);
  3633. for (int step = i % 4; step < 16; step += 3)
  3634. song.patterns[0].notes.push_back ({ (std::int64_t) step * lynx::ticksPerStep, 200, i, 48 + i, 0.7f });
  3635. }
  3636. song.patterns[0].sortNotes();
  3637. song.setRoute (3, 7, true, 0.6f);
  3638. song.setRoute (7, 9, true, 0.5f);
  3639. song.setRoute (2, 9, true);
  3640. song.mixer[9].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::reverb));
  3641. auto seqState = lynx::RackState::build (song, nullptr, 48000.0);
  3642. auto parState = lynx::RackState::build (song, nullptr, 48000.0);
  3643. CHECK (parState->parallel && parState->mixerLayers.size() == 3);
  3644. lynx::WorkerPool pool (3);
  3645. lynx::RackRenderer seq, par;
  3646. seq.prepare (48000.0, 512);
  3647. par.prepare (48000.0, 512);
  3648. par.setWorkerPool (&pool);
  3649. std::vector<float> l1 (512), r1 (512), l2 (512), r2 (512);
  3650. const auto tps = lynx::ticksPerSample (song.bpm, 48000.0);
  3651. bool same = true;
  3652. float peak = 0.0f;
  3653. for (int block = 0; block < 200; ++block)
  3654. {
  3655. seq.process (seqState.get(), true, block * 512 * tps, 512, l1.data(), r1.data());
  3656. par.process (parState.get(), true, block * 512 * tps, 512, l2.data(), r2.data());
  3657. same = same && l1 == l2 && r1 == r2;
  3658. for (auto v : l1)
  3659. peak = std::max (peak, std::abs (v));
  3660. }
  3661. CHECK (same);
  3662. CHECK (peak > 0.05f);
  3663. // the pool handles many small rounds in a row
  3664. std::atomic<int> sum { 0 };
  3665. auto add = [&sum] (int i) { sum.fetch_add (i + 1); };
  3666. for (int round = 0; round < 2000; ++round)
  3667. pool.parallelFor (5, add);
  3668. CHECK (sum.load() == 2000 * 15);
  3669. }
  3670. TEST (arrangements_switch_and_keep_clip_indices)
  3671. {
  3672. auto s = lynx::Song::makeDefault();
  3673. s.patterns.emplace_back().name = "B";
  3674. s.playlist = { { 1, 0, 0, 960, 0 } };
  3675. s.loopEnd = 960;
  3676. CHECK (s.arrangements.size() == 1 && s.currentArrangement == 0);
  3677. const auto second = s.addArrangement ("Versão curta", true);
  3678. CHECK (second == 1 && s.currentArrangement == 1 && s.playlist.size() == 1 && s.loopEnd == 960);
  3679. s.playlist.push_back ({ 0, 1, 960, 960, 0 });
  3680. s.loopEnd = 0;
  3681. s.selectArrangement (0);
  3682. CHECK (s.playlist.size() == 1 && s.loopEnd == 960 && s.arrangements[1].clips.size() == 2);
  3683. // removing pattern 0 fixes the clips stored in the other arrangement
  3684. s.removePattern (0);
  3685. CHECK (s.playlist.size() == 1 && s.playlist[0].pattern == 0);
  3686. CHECK (s.arrangements[1].clips.size() == 1 && s.arrangements[1].clips[0].pattern == 0);
  3687. s.removeArrangement (0);
  3688. CHECK (s.arrangements.size() == 1 && s.currentArrangement == 0 && s.playlist.size() == 1 && s.loopEnd == 0);
  3689. }
  3690. namespace
  3691. {
  3692. // Test effect that inverts the signal and counts how many times it processed.
  3693. class CountingInverter final : public lynx::Effect
  3694. {
  3695. public:
  3696. void prepare (double) noexcept override {}
  3697. void reset() noexcept override {}
  3698. void process (float* l, float* r, int n, const lynx::EffectParams&, double) noexcept override
  3699. {
  3700. ++calls;
  3701. for (int i = 0; i < n; ++i)
  3702. {
  3703. l[i] = -l[i];
  3704. r[i] = -r[i];
  3705. }
  3706. }
  3707. int calls = 0;
  3708. };
  3709. } // namespace
  3710. TEST (keyboard_controller_outputs_key_value)
  3711. {
  3712. std::vector<std::uint8_t> blob (554, 0);
  3713. const std::uint32_t version = 3;
  3714. std::memcpy (blob.data(), &version, 4);
  3715. const float key60 = 0.7f, off = 0.2f;
  3716. std::memcpy (blob.data() + 12 + 60 * 4, &key60, 4);
  3717. std::memcpy (blob.data() + 548, &off, 4);
  3718. blob[552] = 1; // auto release
  3719. lynx::ChannelDef c;
  3720. c.instrument = lynx::InstrumentKind::controller;
  3721. c.controllerState = blob;
  3722. auto inst = lynx::makeInstrument (lynx::InstrumentKind::controller);
  3723. inst->prepare (48000.0);
  3724. inst->configure (c, 120.0);
  3725. std::vector<float> l (64), r (64);
  3726. inst->noteOn (60, 1.0f);
  3727. inst->render (l.data(), r.data(), 64, 1.0f, 1.0f);
  3728. CHECK (std::abs (inst->controlOutput (0) - 0.7f) < 1e-6f);
  3729. inst->noteOff (60);
  3730. CHECK (std::abs (inst->controlOutput (0) - 0.2f) < 1e-6f);
  3731. }
  3732. TEST (envelope_controller_ducks_on_each_note)
  3733. {
  3734. // a unipolar articulator like "Basic Sidechain": base 0.05, drops to 0 on the note and rises to 1 in 0.3 s
  3735. lynx::ControllerArticulator a;
  3736. a.envOn = true;
  3737. a.base = 0.05f;
  3738. a.envLevel = 1.0f;
  3739. a.count = 3;
  3740. a.time = { 0.0f, 0.2f, 0.3f };
  3741. a.level = { 0.0f, 0.75f, 1.0f };
  3742. CHECK (std::abs (lynx::controllerValue (a, 0.0, -1.0) - 0.05f) < 1e-4f);
  3743. CHECK (std::abs (lynx::controllerValue (a, 0.1, -1.0) - 0.425f) < 1e-3f);
  3744. CHECK (lynx::controllerValue (a, 1.0, -1.0) > 0.99f); // no sustain: runs to the end and stays
  3745. a.sustain = 1;
  3746. CHECK (std::abs (lynx::controllerValue (a, 1.0, -1.0) - 0.8f) < 1e-3f); // held at sustain
  3747. CHECK (lynx::controllerValue (a, 1.0, 0.5) > 0.99f); // released: continues to the end
  3748. a.bipolar = true;
  3749. a.base = 0.5f;
  3750. a.sustain = -1;
  3751. CHECK (std::abs (lynx::controllerValue (a, 0.0, -1.0) - 0.0f) < 1e-4f); // bipolar: 0.5 + (0 − 0.5)
  3752. }
  3753. TEST (peak_controller_drives_live_automation)
  3754. {
  3755. // track 1: source (DC 0.5) with Peak Controller; track 2: DC 0.5 with volume linked to the controller
  3756. auto render = [] (bool linked) {
  3757. lynx::Song s;
  3758. s.mixer = lynx::Song::defaultMixer (2);
  3759. for (int t = 1; t <= 2; ++t)
  3760. {
  3761. lynx::ChannelDef c;
  3762. c.instrument = lynx::InstrumentKind::sampler;
  3763. c.samplePath = "dc";
  3764. c.volume = 1.0f;
  3765. c.mixerTrack = t;
  3766. s.channels.push_back (c);
  3767. }
  3768. s.patterns.emplace_back();
  3769. auto peak = lynx::makeEffectSlot (lynx::EffectKind::peakController);
  3770. peak.params[0] = 1.0f; // base 1
  3771. peak.params[1] = 0.0f; // amount −1: 1 − peak
  3772. peak.params[2] = 0.5f; // no tension
  3773. s.mixer[1].effects.push_back (peak);
  3774. if (linked)
  3775. {
  3776. lynx::Automation a;
  3777. a.name = "Peak";
  3778. a.target = { lynx::AutomationTargetKind::mixerVolume, 2 };
  3779. a.source = { 1, 0, 0 };
  3780. s.automations.push_back (a);
  3781. }
  3782. lynx::RackState::Factories f;
  3783. f.samples = [] (const std::string&) {
  3784. auto d = std::make_shared<lynx::SampleData>();
  3785. d->left.assign (48000, 0.5f);
  3786. return std::shared_ptr<const lynx::SampleData> (d);
  3787. };
  3788. auto state = lynx::RackState::build (s, nullptr, 48000.0, f);
  3789. lynx::RackRenderer r;
  3790. r.prepare (48000.0, 512);
  3791. lynx::LiveEventQueue live;
  3792. for (int ch = 0; ch < 2; ++ch)
  3793. {
  3794. lynx::NoteEvent on;
  3795. on.channel = ch;
  3796. on.velocity = 1.0f;
  3797. live.push (on);
  3798. }
  3799. std::vector<float> l (4800), rr (4800);
  3800. r.process (state.get(), false, 0.0, 4800, l.data(), rr.data(), &live);
  3801. return l[4000];
  3802. };
  3803. const auto free = render (false), ducked = render (true);
  3804. CHECK (std::isfinite (ducked) && ducked > 0.0f);
  3805. CHECK (ducked < free - 0.05f); // the 0.5 peak on track 1 lowers track 2's volume
  3806. }
  3807. TEST (effect_slot_dry_wet_and_smart_disable)
  3808. {
  3809. lynx::Song s;
  3810. s.mixer = lynx::Song::defaultMixer (1);
  3811. lynx::ChannelDef c;
  3812. c.instrument = lynx::InstrumentKind::sampler;
  3813. c.samplePath = "dc";
  3814. c.volume = 1.0f;
  3815. c.mixerTrack = 1;
  3816. s.channels.push_back (c);
  3817. s.patterns.emplace_back();
  3818. lynx::EffectSlot fx;
  3819. fx.kind = lynx::EffectKind::plugin;
  3820. fx.plugin.id = "inversor";
  3821. fx.mix = 0.25f; // 75% dry (+0.5) and 25% wet (-0.5) = +0.25
  3822. s.mixer[1].effects.push_back (fx);
  3823. auto inverter = std::make_shared<CountingInverter>();
  3824. lynx::RackState::Factories f;
  3825. f.samples = [] (const std::string&) {
  3826. auto d = std::make_shared<lynx::SampleData>();
  3827. d->left.assign (4800, 0.5f);
  3828. return std::shared_ptr<const lynx::SampleData> (d);
  3829. };
  3830. f.pluginEffects = [inverter] (const lynx::PluginRef&, double) -> std::shared_ptr<lynx::Effect> { return inverter; };
  3831. auto state = lynx::RackState::build (s, nullptr, 48000.0, f);
  3832. lynx::RackRenderer r;
  3833. r.prepare (48000.0, 512);
  3834. lynx::LiveEventQueue live;
  3835. lynx::NoteEvent on;
  3836. on.velocity = 1.0f;
  3837. live.push (on);
  3838. std::vector<float> l (480), rr (480);
  3839. r.process (state.get(), false, 0.0, 480, l.data(), rr.data(), &live);
  3840. CHECK (std::abs (l[100] - 0.25f) < 1e-4f);
  3841. // after the sample ends: 4 s of silence and the plugin stops being called
  3842. for (int i = 0; i < 100 * 6; ++i) // 6 s
  3843. r.process (state.get(), false, 0.0, 480, l.data(), rr.data());
  3844. const auto callsAfterSilence = inverter->calls;
  3845. for (int i = 0; i < 100; ++i)
  3846. r.process (state.get(), false, 0.0, 480, l.data(), rr.data());
  3847. CHECK (inverter->calls == callsAfterSilence);
  3848. CHECK (callsAfterSilence < 100 * 6);
  3849. // sound again: processing resumes in the same block
  3850. live.push (on);
  3851. r.process (state.get(), false, 0.0, 480, l.data(), rr.data(), &live);
  3852. CHECK (inverter->calls == callsAfterSilence + 1 && std::abs (l[100] - 0.25f) < 1e-4f);
  3853. }
  3854. TEST (swing_delays_offbeat_sixteenths)
  3855. {
  3856. CHECK (lynx::swingDelay (0, 1.0f) == 0);
  3857. CHECK (lynx::swingDelay (lynx::ticksPerStep, 1.0f) == lynx::ticksPerStep / 2);
  3858. CHECK (lynx::swingDelay (lynx::ticksPerStep * 2, 1.0f) == 0);
  3859. CHECK (lynx::swingDelay (lynx::ticksPerStep + 10, 1.0f) == (lynx::ticksPerStep - 20) / 2); // off the grid: triangular weight (FL)
  3860. CHECK (lynx::swingDelay (lynx::ticksPerStep, 1.0f, 0.5f) == lynx::ticksPerStep / 4); // channel mix
  3861. CHECK (lynx::swingDelay (lynx::ticksPerStep * 3, 0.5f) == lynx::ticksPerStep / 4);
  3862. lynx::Pattern p;
  3863. p.notes = { { 0, 100, 0, 60 }, { lynx::ticksPerStep, 100, 0, 62 } };
  3864. lynx::EventBuffer ev;
  3865. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  3866. lynx::schedulePatternLoop (p, p.effectiveLength (4), 0.0, 12000, tps, ev, 1.0f);
  3867. int onOffset = -1;
  3868. for (auto& e : ev)
  3869. if (e.type == lynx::NoteEvent::Type::on && e.key == 62)
  3870. onOffset = e.sampleOffset;
  3871. CHECK (onOffset == (int) std::floor ((lynx::ticksPerStep * 1.5) / tps));
  3872. }
  3873. TEST (sampler_settings_pitch_reverse_envelope_cut)
  3874. {
  3875. auto ramp = std::make_shared<lynx::SampleData>();
  3876. for (int i = 0; i < 48000; ++i)
  3877. ramp->left.push_back ((float) i / 48000.0f); // ramp: the value tells where the read position is
  3878. ramp->sampleRate = 48000.0;
  3879. auto play = [&] (const lynx::SamplerSettings& s, int key, int frames, bool releaseAfterHalf) {
  3880. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  3881. inst->prepare (48000.0);
  3882. lynx::ChannelDef c;
  3883. c.sampler = s;
  3884. inst->configure (c, 120.0);
  3885. inst->noteOn (key, 1.0f);
  3886. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  3887. inst->render (l.data(), r.data(), frames / 2, 1.0f, 1.0f);
  3888. if (releaseAfterHalf)
  3889. inst->noteOff (key);
  3890. inst->render (l.data() + frames / 2, r.data() + frames / 2, frames - frames / 2, 1.0f, 1.0f);
  3891. return l;
  3892. };
  3893. // +12 semitones: reads twice as fast
  3894. lynx::SamplerSettings up;
  3895. up.pitch = 12.0f;
  3896. CHECK (std::abs (play (up, 60, 1000, false)[999] - 2.0f * 999.0f / 48000.0f) < 1e-3f);
  3897. // reversed: starts from the end
  3898. lynx::SamplerSettings back;
  3899. back.reverse = true;
  3900. CHECK (play (back, 60, 100, false)[10] > 0.99f);
  3901. // 10 ms attack: starts silent and reaches full level
  3902. lynx::SamplerSettings slow;
  3903. slow.attack = 0.01f;
  3904. const auto a = play (slow, 60, 2000, false);
  3905. CHECK (a[10] < 0.2f * (10.0f / 48000.0f) + 1e-6f && std::abs (a[1500] - 1500.0f / 48000.0f) < 1e-4f);
  3906. // 5 ms release: gone right after release; without release it plays in full
  3907. lynx::SamplerSettings rel;
  3908. rel.release = 0.005f;
  3909. CHECK (play (rel, 60, 2000, true)[1999] == 0.0f);
  3910. CHECK (play (lynx::SamplerSettings {}, 60, 2000, true)[1999] > 0.0f);
  3911. // cut itself: the second note cuts the first (one voice remains)
  3912. lynx::SamplerSettings cut;
  3913. cut.cut = true;
  3914. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  3915. inst->prepare (48000.0);
  3916. lynx::ChannelDef cutChannel;
  3917. cutChannel.sampler = cut;
  3918. inst->configure (cutChannel, 120.0);
  3919. inst->noteOn (60, 1.0f);
  3920. std::vector<float> l (2000), r (2000);
  3921. inst->render (l.data(), r.data(), 1000, 1.0f, 1.0f);
  3922. inst->noteOn (60, 1.0f);
  3923. std::fill (l.begin(), l.end(), 0.0f);
  3924. inst->render (l.data(), r.data(), 2000, 1.0f, 1.0f);
  3925. CHECK (std::abs (l[1999] - 1999.0f / 48000.0f) < 1e-4f); // only the new note
  3926. }
  3927. TEST (playlist_split_and_track_mute)
  3928. {
  3929. lynx::Clip c { 0, 3, 960, 3840, 480 };
  3930. const auto rest = lynx::splitClip (c, 2000);
  3931. CHECK (c.start == 960 && c.length == 1040 && c.offset == 480);
  3932. CHECK (rest.start == 2000 && rest.length == 2800 && rest.offset == 480 + 1040 && rest.track == 3);
  3933. auto s = lynx::Song::makeDefault();
  3934. s.mode = lynx::PlayMode::song;
  3935. s.playlist = { { 0, 0, 0, 3840, 0 } };
  3936. lynx::EventBuffer ev;
  3937. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  3938. lynx::scheduleSong (s, 0.0, 48000, tps, ev);
  3939. CHECK (ev.size() > 0);
  3940. s.playlistTracks.resize (1);
  3941. s.playlistTracks[0].muted = true;
  3942. ev.clear();
  3943. lynx::scheduleSong (s, 0.0, 48000, tps, ev);
  3944. CHECK (ev.size() == 0);
  3945. }
  3946. TEST (note_pan_pitch_and_mute)
  3947. {
  3948. lynx::Pattern p;
  3949. lynx::Note a { 0, 240, 0, 60 };
  3950. a.pan = -1.0f;
  3951. a.finePitch = 50.0f;
  3952. lynx::Note b { 240, 240, 0, 62 };
  3953. b.muted = true;
  3954. p.notes = { a, b };
  3955. lynx::EventBuffer ev;
  3956. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  3957. lynx::schedulePatternLoop (p, p.effectiveLength (4), 0.0, 48000, tps, ev);
  3958. int ons = 0;
  3959. for (auto& e : ev)
  3960. if (e.type == lynx::NoteEvent::Type::on)
  3961. {
  3962. ++ons;
  3963. CHECK (e.key == 60 && e.pan == -1.0f && e.cents == 50.0f);
  3964. }
  3965. CHECK (ons == 1); // the muted one doesn't play
  3966. // note pan in the sampler: fully left
  3967. auto dc = std::make_shared<lynx::SampleData>();
  3968. dc->left.assign (4800, 0.5f);
  3969. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, dc);
  3970. inst->prepare (48000.0);
  3971. inst->setNextNoteExpression (-1.0f, 0.0f);
  3972. inst->noteOn (60, 1.0f);
  3973. std::vector<float> l (100), r (100);
  3974. inst->render (l.data(), r.data(), 100, 1.0f, 1.0f);
  3975. CHECK (l[50] > 0.6f && std::abs (r[50]) < 1e-6f);
  3976. }
  3977. TEST (tempo_automation_changes_speed_and_duration)
  3978. {
  3979. auto song = lynx::Song::makeDefault();
  3980. song.bpm = 120.0;
  3981. song.mode = lynx::PlayMode::song;
  3982. const auto bar = (std::int64_t) lynx::ppq * 4;
  3983. song.playlist = { { 0, 0, 0, bar, 0 }, { 0, 0, bar, bar, 0 } };
  3984. lynx::Automation tempo;
  3985. tempo.target = { lynx::AutomationTargetKind::tempo, 0 };
  3986. const auto v120 = lynx::valueFromTempo (120.0), v240 = lynx::valueFromTempo (240.0);
  3987. tempo.points = { { 0, v120 }, { bar - 1, v120 }, { bar, v240 } }; // step: 120 -> 240 at bar 2
  3988. song.automations.push_back (tempo);
  3989. lynx::Clip clip;
  3990. clip.kind = lynx::ClipKind::automation;
  3991. clip.automation = 0;
  3992. clip.track = 1;
  3993. clip.length = bar * 2;
  3994. song.playlist.push_back (clip);
  3995. CHECK (std::abs (song.tempoAt (100.0) - 120.0) < 0.01 && std::abs (song.tempoAt ((double) bar + 100.0) - 240.0) < 0.01);
  3996. // 1 bar at 120 (2 s) + 1 at 240 (1 s)
  3997. CHECK (std::abs (song.secondsForTicks (bar * 2) - 3.0) < 0.01);
  3998. auto state = lynx::RackState::build (song, nullptr, 48000.0);
  3999. CHECK (state->tempoAutomation == 0);
  4000. lynx::RackRenderer r;
  4001. r.prepare (48000.0, 512);
  4002. std::vector<float> l (512), rr (512);
  4003. r.process (state.get(), true, 10.0, 512, l.data(), rr.data());
  4004. CHECK (std::abs (r.currentBpm() - 120.0) < 0.01);
  4005. r.process (state.get(), true, (double) bar + 10.0, 512, l.data(), rr.data());
  4006. CHECK (std::abs (r.currentBpm() - 240.0) < 0.01);
  4007. }
  4008. TEST (bounce_insert_song_and_apply)
  4009. {
  4010. auto s = lynx::Song::makeDefault();
  4011. s.setRoute (3, 7, true, 0.5f);
  4012. s.mixer[0].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::reverb));
  4013. s.mixer[2].solo = true;
  4014. const auto b = lynx::makeBounceSong (s, 3);
  4015. CHECK (b.mixer[3].solo && ! b.mixer[2].solo && b.mixer[3].toMaster && b.mixer[3].sends.empty());
  4016. CHECK (b.mixer[0].effects.empty() && b.mode == lynx::PlayMode::song);
  4017. const auto audible = b.soloAudible();
  4018. CHECK (audible[3] && ! audible[1] && ! audible[7]);
  4019. const auto channels = s.channels.size();
  4020. const auto inserts = s.mixer.size();
  4021. const auto created = lynx::applyBounce (s, 3, "C:/x.wav", 3840);
  4022. CHECK (created == (int) inserts && s.mixer.size() == inserts + 1 && s.mixer[3].muted);
  4023. CHECK (s.mixer[(std::size_t) created].sends.size() == 1 && s.mixer[(std::size_t) created].sends[0].target == 7);
  4024. CHECK (s.channels.size() == channels + 1 && s.channels.back().mixerTrack == created);
  4025. CHECK (s.playlist.back().kind == lynx::ClipKind::audio && s.playlist.back().length == 3840);
  4026. }
  4027. TEST (mixer_stereo_separation_phase_swap)
  4028. {
  4029. lynx::MixerTrack t;
  4030. std::vector<float> l { 1.0f }, r { 0.0f };
  4031. t.stereo = 1.0f; // mono
  4032. lynx::RackRenderer::applyStereoForTest (t, l.data(), r.data(), 1);
  4033. CHECK (std::abs (l[0] - 0.5f) < 1e-6f && std::abs (r[0] - 0.5f) < 1e-6f);
  4034. l = { 1.0f };
  4035. r = { 0.0f };
  4036. t.stereo = -1.0f; // doubled side: 1.5 L - 0.5 R
  4037. lynx::RackRenderer::applyStereoForTest (t, l.data(), r.data(), 1);
  4038. CHECK (std::abs (l[0] - 1.5f) < 1e-6f && std::abs (r[0] + 0.5f) < 1e-6f);
  4039. l = { 1.0f };
  4040. r = { 0.25f };
  4041. t.stereo = 0.0f;
  4042. t.swapChannels = true;
  4043. t.invertPhase = true;
  4044. lynx::RackRenderer::applyStereoForTest (t, l.data(), r.data(), 1);
  4045. CHECK (l[0] == -0.25f && r[0] == -1.0f);
  4046. }
  4047. TEST (effects_limiter_filter_distortion_chorus)
  4048. {
  4049. const double sr = 48000.0;
  4050. auto sine = [] (float hz, float amp, int n) {
  4051. std::vector<float> v ((std::size_t) n);
  4052. for (int i = 0; i < n; ++i)
  4053. v[(std::size_t) i] = amp * std::sin (2.0f * 3.14159265f * hz * (float) i / 48000.0f);
  4054. return v;
  4055. };
  4056. auto peak = [] (const std::vector<float>& v, int from) {
  4057. float p = 0.0f;
  4058. for (std::size_t i = (std::size_t) from; i < v.size(); ++i)
  4059. p = std::max (p, std::abs (v[i]));
  4060. return p;
  4061. };
  4062. // limiter: +12 dB on a 0.9 sine never exceeds the ceiling (-1 dB) and reports the latency
  4063. auto lim = lynx::makeEffect (lynx::EffectKind::limiter);
  4064. lim->prepare (sr);
  4065. auto slot = lynx::makeEffectSlot (lynx::EffectKind::limiter);
  4066. slot.params[0] = 11.0f / 12.0f; // -1 dB
  4067. slot.params[1] = 0.5f; // +12 dB
  4068. auto l = sine (100.0f, 0.9f, 48000), r = l;
  4069. lim->process (l.data(), r.data(), 48000, slot.params, 120.0);
  4070. CHECK (peak (l, 0) <= std::pow (10.0f, -1.0f / 20.0f) + 1e-4f);
  4071. CHECK (peak (l, 4800) > 0.8f);
  4072. CHECK (lim->latencySamples() == 72);
  4073. // low-pass filter at 500 Hz knocks down an 8 kHz sine
  4074. auto lp = lynx::makeEffect (lynx::EffectKind::filter);
  4075. lp->prepare (sr);
  4076. auto fs = lynx::makeEffectSlot (lynx::EffectKind::filter);
  4077. fs.params[1] = std::log (500.0f / 20.0f) / std::log (1000.0f);
  4078. l = sine (8000.0f, 1.0f, 9600);
  4079. r = l;
  4080. lp->process (l.data(), r.data(), 9600, fs.params, 120.0);
  4081. CHECK (peak (l, 4800) < 0.05f);
  4082. // distortion and chorus: finite, audible output
  4083. for (auto kind : { lynx::EffectKind::distortion, lynx::EffectKind::chorus })
  4084. {
  4085. auto fx = lynx::makeEffect (kind);
  4086. fx->prepare (sr);
  4087. auto ps = lynx::makeEffectSlot (kind);
  4088. l = sine (220.0f, 0.5f, 9600);
  4089. r = l;
  4090. fx->process (l.data(), r.data(), 9600, ps.params, 120.0);
  4091. bool finite = true;
  4092. for (auto v : l)
  4093. finite = finite && std::isfinite (v);
  4094. CHECK (finite && peak (l, 2400) > 0.1f && peak (l, 0) < 2.0f);
  4095. }
  4096. }
  4097. TEST (slide_notes_glide_without_retrigger)
  4098. {
  4099. // sampler with a ramp: the read speed doubles after a one-octave slide
  4100. auto ramp = std::make_shared<lynx::SampleData>();
  4101. for (int i = 0; i < 96000; ++i)
  4102. ramp->left.push_back ((float) i / 96000.0f);
  4103. ramp->sampleRate = 48000.0;
  4104. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  4105. inst->prepare (48000.0);
  4106. inst->noteOn (60, 1.0f);
  4107. std::vector<float> l (2000), r (2000);
  4108. inst->render (l.data(), r.data(), 1000, 1.0f, 1.0f);
  4109. const auto stepBefore = l[999] - l[998];
  4110. inst->slideTo (72, 0.0f, 100.0f);
  4111. std::fill (l.begin(), l.end(), 0.0f);
  4112. inst->render (l.data(), r.data(), 1000, 1.0f, 1.0f);
  4113. const auto stepAfter = l[999] - l[998];
  4114. CHECK (std::abs (stepAfter / stepBefore - 2.0f) < 0.01f);
  4115. // the sequencer sends "slide" (no off) for the slide note
  4116. lynx::Pattern p;
  4117. lynx::Note base { 0, 960, 0, 48 };
  4118. lynx::Note glide { 480, 240, 0, 55 };
  4119. glide.slide = true;
  4120. p.notes = { base, glide };
  4121. lynx::EventBuffer ev;
  4122. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  4123. lynx::schedulePatternLoop (p, p.effectiveLength (4), 0.0, 30000, tps, ev);
  4124. int ons = 0, offs = 0, slides = 0;
  4125. for (auto& e : ev)
  4126. {
  4127. ons += e.type == lynx::NoteEvent::Type::on;
  4128. offs += e.type == lynx::NoteEvent::Type::off;
  4129. if (e.type == lynx::NoteEvent::Type::slide)
  4130. {
  4131. ++slides;
  4132. CHECK (e.key == 55 && std::abs (e.slideSamples - 240.0f / (float) tps) < 1.0f);
  4133. }
  4134. }
  4135. CHECK (ons == 1 && offs == 1 && slides == 1);
  4136. }
  4137. TEST (synth_fm_phase_modulation)
  4138. {
  4139. auto render = [] (const lynx::SynthSettings& s) {
  4140. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  4141. inst->prepare (48000.0);
  4142. lynx::ChannelDef c;
  4143. c.synth = s;
  4144. inst->configure (c, 120.0);
  4145. inst->noteOn (69, 1.0f); // 440 Hz
  4146. std::vector<float> l (48000), r (48000);
  4147. inst->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  4148. return l;
  4149. };
  4150. // energy (Goertzel) at frequency f over frames [from, to)
  4151. auto energy = [] (const std::vector<float>& x, double f, int from, int to) {
  4152. const auto w = 2.0 * 3.141592653589793 * f / 48000.0, k = 2.0 * std::cos (w);
  4153. double s1 = 0.0, s2 = 0.0;
  4154. for (int i = from; i < to; ++i)
  4155. {
  4156. const auto s0 = x[(std::size_t) i] + k * s1 - s2;
  4157. s2 = s1;
  4158. s1 = s0;
  4159. }
  4160. return s1 * s1 + s2 * s2 - k * s1 * s2;
  4161. };
  4162. lynx::SynthSettings plain;
  4163. plain.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  4164. plain.osc[2] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  4165. plain.cutoff = 20000.0f;
  4166. auto fm = plain;
  4167. fm.fm = 1.0f;
  4168. const auto a = render (plain), b = render (fm);
  4169. // no FM: osc 3 adds (same pitch) and there's no 2nd harmonic; with FM the sidebands appear
  4170. CHECK (energy (a, 880.0, 4800, 24000) < 1e-3 * energy (a, 440.0, 4800, 24000));
  4171. CHECK (energy (b, 880.0, 4800, 24000) > 0.1 * energy (b, 440.0, 4800, 24000));
  4172. CHECK (energy (b, 1320.0, 4800, 24000) > 0.01 * energy (b, 440.0, 4800, 24000));
  4173. for (auto v : b)
  4174. CHECK (std::isfinite (v) && std::abs (v) < 1.0f);
  4175. // index decaying to 0: the start is bright, the end is nearly a sine again
  4176. auto decaying = fm;
  4177. decaying.fmDecay = 0.1f;
  4178. decaying.fmSustain = 0.0f;
  4179. const auto c = render (decaying);
  4180. const auto early = energy (c, 880.0, 0, 2400) / energy (c, 440.0, 0, 2400);
  4181. const auto late = energy (c, 880.0, 36000, 48000) / energy (c, 440.0, 36000, 48000);
  4182. CHECK (early > 0.05 && late < 1e-3);
  4183. }
  4184. TEST (synth_three_oscillators_adsr_filter)
  4185. {
  4186. auto render = [] (const lynx::SynthSettings& s, int frames, int releaseAt) {
  4187. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  4188. inst->prepare (48000.0);
  4189. lynx::ChannelDef c;
  4190. c.synth = s;
  4191. inst->configure (c, 120.0);
  4192. inst->noteOn (69, 1.0f); // A4 = 440 Hz
  4193. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  4194. inst->render (l.data(), r.data(), releaseAt, 1.0f, 1.0f);
  4195. inst->noteOff (69);
  4196. inst->render (l.data() + releaseAt, r.data() + releaseAt, frames - releaseAt, 1.0f, 1.0f);
  4197. return l;
  4198. };
  4199. auto peakIn = [] (const std::vector<float>& v, int from, int to) {
  4200. float p = 0.0f;
  4201. for (int i = from; i < to; ++i)
  4202. p = std::max (p, std::abs (v[(std::size_t) i]));
  4203. return p;
  4204. };
  4205. // default: sounds and fades after the release
  4206. const lynx::SynthSettings standard;
  4207. const auto a = render (standard, 48000, 24000);
  4208. CHECK (peakIn (a, 1000, 20000) > 0.05f && peakIn (a, 40000, 48000) < 1e-3f);
  4209. // pure sine with an open filter: zero-crossing count gives ~440 Hz
  4210. lynx::SynthSettings sine;
  4211. sine.osc[0].wave = lynx::Waveform::sine;
  4212. sine.cutoff = 20000.0f;
  4213. const auto b = render (sine, 48000, 47000);
  4214. int crossings = 0;
  4215. for (int i = 4800; i < 4800 + 48000 / 2; ++i)
  4216. crossings += (b[(std::size_t) i - 1] < 0.0f) != (b[(std::size_t) i] < 0.0f);
  4217. CHECK (std::abs (crossings - 440) < 6); // half a second = 220 cycles = 440 crossings
  4218. float sinePeak = 0.0f;
  4219. for (int i = 4800; i < 9600; ++i)
  4220. sinePeak = std::max (sinePeak, std::abs (b[(std::size_t) i]));
  4221. CHECK (sinePeak > 0.2f && sinePeak < 0.35f); // 0.3 level, approximated sine without clipping
  4222. // second oscillator an octave up adds energy; sustain 0 makes the note decay on its own
  4223. lynx::SynthSettings two = sine;
  4224. two.osc[1] = { lynx::Waveform::sine, 1, 0.0f, 1.0f };
  4225. two.sustain = 0.0f;
  4226. two.decay = 0.1f;
  4227. const auto c = render (two, 48000, 47000);
  4228. CHECK (peakIn (c, 100, 2000) > peakIn (b, 100, 2000) && peakIn (c, 30000, 40000) < 1e-3f);
  4229. }
  4230. TEST (set_target_value_round_trips)
  4231. {
  4232. auto s = lynx::Song::makeDefault();
  4233. s.mixer[2].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay));
  4234. const lynx::AutomationTarget targets[] = {
  4235. { lynx::AutomationTargetKind::channelVolume, 1 }, { lynx::AutomationTargetKind::channelPan, 2 },
  4236. { lynx::AutomationTargetKind::mixerVolume, 3 }, { lynx::AutomationTargetKind::mixerPan, 0 },
  4237. { lynx::AutomationTargetKind::effectParam, 2, 0, 1 }, { lynx::AutomationTargetKind::tempo, 0 },
  4238. };
  4239. for (const auto& t : targets)
  4240. {
  4241. CHECK (s.setTargetValue (t, 0.25f));
  4242. CHECK (std::abs (s.targetValue (t) - 0.25f) < 1e-5f);
  4243. }
  4244. CHECK (! s.setTargetValue ({ lynx::AutomationTargetKind::channelParam, 0, 0, 3 }, 0.5f)); // lives in the plugin
  4245. }
  4246. TEST (cut_groups_stretch_and_envelope_import)
  4247. {
  4248. // open hat (cut by 1) is cut when the closed one (group 1) plays
  4249. lynx::Song s;
  4250. s.mixer = lynx::Song::defaultMixer (2);
  4251. for (int i = 0; i < 2; ++i)
  4252. {
  4253. lynx::ChannelDef c;
  4254. c.instrument = lynx::InstrumentKind::sampler;
  4255. c.samplePath = "dc";
  4256. c.volume = 1.0f;
  4257. c.mixerTrack = i + 1;
  4258. s.channels.push_back (c);
  4259. }
  4260. s.channels[0].cutBy = 1; // open
  4261. s.channels[1].cutGroup = 1; // closed
  4262. auto& p = s.patterns.emplace_back();
  4263. p.notes = { { 0, 100, 0, 60 }, { 960, 100, 1, 60 } };
  4264. auto provider = [] (const std::string&) {
  4265. auto d = std::make_shared<lynx::SampleData>();
  4266. d->left.assign (96000, 0.5f);
  4267. return std::shared_ptr<const lynx::SampleData> (d);
  4268. };
  4269. auto state = lynx::RackState::build (s, nullptr, 48000.0, provider);
  4270. CHECK (state->hasCutGroups && state->cutTargets[1].size() == 1 && state->cutTargets[1][0] == 0);
  4271. lynx::RackRenderer r;
  4272. r.prepare (48000.0, 512);
  4273. std::vector<float> l (512), rr (512);
  4274. const auto tps = lynx::ticksPerSample (s.bpm, 48000.0);
  4275. float afterCut = 0.0f;
  4276. for (double tick = 0.0; tick < 960.0 * 3; tick += 512 * tps)
  4277. {
  4278. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  4279. if (tick > 960.0 * 2) // the closed one continues; the open one has stopped
  4280. afterCut = std::max (afterCut, std::abs (l[256]));
  4281. }
  4282. CHECK (std::abs (afterCut - 0.5f * 0.78f) < 0.01f); // only the closed one (default velocity 0.78)
  4283. // resampling stretch: 1 s of sample stretched to 4 beats at 120 BPM = 2 s
  4284. auto ramp = std::make_shared<lynx::SampleData>();
  4285. for (int i = 0; i < 48000; ++i)
  4286. ramp->left.push_back ((float) i / 48000.0f);
  4287. ramp->sampleRate = 48000.0;
  4288. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  4289. inst->prepare (48000.0);
  4290. lynx::ChannelDef c;
  4291. c.sampler.stretchBeats = 4.0f;
  4292. inst->configure (c, 120.0);
  4293. inst->noteOn (72, 1.0f); // the note pitch doesn't change the speed
  4294. std::vector<float> a (48000), b (48000);
  4295. inst->render (a.data(), b.data(), 48000, 1.0f, 1.0f);
  4296. CHECK (std::abs (a[47999] - 0.5f) < 0.01f); // after 1 s it has read half
  4297. // FL envelope time: 32950 = 2 s; < 101 = 0
  4298. CHECK (std::abs (flp::Channel::envelopeTime (32950) - 2.0) < 0.01 && flp::Channel::envelopeTime (50) == 0.0);
  4299. }
  4300. TEST (time_stretch_keeps_pitch)
  4301. {
  4302. lynx::SampleData sine;
  4303. sine.sampleRate = 48000.0;
  4304. for (int i = 0; i < 48000; ++i)
  4305. sine.left.push_back (0.5f * std::sin (2.0f * 3.14159265f * 440.0f * (float) i / 48000.0f));
  4306. auto crossingsPerSecond = [] (const lynx::SampleData& d) {
  4307. int c = 0;
  4308. const auto n = (int) d.frames();
  4309. for (int i = 4800; i < n - 4800; ++i)
  4310. c += (d.left[(std::size_t) i - 1] < 0.0f) != (d.left[(std::size_t) i] < 0.0f);
  4311. return (double) c / ((double) (n - 9600) / d.sampleRate);
  4312. };
  4313. for (double ratio : { 2.0, 0.5, 1.37 })
  4314. {
  4315. const auto out = lynx::timeStretch (sine, ratio);
  4316. CHECK (std::abs ((double) out->frames() - 48000.0 * ratio) < 2.0);
  4317. CHECK (std::abs (crossingsPerSecond (*out) - 880.0) < 15.0); // 440 Hz stays 440 Hz
  4318. float peak = 0.0f;
  4319. for (std::size_t i = 4800; i + 4800 < out->frames(); ++i)
  4320. peak = std::max (peak, std::abs (out->left[i]));
  4321. CHECK (peak > 0.4f && peak < 0.6f); // no gaps or clipping in the overlap
  4322. }
  4323. }
  4324. TEST (sampler_region_start_and_end)
  4325. {
  4326. auto ramp = std::make_shared<lynx::SampleData>();
  4327. for (int i = 0; i < 10000; ++i)
  4328. ramp->left.push_back ((float) i / 10000.0f);
  4329. ramp->sampleRate = 48000.0;
  4330. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  4331. inst->prepare (48000.0);
  4332. lynx::ChannelDef c;
  4333. c.sampler.regionStart = 0.25f;
  4334. c.sampler.regionEnd = 0.5f;
  4335. inst->configure (c, 120.0);
  4336. inst->noteOn (60, 1.0f);
  4337. std::vector<float> l (6000), r (6000);
  4338. inst->render (l.data(), r.data(), 6000, 1.0f, 1.0f);
  4339. CHECK (std::abs (l[0] - 0.25f) < 0.001f); // starts at the beginning of the slice
  4340. CHECK (l[2400] > 0.48f && l[2600] == 0.0f); // and stops at its end
  4341. }
  4342. TEST (arpeggiator_plays_held_chord_in_steps)
  4343. {
  4344. auto song = lynx::Song::makeDefault();
  4345. song.bpm = 120.0;
  4346. song.patterns[0].notes.clear();
  4347. for (int key : { 60, 64, 67 })
  4348. song.patterns[0].notes.push_back ({ 0, lynx::ppq * 4, 4, key, 0.8f }); // chord held for 1 bar
  4349. song.channels[4].arp.direction = 1; // up
  4350. song.channels[4].arp.stepBeats = 0.25f;
  4351. auto state = lynx::RackState::build (song, nullptr, 48000.0);
  4352. CHECK (state->arpeggiators[4] != nullptr && state->arpeggiators[0] == nullptr);
  4353. // the arpeggiator generates the notes; we count what it hands to the instrument
  4354. auto& arp = *state->arpeggiators[4];
  4355. const auto tps = lynx::ticksPerSample (song.bpm, 48000.0);
  4356. std::vector<int> keys;
  4357. lynx::EventBuffer ev;
  4358. for (double tick = 0.0; tick < lynx::ppq * 2.0; tick += 512 * tps)
  4359. {
  4360. ev.clear();
  4361. lynx::schedulePatternLoop (song.patterns[0], song.patterns[0].effectiveLength (4), tick, 512, tps, ev);
  4362. int in = 0, out = 0;
  4363. for (auto& e : ev)
  4364. if (e.channel == 4)
  4365. arp.input[(std::size_t) in++] = e;
  4366. arp.process (4, arp.input.data(), in, tick, tps, 512, song.channels[4].arp, arp.output.data(), out);
  4367. for (int i = 0; i < out; ++i)
  4368. if (arp.output[(std::size_t) i].type == lynx::NoteEvent::Type::on)
  4369. keys.push_back (arp.output[(std::size_t) i].key);
  4370. }
  4371. // 2 beats = 8 sixteenth steps: 60 64 67 60 64 67 60 64
  4372. CHECK (keys.size() >= 8); // the last block goes slightly past 2 beats
  4373. const int expected[] = { 60, 64, 67, 60, 64, 67, 60, 64 };
  4374. for (std::size_t i = 0; i < keys.size() && i < 8; ++i)
  4375. CHECK (keys[i] == expected[i]);
  4376. // actually rendering also makes sound
  4377. lynx::RackRenderer r;
  4378. r.prepare (48000.0, 512);
  4379. std::vector<float> l (512), rr (512);
  4380. float peak = 0.0f;
  4381. for (double tick = 0.0; tick < lynx::ppq; tick += 512 * tps)
  4382. {
  4383. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  4384. for (auto v : l)
  4385. peak = std::max (peak, std::abs (v));
  4386. }
  4387. CHECK (peak > 0.01f);
  4388. }
  4389. TEST (audio_clip_fades_and_gain)
  4390. {
  4391. lynx::Song s;
  4392. s.bpm = 120.0;
  4393. s.mode = lynx::PlayMode::song;
  4394. s.mixer = lynx::Song::defaultMixer (1);
  4395. lynx::ChannelDef c;
  4396. c.instrument = lynx::InstrumentKind::audioClip;
  4397. c.samplePath = "dc";
  4398. c.volume = 1.0f;
  4399. c.mixerTrack = 1;
  4400. s.channels.push_back (c);
  4401. s.patterns.emplace_back();
  4402. lynx::Clip clip;
  4403. clip.kind = lynx::ClipKind::audio;
  4404. clip.channel = 0;
  4405. clip.length = lynx::ppq * 4; // 2 s at 120 BPM
  4406. clip.fadeIn = lynx::ppq; // 0.5 s
  4407. clip.fadeOut = lynx::ppq;
  4408. clip.gain = 0.5f;
  4409. s.playlist.push_back (clip);
  4410. auto provider = [] (const std::string&) {
  4411. auto d = std::make_shared<lynx::SampleData>();
  4412. d->left.assign (48000 * 4, 1.0f);
  4413. return std::shared_ptr<const lynx::SampleData> (d);
  4414. };
  4415. auto state = lynx::RackState::build (s, nullptr, 48000.0, provider);
  4416. lynx::RackRenderer r;
  4417. r.prepare (48000.0, 512);
  4418. std::vector<float> all;
  4419. std::vector<float> l (512), rr (512);
  4420. const auto tps = lynx::ticksPerSample (s.bpm, 48000.0);
  4421. for (double tick = 0.0; tick < lynx::ppq * 4.0; tick += 512 * tps)
  4422. {
  4423. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  4424. all.insert (all.end(), l.begin(), l.end());
  4425. }
  4426. CHECK (all[100] < 0.01f); // fade-in start
  4427. CHECK (std::abs (all[12000] - 0.25f) < 0.02f); // fade-in midpoint: half of 0.5
  4428. CHECK (std::abs (all[48000] - 0.5f) < 0.01f); // body: the clip gain
  4429. CHECK (std::abs (all[96000 - 12000] - 0.25f) < 0.02f); // fade-out midpoint
  4430. }
  4431. TEST (slicer_detects_hits_and_plays_slices_by_key)
  4432. {
  4433. // 4 hits (decaying noise) every 0.25 s
  4434. lynx::SampleData loop;
  4435. loop.sampleRate = 48000.0;
  4436. loop.left.assign (48000, 0.0f);
  4437. lynx::Noise noise;
  4438. for (int hit = 0; hit < 4; ++hit)
  4439. for (int i = 0; i < 6000; ++i)
  4440. loop.left[(std::size_t) (hit * 12000 + i)] = noise.next() * 0.8f * std::exp (-(float) i / 1500.0f);
  4441. const auto slices = lynx::detectSlices (loop, 0.5f);
  4442. CHECK (slices.size() == 4);
  4443. for (std::size_t i = 0; i < slices.size(); ++i)
  4444. CHECK (std::abs (slices[i] - 0.25f * (float) i) < 0.01f);
  4445. // key 61 plays the second slice, which starts at 0.25 and ends before 0.5
  4446. auto ramp = std::make_shared<lynx::SampleData>();
  4447. for (int i = 0; i < 48000; ++i)
  4448. ramp->left.push_back ((float) i / 48000.0f);
  4449. ramp->sampleRate = 48000.0;
  4450. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  4451. inst->prepare (48000.0);
  4452. lynx::ChannelDef c;
  4453. c.sampler.slices = slices;
  4454. inst->configure (c, 120.0);
  4455. inst->noteOn (61, 1.0f);
  4456. std::vector<float> l (20000), r (20000);
  4457. inst->render (l.data(), r.data(), 20000, 1.0f, 1.0f);
  4458. CHECK (std::abs (l[0] - 0.25f) < 0.01f && l[11000] > 0.45f && l[13000] == 0.0f);
  4459. }
  4460. TEST (project_templates_render_sound)
  4461. {
  4462. const auto names = lynx::templateNames();
  4463. CHECK (names.size() == 4);
  4464. for (int t = 1; t < (int) names.size(); ++t)
  4465. {
  4466. auto song = lynx::makeTemplate (t);
  4467. auto state = lynx::RackState::build (song, nullptr, 48000.0);
  4468. lynx::RackRenderer r;
  4469. r.prepare (48000.0, 512);
  4470. std::vector<float> l (512), rr (512);
  4471. const auto tps = lynx::ticksPerSample (song.bpm, 48000.0);
  4472. float peak = 0.0f;
  4473. for (double tick = 0.0; tick < lynx::ppq * 4.0; tick += 512 * tps)
  4474. {
  4475. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  4476. for (auto v : l)
  4477. peak = std::max (peak, std::abs (v));
  4478. }
  4479. CHECK (peak > 0.05f && peak < 4.0f);
  4480. }
  4481. CHECK (lynx::makeTemplate (0).patterns[0].notes.empty());
  4482. }
  4483. // --- interface translations (resources/i18n) -------------------------------------------------------
  4484. namespace i18ntest
  4485. {
  4486. std::string readFile (const std::filesystem::path& path)
  4487. {
  4488. std::ifstream in (path, std::ios::binary);
  4489. return { std::istreambuf_iterator<char> (in), std::istreambuf_iterator<char>() };
  4490. }
  4491. std::string unescape (const std::string& s)
  4492. {
  4493. std::string out;
  4494. for (std::size_t i = 0; i < s.size(); ++i)
  4495. {
  4496. if (s[i] == '\\' && i + 1 < s.size())
  4497. {
  4498. const auto n = s[++i];
  4499. out += n == 'n' ? '\n' : n == 't' ? '\t' : n;
  4500. }
  4501. else
  4502. out += s[i];
  4503. }
  4504. return out;
  4505. }
  4506. // reads a quoted string starting at s[pos] == '"'; returns the raw (escaped) contents and moves pos past the closing quote
  4507. bool quoted (const std::string& s, std::size_t& pos, std::string& raw)
  4508. {
  4509. if (pos >= s.size() || s[pos] != '"')
  4510. return false;
  4511. raw.clear();
  4512. for (++pos; pos < s.size() && s[pos] != '"' && s[pos] != '\n'; ++pos)
  4513. {
  4514. if (s[pos] == '\\' && pos + 1 < s.size())
  4515. raw += s[pos++];
  4516. raw += s[pos];
  4517. }
  4518. if (pos >= s.size() || s[pos] != '"')
  4519. return false;
  4520. ++pos;
  4521. return true;
  4522. }
  4523. // JUCE LocalisedStrings format: "english" = "translation"; duplicates are reported in `duplicates`
  4524. std::map<std::string, std::string> parseTable (const std::string& text, std::vector<std::string>& duplicates)
  4525. {
  4526. std::map<std::string, std::string> table;
  4527. std::istringstream lines (text);
  4528. std::string line;
  4529. while (std::getline (lines, line))
  4530. {
  4531. std::size_t pos = line.find_first_not_of (" \t");
  4532. std::string key, value;
  4533. if (pos == std::string::npos || ! quoted (line, pos, key))
  4534. continue;
  4535. pos = line.find ('"', pos);
  4536. if (pos == std::string::npos || ! quoted (line, pos, value))
  4537. value.clear();
  4538. const auto k = unescape (key);
  4539. if (table.count (k) != 0)
  4540. duplicates.push_back (k);
  4541. table[k] = unescape (value);
  4542. }
  4543. return table;
  4544. }
  4545. // string literals passed to tr() / TR_NOOP() in the sources (adjacent literals are concatenated)
  4546. std::map<std::string, std::string> sourceKeys (const std::filesystem::path& srcDir)
  4547. {
  4548. std::map<std::string, std::string> keys;
  4549. for (const auto& entry : std::filesystem::recursive_directory_iterator (srcDir))
  4550. {
  4551. const auto ext = entry.path().extension().string();
  4552. if (! entry.is_regular_file() || (ext != ".cpp" && ext != ".h"))
  4553. continue;
  4554. // drop // comment lines (they may quote tr ("...") as an example)
  4555. std::string text, line;
  4556. std::istringstream in (readFile (entry.path()));
  4557. while (std::getline (in, line))
  4558. {
  4559. const auto first = line.find_first_not_of (" \t");
  4560. text += (first != std::string::npos && line.compare (first, 2, "//") == 0) ? std::string() : line;
  4561. text += '\n';
  4562. }
  4563. auto isIdent = [] (char c) { return std::isalnum ((unsigned char) c) || c == '_'; };
  4564. for (const std::string name : { "tr", "TR_NOOP" })
  4565. for (auto at = text.find (name); at != std::string::npos; at = text.find (name, at + 1))
  4566. {
  4567. if ((at > 0 && isIdent (text[at - 1])) || isIdent (text[at + name.size()]))
  4568. continue;
  4569. auto pos = text.find_first_not_of (" \t\n", at + name.size());
  4570. if (pos == std::string::npos || text[pos] != '(')
  4571. continue;
  4572. pos = text.find_first_not_of (" \t\n", pos + 1);
  4573. std::string key, raw;
  4574. bool any = false;
  4575. while (pos != std::string::npos && quoted (text, pos, raw))
  4576. {
  4577. key += raw;
  4578. any = true;
  4579. pos = text.find_first_not_of (" \t\n", pos);
  4580. }
  4581. if (any)
  4582. keys.emplace (unescape (key), entry.path().filename().string());
  4583. }
  4584. }
  4585. return keys;
  4586. }
  4587. std::set<std::string> placeholders (const std::string& s)
  4588. {
  4589. std::set<std::string> found;
  4590. for (auto open = s.find ('{'); open != std::string::npos; open = s.find ('{', open + 1))
  4591. if (const auto close = s.find ('}', open); close != std::string::npos && close - open <= 3)
  4592. found.insert (s.substr (open, close - open + 1));
  4593. return found;
  4594. }
  4595. } // namespace i18ntest
  4596. TEST (translations_cover_every_ui_string)
  4597. {
  4598. using namespace i18ntest;
  4599. const auto text = readFile ("resources/i18n/pt-BR.txt");
  4600. CHECK (! text.empty());
  4601. std::vector<std::string> duplicates;
  4602. const auto table = parseTable (text, duplicates);
  4603. CHECK (table.size() > 300);
  4604. CHECK (duplicates.empty());
  4605. for (const auto& d : duplicates)
  4606. std::printf (" duplicate pt-BR entry: \"%s\"\n", d.c_str());
  4607. const auto keys = sourceKeys ("src");
  4608. CHECK (keys.size() > 300);
  4609. int missing = 0;
  4610. for (const auto& [key, file] : keys)
  4611. if (auto it = table.find (key); it == table.end() || it->second.empty())
  4612. {
  4613. ++missing;
  4614. std::printf (" no pt-BR translation for \"%s\" (%s)\n", key.c_str(), file.c_str());
  4615. }
  4616. CHECK (missing == 0);
  4617. // no empty values, and every {n} placeholder survives the translation
  4618. int empty = 0, badPlaceholders = 0;
  4619. for (const auto& [english, portuguese] : table)
  4620. {
  4621. empty += portuguese.empty() ? 1 : 0;
  4622. if (placeholders (english) != placeholders (portuguese))
  4623. {
  4624. ++badPlaceholders;
  4625. std::printf (" placeholders differ: \"%s\"\n", english.c_str());
  4626. }
  4627. }
  4628. CHECK (empty == 0);
  4629. CHECK (badPlaceholders == 0);
  4630. }
  4631. TEST (translations_embedded_table_is_up_to_date)
  4632. {
  4633. // src/ui/I18nData.h must be regenerated (tools/make_i18n.py) whenever the .txt changes
  4634. const auto text = i18ntest::readFile ("resources/i18n/pt-BR.txt");
  4635. CHECK (text.size() == sizeof (lynx::i18n::data::ptBR));
  4636. CHECK (std::memcmp (text.data(), lynx::i18n::data::ptBR, std::min (text.size(), sizeof (lynx::i18n::data::ptBR))) == 0);
  4637. }
  4638. // --- workflow shell: pattern/channel operations, key map, workspace layout, control math -------------
  4639. TEST (workflow_pattern_navigation_and_insert)
  4640. {
  4641. auto song = lynx::Song::makeDefault();
  4642. song.patterns.resize (3);
  4643. song.patterns[1].name = "B";
  4644. song.patterns[2].name = "C";
  4645. song.patterns[2].notes.push_back ({});
  4646. song.currentPattern = 0;
  4647. CHECK (lynx::stepPattern (song, 1) == 1 && lynx::stepPattern (song, -1) == 0 && lynx::stepPattern (song, 10) == 2);
  4648. // pattern 0 has the default notes, 1 is empty, 2 has a note
  4649. CHECK (! lynx::isPatternEmpty (song.patterns[0]) && lynx::isPatternEmpty (song.patterns[1]));
  4650. CHECK (lynx::findNextEmptyPattern (song, 0) == 1 && lynx::findNextEmptyPattern (song, 1) == -1);
  4651. CHECK (lynx::gotoNextEmptyPattern (song) == 1 && song.currentPattern == 1);
  4652. song.patterns[1].notes.push_back ({});
  4653. const auto before = song.patterns.size();
  4654. CHECK (lynx::gotoNextEmptyPattern (song) == (int) before && song.patterns.size() == before + 1);
  4655. CHECK (song.patterns.back().name == "Pattern 1" || song.patterns.back().name.rfind ("Pattern ", 0) == 0);
  4656. // insert keeps Playlist clips on their patterns
  4657. lynx::Clip clip;
  4658. clip.pattern = 2;
  4659. song.playlist = { clip };
  4660. song.arrangements.push_back ({ "Other", { clip }, 0, 0, {} });
  4661. CHECK (lynx::insertPattern (song, 1, "New") == 1 && song.currentPattern == 1);
  4662. CHECK (song.patterns[1].name == "New" && song.patterns[1].notes.empty() && song.patterns[3].name == "C");
  4663. CHECK (song.playlist[0].pattern == 3 && song.arrangements[1].clips[0].pattern == 3);
  4664. }
  4665. TEST (workflow_split_pattern_by_channel)
  4666. {
  4667. auto song = lynx::Song::makeDefault();
  4668. song.patterns.resize (1);
  4669. auto& p = song.patterns[0];
  4670. p.name = "Beat";
  4671. p.notes.clear();
  4672. for (int i = 0; i < 4; ++i)
  4673. p.notes.push_back ({ (std::int64_t) i * lynx::ticksPerStep, lynx::ticksPerStep, i % 2 == 0 ? 0 : 2, 60 });
  4674. song.channels[2].colour = 0xff112233;
  4675. lynx::Clip clip;
  4676. clip.pattern = 0;
  4677. song.playlist = { clip };
  4678. const auto created = lynx::splitPatternByChannel (song, 0);
  4679. CHECK (created == 2 && song.patterns.size() == 3);
  4680. CHECK (song.patterns[0].notes.size() == 4); // the original is unchanged
  4681. CHECK (song.patterns[1].name == "Beat - " + song.channels[0].name && song.patterns[1].notes.size() == 2);
  4682. CHECK (song.patterns[2].colour == 0xff112233u && song.patterns[2].notes.size() == 2 && song.patterns[2].notes[0].channel == 2);
  4683. CHECK (song.playlist[0].pattern == 0);
  4684. CHECK (lynx::splitPatternByChannel (song, 99) == 0);
  4685. }
  4686. TEST (workflow_channel_selection)
  4687. {
  4688. lynx::ChannelSelection s;
  4689. s.selectOnly (2);
  4690. s.toggle (5);
  4691. s.toggle (0);
  4692. CHECK ((s.rows == std::vector<int> { 0, 2, 5 }) && s.contains (5) && ! s.contains (3));
  4693. s.toggle (2);
  4694. CHECK ((s.rows == std::vector<int> { 0, 5 }));
  4695. s.selectOnly (3);
  4696. s.extendTo (6);
  4697. CHECK ((s.rows == std::vector<int> { 3, 4, 5, 6 }));
  4698. s.extendTo (1);
  4699. CHECK ((s.rows == std::vector<int> { 1, 2, 3 }));
  4700. s.selectOnly (4);
  4701. s.toggle (4); // the last one stays
  4702. CHECK ((s.rows == std::vector<int> { 4 }));
  4703. s.selectAll (3);
  4704. CHECK ((s.rows == std::vector<int> { 0, 1, 2 }));
  4705. s.rows = { 7, 9 };
  4706. s.clamp (5);
  4707. CHECK (s.rows.size() == 1 && s.rows[0] < 5);
  4708. }
  4709. TEST (workflow_move_clone_insert_channels)
  4710. {
  4711. auto song = lynx::Song::makeDefault();
  4712. const auto names = [&] {
  4713. std::vector<std::string> n;
  4714. for (const auto& c : song.channels)
  4715. n.push_back (c.name);
  4716. return n;
  4717. };
  4718. const auto original = names();
  4719. const auto count = (int) song.channels.size();
  4720. CHECK (count >= 4);
  4721. // references that must follow their channel
  4722. song.patterns[0].notes.push_back ({ 0, 240, 1, 64 });
  4723. lynx::Automation a;
  4724. a.target = { lynx::AutomationTargetKind::channelVolume, 1 };
  4725. song.automations.push_back (a);
  4726. song.midiLinks.push_back ({ 7, -1, { lynx::AutomationTargetKind::channelPan, 3 } });
  4727. lynx::Clip audio;
  4728. audio.kind = lynx::ClipKind::audio;
  4729. audio.channel = 3;
  4730. song.playlist.push_back (audio);
  4731. std::vector<int> selection { 1, 3 };
  4732. CHECK (lynx::moveChannels (song, selection, -1));
  4733. CHECK ((selection == std::vector<int> { 0, 2 }));
  4734. CHECK (song.channels[0].name == original[1] && song.channels[1].name == original[0] && song.channels[2].name == original[3]
  4735. && song.channels[3].name == original[2]);
  4736. CHECK (song.automations[0].target.index == 0 && song.midiLinks[0].target.index == 2 && song.playlist.back().channel == 2);
  4737. CHECK (std::any_of (song.patterns[0].notes.begin(), song.patterns[0].notes.end(),
  4738. [] (const lynx::Note& n) { return n.channel == 0 && n.key == 64; }));
  4739. CHECK (! lynx::moveChannels (song, selection, -1)); // the block is at the top
  4740. CHECK (lynx::moveChannels (song, selection, 1) && (selection == std::vector<int> { 1, 3 }) && names() == original);
  4741. // clone: settings, not notes, right below, with a new name
  4742. song.channels[1].volume = 0.33f;
  4743. const auto notesBefore = song.patterns[0].notes.size();
  4744. const auto clone = lynx::cloneChannel (song, 1);
  4745. CHECK (clone == 2 && (int) song.channels.size() == count + 1);
  4746. CHECK (song.channels[2].name == original[1] + " #2" && song.channels[2].volume == 0.33f);
  4747. CHECK (song.patterns[0].notes.size() == notesBefore);
  4748. CHECK (song.channels[3].name == original[2] && song.automations[0].target.index == 1);
  4749. CHECK (lynx::cloneChannel (song, 1) == 2 && song.channels[2].name == original[1] + " #3");
  4750. // remove several
  4751. CHECK (lynx::removeChannels (song, { 2, 3, 2 }) == 2 && (int) song.channels.size() == count);
  4752. CHECK (names() == original);
  4753. }
  4754. TEST (workflow_send_channels_to_free_inserts)
  4755. {
  4756. auto song = lynx::Song::makeDefault();
  4757. for (auto& c : song.channels)
  4758. c.mixerTrack = 0;
  4759. song.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay)); // not free: has effects
  4760. song.channels[0].mixerTrack = 2; // not free: used
  4761. song.setRoute (5, 3, true); // 3 is not free: receives a send
  4762. CHECK (! lynx::isInsertFree (song, 1) && ! lynx::isInsertFree (song, 2) && ! lynx::isInsertFree (song, 3) && lynx::isInsertFree (song, 4));
  4763. song.channels[1].colour = 0xff445566;
  4764. const auto tracks = lynx::sendChannelsToFreeInserts (song, { 1, 2 });
  4765. CHECK ((tracks == std::vector<int> { 4, 5 }) || (tracks == std::vector<int> { 4, 6 }));
  4766. CHECK (song.channels[1].mixerTrack == 4 && song.mixer[4].name == song.channels[1].name && song.mixer[4].colour == 0xff445566u);
  4767. CHECK (song.mixer[(std::size_t) tracks[1]].name == song.channels[2].name);
  4768. // with no free insert left, a new one is added at the end
  4769. auto full = lynx::Song::makeDefault();
  4770. full.mixer = lynx::Song::defaultMixer (1);
  4771. full.channels[0].mixerTrack = 1;
  4772. const auto added = lynx::sendChannelsToFreeInserts (full, { 1 });
  4773. CHECK (added.size() == 1 && added[0] == 2 && full.mixer.size() == 3 && full.channels[1].mixerTrack == 2);
  4774. }
  4775. TEST (workflow_palette_random_colour)
  4776. {
  4777. const auto& palette = lynx::lynxPalette();
  4778. for (std::uint32_t seed = 0; seed < 50; ++seed)
  4779. {
  4780. const auto current = palette[seed % palette.size()];
  4781. const auto c = lynx::randomPaletteColour (current, seed);
  4782. CHECK (c != current && std::find (palette.begin(), palette.end(), c) != palette.end());
  4783. }
  4784. }
  4785. TEST (workflow_key_map)
  4786. {
  4787. using namespace lynx::keys;
  4788. KeyMap map;
  4789. const auto global = Context::global, rack = Context::channelRack;
  4790. CHECK (map.find ({ space, none }, global, true) == "transport.playStop");
  4791. CHECK (map.find ({ space, ctrl }, global, true) == "transport.pause");
  4792. CHECK (map.find ({ f6, none }, global, true) == "panel.channelRack");
  4793. CHECK (map.find ({ f8, alt }, global, false) == "panel.browser");
  4794. CHECK (map.find ({ insert, ctrl | shift }, global, false) == "pattern.insert");
  4795. CHECK (map.find ({ numpadPlus, none }, rack, true) == "pattern.next");
  4796. // panel context: only while focused
  4797. CHECK (map.find ({ 'L', ctrl }, rack, true) == "rack.sendToInserts");
  4798. CHECK (map.find ({ 'L', ctrl }, global, true).empty());
  4799. CHECK (map.find ({ up, alt }, rack, false) == "rack.moveUp");
  4800. // typing piano: note keys play, other plain keys only for whilePiano actions; chords always work
  4801. CHECK (KeyMap::playsNote ({ 'Z', none }, true) && ! KeyMap::playsNote ({ 'Z', none }, false) && ! KeyMap::playsNote ({ 'Z', ctrl }, true));
  4802. CHECK (map.find ({ 'L', none }, global, true) == "transport.toggleMode");
  4803. CHECK (map.find ({ '1', none }, rack, false) == "rack.mute1" && map.find ({ '0', none }, rack, false) == "rack.mute10");
  4804. CHECK (map.find ({ '1', none }, rack, true).empty()); // a plain digit is not a shortcut while the piano is on
  4805. CHECK (map.find ({ '2', ctrl }, rack, true) == "rack.solo2");
  4806. CHECK (typingPianoNote ('Z') == 60 && typingPianoNote ('q') == 72 && typingPianoNote ('P') == 88 && typingPianoNote ('L') == -1);
  4807. CHECK (map.conflicts().empty());
  4808. // chord text
  4809. CHECK (toString ({ f4, ctrl | shift }) == "Ctrl+Shift+F4" && toString ({ numpadMinus, none }) == "Numpad -");
  4810. CHECK (parseChord ("Shift+Ctrl+Ins") == (Chord { insert, ctrl | shift }));
  4811. CHECK (parseChord ("alt+up") == (Chord { up, alt }) && parseChord ("k") == (Chord { 'K', none }));
  4812. CHECK (parseChord ("Numpad +") == (Chord { numpadPlus, none }) && ! parseChord ("F13") && ! parseChord ("Ctrl+"));
  4813. for (const auto& a : actions())
  4814. for (const auto& c : a.defaults)
  4815. CHECK (parseChord (toString (c)) == c);
  4816. // JSON overrides
  4817. std::vector<std::string> errors;
  4818. CHECK (map.loadJson (R"({ "pattern.next": "Ctrl+Right", "rack.clone": ["Alt+D", "Ctrl+D"], "help.shortcuts": "", "nope": "F1", "file.open": "Hyper+Q" })", &errors));
  4819. CHECK (errors.size() == 2);
  4820. CHECK (map.find ({ right, ctrl }, global, false) == "pattern.next" && map.find ({ numpadPlus, none }, global, false).empty());
  4821. CHECK (map.find ({ 'D', ctrl }, rack, false) == "rack.clone" && map.find ({ f1, none }, global, false).empty());
  4822. map.setChords ("pattern.previous", { { right, ctrl } });
  4823. CHECK (map.conflicts().size() == 1);
  4824. KeyMap reloaded;
  4825. CHECK (reloaded.loadJson (map.toJson()) && reloaded.chordsFor ("rack.clone") == map.chordsFor ("rack.clone"));
  4826. CHECK (! map.loadJson ("[1, 2]") && ! map.loadJson ("{\"a\": }"));
  4827. map.resetToDefaults();
  4828. CHECK (map.find ({ numpadPlus, none }, global, false) == "pattern.next");
  4829. }
  4830. TEST (workflow_workspace_layout)
  4831. {
  4832. using namespace lynx::workspace;
  4833. auto l = Layout::makeDefault (1280, 620);
  4834. // every visible panel is inside the desktop; the default shows Browser, Playlist and Channel Rack
  4835. for (const auto& p : l.panels)
  4836. CHECK (p.bounds.x >= 0 && p.bounds.y >= 0 && p.bounds.right() <= 1280 && p.bounds.bottom() <= 620 && p.bounds.w >= minWidth);
  4837. CHECK (l[Panel::browser].visible && l[Panel::playlist].visible && l[Panel::channelRack].visible);
  4838. CHECK (! l[Panel::pianoRoll].visible && ! l[Panel::mixer].visible);
  4839. CHECK (l[Panel::playlist].bounds.x == l[Panel::browser].bounds.right() && l[Panel::playlist].bounds.right() == 1280);
  4840. CHECK (l.isFrontmost (Panel::channelRack) && l.focused == Panel::channelRack);
  4841. // toggle: show+focus, focus, hide
  4842. CHECK (l.toggle (Panel::mixer) && l.focused == Panel::mixer && l.isFrontmost (Panel::mixer));
  4843. CHECK (l.toggle (Panel::channelRack) && l.focused == Panel::channelRack && l.isFrontmost (Panel::channelRack));
  4844. CHECK (! l.toggle (Panel::channelRack) && ! l[Panel::channelRack].visible && l.focused == Panel::mixer);
  4845. l.toggleMaximised (Panel::playlist);
  4846. CHECK (l[Panel::playlist].maximised && l.focused == Panel::playlist);
  4847. // save and load at another size: positions scale
  4848. l[Panel::mixer].detached = true;
  4849. l[Panel::mixer].windowBounds = { 100, 50, 900, 500 };
  4850. const auto text = l.serialise();
  4851. const auto big = Layout::parse (text, 2560, 1240);
  4852. CHECK (big.has_value());
  4853. if (big)
  4854. {
  4855. CHECK ((*big)[Panel::playlist].maximised && (*big)[Panel::mixer].detached && (*big)[Panel::mixer].windowBounds.w == 900);
  4856. CHECK (std::abs ((*big)[Panel::playlist].bounds.x - 2 * l[Panel::playlist].bounds.x) <= 1);
  4857. CHECK (big->order == l.order && big->focused == l.focused);
  4858. }
  4859. 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));
  4860. // resize keeps panels inside and edges glued to the border
  4861. l.resize (1000, 500);
  4862. CHECK (l[Panel::playlist].bounds.right() == 1000 && l[Panel::browser].bounds.bottom() == 500);
  4863. for (const auto& p : l.panels)
  4864. CHECK (p.bounds.right() <= 1000 && p.bounds.bottom() <= 500);
  4865. // off-screen panels come back
  4866. l[Panel::pianoRoll].bounds = { 5000, -300, 400, 300 };
  4867. CHECK (l.bringBackOffscreen() == 1 && l[Panel::pianoRoll].bounds.x + 400 <= 1000 && l[Panel::pianoRoll].bounds.y == 0);
  4868. // snapping: to the desktop, to another panel, and resizing one edge
  4869. CHECK ((snap ({ 5, 6, 200, 100 }, {}, 1000, 500) == Rect { 0, 0, 200, 100 }));
  4870. CHECK ((snap ({ 304, 50, 200, 100 }, { { 0, 0, 300, 400 } }, 1000, 500) == Rect { 300, 50, 200, 100 }));
  4871. CHECK ((snap ({ 304, 50, 200, 100 }, { { 0, 0, 300, 400 } }, 1000, 500, 2) == Rect { 304, 50, 200, 100 })); // out of range
  4872. CHECK ((snap ({ 100, 100, 195, 100 }, { { 300, 0, 300, 400 } }, 1000, 500, 8, right) == Rect { 100, 100, 200, 100 }));
  4873. CHECK ((snap ({ 100, 100, 195, 100 }, { { 300, 1000, 300, 400 } }, 2000, 2000, 8, right) == Rect { 100, 100, 195, 100 })); // not facing
  4874. }
  4875. TEST (workflow_control_math)
  4876. {
  4877. using namespace lynx::controls;
  4878. CHECK (std::abs (dragValue (0.5, 75, 0, 1, 150, false) - 1.0) < 1e-9);
  4879. CHECK (std::abs (dragValue (0.5, 75, 0, 1, 150, true) - 0.55) < 1e-9);
  4880. CHECK (dragValue (0.5, -1000, -1, 1, 150, false) == -1.0);
  4881. 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);
  4882. CHECK (wheelValue (3, 1, 0, 10, true, 1) == 4.0); // integer controls move at least one step
  4883. CHECK (std::abs (snapToInterval (0.234, 0, 0.1) - 0.2) < 1e-9);
  4884. CHECK (tempoDrag (130.0, 8, false, false) == 132.0 && tempoDrag (130.0, -3, false, false) == 130.0);
  4885. CHECK (std::abs (tempoDrag (130.0, 25, true, false) - 130.25) < 1e-9);
  4886. CHECK (std::abs (tempoDrag (130.0, 8, false, true) - 130.2) < 1e-9);
  4887. CHECK (tempoDrag (520.0, 400, false, false) == lynx::maxTempo && halfTempo (15.0) == lynx::minTempo && doubleTempo (130.0) == 260.0);
  4888. TapTempo tap;
  4889. CHECK (! tap.tap (1000.0));
  4890. CHECK (tap.tap (1500.0) == 120.0);
  4891. CHECK (tap.tap (2000.0) == 120.0 && tap.count() == 3);
  4892. CHECK (std::abs (*tap.tap (2400.0) - 128.57) < 0.01); // average of 500, 500, 400 ms
  4893. CHECK (! tap.tap (9000.0) && tap.count() == 1); // a long pause starts over
  4894. }
  4895. int main (int argc, char** argv)
  4896. {
  4897. if (argc > 1)
  4898. realFlpDir = argv[1];
  4899. const char* only = std::getenv ("LYNX_TEST"); // run only the tests whose name contains this
  4900. for (auto& [name, fn] : registry())
  4901. {
  4902. if (only != nullptr && std::strstr (name, only) == nullptr)
  4903. continue;
  4904. std::printf ("%s\n", name);
  4905. fn();
  4906. }
  4907. std::printf ("\n%d checks, %d failures\n", checks, failures);
  4908. return failures == 0 ? 0 : 1;
  4909. }
  4910. TEST (synth_cutoff_keytrack)
  4911. {
  4912. // the cutoff follows the note from key 48 (130.81 Hz), like Harmor's "Key to filter frequency"
  4913. auto rms = [] (float keyTrack, int key) {
  4914. lynx::SynthSettings s;
  4915. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  4916. s.cutoff = 130.81f;
  4917. s.keyTrack = keyTrack;
  4918. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  4919. inst->prepare (48000.0);
  4920. lynx::ChannelDef c;
  4921. c.synth = s;
  4922. inst->configure (c, 120.0);
  4923. inst->noteOn (key, 1.0f);
  4924. std::vector<float> l (24000), r (24000);
  4925. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  4926. double e = 0.0;
  4927. for (int i = 4800; i < 24000; ++i)
  4928. e += (double) l[(std::size_t) i] * l[(std::size_t) i];
  4929. return std::sqrt (e / 19200.0);
  4930. };
  4931. const auto fixed = rms (0.0f, 72), tracked = rms (1.0f, 72);
  4932. CHECK (tracked > 4.0 * fixed); // 2 octaves up: without keytrack the low-pass cuts
  4933. CHECK (std::abs (rms (1.0f, 48) - rms (0.0f, 48)) < 0.05 * rms (0.0f, 48)); // unchanged at the reference key
  4934. }
  4935. namespace
  4936. {
  4937. std::vector<float> renderSynthNote (const lynx::SynthSettings& s, int key, int frames)
  4938. {
  4939. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  4940. inst->prepare (48000.0);
  4941. lynx::ChannelDef c;
  4942. c.synth = s;
  4943. inst->configure (c, 120.0);
  4944. inst->noteOn (key, 1.0f);
  4945. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  4946. inst->render (l.data(), r.data(), frames, 1.0f, 1.0f);
  4947. return l;
  4948. }
  4949. double goertzel (const std::vector<float>& x, double f, int from, int to)
  4950. {
  4951. const auto w = 2.0 * 3.141592653589793 * f / 48000.0, k = 2.0 * std::cos (w);
  4952. double s1 = 0.0, s2 = 0.0;
  4953. for (int i = from; i < to; ++i)
  4954. {
  4955. const auto s0 = x[(std::size_t) i] + k * s1 - s2;
  4956. s2 = s1;
  4957. s1 = s0;
  4958. }
  4959. return s1 * s1 + s2 * s2 - k * s1 * s2;
  4960. }
  4961. } // namespace
  4962. TEST (synth_pitch_sweep_ring_and_bands)
  4963. {
  4964. lynx::SynthSettings sine;
  4965. sine.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  4966. sine.cutoff = 20000.0f;
  4967. // sweep: starts at f·(1 + sweep) and returns to f (time constant s = 10 ms; s⁴ falls 4× faster)
  4968. auto sweep = sine;
  4969. sweep.sweep = 1.0f;
  4970. sweep.sweepTime = 0.01f;
  4971. const auto a = renderSynthNote (sweep, 69, 24000);
  4972. auto crossings = [] (const std::vector<float>& x, int to) {
  4973. int n = 0;
  4974. for (int i = 1; i < to; ++i)
  4975. n += (x[(std::size_t) i - 1] < 0.0f) != (x[(std::size_t) i] < 0.0f);
  4976. return n;
  4977. };
  4978. CHECK (crossings (a, 480) > 1.3 * crossings (renderSynthNote (sine, 69, 480), 480)); // 10 ms: much higher
  4979. CHECK (goertzel (a, 440.0, 12000, 24000) > 100.0 * goertzel (a, 880.0, 12000, 24000));
  4980. // ring with |a| = 1: carrier 440 × modulator 110 -> only 330 and 550, no 440
  4981. auto ring = sine;
  4982. ring.am = ring.ring = true;
  4983. ring.osc[2] = { lynx::Waveform::sine, -2, 0.0f, 1.0f };
  4984. const auto b = renderSynthNote (ring, 69, 24000);
  4985. CHECK (goertzel (b, 330.0, 4800, 24000) > 100.0 * goertzel (b, 440.0, 4800, 24000));
  4986. CHECK (goertzel (b, 550.0, 4800, 24000) > 100.0 * goertzel (b, 440.0, 4800, 24000));
  4987. // 3 bands: muting the high knocks down a 4 kHz note and barely touches an 80 Hz one
  4988. auto bands = sine;
  4989. bands.bandGain = { 1.0f, 1.0f, 0.0f };
  4990. auto rms = [] (const std::vector<float>& x) {
  4991. double e = 0.0;
  4992. for (std::size_t i = 4800; i < x.size(); ++i)
  4993. e += (double) x[i] * x[i];
  4994. return std::sqrt (e / (double) (x.size() - 4800));
  4995. };
  4996. CHECK (rms (renderSynthNote (bands, 107, 24000)) < 0.3 * rms (renderSynthNote (sine, 107, 24000)));
  4997. CHECK (rms (renderSynthNote (bands, 28, 24000)) > 0.85 * rms (renderSynthNote (sine, 28, 24000)));
  4998. }
  4999. TEST (love_philter_map_evaluation)
  5000. {
  5001. lynx::LovePhilterMap line { { { 0.0, 0.0 }, { 1.0, 1.0 } } };
  5002. CHECK (std::abs (lynx::lovePhilterMapAt (line, 0.5) - 0.5) < 1e-9);
  5003. CHECK (std::abs (lynx::lovePhilterMapAt (line, 1.0) - 1.0) < 1e-9);
  5004. // steps (Δx = 0): 1 until 0.4375, ramp to 0 at 0.5, then 0
  5005. lynx::LovePhilterMap steps { { { 0.0, 1.0 }, { 0.4375, 1.0 }, { 0.0625, 0.0 }, { 0.5, 0.0 } } };
  5006. CHECK (lynx::lovePhilterMapAt (steps, 0.27) == 1.0);
  5007. CHECK (lynx::lovePhilterMapAt (steps, 0.75) == 0.0);
  5008. CHECK (std::abs (lynx::lovePhilterMapAt (steps, 0.46875) - 0.5) < 1e-9);
  5009. CHECK (lynx::lovePhilterMapAt ({}, 0.3) == 1.0);
  5010. }
  5011. TEST (lofi_holds_and_quantizes)
  5012. {
  5013. auto fx = lynx::makeEffect (lynx::EffectKind::lofi);
  5014. fx->prepare (48000.0);
  5015. auto slot = lynx::makeEffectSlot (lynx::EffectKind::lofi);
  5016. slot.params[0] = 0.5f; // 128·0.125 + 1 = 17 samples
  5017. slot.params[1] = 1.0f; // 65536/2049 ≈ 32 levels
  5018. std::vector<float> l (170), r (170);
  5019. for (std::size_t i = 0; i < l.size(); ++i)
  5020. l[i] = r[i] = 0.9f * (float) std::sin (0.05 * (double) i);
  5021. const auto original = l;
  5022. fx->process (l.data(), r.data(), 170, slot.params, 120.0);
  5023. for (int i = 0; i < 17; ++i)
  5024. CHECK (l[(std::size_t) i] == l[0]);
  5025. CHECK (l[17] != l[16]);
  5026. const auto step = 2.0f * 2049.0f / 65536.0f;
  5027. for (auto v : l)
  5028. CHECK (std::abs (v / step - std::round (v / step)) < 1e-3f);
  5029. CHECK (std::abs (l[0] - original[0]) <= step);
  5030. CHECK (lynx::formatEffectParam (lynx::EffectKind::lofi, 1, 0.0f, 120.0) == "16.0 bits");
  5031. }
  5032. namespace
  5033. {
  5034. lynx::EffectParams effectorParams (int type, float x, float y)
  5035. {
  5036. auto slot = lynx::makeEffectSlot (lynx::EffectKind::effector);
  5037. slot.params[0] = (float) type / 11.0f;
  5038. slot.params[3] = x;
  5039. slot.params[4] = y;
  5040. return slot.params;
  5041. }
  5042. } // namespace
  5043. TEST (effector_algorithms)
  5044. {
  5045. CHECK (lynx::effector::typeOf (8.0f / 11.0f) == 8);
  5046. CHECK (std::string (lynx::effector::typeName (11)) == "Ring");
  5047. CHECK (std::abs (lynx::effector::rateBeats (0.5f, 0.0f) - 0.75) < 1e-9); // trunc(8·0.5 + 0.5) = 4 -> 3/4
  5048. CHECK (std::abs (lynx::effector::rateBeats (1.0f, 0.5f) - 2.0) < 1e-9); // 8 × (1 − 0.5)²
  5049. auto run = [] (const lynx::EffectParams& p, std::vector<float> in, double bpm = 120.0) {
  5050. auto fx = lynx::makeEffect (lynx::EffectKind::effector);
  5051. fx->prepare (48000.0);
  5052. fx->setSongPosition (0.0);
  5053. auto r = in;
  5054. fx->process (in.data(), r.data(), (int) in.size(), p, bpm);
  5055. return in;
  5056. };
  5057. // Distort with Y = 1 (everything goes to the cascade): 0.5 comes out 0.5 (compensation G = 0.5/F(0.5))
  5058. {
  5059. auto p = effectorParams (0, 0.5f, 1.0f);
  5060. const auto out = run (p, std::vector<float> (4800, 0.5f));
  5061. CHECK (std::abs (out.back() - 0.5f) < 1e-3f);
  5062. const auto small = run (p, std::vector<float> (4800, 0.05f));
  5063. CHECK (small.back() > 0.45f && small.back() < 0.5f); // saturates near ±0.5
  5064. }
  5065. // Ring: DC 1 becomes the carrier sine, 2^(8.7·0 + 5) = 32 Hz -> 32 cycles per second
  5066. {
  5067. auto p = effectorParams (11, 0.0f, 0.0f);
  5068. const auto out = run (p, std::vector<float> (48000, 1.0f));
  5069. int crossings = 0;
  5070. for (std::size_t i = 4800; i < out.size(); ++i)
  5071. crossings += (out[i - 1] < 0.0f) != (out[i] < 0.0f);
  5072. CHECK (crossings >= 56 && crossings <= 60); // 0.9 s × 32 Hz × 2
  5073. }
  5074. // Trancer, Y = 0: at the start of the period the gain drops to zero; X = 1 returns only at the end of the period
  5075. {
  5076. auto p = effectorParams (8, 1.0f, 0.0f);
  5077. p[5] = 1.0f; // 8/1 = 8 beats = 4 s at 120 BPM
  5078. const auto out = run (p, std::vector<float> (48000, 1.0f));
  5079. CHECK (out[100] > 0.3f); // still rising on the "and" (1% of the period = 40 ms)
  5080. CHECK (out[24000] < 0.05f); // 0.5 s: trough
  5081. }
  5082. // Reverb with Wet = 0: the dry passes intact
  5083. {
  5084. auto p = effectorParams (6, 0.5f, 0.5f);
  5085. p[2] = 0.0f;
  5086. std::vector<float> in (4800);
  5087. for (std::size_t i = 0; i < in.size(); ++i)
  5088. in[i] = (float) std::sin (0.01 * (double) i);
  5089. const auto out = run (p, in);
  5090. for (std::size_t i = 0; i < in.size(); ++i)
  5091. CHECK (std::abs (out[i] - in[i]) < 1e-6f);
  5092. }
  5093. // Delay: the echo arrives after the Mod Rate period (1/4 beat at 120 BPM = 125 ms), at level X²
  5094. {
  5095. auto p = effectorParams (5, 0.7f, 0.5f);
  5096. p[5] = 1.0f / 8.0f; // index 1 = 1/4
  5097. std::vector<float> in (12000, 0.0f);
  5098. in[0] = 1.0f;
  5099. const auto out = run (p, in);
  5100. CHECK (std::abs (out[6000] - 0.49f) < 0.02f);
  5101. CHECK (std::abs (out[3000]) < 1e-6f);
  5102. }
  5103. // Stutter: repeats the recorded start every period
  5104. {
  5105. auto p = effectorParams (9, 0.0f, 0.0f);
  5106. p[5] = 0.0f; // 1/8 beat = 62.5 ms = 3000 samples
  5107. std::vector<float> in (9000);
  5108. for (std::size_t i = 0; i < in.size(); ++i)
  5109. in[i] = (float) i / 9000.0f;
  5110. const auto out = run (p, in);
  5111. CHECK (std::abs (out[3000 + 500] - in[500]) < 0.01f); // after the crossfade, it's the start again
  5112. CHECK (std::abs (out[1000] - in[1000]) < 1e-6f);
  5113. }
  5114. }
  5115. TEST (crossover_linkwitz_riley_sums_flat)
  5116. {
  5117. // low band + high band of the same crossover: sum with magnitude 1 (Linkwitz-Riley; for 12 and 36 dB the HP is inverted)
  5118. for (const auto combo : { 1, 3, 4, 5, 6, 7 })
  5119. for (const auto testHz : { 200.0, 1000.0, 5000.0 })
  5120. {
  5121. auto run = [&] (bool high) {
  5122. auto fx = lynx::makeEffect (lynx::EffectKind::crossover);
  5123. fx->prepare (48000.0);
  5124. auto slot = lynx::makeEffectSlot (lynx::EffectKind::crossover);
  5125. const auto value = (float) (std::log2 (1000.0 / 30.0) / 9.0589);
  5126. slot.params[high ? 0 : 3] = 1.0f;
  5127. slot.params[high ? 1 : 4] = value;
  5128. slot.params[high ? 2 : 5] = (float) combo / 7.0f;
  5129. std::vector<float> l (24000), r (24000);
  5130. for (std::size_t i = 0; i < l.size(); ++i)
  5131. l[i] = r[i] = (float) std::sin (2.0 * 3.141592653589793 * testHz * (double) i / 48000.0);
  5132. fx->process (l.data(), r.data(), 24000, slot.params, 120.0);
  5133. return l;
  5134. };
  5135. const auto low = run (false), high = run (true);
  5136. double peak = 0.0;
  5137. for (std::size_t i = 12000; i < low.size(); ++i)
  5138. peak = std::max (peak, (double) std::abs (low[i] + high[i]));
  5139. CHECK (std::abs (peak - 1.0) < 0.02);
  5140. }
  5141. // 96 dB/oct: two octaves above the cutoff the low-pass is already below −150 dB... in practice, very low
  5142. auto fx = lynx::makeEffect (lynx::EffectKind::crossover);
  5143. fx->prepare (48000.0);
  5144. auto slot = lynx::makeEffectSlot (lynx::EffectKind::crossover);
  5145. slot.params[3] = 1.0f;
  5146. slot.params[4] = (float) (std::log2 (500.0 / 30.0) / 9.0589);
  5147. slot.params[5] = 1.0f;
  5148. std::vector<float> l (24000), r (24000);
  5149. for (std::size_t i = 0; i < l.size(); ++i)
  5150. l[i] = r[i] = (float) std::sin (2.0 * 3.141592653589793 * 2000.0 * (double) i / 48000.0);
  5151. fx->process (l.data(), r.data(), 24000, slot.params, 120.0);
  5152. float peak = 0.0f;
  5153. for (std::size_t i = 12000; i < l.size(); ++i)
  5154. peak = std::max (peak, std::abs (l[i]));
  5155. CHECK (peak < 1e-4f);
  5156. }
  5157. TEST (rhythm_gain_and_autopan)
  5158. {
  5159. // 1-beat gate: 1 → 0 at 0.5 beat (linear) → 1 at the end; at 120 BPM 1 beat = 24000 samples at 48 kHz
  5160. auto slot = lynx::makeEffectSlot (lynx::EffectKind::rhythmGain);
  5161. slot.params[0] = 1.0f / 64.0f;
  5162. slot.params[1] = 3.0f / 12.0f;
  5163. const float pts[3][3] = { { 0.0f, 1.0f, 0.5f }, { 0.5f, 0.0f, 0.5f }, { 1.0f, 1.0f, 0.5f } };
  5164. for (int k = 0; k < 3; ++k)
  5165. for (int j = 0; j < 3; ++j)
  5166. slot.params[(std::size_t) (2 + 3 * k + j)] = pts[k][j];
  5167. auto fx = lynx::makeEffect (lynx::EffectKind::rhythmGain);
  5168. fx->prepare (48000.0);
  5169. fx->setSongPosition (960.0 * 2.0); // beat 2: phase 0
  5170. std::vector<float> l (24000, 1.0f), r (24000, 1.0f);
  5171. fx->process (l.data(), r.data(), 24000, slot.params, 120.0);
  5172. CHECK (std::abs (l[0] - 1.0f) < 1e-3f);
  5173. CHECK (std::abs (l[6000] - 0.5f) < 1e-3f);
  5174. CHECK (l[12000] < 1e-3f);
  5175. CHECK (std::abs (l[18000] - 0.5f) < 1e-3f);
  5176. // positive tension: changes quickly at the start of the segment
  5177. CHECK (lynx::effectInfo (lynx::EffectKind::rhythmGain).params.size() == 39);
  5178. // auto-pan: 1-beat period, full depth; start phase 0.75 -> W = 0 rising (pan centered)
  5179. auto pan = lynx::makeEffectSlot (lynx::EffectKind::autoPan);
  5180. pan.params[0] = 1.0f / 64.0f;
  5181. pan.params[1] = 1.0f;
  5182. auto ap = lynx::makeEffect (lynx::EffectKind::autoPan);
  5183. ap->prepare (48000.0);
  5184. ap->setSongPosition (0.0);
  5185. std::vector<float> a (24000, 1.0f), b (24000, 1.0f);
  5186. ap->process (a.data(), b.data(), 24000, pan.params, 120.0);
  5187. CHECK (std::abs (a[0] - 1.0f) < 1e-3f && std::abs (b[0] - 1.0f) < 1e-3f);
  5188. CHECK (a[6000] < 0.01f && std::abs (b[6000] - 1.0f) < 1e-3f); // ¼ cycle later: fully right
  5189. }
  5190. TEST (vocoder_side_inputs_split_modulator_and_carrier)
  5191. {
  5192. // "Side inputs" mode (Vocodex): modulator from side input 1 (noise in the first half), carrier from side input 2
  5193. // (saw), own input silent → the output follows the side modulator; with input 1 silent, the output is silent
  5194. auto slot = lynx::makeEffectSlot (lynx::EffectKind::vocoder);
  5195. slot.params[16] = 1.0f;
  5196. auto fx = lynx::makeEffect (lynx::EffectKind::vocoder);
  5197. fx->prepare (48000.0);
  5198. std::vector<float> modL (48000), car (48000), l (48000, 0.0f), r (48000, 0.0f);
  5199. std::uint32_t seed = 1;
  5200. for (std::size_t i = 0; i < modL.size(); ++i)
  5201. {
  5202. seed = seed * 1664525u + 1013904223u;
  5203. modL[i] = i < 24000 ? ((float) (seed >> 8) / 16777216.0f - 0.5f) : 0.0f;
  5204. car[i] = (float) (2.0 * std::fmod ((double) i * 220.0 / 48000.0, 1.0) - 1.0) * 0.5f;
  5205. }
  5206. for (int done = 0; done < 48000; done += 480)
  5207. {
  5208. fx->setSidechain (modL.data() + done, modL.data() + done);
  5209. fx->setSidechain2 (car.data() + done, car.data() + done);
  5210. fx->process (l.data() + done, r.data() + done, 480, slot.params, 120.0);
  5211. }
  5212. auto rms = [&] (int from, int to) {
  5213. double e = 0.0;
  5214. for (int i = from; i < to; ++i)
  5215. e += (double) l[(std::size_t) i] * l[(std::size_t) i];
  5216. return std::sqrt (e / (to - from));
  5217. };
  5218. CHECK (rms (6000, 20000) > 0.01);
  5219. CHECK (rms (40000, 48000) < 0.1 * rms (6000, 20000));
  5220. // the side modulator configured but silent: nothing comes out (the own input is not used instead)
  5221. std::vector<float> a (4800, 0.3f), b (4800, 0.3f);
  5222. for (int done = 0; done < 4800; done += 480)
  5223. {
  5224. fx->setSidechain (nullptr, nullptr);
  5225. fx->setSidechain2 (car.data() + done, car.data() + done);
  5226. fx->process (a.data() + done, b.data() + done, 480, slot.params, 120.0);
  5227. }
  5228. CHECK (std::abs (a[4700]) < 0.05f);
  5229. }
  5230. TEST (vocoder_follows_modulator)
  5231. {
  5232. // modulator (L) plays only in the first half; carrier (R) is a continuous saw: the wet follows the modulator
  5233. auto slot = lynx::makeEffectSlot (lynx::EffectKind::vocoder);
  5234. auto fx = lynx::makeEffect (lynx::EffectKind::vocoder);
  5235. fx->prepare (48000.0);
  5236. std::vector<float> l (48000), r (48000);
  5237. std::uint32_t seed = 1;
  5238. for (std::size_t i = 0; i < l.size(); ++i)
  5239. {
  5240. seed = seed * 1664525u + 1013904223u;
  5241. l[i] = i < 24000 ? ((float) (seed >> 8) / 16777216.0f - 0.5f) : 0.0f;
  5242. r[i] = (float) (2.0 * std::fmod ((double) i * 220.0 / 48000.0, 1.0) - 1.0) * 0.5f;
  5243. }
  5244. fx->process (l.data(), r.data(), 48000, slot.params, 120.0);
  5245. auto rms = [&] (int from, int to) {
  5246. double e = 0.0;
  5247. for (int i = from; i < to; ++i)
  5248. e += (double) l[(std::size_t) i] * l[(std::size_t) i];
  5249. return std::sqrt (e / (to - from));
  5250. };
  5251. CHECK (rms (6000, 20000) > 0.01);
  5252. CHECK (rms (40000, 48000) < 0.1 * rms (6000, 20000)); // modulator silent: the vocoder fades out (100 ms release)
  5253. for (std::size_t i = 0; i < l.size(); ++i)
  5254. CHECK (l[i] == r[i] && std::isfinite (l[i])); // mono output
  5255. }
  5256. // Vocodex (REA_rodada35): a synthetic state in FL's layout (version 8, 13 maps, 20 parameters, the 0x24 block,
  5257. // 13 map-axis bytes, tone, notes)
  5258. struct VocodexSpec
  5259. {
  5260. // Wet, SG, ModVol, ModHP, CarVol, CarLP, CarNoise, CarNoiseHP, Hold, Att, AttCurve, Rel, RelCurve, Freeze, BW,
  5261. // Flatness, ModBW, ModPitch, FatPitch, FatPan
  5262. 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 };
  5263. std::array<std::int32_t, 7> block { 0, 2, 0, 24, 1, 1, 2 }; // hold mode, order, unison, bands, draft field, ModIn, CarIn
  5264. 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
  5265. std::vector<std::uint8_t> bytes() const
  5266. {
  5267. std::vector<std::uint8_t> d;
  5268. 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); };
  5269. auto i32 = [&] (std::int32_t v) { put (&v, 4); };
  5270. i32 (8 << 16);
  5271. for (int m = 0; m < 13; ++m)
  5272. {
  5273. const double y0 = m == 8 ? 0.1429 : (m == 3 || m == 4 || m == 11) ? 0.0 : 0.5;
  5274. const double y1 = m == 8 ? 0.9918 : y0;
  5275. i32 (1), i32 (0), i32 (2);
  5276. for (const auto& [dx, y] : { std::pair { 0.0, y0 }, std::pair { 1.0, y1 } })
  5277. {
  5278. put (&dx, 8), put (&y, 8);
  5279. i32 (0), i32 (0); // tension (f32 0), flags
  5280. }
  5281. const std::array<std::uint8_t, 20> tail {};
  5282. put (tail.data(), tail.size());
  5283. }
  5284. for (auto v : params)
  5285. i32 (v);
  5286. for (auto v : block)
  5287. i32 (v);
  5288. put (flags.data(), flags.size());
  5289. const std::array<std::uint8_t, 13> axis {};
  5290. put (axis.data(), axis.size());
  5291. d.push_back (3), put ("PWM", 3);
  5292. i32 (1), i32 (60);
  5293. return d;
  5294. }
  5295. };
  5296. std::vector<float> vocodexSaw (int n, double hz, double fs)
  5297. {
  5298. std::vector<float> out ((std::size_t) n);
  5299. for (int i = 0; i < n; ++i)
  5300. out[(std::size_t) i] = (float) (2.0 * std::fmod (i * hz / fs, 1.0) - 1.0) * 0.4f;
  5301. return out;
  5302. }
  5303. TEST (vocodex_state_parse_and_conversion)
  5304. {
  5305. VocodexSpec spec;
  5306. spec.block = { 1, 3, 2, 40, 0, 2, 1 };
  5307. spec.params[17] = -1200;
  5308. const auto raw = spec.bytes();
  5309. const auto s = lynx::vocodex::parseState (raw);
  5310. CHECK (s.has_value());
  5311. if (! s)
  5312. return;
  5313. CHECK (s->version == 8 && s->holdMode == 1 && s->order == 3 && s->unison == 2 && s->bands == 40);
  5314. CHECK (s->draft() && s->modIn == 2 && s->carIn == 1 && s->minTimes && s->subtractiveGate && ! s->lrEncoding);
  5315. CHECK (s->params[lynx::vocodex::modPitch] == -1200 && s->params[lynx::vocodex::carLp] == 65536);
  5316. 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);
  5317. CHECK (s->tone == "PWM" && s->notes.size() == 1 && s->notes[0] == 60);
  5318. const auto v = lynx::vocodexEffect (raw);
  5319. CHECK (v && v->slot.kind == lynx::EffectKind::vocodex && v->slot.state == raw && v->modIn == 2 && v->carIn == 1 && v->notes.empty());
  5320. spec.block[6] = -1; // internal synth carrier: not available yet → reported
  5321. spec.params[1] = 150; // Soundgoodizer stage
  5322. const auto w = lynx::vocodexEffect (spec.bytes());
  5323. CHECK (w && w->carIn == -1 && w->notes.size() == 2);
  5324. CHECK (! lynx::vocodex::parseState ({ 1, 2, 3 }).has_value());
  5325. }
  5326. TEST (vocodex_vocodes_side_inputs)
  5327. {
  5328. // modulator on side input 1 (noise in the first half), carrier on side input 2 (saw), own input silent: the
  5329. // output follows the modulator's envelope and fades after it stops
  5330. VocodexSpec spec;
  5331. lynx::EffectSlot slot = lynx::makeEffectSlot (lynx::EffectKind::vocodex);
  5332. slot.state = spec.bytes();
  5333. auto fx = lynx::makeEffect (slot);
  5334. fx->prepare (48000.0);
  5335. CHECK (fx->latencySamples() == 0);
  5336. const auto car = vocodexSaw (48000, 110.0, 48000.0);
  5337. std::vector<float> mod (48000), l (48000, 0.0f), r (48000, 0.0f);
  5338. std::uint32_t seed = 7;
  5339. for (std::size_t i = 0; i < mod.size(); ++i)
  5340. {
  5341. seed = seed * 1664525u + 1013904223u;
  5342. mod[i] = i < 24000 ? ((float) (seed >> 8) / 16777216.0f - 0.5f) : 0.0f;
  5343. }
  5344. for (int done = 0; done < 48000; done += 512)
  5345. {
  5346. const int n = std::min (512, 48000 - done);
  5347. fx->setSidechain (mod.data() + done, mod.data() + done);
  5348. fx->setSidechain2 (car.data() + done, car.data() + done);
  5349. fx->process (l.data() + done, r.data() + done, n, slot.params, 120.0);
  5350. }
  5351. auto rms = [&] (int from, int to) {
  5352. double e = 0.0;
  5353. for (int i = from; i < to; ++i)
  5354. e += (double) l[(std::size_t) i] * l[(std::size_t) i] + (double) r[(std::size_t) i] * r[(std::size_t) i];
  5355. return std::sqrt (e / (2.0 * (to - from)));
  5356. };
  5357. CHECK (rms (6000, 20000) > 0.02);
  5358. CHECK (rms (40000, 48000) < 0.01 * rms (6000, 20000));
  5359. CHECK (std::abs (l[0]) < 1e-6f); // the gains ramp up from 0 when the plugin is created
  5360. }
  5361. TEST (vocodex_draft_latency_and_pass_through)
  5362. {
  5363. // carrier pass-through at unit gain only (Wet 0): after a Flush the gains snap, so the output is the carrier,
  5364. // 16 samples late in Draft
  5365. VocodexSpec spec;
  5366. spec.params[0] = 0; // Wet
  5367. spec.params[4] = 12800; // CarVol = 1
  5368. for (const int draftField : { 1, 0 })
  5369. {
  5370. spec.block[4] = draftField;
  5371. const auto s = lynx::vocodex::parseState (spec.bytes());
  5372. CHECK (s.has_value());
  5373. lynx::vocodex::Engine engine;
  5374. engine.prepare (*s, 44100.0, 300, s->draft());
  5375. CHECK (engine.latencySamples() == (draftField == 0 ? 16 : 0));
  5376. engine.flush();
  5377. const auto saw = vocodexSaw (3000, 220.0, 44100.0);
  5378. std::vector<float> car (6000), mod (6000, 0.0f), out (6000);
  5379. for (int i = 0; i < 3000; ++i)
  5380. car[(std::size_t) (2 * i)] = car[(std::size_t) (2 * i + 1)] = saw[(std::size_t) i];
  5381. static constexpr int sizes[] { 300, 37, 128, 1, 255, 16, 299 }; // uneven blocks exercise the FIFOs
  5382. for (int done = 0, k = 0, n = 0; done < 3000; done += n, ++k)
  5383. {
  5384. n = std::min (sizes[k % 7], 3000 - done);
  5385. engine.process (mod.data() + 2 * done, mod.data() + 2 * done, car.data() + 2 * done, out.data() + 2 * done, n);
  5386. }
  5387. const int lag = engine.latencySamples();
  5388. auto maxError = 0.0f;
  5389. for (int i = lag; i < 3000; ++i)
  5390. maxError = std::max (maxError, std::abs (out[(std::size_t) (2 * i)] - saw[(std::size_t) (i - lag)]));
  5391. CHECK (maxError == 0.0f);
  5392. }
  5393. }
  5394. TEST (vocodex_soundgoodizer_stage_limits_the_output)
  5395. {
  5396. // SG > 0: the vocoder's output (loud here: Wet 2000) goes through the Soundgoodizer approximation, whose
  5397. // master limiter keeps the peaks under −0.2 dBFS; its look-ahead is reported as latency
  5398. VocodexSpec spec;
  5399. spec.params[0] = 2000;
  5400. spec.params[1] = 250;
  5401. lynx::EffectSlot slot = lynx::makeEffectSlot (lynx::EffectKind::vocodex);
  5402. slot.state = spec.bytes();
  5403. auto fx = lynx::makeEffect (slot);
  5404. fx->prepare (48000.0);
  5405. CHECK (fx->latencySamples() == 72); // 1.5 ms at 48 kHz
  5406. const auto car = vocodexSaw (48000, 110.0, 48000.0);
  5407. std::vector<float> mod (48000), l (48000, 0.0f), r (48000, 0.0f);
  5408. for (std::size_t i = 0; i < mod.size(); ++i)
  5409. mod[i] = 0.9f * (float) std::sin (0.07 * (double) i) * (float) std::sin (0.0003 * (double) i);
  5410. auto peak = 0.0f;
  5411. for (int done = 0; done < 48000; done += 512)
  5412. {
  5413. const int n = std::min (512, 48000 - done);
  5414. fx->setSidechain (mod.data() + done, mod.data() + done);
  5415. fx->setSidechain2 (car.data() + done, car.data() + done);
  5416. fx->process (l.data() + done, r.data() + done, n, slot.params, 120.0);
  5417. }
  5418. for (std::size_t i = 0; i < l.size(); ++i)
  5419. peak = std::max ({ peak, std::abs (l[i]), std::abs (r[i]) });
  5420. CHECK (peak > 0.5f && peak <= 0.9775f);
  5421. }
  5422. TEST (vocodex_tail_bypass_and_noise)
  5423. {
  5424. // both inputs silent for longer than 0.5 s + hold + release: the own input passes unchanged
  5425. VocodexSpec spec;
  5426. const auto s = lynx::vocodex::parseState (spec.bytes());
  5427. CHECK (s.has_value());
  5428. lynx::vocodex::Engine engine;
  5429. engine.prepare (*s, 44100.0, 512, false);
  5430. std::vector<float> zero (1024, 0.0f), own (1024), out (1024);
  5431. for (std::size_t i = 0; i < own.size(); ++i)
  5432. own[i] = 0.25f * (float) std::sin (0.01 * (double) i);
  5433. for (int b = 0; b < 80; ++b)
  5434. engine.process (own.data(), zero.data(), zero.data(), out.data(), 512);
  5435. CHECK (out == own);
  5436. // carrier noise: the IPP-compatible generator restarts from the same seed after a Flush
  5437. spec.params[6] = 9000;
  5438. const auto noisy = lynx::vocodex::parseState (spec.bytes());
  5439. lynx::vocodex::Engine a;
  5440. a.prepare (*noisy, 44100.0, 512, false);
  5441. std::vector<float> mod (1024), first (1024), second (1024);
  5442. for (std::size_t i = 0; i < mod.size(); ++i)
  5443. mod[i] = 0.3f * (float) std::sin (0.05 * (double) i);
  5444. a.flush();
  5445. a.process (own.data(), mod.data(), zero.data(), first.data(), 512);
  5446. a.flush();
  5447. a.process (own.data(), mod.data(), zero.data(), second.data(), 512);
  5448. CHECK (first == second);
  5449. auto energy = 0.0;
  5450. for (auto v : first)
  5451. energy += (double) v * v;
  5452. CHECK (energy > 1e-6 && std::isfinite (energy));
  5453. }
  5454. TEST (synth_spectral_oscillator)
  5455. {
  5456. // 1/n spectrum = saw: same harmonic proportions and same level as LYNX's saw
  5457. lynx::SynthSettings saw;
  5458. saw.osc[0] = { lynx::Waveform::saw, 0, 0.0f, 1.0f };
  5459. saw.cutoff = 20000.0f;
  5460. auto spectral = saw;
  5461. spectral.osc[0].wave = lynx::Waveform::spectral;
  5462. for (int n = 1; n <= lynx::SynthSettings::spectrumSize; ++n)
  5463. spectral.spectrum[(std::size_t) n - 1] = 1.0f / (float) n;
  5464. const auto a = renderSynthNote (saw, 57, 24000), b = renderSynthNote (spectral, 57, 24000); // 220 Hz
  5465. for (const auto h : { 1, 2, 3, 5 })
  5466. {
  5467. const auto ea = goertzel (a, 220.0 * h, 4800, 24000), eb = goertzel (b, 220.0 * h, 4800, 24000);
  5468. CHECK (std::abs (10.0 * std::log10 (eb / ea)) < 0.5); // within 0.5 dB
  5469. }
  5470. // odd only: no 2nd harmonic
  5471. auto odd = spectral;
  5472. for (int n = 2; n <= lynx::SynthSettings::spectrumSize; n += 2)
  5473. odd.spectrum[(std::size_t) n - 1] = 0.0f;
  5474. const auto c = renderSynthNote (odd, 57, 24000);
  5475. CHECK (goertzel (c, 440.0, 4800, 24000) < 1e-4 * goertzel (c, 220.0, 4800, 24000));
  5476. // high note: the band-limited tables don't pass Nyquist (no aliasing below the fundamental)
  5477. const auto d = renderSynthNote (spectral, 105, 24000); // 3520 Hz
  5478. CHECK (goertzel (d, 1000.0, 4800, 24000) < 1e-3 * goertzel (d, 3520.0, 4800, 24000));
  5479. }
  5480. TEST (compressor_sidechain_ducks_and_orders_mixer)
  5481. {
  5482. // the detector listens to the side input: quiet signal on the track, loud kick on the sidechain -> reduction
  5483. auto slot = lynx::makeEffectSlot (lynx::EffectKind::compressor);
  5484. slot.params[0] = 0.5f; // threshold
  5485. slot.params[1] = 1.0f; // high ratio
  5486. slot.params[4] = 0.0f;
  5487. auto run = [&] (bool withSidechain) {
  5488. auto fx = lynx::makeEffect (lynx::EffectKind::compressor);
  5489. fx->prepare (48000.0);
  5490. std::vector<float> l (4800, 0.1f), r (4800, 0.1f), kick (4800, 1.0f);
  5491. if (withSidechain)
  5492. fx->setSidechain (kick.data(), kick.data());
  5493. fx->process (l.data(), r.data(), 4800, slot.params, 120.0);
  5494. return l.back();
  5495. };
  5496. const auto alone = run (false), ducked = run (true);
  5497. CHECK (ducked < 0.5f * alone);
  5498. // order: track 5 listens to 7 via sidechain -> 7 comes before 5
  5499. auto song = lynx::Song::makeDefault();
  5500. while (song.mixer.size() < 8)
  5501. song.mixer.push_back ({});
  5502. auto comp = lynx::makeEffectSlot (lynx::EffectKind::compressor);
  5503. comp.sidechain = 7;
  5504. song.mixer[5].effects.push_back (comp);
  5505. const auto order = song.mixerOrder();
  5506. const auto at = [&] (int t) { return std::find (order.begin(), order.end(), t) - order.begin(); };
  5507. CHECK (at (7) < at (5));
  5508. }
  5509. TEST (pitch_correction_pulls_to_allowed_note)
  5510. {
  5511. auto run = [] (const lynx::EffectParams& p, double hz) {
  5512. auto fx = lynx::makeEffect (lynx::EffectKind::pitchCorrect);
  5513. fx->prepare (48000.0);
  5514. std::vector<float> l (48000 * 2), r;
  5515. for (std::size_t i = 0; i < l.size(); ++i)
  5516. l[i] = 0.5f * (float) std::sin (2.0 * 3.141592653589793 * hz * (double) i / 48000.0);
  5517. r = l;
  5518. fx->process (l.data(), r.data(), (int) l.size(), p, 120.0);
  5519. // frequency from zero crossings in the last second
  5520. int crossings = 0;
  5521. for (std::size_t i = 48000 + 1; i < l.size(); ++i)
  5522. crossings += (l[i - 1] < 0.0f) != (l[i] < 0.0f);
  5523. return crossings / 2.0;
  5524. };
  5525. auto slot = lynx::makeEffectSlot (lynx::EffectKind::pitchCorrect); // chromatic, instant, A 440
  5526. CHECK (std::abs (run (slot.params, 452.0) - 440.0) < 4.0);
  5527. for (int k = 0; k < 12; ++k)
  5528. slot.params[(std::size_t) (5 + k)] = k == 0 ? 1.0f : 0.0f; // only C
  5529. CHECK (std::abs (run (slot.params, 452.0) - 523.25) < 5.0); // C5 (523 Hz) is closer than C4 (262)
  5530. slot.params[2] = 1.0f; // turn everything off: passes unchanged
  5531. CHECK (std::abs (run (slot.params, 452.0) - 452.0) < 4.0);
  5532. }
  5533. TEST (pitch_correction_bypass_is_a_pure_delay)
  5534. {
  5535. // FL's Pitcher with Bypass All still runs its shifter: the plain path is an exact 9-sample delay, the formant
  5536. // path (256-Hann overlap-add) an exact 257-sample delay, and Gender changes nothing without a shift
  5537. // (REA_rodada30 §2.4/2.5); both are reported as latency
  5538. std::vector<float> in (48000);
  5539. for (std::size_t i = 0; i < in.size(); ++i)
  5540. in[i] = 0.5f * (float) std::sin (2.0 * 3.141592653589793 * 440.0 * (double) i / 48000.0)
  5541. + 0.2f * (float) std::sin (2.0 * 3.141592653589793 * 1234.5 * (double) i / 48000.0);
  5542. auto run = [&] (bool formant, float gender, int& latency) {
  5543. auto fx = lynx::makeEffect (lynx::EffectKind::pitchCorrect);
  5544. fx->prepare (48000.0);
  5545. auto slot = lynx::makeEffectSlot (lynx::EffectKind::pitchCorrect);
  5546. slot.params[2] = 1.0f;
  5547. slot.params[29] = formant ? 1.0f : 0.0f;
  5548. slot.params[30] = gender;
  5549. auto l = in, r = in;
  5550. for (std::size_t i = 0; i < l.size(); i += 480)
  5551. fx->process (l.data() + i, r.data() + i, 480, slot.params, 120.0);
  5552. latency = fx->latencySamples();
  5553. return l;
  5554. };
  5555. int latency = 0;
  5556. auto plain = run (false, 0.5f, latency);
  5557. CHECK (latency == 9);
  5558. auto worst = 0.0f;
  5559. for (std::size_t i = 4000; i < in.size(); ++i)
  5560. worst = std::max (worst, std::abs (plain[i] - in[i - 9]));
  5561. CHECK (worst < 1e-5f);
  5562. auto formant = run (true, 0.8f, latency);
  5563. CHECK (latency == 257);
  5564. worst = 0.0f;
  5565. for (std::size_t i = 4000; i < in.size(); ++i)
  5566. worst = std::max (worst, std::abs (formant[i] - in[i - 257]));
  5567. CHECK (worst < 1e-5f);
  5568. }
  5569. TEST (pitch_correction_formant_path)
  5570. {
  5571. // Formant on: PSOLA keeps the correction (output pitch = grain spacing) while Gender resamples the grains:
  5572. // the spectrum of a saw moves up with Gender > 0.5 and down with Gender < 0.5
  5573. auto run = [] (float gender) {
  5574. auto fx = lynx::makeEffect (lynx::EffectKind::pitchCorrect);
  5575. fx->prepare (48000.0);
  5576. auto slot = lynx::makeEffectSlot (lynx::EffectKind::pitchCorrect); // chromatic, instant, A 440
  5577. slot.params[29] = 1.0f;
  5578. slot.params[30] = gender;
  5579. std::vector<float> l (48000 * 2), r;
  5580. for (std::size_t i = 0; i < l.size(); ++i)
  5581. l[i] = 0.5f * (float) (2.0 * std::fmod (452.0 * (double) i / 48000.0, 1.0) - 1.0); // saw
  5582. r = l;
  5583. fx->process (l.data(), r.data(), (int) l.size(), slot.params, 120.0);
  5584. l.erase (l.begin(), l.begin() + 48000);
  5585. return l;
  5586. };
  5587. // period by autocorrelation (lags 60…160 = 300…800 Hz)
  5588. auto pitch = [] (const std::vector<float>& x) {
  5589. auto best = 0.0, bestLag = 0.0;
  5590. for (int lag = 60; lag <= 160; ++lag)
  5591. {
  5592. auto sum = 0.0;
  5593. for (std::size_t i = 0; i + (std::size_t) lag < x.size(); ++i)
  5594. sum += (double) x[i] * x[i + (std::size_t) lag];
  5595. if (sum > best)
  5596. {
  5597. best = sum;
  5598. bestLag = lag;
  5599. }
  5600. }
  5601. return 48000.0 / bestLag;
  5602. };
  5603. // brightness: energy of the first difference relative to the energy
  5604. auto brightness = [] (const std::vector<float>& x) {
  5605. auto e = 0.0, d = 0.0;
  5606. for (std::size_t i = 1; i < x.size(); ++i)
  5607. {
  5608. e += (double) x[i] * x[i];
  5609. d += (double) (x[i] - x[i - 1]) * (x[i] - x[i - 1]);
  5610. }
  5611. return d / e;
  5612. };
  5613. const auto neutral = run (0.5f), up = run (0.8f), down = run (0.3f);
  5614. CHECK (std::abs (pitch (neutral) - 440.0) < 5.0); // 452 Hz pulled to A
  5615. CHECK (std::abs (pitch (up) - 440.0) < 5.0); // Gender does not move the pitch
  5616. CHECK (brightness (up) > 1.5 * brightness (neutral));
  5617. CHECK (brightness (down) < 0.7 * brightness (neutral));
  5618. }
  5619. TEST (parallel_container_inner_links_modulate)
  5620. {
  5621. // one branch: utility (gain) + a control-only auto-pan LFO (1 beat); the link maps the LFO 0..1 onto the
  5622. // utility gain −24 dB..0 dB, so the level must swing; without the link it stays put
  5623. auto container = lynx::makeEffectSlot (lynx::EffectKind::parallel);
  5624. auto gain = lynx::makeEffectSlot (lynx::EffectKind::utility);
  5625. auto lfo = lynx::makeEffectSlot (lynx::EffectKind::autoPan);
  5626. lfo.params[0] = 1.0f / 64.0f;
  5627. lfo.params[4] = 1.0f; // control only: audio passes unchanged
  5628. container.branches.push_back ({ { gain, lfo }, 1.0f });
  5629. lynx::EffectLink link;
  5630. link.source = 1;
  5631. link.param = 0;
  5632. for (int i = 0; i <= 32; ++i)
  5633. link.curve.push_back (0.5f * (float) i / 32.0f);
  5634. auto levels = [&] (bool linked) {
  5635. auto slot = container;
  5636. if (linked)
  5637. slot.links.push_back (link);
  5638. auto fx = lynx::makeParallelEffect (slot);
  5639. fx->prepare (48000.0);
  5640. float lo = 1e9f, hi = 0.0f;
  5641. for (int block = 0; block < 94; ++block) // ~1 beat at 120 BPM in 256-sample blocks
  5642. {
  5643. std::vector<float> l (256, 1.0f), r (256, 1.0f);
  5644. fx->setSongPosition (block * 256.0 / 48000.0 * 2.0 * 960.0); // the engine positions every block
  5645. fx->process (l.data(), r.data(), 256, slot.params, 120.0);
  5646. lo = std::min (lo, std::abs (l[128]));
  5647. hi = std::max (hi, std::abs (l[128]));
  5648. }
  5649. return std::pair { lo, hi };
  5650. };
  5651. const auto [lo, hi] = levels (true);
  5652. CHECK (hi > 0.8f && lo < 0.12f);
  5653. const auto [lo0, hi0] = levels (false);
  5654. CHECK (std::abs (hi0 - lo0) < 1e-4f);
  5655. }
  5656. TEST (synth_spectrum_decays_per_harmonic)
  5657. {
  5658. // 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
  5659. lynx::SynthSettings s;
  5660. s.osc[0] = { lynx::Waveform::spectral, 0, 0.0f, 1.0f };
  5661. s.cutoff = 20000.0f;
  5662. s.decay = 0.0f;
  5663. s.sustain = 1.0f;
  5664. s.spectrum[0] = 1.0f;
  5665. s.spectrum[2] = 1.0f;
  5666. s.spectrumDecay[2] = 0.2f;
  5667. const auto x = renderSynthNote (s, 57, 48000); // 220 Hz, 48 kHz, 1 s
  5668. // equal 2400-sample windows (Goertzel power grows with the window): 10…60 ms and 500…550 ms
  5669. const auto early1 = goertzel (x, 220.0, 480, 2880), early3 = goertzel (x, 660.0, 480, 2880);
  5670. const auto late1 = goertzel (x, 220.0, 24000, 26400), late3 = goertzel (x, 660.0, 24000, 26400);
  5671. CHECK (early3 > 0.05 * early1); // ≈ −9 dB on average over 10…60 ms
  5672. CHECK (late3 < 1e-4 * late1);
  5673. CHECK (std::abs (10.0 * std::log10 (late1 / early1)) < 1.0); // the 1st holds
  5674. // without per-harmonic decay the spectrum stays as it is
  5675. s.spectrumDecay[2] = 0.0f;
  5676. const auto y = renderSynthNote (s, 57, 48000);
  5677. CHECK (std::abs (10.0 * std::log10 (goertzel (y, 660.0, 24000, 26400) / goertzel (y, 660.0, 480, 2880))) < 1.0);
  5678. }
  5679. TEST (worker_pool_runs_each_index_once_per_round)
  5680. {
  5681. // rounds of alternating sizes (a stalled worker must never run an index of a later round), each index
  5682. // exactly once, and nothing running after parallelFor returns
  5683. lynx::WorkerPool pool (3);
  5684. std::vector<std::atomic<int>> hits (64);
  5685. std::atomic<int> round { 0 }, outside { 0 }, wrongRound { 0 };
  5686. std::atomic<bool> open { false };
  5687. int failures = 0;
  5688. for (int r = 1; r <= 20000; ++r)
  5689. {
  5690. const auto n = (r % 3 == 0) ? 64 : (r % 3 == 1 ? 2 : 9);
  5691. for (int i = 0; i < n; ++i)
  5692. hits[(std::size_t) i].store (0);
  5693. round.store (r);
  5694. open.store (true);
  5695. auto fn = [&, r] (int i) {
  5696. if (! open.load())
  5697. outside.fetch_add (1);
  5698. if (round.load() != r)
  5699. wrongRound.fetch_add (1);
  5700. hits[(std::size_t) i].fetch_add (1);
  5701. };
  5702. pool.parallelFor (n, fn);
  5703. open.store (false);
  5704. for (int i = 0; i < n; ++i)
  5705. failures += hits[(std::size_t) i].load() != 1;
  5706. }
  5707. CHECK (failures == 0);
  5708. CHECK (outside.load() == 0);
  5709. CHECK (wrongRound.load() == 0);
  5710. }
  5711. TEST (ladder_filter_follows_toxic_law)
  5712. {
  5713. // the 4-pole ladder: −24 dB/oct far above the cutoff (vs −12 for the SVF), resonance raises the corner, and
  5714. // the input saturation keeps it bounded even at full resonance
  5715. auto level = [] (bool ladder, float res, double hz) {
  5716. lynx::SynthSettings s;
  5717. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  5718. s.cutoff = 500.0f;
  5719. s.resonance = res;
  5720. s.ladder = ladder;
  5721. const auto key = (int) std::lround (69.0 + 12.0 * std::log2 (hz / 440.0));
  5722. const auto x = renderSynthNote (s, key, 48000);
  5723. double e = 0.0, peak = 0.0;
  5724. for (std::size_t i = 24000; i < 48000; ++i)
  5725. e += (double) x[i] * x[i], peak = std::max (peak, (double) std::abs (x[i]));
  5726. return std::pair { std::sqrt (e / 24000.0), peak };
  5727. };
  5728. 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
  5729. const auto svfHigh = level (false, 0.0f, 3520.0).first / level (false, 0.0f, 110.0).first;
  5730. CHECK (20.0 * std::log10 (high / low) < -55.0); // ≈ 24 dB/oct over ~2.8 octaves
  5731. CHECK (20.0 * std::log10 (svfHigh) > -45.0); // the 2-pole SVF falls much less
  5732. const auto corner0 = level (true, 0.0f, 523.25).first, corner1 = level (true, 0.6f, 523.25).first;
  5733. CHECK (corner1 > 1.5 * corner0); // resonance boosts near the cutoff
  5734. const auto loud = level (true, 1.0f, 523.25);
  5735. CHECK (std::isfinite (loud.first) && loud.second < 20.0); // self-oscillation stays bounded
  5736. }
  5737. TEST (synth_spectrum_settles_on_target)
  5738. {
  5739. // ALT DECAY-like morph: harmonic 3 starts at 1 and settles on 0.25 (−12 dB) instead of fading out
  5740. lynx::SynthSettings s;
  5741. s.osc[0] = { lynx::Waveform::spectral, 0, 0.0f, 1.0f };
  5742. s.cutoff = 20000.0f;
  5743. s.decay = 0.0f;
  5744. s.sustain = 1.0f;
  5745. s.spectrum[0] = 1.0f;
  5746. s.spectrum[2] = 1.0f;
  5747. s.spectrumDecay[2] = 0.1f;
  5748. s.spectrumTarget[2] = 0.25f;
  5749. const auto x = renderSynthNote (s, 57, 48000);
  5750. const auto ratio = goertzel (x, 660.0, 24000, 26400) / goertzel (x, 220.0, 24000, 26400);
  5751. CHECK (std::abs (10.0 * std::log10 (ratio) - 20.0 * std::log10 (0.25)) < 1.0);
  5752. }
  5753. TEST (kepler_chorus_is_stereo_and_keeps_level)
  5754. {
  5755. // chorus I on a sine: L and R differ (opposite LFO phases), the level stays close to the dry one
  5756. lynx::SynthSettings s;
  5757. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  5758. s.cutoff = 20000.0f;
  5759. auto dry = s;
  5760. s.chorus = 1;
  5761. auto render = [] (const lynx::SynthSettings& set) {
  5762. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  5763. inst->prepare (48000.0);
  5764. lynx::ChannelDef c;
  5765. c.synth = set;
  5766. inst->configure (c, 120.0);
  5767. inst->noteOn (69, 1.0f);
  5768. std::vector<float> l (96000), r (96000);
  5769. inst->render (l.data(), r.data(), 96000, 1.0f, 1.0f);
  5770. return std::pair { l, r };
  5771. };
  5772. const auto [l, r] = render (s);
  5773. const auto [dl, dr] = render (dry);
  5774. double diff = 0.0, e = 0.0, ed = 0.0;
  5775. for (std::size_t i = 48000; i < 96000; ++i)
  5776. diff += std::abs (l[i] - r[i]), e += (double) l[i] * l[i], ed += (double) dl[i] * dl[i];
  5777. CHECK (diff / 48000.0 > 1e-3);
  5778. CHECK (std::abs (10.0 * std::log10 (e / ed)) < 3.0);
  5779. }
  5780. TEST (fl_pan_law_matches_love_philter_dll)
  5781. {
  5782. // values printed by the installation's Love Philter pan routine for vol 0.8 (REA_rodada27 §3.1, lppan.txt)
  5783. struct Row { double pan, ll, rr, rl, lr; };
  5784. const Row rows[] = { { -1.5, 0.239782482, -0.432956904, 0.805467963, 0.0 }, { -0.5, 0.805467963, 0.432956904, 0.239782482, 0.0 },
  5785. { 0.0, 0.8, 0.8, 0.0, 0.0 }, { 0.75, 0.220719516, 0.707889318, 0.0, 0.401742548 },
  5786. { 1.0, 0.0, 0.565685451, 0.0, 0.565685451 } };
  5787. for (const auto& row : rows)
  5788. {
  5789. float ll, rl, lr, rr;
  5790. lynx::flPanMatrix (row.pan, ll, rl, lr, rr);
  5791. CHECK (std::abs (0.8 * ll - row.ll) < 1e-6 && std::abs (0.8 * rr - row.rr) < 1e-6);
  5792. CHECK (std::abs (0.8 * rl - row.rl) < 1e-6 && std::abs (0.8 * lr - row.lr) < 1e-6);
  5793. }
  5794. }
  5795. TEST (effector_units_match_fl_dll_impulse_responses)
  5796. {
  5797. // impulse responses of the installation's Effector engine (REA_rodada27 §2, eu_<kind>_<X>_<Y>.txt; LFO off,
  5798. // wet 1, blocks of 256): samples 1, 10, 100 and 1000
  5799. struct Case { int kind; float x, y; double v[4]; };
  5800. const Case cases[] = { { 3, 0.5f, 0.5f, { -0.603055418, 0.159798339, -0.0055043716, -1.06241259e-06 } },
  5801. { 4, 0.2f, 0.5f, { 4.68885949e-26, 4.20032622e-19, 0.000487731799, 2.27715846e-09 } },
  5802. { 4, 0.8f, 0.3f, { -0.293783396, -0.0306414738, -0.00068128563, 1.358577e-15 } } };
  5803. for (const auto& c : cases)
  5804. {
  5805. auto fx = lynx::effector::make();
  5806. fx->prepare (44100.0);
  5807. lynx::EffectParams p {};
  5808. p[lynx::effector::type] = c.kind / 11.0f;
  5809. p[lynx::effector::wetMix] = 1.0f;
  5810. p[lynx::effector::paramX] = c.x;
  5811. p[lynx::effector::paramY] = c.y;
  5812. p[lynx::effector::modX] = p[lynx::effector::modY] = 0.5f;
  5813. p[lynx::effector::modRate] = 0.5f;
  5814. p[lynx::effector::inputLevel] = 1.0f;
  5815. p[lynx::effector::outputGain] = 0.5f;
  5816. std::vector<float> l (1024, 0.0f), r (1024, 0.0f);
  5817. l[0] = r[0] = 1.0f;
  5818. for (int d = 0; d < 1024; d += 256)
  5819. fx->process (l.data() + d, r.data() + d, 256, p, 120.0);
  5820. const int at[4] { 1, 10, 100, 1000 };
  5821. for (int k = 0; k < 4; ++k)
  5822. CHECK (std::abs (l[(std::size_t) at[k]] - c.v[k]) < 2e-7 + 1e-5 * std::abs (c.v[k]));
  5823. }
  5824. }
  5825. TEST (harmless_stereo_tremolo_and_vibrato)
  5826. {
  5827. // tremolo d = 1: each side swings between 0 and 1.25 at 5 Hz, L and R in anti-phase; vibrato modulates the pitch
  5828. lynx::SynthSettings s;
  5829. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  5830. s.cutoff = 20000.0f;
  5831. s.stereoTremolo = 1.0f;
  5832. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  5833. inst->prepare (48000.0);
  5834. lynx::ChannelDef c;
  5835. c.synth = s;
  5836. inst->configure (c, 120.0);
  5837. inst->noteOn (69, 1.0f);
  5838. std::vector<float> l (48000), r (48000);
  5839. inst->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  5840. 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; };
  5841. // θ = 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
  5842. CHECK (envelope (l, 19200) > 4.0f * envelope (r, 19200));
  5843. CHECK (envelope (r, 24000) > 4.0f * envelope (l, 24000));
  5844. // vibrato 100 cents: zero crossings vary in spacing; without it they are regular
  5845. auto crossingsSpread = [] (float cents) {
  5846. lynx::SynthSettings v;
  5847. v.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  5848. v.cutoff = 20000.0f;
  5849. v.vibratoCents = cents;
  5850. const auto x = renderSynthNote (v, 69, 48000);
  5851. std::vector<int> zc;
  5852. for (int i = 24000; i < 48000; ++i)
  5853. if (x[(std::size_t) i - 1] < 0.0f && x[(std::size_t) i] >= 0.0f)
  5854. zc.push_back (i);
  5855. int lo = 1 << 30, hi = 0;
  5856. for (std::size_t k = 1; k < zc.size(); ++k)
  5857. lo = std::min (lo, zc[k] - zc[k - 1]), hi = std::max (hi, zc[k] - zc[k - 1]);
  5858. return hi - lo;
  5859. };
  5860. CHECK (crossingsSpread (0.0f) <= 1);
  5861. CHECK (crossingsSpread (100.0f) >= 4);
  5862. }
  5863. TEST (physical_models_sound_and_end)
  5864. {
  5865. // Sakura: a plucked string with default-ish parameters rings and fades after the release; Drumpad: a hit decays
  5866. for (const auto kind : { lynx::InstrumentKind::sakura, lynx::InstrumentKind::drumpad })
  5867. {
  5868. lynx::ChannelDef c;
  5869. c.instrument = kind;
  5870. if (kind == lynx::InstrumentKind::sakura)
  5871. {
  5872. c.modelParams.assign (146, 0.5f);
  5873. c.modelParams[111] = 3.0f; // both strings at the note
  5874. c.modelParams[113] = 0.5f; // octave ×1
  5875. c.modelParams[6] = c.modelParams[11] = 0.99f; // long decay
  5876. c.modelParams[31] = 0.0f; // noise exciter
  5877. }
  5878. else
  5879. {
  5880. c.modelParams.assign (38, 0.5f);
  5881. c.modelParams[0] = 1.0f; // retrigger noise
  5882. c.modelParams[30] = c.modelParams[31] = c.modelParams[32] = c.modelParams[33] = 0.0f; // no velocity morph
  5883. }
  5884. auto inst = lynx::makeInstrument (kind);
  5885. inst->prepare (48000.0);
  5886. inst->configure (c, 120.0);
  5887. inst->noteOn (60, 0.8f);
  5888. std::vector<float> l (48000), r (48000);
  5889. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  5890. inst->noteOff (60);
  5891. inst->render (l.data() + 24000, r.data() + 24000, 24000, 1.0f, 1.0f);
  5892. double early = 0.0;
  5893. for (int i = 0; i < 12000; ++i)
  5894. early += (double) l[(std::size_t) i] * l[(std::size_t) i];
  5895. CHECK (early > 1e-6);
  5896. CHECK (std::all_of (l.begin(), l.end(), [] (float v) { return std::isfinite (v); }));
  5897. std::vector<float> tail (480000), tailR (480000);
  5898. inst->render (tail.data(), tailR.data(), 480000, 1.0f, 1.0f); // 10 s later the voice has ended
  5899. CHECK (inst->idle());
  5900. }
  5901. }
  5902. TEST (squeeze_matches_fl_model)
  5903. {
  5904. // Fruity Squeeze: Steps quantises, Mix 0 passes the input dry ×Volume/127; a silent block is left untouched
  5905. auto slot = lynx::makeEffectSlot (lynx::EffectKind::squeeze);
  5906. slot.params[1] = 0.0f; // mix 0: dry only
  5907. auto fx = lynx::makeEffect (lynx::EffectKind::squeeze);
  5908. fx->prepare (44100.0);
  5909. std::vector<float> l (512, 0.3f), r (512, -0.2f);
  5910. fx->process (l.data(), r.data(), 512, slot.params, 120.0);
  5911. CHECK (std::abs (l[100] - 0.3f) < 1e-6f && std::abs (r[100] + 0.2f) < 1e-6f); // Volume 127/127
  5912. slot.params[1] = 1.0f; // wet only
  5913. slot.params[2] = 32000.0f / 32768.0f; // 32768^(1 − 32000/32768) ≈ 1.27 levels per unit → heavy quantisation
  5914. std::vector<float> a (512), b (512);
  5915. for (int i = 0; i < 512; ++i)
  5916. a[(std::size_t) i] = b[(std::size_t) i] = 0.4f * (float) std::sin (i * 0.05);
  5917. fx->process (a.data(), b.data(), 512, slot.params, 120.0);
  5918. const auto levels = std::pow (32768.0f, 1.0f - 32000.0f / 32768.0f);
  5919. for (int i = 0; i < 512; i += 37)
  5920. CHECK (std::abs (a[(std::size_t) i] * levels - std::nearbyint (a[(std::size_t) i] * levels)) < 1e-3f);
  5921. std::vector<float> z (512, 0.0f), z2 (512, 0.0f);
  5922. fx->process (z.data(), z2.data(), 512, slot.params, 120.0);
  5923. CHECK (z[10] == 0.0f);
  5924. }
  5925. TEST (sakura_matrix_and_effects)
  5926. {
  5927. // REA_rodada29 §1: velocity → level follows 10^(2m)·0.05 (vel 1 vs 0.5 → ×10 in amplitude); the delay leaves
  5928. // an echo after the note has ended and keeps the instrument from going idle until its tail is silent
  5929. auto base = [] {
  5930. lynx::ChannelDef c;
  5931. c.instrument = lynx::InstrumentKind::sakura;
  5932. c.modelParams.assign (146, 0.0f);
  5933. const std::pair<int, float> values[] { { 0, 0.375f }, { 1, 0.5f }, { 3, 0.5f }, { 4, 1.0f }, { 6, 0.95f }, { 9, 0.3f },
  5934. { 11, 0.95f }, { 14, 0.3f }, { 18, 0.5f }, { 19, 0.5f }, { 27, 0.5f }, { 28, 1.0f },
  5935. { 29, 0.7f }, { 31, 1.0f }, { 32, 0.5f }, { 111, 3.0f }, { 113, 0.5f } };
  5936. for (const auto& [i, v] : values)
  5937. c.modelParams[(std::size_t) i] = v;
  5938. return c;
  5939. };
  5940. auto render = [] (const lynx::ChannelDef& c, float velocity, int held, int total) {
  5941. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sakura);
  5942. inst->prepare (48000.0);
  5943. inst->configure (c, 120.0);
  5944. inst->noteOn (60, velocity);
  5945. std::vector<float> l ((std::size_t) total), r ((std::size_t) total);
  5946. for (int s = 0; s < total; s += 256)
  5947. {
  5948. if (s == held)
  5949. inst->noteOff (60);
  5950. inst->render (l.data() + s, r.data() + s, std::min (256, total - s), 1.0f, 1.0f);
  5951. }
  5952. return std::make_pair (l, std::move (inst));
  5953. };
  5954. auto energy = [] (const std::vector<float>& x, int from, int to) {
  5955. double e = 0.0;
  5956. for (int i = from; i < to; ++i)
  5957. e += (double) x[(std::size_t) i] * x[(std::size_t) i];
  5958. return e;
  5959. };
  5960. auto c = base();
  5961. c.modelParams[79] = 6.0f; // slot 1: velocity → level, amount 1
  5962. c.modelParams[80] = 1.0f;
  5963. c.modelParams[82] = 1.0f;
  5964. const auto loud = energy (render (c, 1.0f, 24064, 24064).first, 0, 24064);
  5965. const auto soft = energy (render (c, 0.5f, 24064, 24064).first, 0, 24064);
  5966. CHECK (loud > 1e-6 && std::abs (loud / soft - 100.0) < 1.0);
  5967. auto d = base();
  5968. auto [dry, dryInst] = render (d, 0.8f, 4864, 72000);
  5969. d.modelParams[63] = 1.0f; // delay on: time 0.5 → ≈ 0.52 s, wet 1, no feedback: one echo
  5970. d.modelParams[64] = 0.5f;
  5971. d.modelParams[69] = 1.0f;
  5972. auto [wet, wetInst] = render (d, 0.8f, 4864, 72000);
  5973. CHECK (energy (wet, 26000, 40000) > 100.0 * energy (dry, 26000, 40000) + 1e-9); // the note ends near 0.2 s
  5974. CHECK (dryInst->idle() || energy (dry, 70000, 72000) < 1e-12);
  5975. CHECK (! wetInst->idle()); // the echo tail has not been silent for 3 s yet
  5976. }
  5977. TEST (drumsynth_live_engine)
  5978. {
  5979. // REA_rodada30 §1: key → patch slot, state parsing, the engine against our reference model (no DLL: synthesised
  5980. // sources only, noise from the fallback seed), voice modes, patch level/pan
  5981. CHECK (lynx::drumSynthKeyToSlot (48) == 0 && lynx::drumSynthKeyToSlot (71) == 23 && lynx::drumSynthKeyToSlot (0) == 24);
  5982. CHECK (lynx::drumSynthKeyToSlot (47) == 71 && lynx::drumSynthKeyToSlot (72) == 72 && lynx::drumSynthKeyToSlot (119) == 119);
  5983. CHECK (lynx::drumSynthKeyToSlot (120) == -1);
  5984. // a version 3 state: 120 names, 120 × 38 ints (send track −1 becomes 0 below version 4), flags
  5985. std::vector<std::uint8_t> blob;
  5986. auto put = [&] (std::uint32_t v) { for (int k = 0; k < 4; ++k) blob.push_back ((std::uint8_t) (v >> (8 * k))); };
  5987. put (3);
  5988. put (66);
  5989. for (int i = 0; i < 120; ++i)
  5990. blob.push_back (2), blob.push_back ('a'), blob.push_back ((std::uint8_t) ('0' + i % 10));
  5991. for (int i = 0; i < 120 * 38; ++i)
  5992. put ((std::uint32_t) (i % 38 == 36 ? -1 : i % 38 == 4 ? 300 : 0));
  5993. put (0);
  5994. const auto parsed = lynx::drumSynthLiveParams (blob);
  5995. CHECK (parsed && (int) parsed->size() == lynx::drumSynthParamCount);
  5996. CHECK (parsed && (*parsed)[36] == 0.0f && (*parsed)[38 * 7 + 4] == 300.0f && (*parsed)[(std::size_t) lynx::drumSynthEditorKeyIndex] == 66.0f);
  5997. blob.resize (500);
  5998. CHECK (! lynx::drumSynthLiveParams (blob));
  5999. // patch on key 60 (slot 12): tone-mode Osc1 with sweep and click, noise-band Osc2, ring, 2 retriggers
  6000. 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,
  6001. 0, 0, 0, 0, 0, 0, 30, -1, 0, 0, 64 };
  6002. lynx::ChannelDef c;
  6003. c.instrument = lynx::InstrumentKind::drumsynth;
  6004. c.modelParams.assign ((std::size_t) lynx::drumSynthParamCount, 0.0f);
  6005. for (int s = 0; s < 120; ++s)
  6006. c.modelParams[(std::size_t) (38 * s + 15)] = c.modelParams[(std::size_t) (38 * s + 34)] = -1.0f;
  6007. for (int i = 0; i < 38; ++i)
  6008. c.modelParams[(std::size_t) (38 * 12 + i)] = (float) patch[i];
  6009. auto render = [] (const lynx::ChannelDef& def, std::vector<int> keys, int total, float gl = 1.0f, float gr = 1.0f) {
  6010. auto inst = lynx::makeInstrument (lynx::InstrumentKind::drumsynth);
  6011. inst->configure (def, 120.0);
  6012. inst->prepare (48000.0);
  6013. std::vector<float> l ((std::size_t) total), r ((std::size_t) total);
  6014. for (int s = 0; s < total; s += 512)
  6015. {
  6016. for (std::size_t k = 0; k + 1 < keys.size(); k += 2)
  6017. if (keys[k + 1] == s)
  6018. inst->noteOn (keys[k], 100.0f / 128.0f);
  6019. inst->render (l.data() + s, r.data() + s, std::min (512, total - s), gl, gr);
  6020. }
  6021. return std::make_tuple (l, r, std::move (inst));
  6022. };
  6023. {
  6024. auto [l, r, inst] = render (c, { 60, 0 }, 9600);
  6025. // reference model (REA round 30 dsl_model.py, seed 0x56CE, FL velocity 100, V = 1, centre: × g(100)·cos(π/4))
  6026. const std::pair<int, float> golden[] { { 0, -0.0074092713f }, { 10, -0.13961405f }, { 100, -0.47290668f }, { 1000, -0.29188696f },
  6027. { 3000, -0.22130175f }, { 6000, -0.049537566f }, { 9599, 0.010392102f } };
  6028. for (const auto& [i, v] : golden)
  6029. CHECK (std::abs (l[(std::size_t) i] - v) < 2e-6f && std::abs (r[(std::size_t) i] - v) < 2e-6f);
  6030. std::vector<float> tail (48000 * 4), tailR (tail.size());
  6031. inst->render (tail.data(), tailR.data(), (int) tail.size(), 1.0f, 1.0f);
  6032. CHECK (inst->idle()); // the engine reported the voice finished
  6033. }
  6034. auto energy = [] (const std::vector<float>& x, int from, int to) {
  6035. double e = 0.0;
  6036. for (int i = from; i < to; ++i)
  6037. e += (double) x[(std::size_t) i] * x[(std::size_t) i];
  6038. return e;
  6039. };
  6040. // a key without a patch level (slot 0, level 0) and a key outside the 120 patches are silent
  6041. CHECK (energy (std::get<0> (render (c, { 48, 0, 125, 0 }, 4096)), 0, 4096) == 0.0);
  6042. // mono: a second hit on the same key cuts the first; poly: both ring together (Osc2 off: no noise, deterministic)
  6043. auto tone = c;
  6044. tone.modelParams[38 * 12 + 14] = 0.0f;
  6045. const auto single = std::get<0> (render (tone, { 60, 0 }, 8192));
  6046. const auto mono = std::get<0> (render (tone, { 60, 0, 60, 2048 }, 8192));
  6047. auto poly = tone;
  6048. poly.modelParams[38 * 12 + 24] = 1.0f;
  6049. const auto both = std::get<0> (render (poly, { 60, 0, 60, 2048 }, 8192));
  6050. double monoDiff = 0.0, polyDiff = 0.0;
  6051. for (int i = 2048 + 300; i < 8192; ++i) // after the cut fade: mono = only the second hit, a copy of the first
  6052. 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]);
  6053. CHECK (monoDiff < 1e-3 && polyDiff > 1.0);
  6054. // patch pan +64 → right only; channel volume counts twice (FL applies Final.Vol in the engine and at the host)
  6055. auto right = c;
  6056. right.modelParams[38 * 12 + 1] = 64.0f;
  6057. const auto [pl, pr, pi] = render (right, { 60, 0 }, 4096);
  6058. CHECK (energy (pl, 0, 4096) < 1e-12 * energy (pr, 0, 4096) && energy (pr, 0, 4096) > 1.0);
  6059. const auto full = std::get<0> (render (tone, { 60, 0 }, 4096));
  6060. const auto half = std::get<0> (render (tone, { 60, 0 }, 4096, 0.5f, 0.5f));
  6061. CHECK (std::abs (half[100] - 0.25f * full[100]) < 1e-6f && std::abs (full[100]) > 0.01f);
  6062. }
  6063. TEST (kepler_lfo_bpm_sync)
  6064. {
  6065. // 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)
  6066. std::vector<std::uint8_t> state (0x21 + 34 * 4, 0);
  6067. auto putU32 = [&] (std::size_t o, std::uint32_t v) { std::memcpy (state.data() + o, &v, 4); };
  6068. putU32 (12, 9);
  6069. std::memcpy (state.data() + 16, "Kepler-1", 9);
  6070. putU32 (0x19, 4);
  6071. putU32 (0x1D, 34);
  6072. float k[34] {};
  6073. k[5] = 0.602085769f; // "Pads - Kepler" demo: n = 286
  6074. k[6] = 1.0f;
  6075. k[10] = 1.0f; // vibrato on
  6076. k[33] = 1.0f;
  6077. std::memcpy (state.data() + 0x21, k, sizeof k);
  6078. lynx::SynthSettings s;
  6079. float gain = 0.0f;
  6080. CHECK (lynx::synthFromKepler (state, s, gain));
  6081. CHECK (s.lfo[lynx::lfoPitch].sync && s.lfo[lynx::lfoPitch].secondsTiming);
  6082. CHECK (std::abs (s.lfo[lynx::lfoPitch].period - 286.0f / 192.0f) < 1e-6f);
  6083. k[5] = 0.0f; // slowest: 32 beats
  6084. std::memcpy (state.data() + 0x21, k, sizeof k);
  6085. CHECK (lynx::synthFromKepler (state, s, gain) && std::abs (s.lfo[lynx::lfoPitch].period - 32.0f) < 1e-6f);
  6086. k[6] = 0.0f; // free rate in seconds
  6087. std::memcpy (state.data() + 0x21, k, sizeof k);
  6088. CHECK (lynx::synthFromKepler (state, s, gain) && ! s.lfo[lynx::lfoPitch].sync);
  6089. }
  6090. namespace
  6091. {
  6092. // A Harmor state written from scratch (REA_rodada11 §4.1 layout, version 18): part A only — a decaying-harmonics
  6093. // timbre, low-pass + resonance, filter envelope, 3-voice unison, vibrato, pluck, tremolo, volume envelope with a
  6094. // velocity map — and the global block. Every other curve is neutral.
  6095. std::vector<std::uint8_t> harmorTestState (bool panLfo = true)
  6096. {
  6097. std::vector<std::uint8_t> b;
  6098. 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))); };
  6099. 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))); };
  6100. struct Pt { double dx, y, tension; int mode; };
  6101. auto curve = [&] (const std::vector<Pt>& pts, std::array<std::int32_t, 5> hdr) {
  6102. i32 (3), i32 (3), i32 ((std::int32_t) pts.size());
  6103. for (const auto& p : pts)
  6104. {
  6105. f64 (p.dx), f64 (p.y);
  6106. const auto t = (float) p.tension;
  6107. std::uint32_t u;
  6108. std::memcpy (&u, &t, 4);
  6109. i32 ((std::int32_t) u);
  6110. b.push_back ((std::uint8_t) p.mode), b.push_back (0), b.push_back (0), b.push_back (0);
  6111. }
  6112. for (auto h : hdr)
  6113. i32 (h);
  6114. };
  6115. const std::array<std::int32_t, 5> off { 0, 0, -1, -1, -1 }, on { 0, 1, -1, -1, -1 };
  6116. 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); };
  6117. i32 (18);
  6118. i32 (1 | 4);
  6119. std::vector<std::uint8_t> part;
  6120. std::swap (b, part);
  6121. std::array<std::int32_t, 386> p {};
  6122. const std::pair<int, int> values[] = { { 0, 500 }, { 3, 1000 }, { 9, 1024 }, { 11, 1000 }, { 12, 1000 }, { 17, 300 }, { 18, 4000 },
  6123. { 19, 500 }, { 20, 1000 }, { 24, 500 }, { 25, 500 }, { 28, 500 }, { 29, 256 }, { 30, -1 }, { 31, -1 }, { 33, -1 }, { 34, 3 },
  6124. { 35, 1 }, { 37, 192 }, { 38, 128 }, { 39, 500 }, { 40, 10000 }, { 41, 1 }, { 42, 10000 }, { 43, 1 }, { 45, 200 }, { 46, 500 },
  6125. { 47, 1 }, { 49, -140 }, { 50, 1200 }, { 51, 0 }, { 52, 5000 }, { 54, 500 }, { 56, 600 }, { 57, 300 }, { 59, 500 }, { 60, 600 },
  6126. { 64, 8192 }, { 66, 500 }, { 72, 600 }, { 74, 1000 }, { 75, 600 }, { 78, 5000 }, { 79, 500 }, { 80, 3000 } };
  6127. for (const auto& [i, v] : values)
  6128. p[(std::size_t) i] = v;
  6129. for (auto v : p)
  6130. i32 (v);
  6131. for (int i = 0; i < 12; ++i)
  6132. i32 (i); // module order
  6133. std::array<std::uint8_t, 0x4b> misc {};
  6134. auto put = [&] (int o, std::int32_t v) { std::memcpy (misc.data() + o, &v, 4); };
  6135. const float one = 1.0f;
  6136. put (0x08, 107), put (0x1c, 1), put (0x28, 200), std::memcpy (misc.data() + 0x30, &one, 4);
  6137. put (0x34, 0), put (0x38, 4), put (0x3c, 100), put (0x40, 108);
  6138. misc[0x44] = 1;
  6139. b.insert (b.end(), misc.begin(), misc.end());
  6140. 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 };
  6141. for (int k = 0; k < 43; ++k)
  6142. {
  6143. static const int mode2[] = { 2, 14, 23, 28, 30, 38, 39, 41, 42 }; // ×2 around 0.5: 1.0 is neutral
  6144. const bool centred = std::find (std::begin (mode1), std::end (mode1), k) != std::end (mode1);
  6145. const bool doubled = std::find (std::begin (mode2), std::end (mode2), k) != std::end (mode2);
  6146. const double neutral = centred && ! doubled ? 0.5 : 1.0;
  6147. i32 (3);
  6148. i32 (1065353216), i32 (1065353216), i32 (1065353216);
  6149. if (k == 1) // volume envelope: attack, decay to the sustain point, release
  6150. 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 });
  6151. else if (k == 4) // filter-1 envelope
  6152. curve ({ { 0, 1, 0, 0 }, { 0.25, 0.2, -0.5, 0 } }, { 0, 1, -1, -1, -1 });
  6153. else
  6154. flat (neutral);
  6155. for (int a : { 128, 128, 0, 128 })
  6156. i32 (a);
  6157. if (k == 0 && panLfo) // pan LFO
  6158. flat (1.0, on);
  6159. else
  6160. flat (0.5);
  6161. for (int a : { k == 0 ? 40000 : 0, 0, 0, 0 })
  6162. i32 (a);
  6163. i32 (0);
  6164. for (int m = 2; m < 11; ++m)
  6165. if (k == 1 && m == 3)
  6166. curve ({ { 0, 0.2, 0, 0 }, { 1, 1, -0.3, 0 } }, off); // velocity → volume
  6167. else
  6168. flat (neutral);
  6169. }
  6170. for (int c = 0; c < 26; ++c)
  6171. if (c == 2 || c == 3)
  6172. curve ({ { 0, 0.25, 0, 0 }, { 0.006, 0.12, -0.46, 0 }, { 0.994, 0, 0, 0 } }, off); // timbres
  6173. else if (c == 14)
  6174. curve ({ { 0, 1, 0, 0 }, { 1, 0, 0, 0 } }, off); // pluck curve
  6175. else
  6176. 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)));
  6177. std::swap (b, part);
  6178. i32 ((std::int32_t) part.size());
  6179. b.insert (b.end(), part.begin(), part.end());
  6180. std::array<std::int32_t, 53> g {};
  6181. g[0] = g[1] = g[2] = 256, g[10] = 500, g[11] = 1000, g[12] = 1000, g[15] = 1000;
  6182. for (auto v : g)
  6183. i32 (v);
  6184. for (int i = 0; i < 6; ++i)
  6185. i32 (i);
  6186. std::array<std::uint8_t, 0x3d> gm {};
  6187. const std::int32_t cr = 200, vr = 1;
  6188. std::memcpy (gm.data() + 12, &vr, 4);
  6189. std::memcpy (gm.data() + 24, &cr, 4);
  6190. b.insert (b.end(), gm.begin(), gm.end());
  6191. return b;
  6192. }
  6193. } // namespace
  6194. TEST (harmor_engine)
  6195. {
  6196. // REA_rodada34: state parsing, the additive engine against our reference model (hmodel.py), host levels, voice end
  6197. const auto blob = harmorTestState();
  6198. if (const char* dump = std::getenv ("LYNX_DUMP_HARMOR"))
  6199. std::ofstream (dump, std::ios::binary).write ((const char*) blob.data(), (std::streamsize) blob.size());
  6200. CHECK (lynx::harmorStateUsable (blob));
  6201. CHECK (lynx::harmorFallbacks (blob).size() == 1); // (only the harmonic-randomness note)
  6202. const auto at = lynx::harmorParamOffset (blob, 0, 52);
  6203. std::int32_t cutoff = 0;
  6204. CHECK (at > 0 && (std::memcpy (&cutoff, blob.data() + at, 4), cutoff == 5000));
  6205. CHECK (lynx::harmorParamOffset (blob, 1, 52) < 0 && lynx::harmorParamOffset (blob, -1, 12) > at);
  6206. auto broken = blob;
  6207. broken.resize (broken.size() / 2);
  6208. CHECK (! lynx::harmorStateUsable (broken));
  6209. auto old = blob;
  6210. old[0] = 15; // articulators and curves are stored from version 16
  6211. CHECK (! lynx::harmorStateUsable (old));
  6212. lynx::ChannelDef c;
  6213. c.instrument = lynx::InstrumentKind::harmor;
  6214. c.pluginState = blob;
  6215. auto render = [] (const lynx::ChannelDef& def, int total, float gl, float gr, int offAt) {
  6216. auto inst = lynx::makeInstrument (lynx::InstrumentKind::harmor);
  6217. inst->configure (def, 120.0);
  6218. inst->prepare (44100.0);
  6219. std::vector<float> l ((std::size_t) total), r ((std::size_t) total);
  6220. inst->noteOn (60, 0.78125f);
  6221. for (int s = 0; s < total; s += 512)
  6222. {
  6223. if (s == offAt)
  6224. inst->noteOff (60);
  6225. inst->render (l.data() + s, r.data() + s, std::min (512, total - s), gl, gr);
  6226. }
  6227. return std::make_tuple (l, r, std::move (inst));
  6228. };
  6229. {
  6230. // reference model (REA round 34 hmodel.py; C5 at FL velocity 100, Final.Vol 1, centre, released at 6144, the
  6231. // Mersenne Twister seeded like LYNX's)
  6232. auto [l, r, inst] = render (c, 8192, 1.0f, 1.0f, 6144);
  6233. const std::tuple<int, float, float> golden[] {
  6234. { 0, 0.0f, 0.0f }, { 100, 0.00947693f, 0.04249846f }, { 1000, 0.08140575f, -0.03251422f }, { 3000, 0.05928446f, -0.00247572f },
  6235. { 6000, 0.02997839f, 0.14549091f }, { 7000, -0.01121871f, 0.04197952f }, { 8191, 0.00314545f, 0.03857505f } };
  6236. for (const auto& [i, gl, gr] : golden)
  6237. CHECK (std::abs (l[(std::size_t) i] - gl) < 2e-6f && std::abs (r[(std::size_t) i] - gr) < 2e-6f);
  6238. // after the release the volume envelope ends, the record declicks and the instrument goes idle
  6239. std::vector<float> tail (44100), tailR (tail.size());
  6240. inst->render (tail.data(), tailR.data(), (int) tail.size(), 1.0f, 1.0f);
  6241. CHECK (inst->idle());
  6242. CHECK (std::abs (tail.back()) == 0.0f);
  6243. }
  6244. // the reference renderer gives the same samples as the instrument
  6245. {
  6246. const auto ref = lynx::harmor::renderReference (blob, { { 0, 60, 0.78125, 1.0, 0.0, 6144 } }, 44100.0, 8192);
  6247. const auto [l, r, inst] = render (c, 8192, 1.0f, 1.0f, 6144);
  6248. double worst = 0.0;
  6249. for (int i = 0; i < 8192; ++i)
  6250. 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]) });
  6251. CHECK (worst == 0.0);
  6252. }
  6253. // FL's level law applied once: half the channel volume halves the output; full right pan silences the left side
  6254. const auto full = std::get<0> (render (c, 2048, 1.0f, 1.0f, -1));
  6255. const auto half = std::get<0> (render (c, 2048, 0.5f, 0.5f, -1));
  6256. CHECK (std::abs (half[1000] - 0.5f * full[1000]) < 1e-6f && std::abs (full[1000]) > 0.01f);
  6257. auto mono = c;
  6258. mono.pluginState = harmorTestState (false); // no pan LFO ...
  6259. const std::int32_t one = 1;
  6260. std::memcpy (mono.pluginState.data() + lynx::harmorParamOffset (mono.pluginState, 0, 34), &one, 4); // ... nor unison spread
  6261. const auto [pl, pr, pi] = render (mono, 2048, 0.0f, 1.41421356f, -1);
  6262. double el = 0.0, er = 0.0;
  6263. for (int i = 0; i < 2048; ++i)
  6264. el += (double) pl[(std::size_t) i] * pl[(std::size_t) i], er += (double) pr[(std::size_t) i] * pr[(std::size_t) i];
  6265. CHECK (el < 1e-10 * er && er > 1e-3);
  6266. }
  6267. namespace
  6268. {
  6269. // An Ogun state written from scratch (REA_rodada37 §1.3 layout, version 18; zlib with stored blocks): richness 4
  6270. // (255 partials), pre-decay, decay/release, fullness, Seed 1 + fixed Seed 2 with morph, 3-voice unison, a 2-stage
  6271. // low-pass with an LFO on its cutoff, a volume envelope with a sustain point and a velocity map, declick, normalisation,
  6272. // Impulse/Decay maps, and every plugin effect (EQ band, chorus, ping-pong delay, reverb). Everything else is neutral.
  6273. std::vector<std::uint8_t> ogunTestState()
  6274. {
  6275. std::vector<std::uint8_t> b;
  6276. 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))); };
  6277. auto f32v = [&] (float v) { std::uint32_t u; std::memcpy (&u, &v, 4); i32 ((std::int32_t) u); };
  6278. 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))); };
  6279. struct Pt { double dx, y, tension; int mode; };
  6280. auto curve = [&] (int type, const std::vector<Pt>& pts, std::array<std::int32_t, 5> hdr) {
  6281. i32 (type), i32 (3), i32 ((std::int32_t) pts.size());
  6282. for (const auto& p : pts)
  6283. {
  6284. f64 (p.dx), f64 (p.y), f32v ((float) p.tension);
  6285. b.push_back ((std::uint8_t) p.mode), b.push_back (0), b.push_back (0), b.push_back (0);
  6286. }
  6287. for (auto h : hdr)
  6288. i32 (h);
  6289. };
  6290. const std::array<std::int32_t, 5> off { 0, 0, -1, -1, -1 }, on { 0, 1, -1, -1, -1 };
  6291. auto flat = [&] (int type, double y) { curve (type, { { 0, y, 0, 0 }, { 1, y, 0, 0 } }, off); };
  6292. std::array<std::int32_t, 64> P {};
  6293. const std::pair<int, int> values[] = { { 0, 128 }, { 5, 300 }, { 6, 3000 }, { 7, 2000 }, { 8, 200 }, { 9, 500 }, { 10, 12 },
  6294. { 11, 34 }, { 12, 3 }, { 13, 64 }, { 14, 64 }, { 15, 40 }, { 16, 64 }, { 17, 180 }, { 18, 60 }, { 19, 2 }, { 20, 300 },
  6295. { 21, 400 }, { 22, 40 }, { 23, 30 }, { 24, 20 }, { 25, 64 }, { 26, 40 }, { 27, 96 }, { 28, 100 }, { 29, 64 }, { 30, 2 },
  6296. { 31, 19 }, { 32, 221 }, { 33, 0 }, { 34, 50 }, { 35, 100 }, { 36, 20 }, { 37, 60 }, { 38, 2 }, { 39, 64 }, { 40, 300 },
  6297. { 43, 30000 }, { 46, 20000 }, { 49, 0 }, { 50, 2 }, { 51, 0 }, { 52, 9 }, { 53, 1 }, { 54, 0 },
  6298. { 55, 0x01000000 }, // +0x20b: pitch follows the key
  6299. { 56, 0x00010000 }, // +0x20e: declick
  6300. { 62, 0x00000100 } }; // +0x225: normalise
  6301. for (const auto& [i, v] : values)
  6302. P[(std::size_t) i] = v;
  6303. for (auto v : P)
  6304. i32 (v);
  6305. b.push_back (0), b.push_back (1), b.push_back (0); // delay: not tempo-based, on
  6306. i32 (1), i32 (1), i32 (1); // EQ band types: peaking
  6307. b.push_back (0); // comment: 0 characters
  6308. for (int k = 0; k < 13; ++k)
  6309. {
  6310. static constexpr int sum[] = { 1, 2, 3, 9, 11, 12 };
  6311. const double neutral = std::find (std::begin (sum), std::end (sum), k) != std::end (sum) ? 0.5 : 1.0;
  6312. i32 (1);
  6313. f32v (0.0f), f32v (1.0f), f32v (k == 1 ? 0.3f : 0.0f);
  6314. if (k == 0) // volume envelope: attack, decay to the sustain point, release
  6315. curve (1, { { 0, 0, 0, 0 }, { 0.02, 1, 0.3, 0 }, { 0.3, 0.5, -0.4, 0 }, { 0.5, 0, 0.2, 0 } }, { 0, 1, 2, -1, 2 });
  6316. else
  6317. flat (1, neutral);
  6318. for (int a : { 128, 128, 128, 128 })
  6319. i32 (a);
  6320. if (k == 1) // cutoff LFO
  6321. curve (2, { { 0, 0.8, 0, 0 } }, on);
  6322. else
  6323. flat (2, 0.5);
  6324. for (int a : { k == 1 ? 40000 : 0, 0, 0, 0 })
  6325. i32 (a);
  6326. i32 (0);
  6327. for (int m = 0; m < 4; ++m)
  6328. if (k == 0 && m == 1)
  6329. curve (3, { { 0, 0.3, 0, 0 }, { 1, 1, -0.2, 0 } }, off); // velocity → volume
  6330. else
  6331. flat (3, neutral);
  6332. }
  6333. flat (3, 0.0); // Forced: none
  6334. curve (3, { { 0, 0.6, 0, 0 }, { 1, 0.4, 0.3, 0 } }, off); // Impulse EQ
  6335. curve (3, { { 0, 0.5, 0, 0 }, { 1, 0.3, 0, 0 } }, off); // Decay EQ
  6336. flat (3, 0.5); // Release EQ
  6337. // u32 version + zlib (stored blocks)
  6338. std::vector<std::uint8_t> s { 18, 0, 0, 0, 0x78, 0x01 };
  6339. for (std::size_t i = 0; i < b.size();)
  6340. {
  6341. const auto len = std::min<std::size_t> (65535, b.size() - i);
  6342. s.push_back (i + len >= b.size() ? 1 : 0);
  6343. s.push_back ((std::uint8_t) len), s.push_back ((std::uint8_t) (len >> 8));
  6344. s.push_back ((std::uint8_t) ~len), s.push_back ((std::uint8_t) (~len >> 8));
  6345. s.insert (s.end(), b.begin() + (std::ptrdiff_t) i, b.begin() + (std::ptrdiff_t) (i + len));
  6346. i += len;
  6347. }
  6348. std::uint32_t a1 = 1, a2 = 0;
  6349. for (auto c : b)
  6350. a1 = (a1 + c) % 65521u, a2 = (a2 + a1) % 65521u;
  6351. for (int sh = 24; sh >= 0; sh -= 8)
  6352. s.push_back ((std::uint8_t) (((a2 << 16) | a1) >> sh));
  6353. return s;
  6354. }
  6355. } // namespace
  6356. TEST (ogun_engine)
  6357. {
  6358. // REA_rodada37: state parsing, the engine against our reference model (ogmodel.py), host levels, export quality
  6359. const auto blob = ogunTestState();
  6360. if (const char* dump = std::getenv ("LYNX_DUMP_OGUN"))
  6361. std::ofstream (dump, std::ios::binary).write ((const char*) blob.data(), (std::streamsize) blob.size());
  6362. CHECK (lynx::ogunStateUsable (blob));
  6363. CHECK (lynx::ogunFallbacks (blob).empty());
  6364. CHECK (lynx::ogunParam (blob, 17) == 180 && lynx::ogunParam (blob, 52) == 9 && ! lynx::ogunParam (blob, 64));
  6365. auto broken = blob;
  6366. broken.resize (broken.size() - 300);
  6367. CHECK (! lynx::ogunStateUsable (broken));
  6368. auto old = blob;
  6369. old[0] = 13; // the articulator layout is from version 14
  6370. CHECK (! lynx::ogunStateUsable (old));
  6371. // reference model (REA round 37 ogmodel.Plugin(state).run: C5 velocity 0.75 released at 6144, G5 velocity 0.625 at 2048
  6372. // released at 8192; host block 512)
  6373. const std::vector<lynx::ogun::RefNote> notes { { 0, 60, 0.75, 1.0, 0.0, 0.0, 0.0, 0.0, 0.5, 6144 }, { 2048, 67, 0.625, 1.0, 0.0, 0.0, 0.0, 0.0, 0.5, 8192 } };
  6374. const auto ref = lynx::ogun::renderReference (blob, notes, 44100.0, 16384);
  6375. CHECK (ref.size() == 2 * 16384);
  6376. if (const char* dump = std::getenv ("LYNX_DUMP_OGUN_OUT"))
  6377. std::ofstream (dump, std::ios::binary).write ((const char*) ref.data(), (std::streamsize) (ref.size() * 4));
  6378. const std::tuple<int, float, float> golden[] {
  6379. { 100, -7.763202e-05f, -8.919523e-05f }, { 1000, 0.06195267f, 0.03858230f }, { 3000, 0.01363476f, -0.00378433f },
  6380. { 6000, -0.06601223f, -0.03084030f }, { 9000, 0.04204506f, 0.02452896f }, { 12000, 0.03420147f, -0.01837870f },
  6381. { 16383, -0.00465311f, -0.00119627f } };
  6382. for (const auto& [i, gl, gr] : golden)
  6383. CHECK (std::abs (ref[2 * (std::size_t) i] - gl) < 2e-6f && std::abs (ref[2 * (std::size_t) i + 1] - gr) < 2e-6f);
  6384. // the instrument plays like the reference renderer (Final.Vol 1, centre)
  6385. lynx::ChannelDef c;
  6386. c.instrument = lynx::InstrumentKind::ogun;
  6387. c.pluginState = blob;
  6388. auto render = [&] (const lynx::ChannelDef& def, int total, float gl, float gr, bool held = false) {
  6389. auto inst = lynx::makeInstrument (lynx::InstrumentKind::ogun);
  6390. inst->configure (def, 120.0);
  6391. inst->prepare (44100.0);
  6392. std::vector<float> l ((std::size_t) total), r ((std::size_t) total);
  6393. for (int s = 0; s < total; s += 512)
  6394. {
  6395. if (s == 0)
  6396. inst->noteOn (60, 0.75f);
  6397. if (s == 2048)
  6398. inst->noteOn (67, 0.625f);
  6399. if (s == 6144 && ! held)
  6400. inst->noteOff (60);
  6401. if (s == 8192 && ! held)
  6402. inst->noteOff (67);
  6403. inst->render (l.data() + s, r.data() + s, std::min (512, total - s), gl, gr);
  6404. }
  6405. return std::make_tuple (l, r, std::move (inst));
  6406. };
  6407. {
  6408. auto [l, r, inst] = render (c, 16384, 1.0f, 1.0f);
  6409. double worst = 0.0;
  6410. for (int i = 0; i < 16384; ++i)
  6411. 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]) });
  6412. CHECK (worst == 0.0);
  6413. // the voices end and the effect tails die out: the instrument goes idle
  6414. std::vector<float> tail (44100), tailR (tail.size());
  6415. for (int k = 0; k < 20 && ! inst->idle(); ++k)
  6416. inst->render (tail.data(), tailR.data(), (int) tail.size(), 1.0f, 1.0f);
  6417. CHECK (inst->idle());
  6418. }
  6419. // FL's level law applied once (effects off): half the channel volume halves the output once the gain ramps
  6420. // (limited to 0.001 per sample) have settled on the sustain level; full right pan silences the left side
  6421. {
  6422. auto dry = c;
  6423. for (int i : { 19, 29, 40, 53 })
  6424. CHECK (lynx::ogunSetParam (dry.pluginState, i, 0)); // chorus, delay wet, EQ band and reverb off
  6425. CHECK (lynx::ogunStateUsable (dry.pluginState) && lynx::ogunParam (dry.pluginState, 19) == 0);
  6426. const auto full = std::get<0> (render (dry, 32768, 1.0f, 1.0f, true));
  6427. const auto half = std::get<0> (render (dry, 32768, 0.5f, 0.5f, true));
  6428. double worst = 0.0, peak = 0.0;
  6429. for (int i = 30000; i < 32768; ++i)
  6430. worst = std::max (worst, (double) std::abs (half[(std::size_t) i] - 0.5f * full[(std::size_t) i])),
  6431. peak = std::max (peak, (double) std::abs (full[(std::size_t) i]));
  6432. CHECK (worst <= 1e-7 * peak && peak > 1e-3);
  6433. // FL's default channel volume (100/128): FL hands Ogun Final.Vol = (11^v − 1)/10 (REA_rodada28 §4.1); LYNX's
  6434. // centred channel gains (√2·V·cos(π/4) each) give the reference model's level at that Final.Vol
  6435. const auto V = lynx::channelGain (0.78125f);
  6436. const auto g = V * std::cos (0.25f * 3.14159265f) * 1.41421356f;
  6437. const auto atDefault = std::get<0> (render (dry, 32768, g, g, true));
  6438. const auto refDefault = lynx::ogun::renderReference (dry.pluginState, { { 0, 60, 0.75, V, 0.0, 0.0, 0.0, 0.0, 0.5, -1 },
  6439. { 2048, 67, 0.625, V, 0.0, 0.0, 0.0, 0.0, 0.5, -1 } }, 44100.0, 32768);
  6440. double ei = 0.0, er0 = 0.0;
  6441. for (int i = 30000; i < 32768; ++i)
  6442. ei += (double) atDefault[(std::size_t) i] * atDefault[(std::size_t) i], er0 += (double) refDefault[2 * (std::size_t) i] * refDefault[2 * (std::size_t) i];
  6443. CHECK (er0 > 0.0 && std::abs (10.0 * std::log10 (ei / er0)) < 0.001);
  6444. const auto [pl, pr, pi] = render (dry, 4096, 0.0f, 1.41421356f);
  6445. double el = 0.0, er = 0.0;
  6446. for (int i = 0; i < 4096; ++i)
  6447. el += (double) pl[(std::size_t) i] * pl[(std::size_t) i], er += (double) pr[(std::size_t) i] * pr[(std::size_t) i];
  6448. CHECK (el < 1e-10 * er && er > 1e-3);
  6449. }
  6450. // export: FL renders Ogun at quality 4 (×2 rate, 32-point reader), LYNX too while it renders offline
  6451. {
  6452. lynx::setOfflineRendering (true);
  6453. auto [l, r, inst] = render (c, 8192, 1.0f, 1.0f);
  6454. lynx::setOfflineRendering (false);
  6455. lynx::ogun::RefOptions q4;
  6456. q4.quality = 4;
  6457. const auto ref4 = lynx::ogun::renderReference (blob, notes, 44100.0, 8192, q4);
  6458. double worst = 0.0, diff = 0.0;
  6459. for (int i = 0; i < 8192; ++i)
  6460. worst = std::max (worst, (double) std::abs (ref4[2 * (std::size_t) i] - l[(std::size_t) i])),
  6461. diff = std::max (diff, (double) std::abs (ref[2 * (std::size_t) i] - l[(std::size_t) i]));
  6462. CHECK (worst == 0.0 && diff > 1e-3);
  6463. const std::tuple<int, float, float> golden4[] {
  6464. { 100, 0.00605961f, 0.00628969f }, { 1000, 0.03729841f, 0.01727954f }, { 3000, -0.09010383f, -0.02551294f },
  6465. { 6000, 0.02167798f, -0.01115632f }, { 8191, 0.00320288f, -0.00615792f } };
  6466. for (const auto& [i, gl, gr] : golden4)
  6467. CHECK (std::abs (ref4[2 * (std::size_t) i] - gl) < 2e-6f && std::abs (ref4[2 * (std::size_t) i + 1] - gr) < 2e-6f);
  6468. }
  6469. // feature variants of the same state against the reference model (energy per side over 8192 samples, three
  6470. // samples; C1 released at 6144): qualities, richness, unison, the filter types, ALT DECAY, 1/√h, Seed 2 Random,
  6471. // infinite decay, logarithmic axis, velocity → position, other rates. Goldens from ogmodel.py (REA round 37).
  6472. {
  6473. struct Sample { int at; float l, r; };
  6474. struct Variant { const char* name; std::vector<std::pair<int, int>> params; int rate; double el, er; Sample s[3]; };
  6475. const Variant variants[] {
  6476. { "q1", { { 54, 1 } }, 44100, 11.0970402, 6.87820714, { { 1500, 0.0240363069f, -0.0148524037f }, { 4000, 0.0873190612f, -0.000715861097f }, { 7000, -0.0378603041f, -0.00338819111f } } },
  6477. { "q2", { { 54, 2 } }, 44100, 11.2405446, 6.68045082, { { 1500, 0.0448660068f, -0.00560745923f }, { 4000, -0.0122657465f, 0.0104285963f }, { 7000, -0.0216034129f, -0.0134632047f } } },
  6478. { "q3", { { 54, 3 } }, 44100, 11.3200608, 6.86196449, { { 1500, -0.0031537537f, -0.0242648814f }, { 4000, 0.0426301025f, 0.0364697985f }, { 7000, 0.00843803957f, 0.0302239582f } } },
  6479. { "rich16_q0", { { 52, 16 }, { 54, 0 } }, 44100, 26.7616786, 19.2591256, { { 1500, 0.0728010684f, -0.0116148153f }, { 4000, 0.0797849894f, 0.0765359923f }, { 7000, -0.00811834447f, -0.0104534971f } } },
  6480. { "uni9", { { 12, 9 }, { 15, 20 }, { 16, 0 }, { 14, 16 } }, 44100, 61.7485898, 36.6693432, { { 1500, 0.0531249829f, -0.0374071151f }, { 4000, 0.165054232f, -0.0192129575f }, { 7000, -0.0373774841f, -0.00196591392f } } },
  6481. { "lp1", { { 50, 1 }, { 49, 0 } }, 44100, 7.81941168, 4.72659869, { { 1500, 0.0377117358f, -0.0157920271f }, { 4000, 0.0747607499f, 0.00154248625f }, { 7000, -0.0510631353f, 0.00884498842f } } },
  6482. { "bp3flat", { { 50, 3 }, { 49, 1 }, { 51, 1 } }, 44100, 2.19181431, 1.29483907, { { 1500, 0.0291239917f, -0.00288665155f }, { 4000, -0.0084345676f, -0.00400509313f }, { 7000, -0.00592403999f, 0.00150578981f } } },
  6483. { "bs2", { { 50, 2 }, { 49, 2 } }, 44100, 32.8440514, 25.7202184, { { 1500, 0.0730303749f, -0.0496222489f }, { 4000, 0.0696200803f, 0.0595823973f }, { 7000, -0.0482789353f, 0.0764200836f } } },
  6484. { "hp3", { { 50, 3 }, { 49, 3 } }, 44100, 8.623214, 7.95253188, { { 1500, -0.0325722694f, 0.00703159999f }, { 4000, 0.0183976218f, -0.0372007042f }, { 7000, -0.0126833525f, -0.00160143059f } } },
  6485. { "alt", { { 62, 257 } }, 44100, 17.2485711, 9.99223979, { { 1500, -0.0319156498f, -0.0186850764f }, { 4000, -0.0769012421f, -0.0375530645f }, { 7000, 0.0310976505f, 0.0445244014f } } },
  6486. { "isqrt", { { 62, 65792 } }, 44100, 45.7309307, 27.1224593, { { 1500, -0.04376591f, -0.00845711026f }, { 4000, 0.0351300463f, -0.129557073f }, { 7000, 0.0096148327f, 0.00123740174f } } },
  6487. { "seed2rnd", { { 11, 0 } }, 44100, 16.8228819, 11.5433061, { { 1500, -0.0117614279f, -0.026497297f }, { 4000, 0.00265733898f, -0.07069581f }, { 7000, 0.00576663949f, 0.0565217957f } } },
  6488. { "decinf", { { 6, 10000 } }, 44100, 19.1879226, 11.0487311, { { 1500, -0.0324105881f, -0.0190765262f }, { 4000, -0.0809780285f, -0.0395730771f }, { 7000, 0.034197174f, 0.048585102f } } },
  6489. { "logx", { { 57, 16777216 } }, 44100, 12.3064326, 7.31519289, { { 1500, -0.0438990779f, 0.0096983267f }, { 4000, -0.0175748877f, 0.0313935578f }, { 7000, 0.0639200211f, 0.024419222f } } },
  6490. { "velpos", { { 56, 66304 } }, 44100, 4.9966925, 3.16540662, { { 1500, 0.0083851777f, -0.0165472236f }, { 4000, 0.0630451962f, 0.0156494901f }, { 7000, -0.0293043777f, -0.00182877108f } } },
  6491. { "fs48", { }, 48000, 10.8813888, 6.53592373, { { 1500, -0.0485184453f, -0.0319588967f }, { 4000, 0.0230421089f, -0.0286604818f }, { 7000, -0.0117630213f, -0.017459048f } } },
  6492. { "fs96", { }, 96000, 11.0189683, 6.39821883, { { 1500, -0.0267860368f, -0.0227564126f }, { 4000, 0.0238709711f, -0.0100849615f }, { 7000, -0.0034619756f, 0.0451687202f } } },
  6493. };
  6494. for (const auto& v : variants)
  6495. {
  6496. auto st = blob;
  6497. for (const auto& [i, x] : v.params)
  6498. CHECK (lynx::ogunSetParam (st, i, x));
  6499. const auto y = lynx::ogun::renderReference (st, { { 0, 60, 0.75, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 6144 },
  6500. { 2048, 67, 0.625, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1 } }, (double) v.rate, 8192);
  6501. double el = 0.0, er = 0.0, peak = 0.0;
  6502. for (std::size_t i = 0; i + 1 < y.size(); i += 2)
  6503. el += (double) y[i] * y[i], er += (double) y[i + 1] * y[i + 1], peak = std::max ({ peak, (double) std::abs (y[i]), (double) std::abs (y[i + 1]) });
  6504. bool ok = y.size() == 2 * 8192 && std::abs (el - v.el) <= 1e-5 * v.el && std::abs (er - v.er) <= 1e-5 * v.er;
  6505. for (const auto& smp : v.s)
  6506. ok = ok && std::abs (y[2 * (std::size_t) smp.at] - smp.l) <= 1e-5 * peak && std::abs (y[2 * (std::size_t) smp.at + 1] - smp.r) <= 1e-5 * peak;
  6507. if (! ok)
  6508. std::printf (" Ogun variant %s differs from the model: energy %.9g %.9g (model %.9g %.9g)\n", v.name, el, er, v.el, v.er);
  6509. CHECK (ok);
  6510. }
  6511. }
  6512. }
  6513. // our own Maximus v7 state (layout REA_rodada8 §1.1): 7 globals, 4 × 13 band parameters, 8 envelopes (dx, y, tension, type)
  6514. static std::vector<std::uint8_t> maximusTestState (const std::array<int, 7>& g, const std::array<std::array<int, 13>, 4>& bands,
  6515. const std::array<std::vector<std::array<double, 4>>, 8>& envs, int oversampling)
  6516. {
  6517. std::vector<std::uint8_t> d;
  6518. auto put = [&] (const void* v, std::size_t n) { d.insert (d.end(), (const std::uint8_t*) v, (const std::uint8_t*) v + n); };
  6519. auto i32 = [&] (std::int32_t v) { put (&v, 4); };
  6520. i32 (7);
  6521. for (int copy = 0; copy < 2; ++copy)
  6522. {
  6523. for (auto v : g)
  6524. i32 (v);
  6525. for (const auto& b : bands)
  6526. for (auto v : b)
  6527. i32 (v);
  6528. }
  6529. d.resize (0x1fe, 0);
  6530. std::memcpy (d.data() + 0x1f4, &oversampling, 4);
  6531. for (const auto& e : envs)
  6532. {
  6533. i32 (3), i32 (2), i32 ((std::int32_t) e.size());
  6534. for (const auto& pt : e)
  6535. {
  6536. const double dx = pt[0], y = pt[1];
  6537. const float t = (float) pt[2];
  6538. put (&dx, 8), put (&y, 8), put (&t, 4);
  6539. const std::uint8_t flags[4] { (std::uint8_t) pt[3], 0, 0, 0 };
  6540. put (flags, 4);
  6541. }
  6542. i32 (0), i32 (-1), i32 (-1), i32 (-1), i32 (-1);
  6543. }
  6544. return d;
  6545. }
  6546. // A "Kepler-1" state written from scratch (REA_rodada46 §1.1 layout, version 2): the default panel values
  6547. std::vector<std::uint8_t> keplerTestState()
  6548. {
  6549. const float panel[34] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0.5f, 0.5f, 0, 0, 0, 0.5f, 0.5f };
  6550. std::vector<std::uint8_t> st;
  6551. auto u32 = [&] (std::uint32_t v) { for (int i = 0; i < 4; ++i) st.push_back ((std::uint8_t) (v >> (8 * i))); };
  6552. auto f32 = [&] (float f) { std::uint32_t v; std::memcpy (&v, &f, 4); u32 (v); };
  6553. u32 (0), u32 (0), u32 (0), u32 (9);
  6554. for (char c : std::string ("Kepler-1"))
  6555. st.push_back ((std::uint8_t) c);
  6556. st.push_back (0);
  6557. u32 (2), u32 (34);
  6558. for (auto f : panel)
  6559. f32 (f);
  6560. st.push_back (0);
  6561. f32 (1.0f), f32 (0.5f);
  6562. const auto size = (std::uint32_t) st.size() - 12;
  6563. std::memcpy (st.data() + 4, &size, 4);
  6564. return st;
  6565. }
  6566. std::string keplerDll()
  6567. {
  6568. if (realFlpDir.empty())
  6569. return {};
  6570. return (std::filesystem::path (realFlpDir).parent_path() / "Plugins" / "Fruity" / "Generators" / "Kepler" / "engine_x64.dll").string();
  6571. }
  6572. TEST (kepler_engine)
  6573. {
  6574. const auto st = keplerTestState();
  6575. CHECK (st.size() == 178 && lynx::keplerStateUsable (st));
  6576. CHECK (lynx::keplerPanelOffset (st, 19) == 0x21 + 4 * 19 && lynx::keplerPanelOffset (st, 34) == -1);
  6577. auto broken = st;
  6578. broken[17] = 'X'; // not "Kepler-1"
  6579. CHECK (! lynx::keplerStateUsable (broken) && lynx::keplerPanelOffset (broken, 0) == -1);
  6580. auto v3 = st;
  6581. v3[0x19] = 3; // version 3 needs the gate / noise / oversampling bytes
  6582. CHECK (! lynx::keplerStateUsable (v3));
  6583. const auto dll = keplerDll();
  6584. if (dll.empty() || ! lynx::keplerDllUsable (dll))
  6585. return; // no FL installation (the engine needs the user's own DLL tables)
  6586. // against FL's engine DLL (EXEC, REA_rodada46 §6): three notes, 44.1 kHz, host blocks of 512 — bit-exact
  6587. const std::vector<lynx::kepler::RefNote> notes { { 0, 60, 1.0, 0.0, 0.0, 20000 }, { 8000, 67, 0.6, 0.0, 0.0, 26000 }, { 16000, 55, 0.95, 0.0, 0.0, 30000 } };
  6588. const auto y = lynx::kepler::renderReference (st, dll, notes, 44100.0, 39690);
  6589. CHECK (y.size() == 2 * 39690);
  6590. if (y.size() != 2 * 39690)
  6591. return;
  6592. double el = 0.0, er = 0.0;
  6593. for (std::size_t i = 0; i < y.size(); i += 2)
  6594. el += (double) y[i] * y[i], er += (double) y[i + 1] * y[i + 1];
  6595. std::printf (" Kepler default patch: energy %.9g %.9g (FL's DLL 250.641268)\n", el, er);
  6596. CHECK (std::abs (el - 250.641268) < 1e-6 && std::abs (er - 250.641268) < 1e-6);
  6597. const std::tuple<int, float, float> golden[] { { 5000, 0.0467273332f, 0.0467273332f }, { 12000, -0.119412214f, -0.119412214f },
  6598. { 25000, 0.0855825394f, 0.0855825394f }, { 35000, -3.34166579e-08f, -3.34166579e-08f } };
  6599. for (const auto& [i, l, r] : golden)
  6600. CHECK (y[2 * (std::size_t) i] == l && y[2 * (std::size_t) i + 1] == r);
  6601. // the instrument: FL's wrapper velocity, channel volume as an output gain, idle after the release
  6602. lynx::ChannelDef c;
  6603. c.instrument = lynx::InstrumentKind::kepler;
  6604. c.pluginState = st;
  6605. c.samplePath = dll;
  6606. auto inst = lynx::makeInstrument (lynx::InstrumentKind::kepler);
  6607. inst->configure (c, 120.0);
  6608. inst->prepare (44100.0);
  6609. std::vector<float> l (4096), r (4096);
  6610. inst->noteOn (60, 0.8f);
  6611. double e = 0.0;
  6612. bool finite = true;
  6613. for (int b = 0; b < 8; ++b)
  6614. {
  6615. std::fill (l.begin(), l.end(), 0.0f);
  6616. std::fill (r.begin(), r.end(), 0.0f);
  6617. inst->render (l.data(), r.data(), 4096, 0.5f, 0.5f);
  6618. for (int i = 0; i < 4096; ++i)
  6619. finite = finite && std::isfinite (l[(std::size_t) i]) && std::isfinite (r[(std::size_t) i]), e += (double) l[(std::size_t) i] * l[(std::size_t) i];
  6620. if (b == 3)
  6621. inst->noteOff (60);
  6622. }
  6623. CHECK (finite && e > 1.0);
  6624. for (int b = 0; b < 40; ++b)
  6625. inst->render (l.data(), r.data(), 4096, 0.5f, 0.5f);
  6626. CHECK (inst->idle());
  6627. }
  6628. TEST (kepler_demo_channels)
  6629. {
  6630. // every Kepler channel of FL's demo projects on LYNX's engine against FL's engine DLL (EXEC fingerprints, REA_rodada46 §6;
  6631. // the engine differs from the DLL by −127 dB or less on these, from the DLL library's pow rounding)
  6632. const auto dll = keplerDll();
  6633. if (dll.empty() || ! lynx::keplerDllUsable (dll))
  6634. return;
  6635. struct Sample { int at; float l, r; };
  6636. struct Golden { const char* file; const char* channel; std::size_t stateSize; double el, er; Sample s[4]; };
  6637. const Golden goldens[] {
  6638. { "Demo songs/Edlan & Ella Noël - Song For You.flp", "Pads - Kepler", 181, 2595.34411, 1181.70052, { { 5000, 0.258449465f, 0.284368932f }, { 12000, -0.0648983642f, 0.312173635f }, { 25000, -0.271028787f, 0.103852645f }, { 35000, -0.00873807631f, -0.00636588456f } } },
  6639. { "Demo songs/Purps On The Beat Feat Luclover - Stroll Up.flp", "Kepler", 189, 2.77173241, 1.36643586, { { 5000, 0.00653714081f, 0.00885556825f }, { 12000, 0.0316556357f, 0.0255686305f }, { 25000, -0.00359999924f, -0.0027268643f }, { 35000, 3.38630743e-05f, 3.35237855e-05f } } },
  6640. { "Demo songs/Sid De La Cruz - Secret Agent Rendezvous.flp", "AceBass", 181, 491.893665, 813.858274, { { 5000, 0.00933594909f, 0.0551614426f }, { 12000, 0.11930909f, -0.387893438f }, { 25000, -0.0520403236f, -0.131727993f }, { 35000, 2.78028492e-05f, 2.75182774e-05f } } },
  6641. { "Demo songs/Sid De La Cruz - Secret Agent Rendezvous.flp", "Badious", 181, 19.0406926, 20.1997196, { { 5000, 0.00332317385f, 0.00785329007f }, { 12000, 0.0234184917f, -0.0034834384f }, { 25000, -0.0167671479f, -0.0142839653f }, { 35000, -0.0352748372f, -0.00481338287f } } },
  6642. };
  6643. int checked = 0;
  6644. for (const auto& g : goldens)
  6645. {
  6646. std::ifstream in (std::filesystem::path (realFlpDir) / "Demo projects" / g.file, std::ios::binary);
  6647. const std::vector<std::uint8_t> bytes ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  6648. if (bytes.empty())
  6649. continue;
  6650. const flp::Channel* ch = nullptr;
  6651. const auto project = flp::parseProject (bytes);
  6652. for (const auto& c : project.channels)
  6653. if (c.pluginName == "Kepler" && c.name == g.channel)
  6654. ch = &c;
  6655. CHECK (ch != nullptr);
  6656. if (ch == nullptr)
  6657. continue;
  6658. CHECK (ch->pluginState.size() == g.stateSize && lynx::keplerStateUsable (ch->pluginState));
  6659. const auto y = lynx::kepler::renderReference (ch->pluginState, dll, { { 0, 60, 1.0, 0.0, 0.0, 20000 }, { 8000, 67, 0.6, 0.0, 0.0, 26000 },
  6660. { 16000, 55, 0.95, 0.0, 0.0, 30000 } }, 44100.0, 39690);
  6661. double el = 0.0, er = 0.0, peak = 0.0;
  6662. for (std::size_t i = 0; i + 1 < y.size(); i += 2)
  6663. el += (double) y[i] * y[i], er += (double) y[i + 1] * y[i + 1], peak = std::max ({ peak, (double) std::abs (y[i]), (double) std::abs (y[i + 1]) });
  6664. bool ok = y.size() == 2 * 39690 && std::abs (el - g.el) <= 1e-5 * g.el && std::abs (er - g.er) <= 1e-5 * g.er;
  6665. for (const auto& smp : g.s)
  6666. ok = ok && std::abs (y[2 * (std::size_t) smp.at] - smp.l) <= 1e-5 * peak && std::abs (y[2 * (std::size_t) smp.at + 1] - smp.r) <= 1e-5 * peak;
  6667. if (! ok)
  6668. std::printf (" Kepler %s / %s differs from FL's DLL: energy %.9g %.9g (DLL %.9g %.9g)\n", g.file, g.channel, el, er, g.el, g.er);
  6669. CHECK (ok);
  6670. ++checked;
  6671. }
  6672. std::printf (" Kepler: %d demo channels checked against FL's engine DLL\n", checked);
  6673. CHECK (checked == (int) std::size (goldens));
  6674. }
  6675. TEST (ogun_demo_channels)
  6676. {
  6677. // every Ogun channel of FL's demo projects (with its plugin effects) against the round-37 reference model, which is
  6678. // within −60 dB of FL's DLL on all of them: three notes (C5 1.0 0–20000, G5 0.6 8000–26000, G4 0.95 16000–30000),
  6679. // 39 690 samples at 44.1 kHz, at the state's quality and at the export quality 4. Fingerprint: energy per side and
  6680. // four samples (the engine matches the model within float rounding, −125 dB or better on the whole signal).
  6681. if (realFlpDir.empty())
  6682. return;
  6683. struct Sample { int at; float l, r; };
  6684. struct Golden { const char* file; int ordinal; std::size_t stateSize; bool export4; double el, er; Sample s[4]; };
  6685. const Golden goldens[] {
  6686. { "Demo songs/Astes - Bien Duro.flp", 0, 64728, false, 710.708198, 710.708198, { { 5000, 0.133627325f, 0.133627325f }, { 12000, -0.143534407f, -0.143534407f }, { 25000, 0.079226315f, 0.079226315f }, { 35000, -0.0128487358f, -0.0128487358f } } }, // 3.3.1 Metal Drums: Drum
  6687. { "Demo songs/Astes - Bien Duro.flp", 0, 64728, true, 794.506558, 794.506558, { { 5000, -0.0112881307f, -0.0112881307f }, { 12000, -0.068779245f, -0.068779245f }, { 25000, -0.0289028231f, -0.0289028231f }, { 35000, -0.0161623377f, -0.0161623377f } } }, // 3.3.1 Metal Drums: Drum
  6688. { "Demo songs/Astes - Bien Duro.flp", 1, 4261, false, 297.957631, 297.957631, { { 5000, -0.000330464332f, -0.000330464332f }, { 12000, -0.00156057056f, -0.00156057056f }, { 25000, -9.24126434e-05f, -9.24126434e-05f }, { 35000, 0.0f, 0.0f } } }, // 3.3.1 Metal Drums: Click
  6689. { "Demo songs/Astes - Bien Duro.flp", 1, 4261, true, 189.545711, 189.545711, { { 5000, 0.00102557975f, 0.00102557975f }, { 12000, -0.00522088073f, -0.00522088073f }, { 25000, 5.81103013e-05f, 5.81103013e-05f }, { 35000, 0.0f, 0.0f } } }, // 3.3.1 Metal Drums: Click
  6690. { "Demo songs/Astes - Bien Duro.flp", 2, 133836, false, 125.683557, 125.683557, { { 5000, 0.0176561493f, 0.0176561493f }, { 12000, 0.019205872f, 0.019205872f }, { 25000, 0.0046372693f, 0.0046372693f }, { 35000, -0.00165430119f, -0.00165430119f } } }, // 3.3.2 Tibetan
  6691. { "Demo songs/Astes - Bien Duro.flp", 2, 133836, true, 105.621798, 105.621798, { { 5000, 0.00897848886f, 0.00897848886f }, { 12000, -0.0171215143f, -0.0171215143f }, { 25000, -0.00821319036f, -0.00821319036f }, { 35000, -0.00245537539f, -0.00245537539f } } }, // 3.3.2 Tibetan
  6692. { "Demo songs/Astes - Bien Duro.flp", 3, 97085, false, 2066.75611, 2066.75611, { { 5000, -0.101155393f, -0.101155393f }, { 12000, 0.355391592f, 0.355391592f }, { 25000, 0.00365939317f, 0.00365939317f }, { 35000, -0.0191957876f, -0.0191957876f } } }, // 3.3.3 Chase
  6693. { "Demo songs/Astes - Bien Duro.flp", 3, 97085, true, 1667.28674, 1667.28674, { { 5000, -0.236701503f, -0.236701503f }, { 12000, -0.126374632f, -0.126374632f }, { 25000, 0.0533663221f, 0.0533663221f }, { 35000, -0.0100225089f, -0.0100225089f } } }, // 3.3.3 Chase
  6694. { "Demo songs/Edlan & Ella Noël - Song For You.flp", 0, 819, false, 551.263856, 371.038684, { { 5000, 0.0253486633f, 0.160556272f }, { 12000, 0.194370747f, -0.0359776132f }, { 25000, -0.00528950989f, 0.01478827f }, { 35000, 0.110768802f, -0.0237054806f } } }, // Bellish 11
  6695. { "Demo songs/Edlan & Ella Noël - Song For You.flp", 0, 819, true, 547.662092, 381.048456, { { 5000, 0.0401367024f, 0.0261611789f }, { 12000, -0.157383129f, -0.0282031279f }, { 25000, -0.000249146833f, 0.0388034321f }, { 35000, -0.105665907f, 0.0320193283f } } }, // Bellish 11
  6696. { "Demo songs/LollieVox & Lezina J - I'll Be Your Madonna.flp", 0, 105571, false, 833.288142, 909.880193, { { 5000, 0.0276863724f, 0.214677185f }, { 12000, 0.00827352796f, 0.141611829f }, { 25000, -0.160458148f, 0.0101522766f }, { 35000, -0.0157076102f, 0.00129696913f } } }, // High Chords
  6697. { "Demo songs/LollieVox & Lezina J - I'll Be Your Madonna.flp", 0, 105571, true, 928.749154, 967.940976, { { 5000, -0.0623336285f, -0.0959333256f }, { 12000, 0.0601816922f, -0.0748261437f }, { 25000, -0.0872222036f, -0.101655915f }, { 35000, -0.002591094f, 0.0107459351f } } }, // High Chords
  6698. { "Product demos/Electric Loop - The Ogun Dream.flp", 0, 813, false, 21576.8988, 21576.8988, { { 5000, 0.00724618789f, 0.00724618789f }, { 12000, 0.0337664448f, 0.0337664448f }, { 25000, -1.44279329e-05f, -1.44279329e-05f }, { 35000, 0.0f, 0.0f } } }, // Kick
  6699. { "Product demos/Electric Loop - The Ogun Dream.flp", 0, 813, true, 17857.5027, 17857.5027, { { 5000, -0.0114536202f, -0.0114536202f }, { 12000, -0.00848954543f, -0.00848954543f }, { 25000, 1.20320046e-05f, 1.20320046e-05f }, { 35000, 0.0f, 0.0f } } }, // Kick
  6700. { "Product demos/Electric Loop - The Ogun Dream.flp", 1, 789, false, 172.127165, 170.39981, { { 5000, -0.00470701791f, -0.000373305753f }, { 12000, 0.0417476855f, 0.0339940563f }, { 25000, 0.0204325765f, 0.0191226583f }, { 35000, -0.000425090868f, -0.000144533216f } } }, // Clap
  6701. { "Product demos/Electric Loop - The Ogun Dream.flp", 1, 789, true, 163.557022, 149.810459, { { 5000, 0.00246403809f, 0.0228729937f }, { 12000, 0.0378073864f, 0.0445459485f }, { 25000, -0.0242712852f, -0.0313444398f }, { 35000, -0.00112735468f, -0.00138637482f } } }, // Clap
  6702. { "Product demos/Electric Loop - The Ogun Dream.flp", 2, 635, false, 125.48103, 127.519836, { { 5000, -0.00389297446f, 0.00181007839f }, { 12000, -0.0543250106f, -0.0736973509f }, { 25000, -0.00448145531f, 0.000426211918f }, { 35000, 5.35470353e-05f, 4.34564136e-05f } } }, // High Hat
  6703. { "Product demos/Electric Loop - The Ogun Dream.flp", 2, 635, true, 245.916518, 254.34816, { { 5000, 0.00147765165f, 0.00267027458f }, { 12000, 0.0883170143f, 0.173417449f }, { 25000, -0.00118842872f, 0.000863731664f }, { 35000, -0.000298409053f, -9.04561821e-05f } } }, // High Hat
  6704. { "Product demos/Electric Loop - The Ogun Dream.flp", 3, 45647, false, 271.486026, 271.486026, { { 5000, -4.96093298e-06f, -4.96093298e-06f }, { 12000, 0.000292191253f, 0.000292191253f }, { 25000, -8.18665136e-10f, -8.18665136e-10f }, { 35000, 0.0f, 0.0f } } }, // HiHat
  6705. { "Product demos/Electric Loop - The Ogun Dream.flp", 3, 45647, true, 167.753037, 167.753037, { { 5000, 2.2048649e-05f, 2.2048649e-05f }, { 12000, -1.77328075e-05f, -1.77328075e-05f }, { 25000, -3.00809999e-09f, -3.00809999e-09f }, { 35000, 0.0f, 0.0f } } }, // HiHat
  6706. { "Product demos/Electric Loop - The Ogun Dream.flp", 4, 887, false, 6005.75168, 6293.90961, { { 5000, -0.19636783f, -0.0313744769f }, { 12000, 0.178472087f, 0.601032794f }, { 25000, -0.351912051f, -0.0497151017f }, { 35000, -0.182245821f, -0.181938142f } } }, // Snare
  6707. { "Product demos/Electric Loop - The Ogun Dream.flp", 4, 887, true, 6151.47444, 6049.47136, { { 5000, -0.102814399f, 0.0690701902f }, { 12000, 0.0902677849f, 0.114889771f }, { 25000, -0.173990116f, 0.140671447f }, { 35000, 0.0744562522f, 0.0291433111f } } }, // Snare
  6708. { "Product demos/Electric Loop - The Ogun Dream.flp", 5, 705, false, 6511.3723, 5580.42134, { { 5000, 0.478397369f, 0.536334693f }, { 12000, -0.312448859f, -0.301919997f }, { 25000, 0.260874003f, -0.0129742175f }, { 35000, 0.0223956257f, 0.033103168f } } }, // Swebass 1
  6709. { "Product demos/Electric Loop - The Ogun Dream.flp", 5, 705, true, 6415.0768, 5859.44881, { { 5000, 0.0342692807f, 0.00727743423f }, { 12000, -0.0324966274f, 0.125386745f }, { 25000, -0.0785191655f, -0.25017795f }, { 35000, -0.0524680056f, -0.0384391509f } } }, // Swebass 1
  6710. { "Product demos/Electric Loop - The Ogun Dream.flp", 6, 708, false, 2487.6041, 2190.17262, { { 5000, -0.0770967156f, -0.00940297544f }, { 12000, 0.329836905f, 0.183736563f }, { 25000, 0.0137981772f, -0.0334252715f }, { 35000, 0.0132095823f, 0.0277119074f } } }, // Swebass 2
  6711. { "Product demos/Electric Loop - The Ogun Dream.flp", 6, 708, true, 2519.26975, 2230.77243, { { 5000, -0.204216316f, -0.16732122f }, { 12000, 0.0762225091f, 0.0964485779f }, { 25000, -0.0833523944f, -0.132980049f }, { 35000, -0.015998248f, 0.0112942485f } } }, // Swebass 2
  6712. { "Product demos/Electric Loop - The Ogun Dream.flp", 7, 109827, false, 1326.11782, 1397.71125, { { 5000, 0.0306534693f, 0.026510708f }, { 12000, -0.139238164f, -0.104713492f }, { 25000, 0.106734768f, 0.0295313746f }, { 35000, 0.258899271f, 0.260215104f } } }, // Midnight Lady
  6713. { "Product demos/Electric Loop - The Ogun Dream.flp", 7, 109827, true, 1252.058, 1287.83169, { { 5000, -0.0980920121f, -0.108575724f }, { 12000, 0.131130368f, 0.176118359f }, { 25000, 0.0581845529f, 0.174699515f }, { 35000, -0.17453593f, 0.0978319347f } } }, // Midnight Lady
  6714. { "Product demos/Electric Loop - The Ogun Dream.flp", 8, 34816, false, 10793.0192, 11904.6549, { { 5000, 0.36459741f, -0.0714551434f }, { 12000, 0.565215111f, -0.205066338f }, { 25000, -0.652977228f, -0.432422459f }, { 35000, -0.284279644f, -0.122116163f } } }, // Supersaw
  6715. { "Product demos/Electric Loop - The Ogun Dream.flp", 8, 34816, true, 10132.5107, 11590.7617, { { 5000, 0.192168862f, 0.0883051828f }, { 12000, -0.590734482f, 0.512839496f }, { 25000, 0.682625771f, 0.287306368f }, { 35000, -0.00662239315f, 0.700808227f } } }, // Supersaw
  6716. { "Product demos/Electric Loop - The Ogun Dream.flp", 9, 94266, false, 826.69243, 1157.08939, { { 5000, 0.0348474756f, -0.168766886f }, { 12000, -0.0719366521f, 0.288826376f }, { 25000, 0.181558818f, 0.0424098521f }, { 35000, -0.321783781f, -0.0548994206f } } }, // Airguitar 3
  6717. { "Product demos/Electric Loop - The Ogun Dream.flp", 9, 94266, true, 830.517691, 772.62552, { { 5000, -0.208309069f, 0.152180359f }, { 12000, -0.264171928f, 0.163982511f }, { 25000, 0.0313629843f, -0.187507361f }, { 35000, 0.133838147f, 0.0704783946f } } }, // Airguitar 3
  6718. { "Product demos/Electric Loop - The Ogun Dream.flp", 10, 1004, false, 12678.7464, 11831.2032, { { 5000, 0.192205578f, 0.613839507f }, { 12000, 0.269521117f, -0.585603476f }, { 25000, 0.0944993123f, 0.0806781948f }, { 35000, -0.16715017f, 0.412193805f } } }, // Trumpet
  6719. { "Product demos/Electric Loop - The Ogun Dream.flp", 10, 1004, true, 12261.8266, 9962.482, { { 5000, 0.422391087f, -0.251674503f }, { 12000, -0.46900028f, -0.57652849f }, { 25000, -0.535878778f, 0.115671799f }, { 35000, -0.545713186f, 0.0383624472f } } }, // Trumpet
  6720. { "Product demos/Electric Loop - The Ogun Dream.flp", 11, 30605, false, 1358.26232, 1520.29691, { { 5000, -0.0350573957f, 0.0372484438f }, { 12000, 0.0963054374f, -0.130206674f }, { 25000, 0.0404771306f, -0.270439237f }, { 35000, -0.0870027244f, 0.0245792065f } } }, // Silverswirll
  6721. { "Product demos/Electric Loop - The Ogun Dream.flp", 11, 30605, true, 964.637209, 1040.25756, { { 5000, 0.111636952f, -0.00114471605f }, { 12000, 0.0483313873f, 0.0637735277f }, { 25000, -0.152803347f, 0.101604536f }, { 35000, 0.0288163591f, 0.0194431469f } } }, // Silverswirll
  6722. { "Product demos/Electric Loop - The Ogun Dream.flp", 12, 34708, false, 21463.1948, 22013.1021, { { 5000, -0.00810255855f, -0.0122786947f }, { 12000, -0.163549975f, -0.203571558f }, { 25000, 0.419101298f, -1.1141516f }, { 35000, 0.498232335f, -0.394363374f } } }, // Padsaw
  6723. { "Product demos/Electric Loop - The Ogun Dream.flp", 12, 34708, true, 22903.9209, 21556.3509, { { 5000, -0.00977799948f, -0.0114432834f }, { 12000, -0.0759382695f, 0.077038914f }, { 25000, -0.556497335f, -1.22787583f }, { 35000, -1.31076968f, -1.73392022f } } }, // Padsaw
  6724. { "Product demos/Electric Loop - The Ogun Dream.flp", 13, 6395, false, 3516.18148, 3565.45486, { { 5000, -0.0564712696f, -0.262329876f }, { 12000, 0.113444217f, 0.168150783f }, { 25000, -0.45024398f, -0.694699228f }, { 35000, 0.151807249f, -0.00405737339f } } }, // Turbular Bells 2
  6725. { "Product demos/Electric Loop - The Ogun Dream.flp", 13, 6395, true, 3571.34372, 3626.15163, { { 5000, -0.0878480822f, -0.275067806f }, { 12000, 0.230907321f, 0.28320539f }, { 25000, -0.470044613f, -0.701287091f }, { 35000, 0.195627496f, 0.0175700653f } } }, // Turbular Bells 2
  6726. };
  6727. std::map<std::string, std::vector<std::vector<std::uint8_t>>> states;
  6728. int checked = 0;
  6729. for (const auto& g : goldens)
  6730. {
  6731. if (! states.contains (g.file))
  6732. {
  6733. std::ifstream in (std::filesystem::path (realFlpDir) / "Demo projects" / g.file, std::ios::binary);
  6734. const std::vector<std::uint8_t> bytes ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  6735. auto& list = states[g.file];
  6736. if (! bytes.empty())
  6737. for (const auto& c : flp::parseProject (bytes).channels)
  6738. if (c.pluginName == "Ogun")
  6739. list.push_back (c.pluginState);
  6740. }
  6741. const auto& list = states[g.file];
  6742. if (list.empty())
  6743. continue; // not this installation
  6744. CHECK ((int) list.size() > g.ordinal);
  6745. if ((int) list.size() <= g.ordinal)
  6746. continue;
  6747. const auto& st = list[(std::size_t) g.ordinal];
  6748. CHECK (st.size() == g.stateSize);
  6749. lynx::ogun::RefOptions opt;
  6750. opt.quality = g.export4 ? 4 : -1;
  6751. const auto y = lynx::ogun::renderReference (st, { { 0, 60, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 20000 },
  6752. { 8000, 67, 0.6, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 26000 },
  6753. { 16000, 55, 0.95, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 30000 } }, 44100.0, 39690, opt);
  6754. double el = 0.0, er = 0.0, peak = 0.0;
  6755. for (std::size_t i = 0; i + 1 < y.size(); i += 2)
  6756. el += (double) y[i] * y[i], er += (double) y[i + 1] * y[i + 1], peak = std::max ({ peak, (double) std::abs (y[i]), (double) std::abs (y[i + 1]) });
  6757. bool ok = y.size() == 2 * 39690 && std::abs (el - g.el) <= 1e-5 * g.el && std::abs (er - g.er) <= 1e-5 * g.er;
  6758. for (const auto& smp : g.s)
  6759. ok = ok && std::abs (y[2 * (std::size_t) smp.at] - smp.l) <= 2e-5 * peak && std::abs (y[2 * (std::size_t) smp.at + 1] - smp.r) <= 2e-5 * peak;
  6760. if (! ok)
  6761. std::printf (" Ogun %s #%d (q%s) differs from the model: energy %.9g %.9g (model %.9g %.9g)\n", g.file, g.ordinal,
  6762. g.export4 ? "4" : "-state", el, er, g.el, g.er);
  6763. CHECK (ok);
  6764. ++checked;
  6765. }
  6766. std::printf (" Ogun: %d demo renders checked against the reference model\n", checked);
  6767. CHECK (checked == (int) std::size (goldens));
  6768. }
  6769. TEST (harmless_rack)
  6770. {
  6771. // REA_rodada36: Harmless's effects rack against our reference model (rack.py / maxmodel.py, which match the
  6772. // installation's Harmless_x64.dll and SG_x64.dll), 44.1 kHz, host blocks of 512
  6773. std::vector<float> inL (8192), inR (8192);
  6774. for (int i = 0; i < 4096; ++i)
  6775. {
  6776. 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));
  6777. inR[(std::size_t) i] = (float) (1.2 * std::sin (2.0 * 3.141592653589793 * 660.0 * i / 44100.0));
  6778. }
  6779. auto run = [&] (const std::array<int, 100>& p, int compType, std::shared_ptr<const lynx::hlfx::MaximusPreset> comp, int total, int voicesUntil) {
  6780. lynx::hlfx::Rack rack;
  6781. std::array<int, 7> t {};
  6782. t[3] = compType;
  6783. rack.prepare (p, t, 44100.0, 120.0, std::move (comp));
  6784. std::vector<float> l (inL.begin(), inL.begin() + total), r (inR.begin(), inR.begin() + total);
  6785. for (int s = 0; s < total; s += 512)
  6786. rack.process (l.data() + s, r.data() + s, std::min (512, total - s), s < voicesUntil);
  6787. return std::make_pair (l, r);
  6788. };
  6789. {
  6790. // chorus type 3 (mix 400), ping-pong delay type 2 (vol 600, feedback 500, 1/4 beat), reverb type 4 (vol 700)
  6791. std::array<int, 100> p {};
  6792. p[90] = 3, p[91] = 400, p[92] = 2, p[93] = 600, p[94] = 500, p[95] = 48, p[96] = 4, p[97] = 700;
  6793. const auto [l, r] = run (p, 0, nullptr, 8192, 4096);
  6794. const std::tuple<int, float, float> golden[] { { 0, 0.0f, 0.0f }, { 500, -0.25248247f, 0.15141529f }, { 3000, -0.65128994f, -0.64854866f },
  6795. { 5000, -0.54308629f, -0.36827448f }, { 6000, -0.98378551f, -0.72790027f },
  6796. { 8191, 0.50599128f, -0.43637198f } };
  6797. for (const auto& [i, gl, gr] : golden)
  6798. CHECK (std::abs (l[(std::size_t) i] - gl) < 2e-6f && std::abs (r[(std::size_t) i] - gr) < 2e-6f);
  6799. }
  6800. {
  6801. // the delay alone: an impulse comes back after round(time·fs·0.3125/bpm) samples × (11^0.6 − 1)/10, then × feedback
  6802. std::array<int, 100> p {};
  6803. p[92] = 1, p[93] = 600, p[94] = 500, p[95] = 48;
  6804. lynx::hlfx::Rack rack;
  6805. rack.prepare (p, {}, 44100.0, 120.0, nullptr);
  6806. std::vector<float> l (16384), r (16384);
  6807. l[0] = 1.0f;
  6808. for (int s = 0; s < 16384; s += 512)
  6809. rack.process (l.data() + s, r.data() + s, 512, s == 0);
  6810. const auto D = 5512; // 48·44100·0.3125/120 = 5512.5 → 5512 (round half to even)
  6811. const auto vol = (float) ((std::exp ((double) (600 * 0.001f) * (double) (float) std::log (11.0)) - 1.0) * (double) 0.1f);
  6812. CHECK (std::abs (l[(std::size_t) D] - vol) < 1e-7f && std::abs (l[(std::size_t) D - 1]) < 1e-12f);
  6813. // the feedback ramps from 0.5 toward 0.5: the second echo is vol·0.5
  6814. CHECK (std::abs (l[(std::size_t) (2 * D)] - vol * 0.5f) < 1e-7f && std::abs (r[(std::size_t) D]) < 1e-12f);
  6815. }
  6816. // the compressor: Maximus states of our own (no preset data), checked against SG_x64.dll by REA round 36
  6817. using Env = std::vector<std::array<double, 4>>;
  6818. const Env def { { 0.0, 0.0, 0.0, 0 }, { 0.5, 0.5, 0.0, 0 }, { 0.5, 0.5, 0.0, 0 } };
  6819. 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,
  6820. int sus = 2882) { return std::array<int, 13> { mode, pre, post, sep, sat, ceil, att, rel2, 2, 5000, 3, sus, 0 }; };
  6821. {
  6822. // master brickwall at −0.22 dB only (bands off / compression off)
  6823. const auto st = maximusTestState ({ 19800, 1, 48065, 1, 1115, 1000, -1 }, { band (3), band (1), band (3), band (0) },
  6824. { def, def, def, def, def, def, def, def }, 0);
  6825. const auto preset = lynx::hlfx::makeMaximusPreset (st);
  6826. CHECK (preset != nullptr);
  6827. std::array<int, 100> p {};
  6828. p[98] = 1000;
  6829. const auto [l, r] = run (p, 1, preset, 4096, 4096);
  6830. // SG_x64.dll's own output (EXEC, REA_rodada40: bit-identical to the port)
  6831. const std::tuple<int, float, float> golden[] { { 100, 0.024997942f, 0.88166064f }, { 1000, 0.56971401f, -0.62808102f },
  6832. { 2047, -0.27541628f, 0.709135f }, { 3000, 0.32431623f, -0.37985197f },
  6833. { 4095, -0.12743522f, -0.15237485f } };
  6834. for (const auto& [i, gl, gr] : golden)
  6835. CHECK (std::abs (l[(std::size_t) i] - gl) < 2e-6f && std::abs (r[(std::size_t) i] - gr) < 2e-6f);
  6836. float peak = 0.0f;
  6837. for (int i = 2048; i < 4096; ++i)
  6838. peak = std::max ({ peak, std::abs (l[(std::size_t) i]), std::abs (r[(std::size_t) i]) });
  6839. CHECK (peak < 0.9751f);
  6840. }
  6841. {
  6842. // 24 dB crossovers, ×2 oversampling, low cut, stereo separation, saturation A, a knee with tension (type 7) and
  6843. // exponential tensions (type 0), release 2 on the master, band mix 600
  6844. const Env knee { { 0.0, 0.0, 0.0, 0 }, { 0.35, 0.35, 0.0, 0 }, { 0.65, 0.6, 0.36, 7 } };
  6845. const Env t0 { { 0.0, 0.0, 0.0, 0 }, { 0.5, 0.5, 0.14, 0 }, { 0.5, 0.5, 0.0, 0 } };
  6846. const Env m0 { { 0.0, 0.0, 0.0, 0 }, { 0.5, 0.5, 0.0, 0 }, { 0.5, 0.6, 0.085, 0 } };
  6847. const auto st = maximusTestState ({ 19800, 1, 48065, 1, 891, 600, 32768 },
  6848. { band (1, 1264, 1296, 500, -500, 1200), band (0, 1340, 1000, -348, 0, 1000, 1115, 0, 1570),
  6849. band (0, 1364, 1152, 0, 0, 1000, 1115, 0, 1186), band (0, 1000, 1000, 0, -196, 1000, 1115, 4464, 1538) },
  6850. { def, def, knee, def, t0, def, m0, def }, 1);
  6851. const auto preset = lynx::hlfx::makeMaximusPreset (st);
  6852. CHECK (preset != nullptr);
  6853. std::array<int, 100> p {};
  6854. p[98] = 600;
  6855. const auto [l, r] = run (p, 2, preset, 4096, 4096);
  6856. // SG_x64.dll's own output (EXEC, REA_rodada40; the port is within −142 dB of it)
  6857. const std::tuple<int, float, float> golden[] { { 100, 0.0f, 0.0f }, { 1000, -0.46856543f, -0.63262129f },
  6858. { 2047, 0.20268451f, 0.54145539f }, { 3000, -0.25613472f, -0.49985155f },
  6859. { 4095, 0.10172445f, 0.050564945f } };
  6860. for (const auto& [i, gl, gr] : golden)
  6861. CHECK (std::abs (l[(std::size_t) i] - gl) < 2e-6f && std::abs (r[(std::size_t) i] - gr) < 2e-6f);
  6862. }
  6863. {
  6864. // an .fst wrapper around a state is found; unsupported states are rejected
  6865. const auto st = maximusTestState ({ 19800, 1, 48065, 1, 1115, 1000, -1 }, { band (3), band (1), band (3), band (0) },
  6866. { def, def, def, def, def, def, def, def }, 0);
  6867. std::vector<std::uint8_t> fst { 'F', 'L', 'h', 'd', 6, 0, 0, 0, 0, 0, 1, 0, 0x60, 0, 'F', 'L', 'd', 't' };
  6868. std::vector<std::uint8_t> body { 0xC9, 8, 'M', 'a', 'x', 'i', 'm', 'u', 's', 0, 0xD5 };
  6869. for (auto n = st.size(); ; n >>= 7)
  6870. {
  6871. body.push_back ((std::uint8_t) ((n & 0x7f) | (n >= 0x80 ? 0x80 : 0)));
  6872. if (n < 0x80)
  6873. break;
  6874. }
  6875. body.insert (body.end(), st.begin(), st.end());
  6876. const auto len = (std::uint32_t) body.size();
  6877. for (int k = 0; k < 4; ++k)
  6878. fst.push_back ((std::uint8_t) (len >> (8 * k)));
  6879. fst.insert (fst.end(), body.begin(), body.end());
  6880. const auto found = lynx::hlfx::maximusStateFromFst (fst);
  6881. CHECK (found && *found == st);
  6882. auto rms = st;
  6883. rms[4 + 4 * (7 + 13 * 3 + 12)] = 1; // RMS detector on the master (decoded in REA_rodada40)
  6884. CHECK (lynx::hlfx::makeMaximusPreset (rms) != nullptr);
  6885. auto masterMid = st;
  6886. masterMid[0x1fc] = 1; // "Master Mid mode": not decoded
  6887. CHECK (lynx::hlfx::makeMaximusPreset (masterMid) == nullptr);
  6888. }
  6889. }
  6890. TEST (maximus_engine)
  6891. {
  6892. // REA_rodada40: the engine on its own (MaximusProcessor), states of our own against the installation's DLLs
  6893. // (goldens = the DLL's output for the same input, EXEC), and the containers of the mixer effect and Vocodex
  6894. std::vector<float> inL (4096), inR (4096);
  6895. for (int i = 0; i < 4096; ++i)
  6896. {
  6897. 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));
  6898. inR[(std::size_t) i] = (float) (1.2 * std::sin (2.0 * 3.141592653589793 * 660.0 * i / 44100.0));
  6899. }
  6900. auto run = [&] (std::shared_ptr<const lynx::hlfx::MaximusPreset> preset, int mix) {
  6901. lynx::hlfx::MaximusProcessor m;
  6902. m.prepare (std::move (preset), 44100.0, mix);
  6903. std::vector<float> l (inL), r (inR);
  6904. for (int s = 0; s < 4096; s += 512)
  6905. m.process (l.data() + s, r.data() + s, 512);
  6906. return std::make_pair (l, r);
  6907. };
  6908. using Env = std::vector<std::array<double, 4>>;
  6909. const Env def { { 0.0, 0.0, 0.0, 0 }, { 0.5, 0.5, 0.0, 0 }, { 0.5, 0.5, 0.0, 0 } };
  6910. const Env knee { { 0.0, 0.0, 0.0, 0 }, { 0.35, 0.35, 0.0, 0 }, { 0.65, 0.6, 0.36, 7 } };
  6911. const Env t0 { { 0.0, 0.0, 0.0, 0 }, { 0.5, 0.5, 0.14, 0 }, { 0.5, 0.5, 0.0, 0 } };
  6912. const Env m0 { { 0.0, 0.0, 0.0, 0 }, { 0.5, 0.5, 0.0, 0 }, { 0.5, 0.6, 0.085, 0 } };
  6913. 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,
  6914. int sus = 2882, int rms = 0) { return std::array<int, 13> { mode, pre, post, sep, sat, ceil, att, rel2, 2, 5000, 3, sus, rms }; };
  6915. auto check = [] (const std::pair<std::vector<float>, std::vector<float>>& out, const std::vector<std::tuple<int, float, float>>& golden) {
  6916. for (const auto& [i, gl, gr] : golden)
  6917. CHECK (std::abs (out.first[(std::size_t) i] - gl) < 2e-6f && std::abs (out.second[(std::size_t) i] - gr) < 2e-6f);
  6918. };
  6919. // RMS detectors, saturation mode B, a 5 Hz low cut, 12 dB high split (SG_x64.dll: port within −152 dB)
  6920. auto st3 = maximusTestState ({ 19800, 1, 48065, 0, 1115, 1000, 0 },
  6921. { band (0, 1500, 1000, 0, 400, 900, 1115, 0, 2882, 1), band (0, 1340, 1000, 0, 0, 1000, 1115, 0, 1570, 1),
  6922. band (1, 1000, 1200, 0, 1000, 1000), band (0, 1000, 1000, 0, 250, 1000, 1115, 4464, 2882, 1) },
  6923. { def, def, knee, def, t0, def, m0, def }, 0);
  6924. const auto p3 = lynx::hlfx::makeMaximusPreset (st3);
  6925. CHECK (p3 != nullptr);
  6926. check (run (p3, 1000), { { 100, 0.0f, 0.0f }, { 1000, 0.87061065f, 0.64004499f }, { 2047, -0.97266865f, 0.60940075f },
  6927. { 3000, 0.96658099f, 0.9250561f }, { 4095, 0.99094611f, -0.964059f } });
  6928. // the same with solo on (UI byte 0x1EF) and the low band selected (0x1E0): bit-identical to SG_x64.dll
  6929. auto solo = st3;
  6930. solo[0x1ef] = 1;
  6931. std::memset (solo.data() + 0x1e0, 0, 4);
  6932. check (run (lynx::hlfx::makeMaximusPreset (solo), 1000),
  6933. { { 100, 3.2922967e-06f, 0.00036916698f }, { 1000, 0.15653539f, -0.047913823f }, { 2047, -0.17336531f, 0.019099623f },
  6934. { 3000, 0.17185682f, -0.017173048f }, { 4095, 0.16714551f, 0.019473195f } });
  6935. // the legacy linear-phase FIR band split (UI byte 0x1FD; SG_x64.dll: port within −148 dB)
  6936. auto fir = st3;
  6937. fir[0x1fd] = 1;
  6938. check (run (lynx::hlfx::makeMaximusPreset (fir), 1000),
  6939. { { 100, 0.0f, 0.0f }, { 1000, 0.97986746f, 0.18555209f }, { 2047, -0.98930448f, -0.95970845f },
  6940. { 3000, 0.98856646f, -0.44592777f }, { 4095, 0.99069679f, 0.94382554f } });
  6941. // Soundgoodizer_x64.dll's own build with a v4 file (its presets' layout): a copy of the round-36 state without
  6942. // oversampling, through a byte-identical copy of the installation's DLL with this file as its preset (EXEC)
  6943. const auto st2 = maximusTestState ({ 19800, 1, 48065, 1, 891, 600, 32768 },
  6944. { band (1, 1264, 1296, 500, -500, 1200), band (0, 1340, 1000, -348, 0, 1000, 1115, 0, 1570),
  6945. band (0, 1364, 1152, 0, 0, 1000, 1115, 0, 1186), band (0, 1000, 1000, 0, -196, 1000, 1115, 4464, 1538) },
  6946. { def, def, knee, def, t0, def, m0, def }, 0);
  6947. std::vector<std::uint8_t> v4 { 4, 0, 0, 0 };
  6948. v4.insert (v4.end(), st2.begin() + 4, st2.begin() + 0x1f5);
  6949. v4.insert (v4.end(), st2.begin() + 0x1fe, st2.end());
  6950. const auto p4 = lynx::hlfx::makeMaximusPreset (v4, lynx::hlfx::MaximusBuild::soundgoodizer);
  6951. CHECK (p4 != nullptr);
  6952. check (run (p4, 600), { { 100, 0.0f, 0.0f }, { 1000, -0.60926896f, -0.6652832f }, { 2047, 0.40872875f, 0.36375371f },
  6953. { 3000, -0.41941205f, -0.61312866f }, { 4095, -0.12878418f, 0.27944946f } });
  6954. CHECK (lynx::hlfx::makeMaximusPreset (st2, lynx::hlfx::MaximusBuild::soundgoodizer) != nullptr); // v7: also read by that build
  6955. // the mixer effect's container and the effect itself
  6956. lynx::maximusfx::Blob blob;
  6957. blob.build = lynx::hlfx::MaximusBuild::soundgoodizer;
  6958. blob.mix = 600;
  6959. blob.state = v4;
  6960. const auto packed = lynx::maximusfx::pack (blob);
  6961. const auto back = lynx::maximusfx::unpack (packed);
  6962. CHECK (back && back->build == blob.build && back->mix == 600 && back->state == v4);
  6963. auto slot = lynx::makeEffectSlot (lynx::EffectKind::maximus);
  6964. slot.state = packed;
  6965. auto fx = lynx::makeEffect (slot);
  6966. fx->prepare (44100.0);
  6967. {
  6968. std::vector<float> l (inL), r (inR);
  6969. for (int s = 0; s < 4096; s += 1024) // longer host blocks are split into the engine's 512-frame calls
  6970. fx->process (l.data() + s, r.data() + s, 1024, slot.params, 120.0);
  6971. const auto ref = run (p4, 600);
  6972. CHECK (l == ref.first && r == ref.second);
  6973. }
  6974. const std::vector<std::uint8_t> sgState { 3, 0, 0, 0, 2, 0, 0, 0, 0x78, 2, 0, 0 };
  6975. const auto sg = lynx::maximusfx::parseSoundgoodizer (sgState);
  6976. CHECK (sg && sg->preset == 2 && sg->amount == 632 && std::string (lynx::maximusfx::soundgoodizerPresetFile (2)) == "c.dat");
  6977. CHECK (lynx::soundgoodizerPresetPath (sgState) == "Plugins\\Fruity\\Effects\\Soundgoodizer\\Data\\Presets\\c.dat");
  6978. CHECK (lynx::soundgoodizerExact (sgState, v4).has_value() && ! lynx::soundgoodizerExact (sgState, {}).has_value());
  6979. // Vocodex's appended installation data survives a round trip and leaves FL's state untouched
  6980. const std::vector<std::uint8_t> flState { 8, 0, 0, 0, 1, 2, 3 };
  6981. lynx::vocodex::InstallData data;
  6982. data.sgDat = st2;
  6983. data.carrierState = { 9, 9, 9 };
  6984. const auto joined = lynx::vocodex::appendInstallData (flState, data);
  6985. const auto [raw, files] = lynx::vocodex::splitInstallData (joined);
  6986. CHECK (raw == flState && files.sgDat == st2 && files.carrierState == data.carrierState);
  6987. CHECK (lynx::vocodex::splitInstallData (flState).first == flState);
  6988. }
  6989. // ---- Sytrus (REA_rodada31) -------------------------------------------------------------------------------------------
  6990. // A Sytrus state built from scratch (version 25 layout, our own values — no FL preset data), zlib "stored" blocks.
  6991. namespace
  6992. {
  6993. struct SytrusTestPatch
  6994. {
  6995. std::vector<std::int32_t> main = std::vector<std::int32_t> (240, 0); // 962-byte main block as ints (+ mute bytes)
  6996. struct Op
  6997. {
  6998. int p[10] { 0, 256, 0, 0, 0, 0, 0, 0, 0, 0 };
  6999. int ratio = 20000, offset = 0, noise = 0;
  7000. std::vector<float> amps { 1.0f };
  7001. std::uint8_t flags[8] {};
  7002. int env1[3] { -1, -1, -1 }; // volume envelope: on (≠ −1 → on), decay point, sustain point
  7003. std::vector<std::pair<double, double>> env1pts;
  7004. } ops[6];
  7005. struct Filt
  7006. {
  7007. int p[10] { 0, 0, 128, 0, 128, 0, 0, 128, 128, 0 };
  7008. int type = 3;
  7009. } filts[3];
  7010. std::array<std::array<std::uint8_t, 23>, 3> delays {};
  7011. std::array<std::int32_t, 9> reverb { 19, 221, 0, 50, 80, 30, 221, 2, 0 };
  7012. bool reverbOn = false;
  7013. int eqmode = 0;
  7014. SytrusTestPatch()
  7015. {
  7016. main[0] = 128, main[1] = 128;
  7017. for (int i = 0; i < 8; ++i)
  7018. main[(std::size_t) (165 + i)] = (i % 4 == 2) ? 0 : 128;
  7019. main[173] = 1, main[175] = 128, main[188] = 128, main[189] = -1, main[190] = main[191] = 256;
  7020. }
  7021. void cell (int layer, int row, int col, int v) { main[(std::size_t) (3 + layer * 81 + row * 9 + col)] = v; }
  7022. std::vector<std::uint8_t> blob() const
  7023. {
  7024. std::vector<std::uint8_t> b;
  7025. 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))); };
  7026. auto f32 = [&] (float v) { std::int32_t x; std::memcpy (&x, &v, 4); i32 (x); };
  7027. 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))); };
  7028. // point lists: kind 1 envelope, 2 LFO, 3 map / shaper curve; format version 3
  7029. auto env = [&] (int kind, const std::vector<std::pair<double, double>>& pts, int on, int decay, int sus) {
  7030. i32 (kind), i32 (3), i32 ((std::int32_t) pts.size());
  7031. for (const auto& [dt, y] : pts)
  7032. f64 (dt), f64 (y), f32 (0.0f), i32 (0);
  7033. i32 (0), i32 (on), i32 (decay), i32 (-1), i32 (sus);
  7034. };
  7035. for (int i = 0; i < 240; ++i)
  7036. if (4 * i + 4 <= 0x320)
  7037. i32 (main[(std::size_t) i]);
  7038. b.resize (962, 0); // mute bytes: none muted
  7039. i32 (0); // global declick amount
  7040. b.push_back (0), b.push_back (0), b.push_back (0); // OSC grouping, DC stage, GIBBS OFF
  7041. for (int k = 0; k < 9; ++k)
  7042. b.push_back (k == 7 ? 1 : 0); // flag group (release multiplier on, as Default.fst)
  7043. for (const auto& d : delays)
  7044. b.insert (b.end(), d.begin(), d.end());
  7045. for (auto v : reverb)
  7046. i32 (v);
  7047. b.push_back (reverbOn ? 1 : 0), b.push_back (0);
  7048. i32 (eqmode);
  7049. for (int k = 0; k < 3; ++k)
  7050. i32 (0), i32 (30000), i32 (20000), i32 (k);
  7051. b.push_back (0); // no info text
  7052. for (int u = 0; u < 10; ++u)
  7053. {
  7054. const int narts = u < 6 ? 6 : (u < 9 ? 8 : 2);
  7055. for (int j = 0; j < 10; ++j)
  7056. i32 (u < 6 ? ops[u].p[j] : (u < 9 ? filts[u - 6].p[j] : 0));
  7057. if (u < 6)
  7058. {
  7059. const auto& o = ops[u];
  7060. const auto at = b.size();
  7061. b.resize (at + 0x828, 0);
  7062. auto put = [&] (std::size_t off, const void* src, std::size_t n) { std::memcpy (b.data() + at + off, src, n); };
  7063. put (0, &o.ratio, 4), put (4, &o.offset, 4), put (8, &o.noise, 4);
  7064. put (0xc, o.amps.data(), 4 * o.amps.size());
  7065. const std::int32_t shape[5] { 0, 0, 0, 0, 128 };
  7066. put (0x80c, shape, sizeof shape);
  7067. put (0x820, o.flags, 8);
  7068. }
  7069. else if (u < 9)
  7070. {
  7071. const auto at = b.size();
  7072. b.resize (at + 0x30, 0);
  7073. std::memcpy (b.data() + at + 0x2c, &filts[u - 6].type, 4);
  7074. env (3, { { 0.0, 0.0 }, { 1.0, 1.0 } }, 0, -1, -1);
  7075. b.push_back (0);
  7076. }
  7077. for (int k = 0; k < narts; ++k)
  7078. {
  7079. const bool add = k == 0 || k == 3 || (u >= 6 && u <= 8 && (k == 2 || k == 3)) || (u < 6 && k == 4);
  7080. const double neutral = add ? 0.5 : 1.0;
  7081. i32 (3), i32 (0), f32 (1.0f), f32 (1.0f);
  7082. if (u < 6 && k == 1 && ops[u].env1[0] != -1)
  7083. env (1, ops[u].env1pts, -1, ops[u].env1[1], ops[u].env1[2]);
  7084. else
  7085. env (1, { { 0.0, 0.0 }, { 1.0, 1.0 } }, 0, -1, -1);
  7086. i32 (128), i32 (128), i32 (0), i32 (128);
  7087. env (2, { { 0.0, 1.0 }, { 1.0, 1.0 } }, 0, -1, -1);
  7088. i32 (40000), i32 (0), i32 (0), i32 (0), i32 (0);
  7089. for (int m = 0; m < 6; ++m)
  7090. env (3, { { 0.0, neutral }, { 1.0, neutral } }, 0, -1, -1);
  7091. }
  7092. }
  7093. b.push_back (0), b.push_back (0);
  7094. // zlib with stored blocks
  7095. std::vector<std::uint8_t> z { 0x78, 0x01 };
  7096. for (std::size_t at = 0; at < b.size(); at += 65535)
  7097. {
  7098. const auto n = std::min<std::size_t> (65535, b.size() - at);
  7099. z.push_back (at + n >= b.size() ? 1 : 0);
  7100. z.push_back ((std::uint8_t) n), z.push_back ((std::uint8_t) (n >> 8));
  7101. z.push_back ((std::uint8_t) ~n), z.push_back ((std::uint8_t) (~n >> 8));
  7102. z.insert (z.end(), b.begin() + (std::ptrdiff_t) at, b.begin() + (std::ptrdiff_t) (at + n));
  7103. }
  7104. std::uint32_t a = 1, c = 0;
  7105. for (auto x : b)
  7106. a = (a + x) % 65521, c = (c + a) % 65521;
  7107. for (int k = 3; k >= 0; --k)
  7108. z.push_back ((std::uint8_t) (((c << 16) | a) >> (8 * k)));
  7109. std::vector<std::uint8_t> out { 25, 0, 0, 0 };
  7110. out.insert (out.end(), z.begin(), z.end());
  7111. return out;
  7112. }
  7113. };
  7114. // renders like FL's Gen_Render calls: notes start/release at the block that contains them
  7115. std::pair<std::vector<float>, std::vector<float>> sytrusRender (const std::vector<std::uint8_t>& blob, bool renderMode, int n,
  7116. std::vector<std::array<int, 3>> notes, double fs = 44100.0)
  7117. {
  7118. lynx::sytrus::Engine e;
  7119. e.setTempo (120.0);
  7120. e.prepare (fs, renderMode, 512);
  7121. e.setPatch (lynx::sytrus::parsePatch (blob));
  7122. std::vector<float> l ((std::size_t) n), r ((std::size_t) n);
  7123. for (int n0 = 0; n0 < n; n0 += 512)
  7124. {
  7125. for (std::size_t k = 0; k < notes.size(); ++k)
  7126. {
  7127. if (notes[k][1] >= n0 && notes[k][1] < n0 + 512)
  7128. {
  7129. lynx::sytrus::NoteParams p;
  7130. p.key = (float) notes[k][0];
  7131. p.id = (std::int64_t) k + 1;
  7132. e.noteOn (p);
  7133. }
  7134. if (notes[k][2] >= n0 && notes[k][2] < n0 + 512)
  7135. e.release ((std::int64_t) k + 1);
  7136. }
  7137. e.render (l.data() + n0, r.data() + n0, std::min (512, n - n0), 1.0f, 0.0f);
  7138. }
  7139. return { l, r };
  7140. }
  7141. } // namespace
  7142. TEST (sytrus_engine_sine)
  7143. {
  7144. // one sine operator, ratio 1, OUT 256, no envelopes: C5 = 523.2511 Hz at 0.7071 (centre of the pan law, §6.1)
  7145. SytrusTestPatch t;
  7146. t.cell (0, 0, 8, 256);
  7147. const auto blob = t.blob();
  7148. CHECK (lynx::sytrus::stateUsable (blob));
  7149. CHECK (lynx::sytrus::parsePatch (blob) != nullptr);
  7150. auto broken = blob;
  7151. broken.resize (broken.size() / 2);
  7152. CHECK (! lynx::sytrus::stateUsable (broken));
  7153. const auto [l, r] = sytrusRender (blob, false, 8192, { { 60, 0, 4096 } });
  7154. double worst = 0.0;
  7155. for (int k = 0; k < 4000; ++k)
  7156. 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)));
  7157. CHECK (worst < 2e-5);
  7158. CHECK (l == r);
  7159. // 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
  7160. // 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)
  7161. int last = 0;
  7162. for (int k = 0; k < 8192; ++k)
  7163. if (l[(std::size_t) k] != 0.0f)
  7164. last = k;
  7165. CHECK (last == 4895);
  7166. // key 69 = 880 Hz; 48 kHz
  7167. const auto [l2, r2] = sytrusRender (blob, false, 4096, { { 69, 0, -1 } }, 48000.0);
  7168. worst = 0.0;
  7169. for (int k = 0; k < 4000; ++k)
  7170. 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)));
  7171. CHECK (worst < 5e-5);
  7172. (void) r2;
  7173. }
  7174. TEST (sytrus_engine_reference)
  7175. {
  7176. // FM 2→1, Vanilla LP filter, volume envelope, unison 3, delay and reverb, 2× oversampling with the 8-sample
  7177. // envelope tick (render settings): against our Python reference model of REA_rodada31 (sytmodel.render)
  7178. SytrusTestPatch t;
  7179. t.main[195] = 0, t.main[196] = 1, t.main[193] = 0, t.main[194] = 1;
  7180. t.main[173] = 3, t.main[174] = 64, t.main[176] = 100;
  7181. t.ops[1].ratio = 40000;
  7182. t.cell (0, 0, 1, 128); // op 2 → op 1 FM
  7183. t.cell (0, 0, 8, 128);
  7184. t.cell (0, 6, 0, 256); // op 1 → filter 1
  7185. t.cell (0, 6, 8, 256);
  7186. t.cell (0, 0, 7, 200); // FX send
  7187. t.filts[0].p[0] = 1, t.filts[0].p[2] = 180, t.filts[0].p[3] = 60;
  7188. t.ops[0].env1[0] = 0, t.ops[0].env1[1] = 1, t.ops[0].env1[2] = 2;
  7189. t.ops[0].env1pts = { { 0.0, 0.0 }, { 0.05, 1.0 }, { 0.1, 0.6 }, { 0.2, 0.0 } };
  7190. const std::int32_t d0[5] { 40, 100, 50, 100, 0 };
  7191. std::memcpy (t.delays[0].data(), d0, 20);
  7192. t.delays[0][22] = 1;
  7193. t.reverb = { 19, 221, 10, 50, 80, 30, 100, 2, 100 };
  7194. t.reverbOn = true;
  7195. const auto blob = t.blob();
  7196. const auto [l, r] = sytrusRender (blob, true, 12000, { { 60, 0, 6000 } });
  7197. // reference values (model render_mode=True, 44.1 kHz, block 512, key 60, velocity 0.78125, release at 6000); the same
  7198. // state rendered by FL's own Sytrus DLL in render mode differs from this by −136 dB (EXEC, REA round 31 harness)
  7199. const std::array<std::pair<int, float>, 8> golden { { { 100, -0.00235529384f }, { 777, -0.175126165f }, { 2000, 0.30976975f }, { 4321, -0.0213534199f },
  7200. { 6100, 0.202372357f }, { 7000, 0.249530748f }, { 9000, 0.0307101421f }, { 11999, 0.176390275f } } };
  7201. for (const auto& [i, v] : golden)
  7202. CHECK (std::abs (l[(std::size_t) i] - v) < 1e-6f);
  7203. const std::array<std::pair<int, float>, 3> goldenR { { { 777, -0.166890964f }, { 4321, -0.212358952f }, { 9000, -0.0251909085f } } };
  7204. for (const auto& [i, v] : goldenR)
  7205. CHECK (std::abs (r[(std::size_t) i] - v) < 1e-6f);
  7206. }
  7207. TEST (sytrus_instrument)
  7208. {
  7209. // the LYNX instrument: state in ChannelDef::pluginState, channel volume/pan recovered from the rack gains
  7210. SytrusTestPatch t;
  7211. t.cell (0, 0, 8, 256);
  7212. lynx::ChannelDef c;
  7213. c.instrument = lynx::InstrumentKind::sytrus;
  7214. c.pluginState = t.blob();
  7215. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sytrus);
  7216. inst->prepare (44100.0);
  7217. inst->configure (c, 120.0);
  7218. CHECK (inst->idle());
  7219. std::vector<float> l (4096), r (4096);
  7220. inst->noteOn (60, 100.0f / 128.0f);
  7221. // 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
  7222. inst->render (l.data(), r.data(), 4096, 0.5f, 0.5f);
  7223. double peak = 0.0;
  7224. for (int k = 1000; k < 4096; ++k)
  7225. peak = std::max (peak, (double) std::abs (l[(std::size_t) k]));
  7226. CHECK (std::abs (peak - 0.5 * 0.70710678) < 1e-3); // Final.Vol 0.5 × the plugin's centre pan law
  7227. CHECK (! inst->idle());
  7228. inst->noteOff (60);
  7229. std::vector<float> tail (44100 * 3), tailR (tail.size());
  7230. inst->render (tail.data(), tailR.data(), (int) tail.size(), 0.5f, 0.5f);
  7231. CHECK (inst->idle());
  7232. CHECK (tail.back() == 0.0f);
  7233. }
  7234. TEST (harmor_effects_rack)
  7235. {
  7236. // REA_rodada38: the rack runs in the state's unit order and the records' FX send joins it at unit 4 — with the FX
  7237. // amount at 1000 every record output bypasses a reverb placed before unit 4 (EXEC: −600 dB vs the rack off)
  7238. auto blob = harmorTestState (false);
  7239. auto set = [&] (std::vector<std::uint8_t>& st, int part, int index, std::int32_t v) {
  7240. std::memcpy (st.data() + lynx::harmorParamOffset (st, part, index), &v, 4);
  7241. };
  7242. set (blob, 0, 10, 1000); // all to the FX send
  7243. auto render = [] (const std::vector<std::uint8_t>& st) {
  7244. return lynx::harmor::renderReference (st, { { 0, 60, 0.8, 1.0, 0.0, 6000 } }, 44100.0, 12000);
  7245. };
  7246. const auto dry = render (blob);
  7247. auto rev = blob;
  7248. set (rev, -1, 22, 1); // reverb on: room 50, diffusion 100, decay 2^3·0.1 s, high cut / damping off, wet 0.8
  7249. 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);
  7250. set (rev, -1, 30, 2), set (rev, -1, 31, 800);
  7251. const auto bypassed = render (rev);
  7252. double eb = 0.0, db = 0.0;
  7253. for (std::size_t i = 0; i < dry.size(); ++i)
  7254. eb += (double) (bypassed[i] - dry[i]) * (bypassed[i] - dry[i]), db += (double) dry[i] * dry[i];
  7255. CHECK (eb < 1e-12 * db && db > 1e-3); // (float rounding of the rack's buffers only)
  7256. auto after = rev;
  7257. const std::int32_t order[6] { 0, 1, 2, 4, 3, 5 }; // the join before the reverb
  7258. for (int k = 0; k < 6; ++k)
  7259. set (after, -1, 53 + k, order[k]);
  7260. const auto wet = render (after);
  7261. double e = 0.0, d = 0.0;
  7262. bool finite = true;
  7263. for (std::size_t i = 0; i < wet.size(); ++i)
  7264. e += (double) (wet[i] - dry[i]) * (wet[i] - dry[i]), d += (double) dry[i] * dry[i], finite = finite && std::isfinite (wet[i]);
  7265. CHECK (finite && e > 1e-4 * d && d > 1e-3);
  7266. // a distortion (type 6) and a delay on the dry path change the sound, stay finite, and the instrument ends quiet
  7267. auto dist = harmorTestState (false);
  7268. {
  7269. const auto at = lynx::harmorParamOffset (dist, -1, 0) + 0xd4 + 0x18 + 48; // global misc +48: distortion type
  7270. const std::int32_t six = 6;
  7271. std::memcpy (dist.data() + at, &six, 4);
  7272. }
  7273. set (dist, -1, 17, 600), set (dist, -1, 19, 1000), set (dist, -1, 21, 1100);
  7274. 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);
  7275. set (dist, -1, 47, 1050);
  7276. lynx::ChannelDef c;
  7277. c.instrument = lynx::InstrumentKind::harmor;
  7278. c.pluginState = dist;
  7279. auto inst = lynx::makeInstrument (lynx::InstrumentKind::harmor);
  7280. inst->configure (c, 120.0);
  7281. inst->prepare (44100.0);
  7282. std::vector<float> l (44100 * 4), r (l.size());
  7283. inst->noteOn (60, 0.8f);
  7284. double energy = 0.0;
  7285. for (int s = 0; s < (int) l.size(); s += 512)
  7286. {
  7287. if (s == 8192)
  7288. inst->noteOff (60);
  7289. inst->render (l.data() + s, r.data() + s, 512, 1.0f, 1.0f);
  7290. }
  7291. for (std::size_t i = 0; i < l.size(); ++i)
  7292. finite = finite && std::isfinite (l[i]) && std::isfinite (r[i]), energy += (double) l[i] * l[i];
  7293. CHECK (finite && energy > 1.0);
  7294. std::vector<float> tail (44100 * 6), tailR (tail.size());
  7295. for (int s = 0; s < (int) tail.size(); s += 512)
  7296. inst->render (tail.data() + s, tailR.data() + s, 512, 1.0f, 1.0f);
  7297. CHECK (inst->idle());
  7298. }
  7299. TEST (harmless_engine)
  7300. {
  7301. // REA_rodada32: state parsing, the additive engine against our reference model (hlmodel.py), host levels, voice end
  7302. std::vector<std::uint8_t> blob;
  7303. 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))); };
  7304. std::array<std::int32_t, 100> p {}; // the reference's clean patch: Saw, open filter, no modulation
  7305. for (int i = 11; i < 23; ++i)
  7306. p[(std::size_t) i] = 1000;
  7307. 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;
  7308. 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;
  7309. // + resonance, pluck, 3-voice unison, tremolo, LFO on pitch
  7310. 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;
  7311. put (12);
  7312. for (auto v : p)
  7313. put (v);
  7314. for (int i = 0; i < 7; ++i)
  7315. put (0);
  7316. put (524); // Custom colour table: 524 × (amplitude, phase)
  7317. for (int i = 0; i < 1048; ++i)
  7318. {
  7319. const auto f = i < 524 ? 1.0f / (float) (i + 1) : 0.25f;
  7320. std::uint32_t bits = 0;
  7321. std::memcpy (&bits, &f, 4);
  7322. put ((std::int32_t) bits);
  7323. }
  7324. const auto parsed = lynx::harmlessParams (blob);
  7325. CHECK (parsed && (int) parsed->size() == lynx::harmlessParamCount);
  7326. CHECK (parsed && (*parsed)[54] == 3500.0f && (*parsed)[99] == 0.0f && (*parsed)[lynx::harmlessCustomFlagIndex] == 1.0f);
  7327. CHECK (parsed && (*parsed)[lynx::harmlessCustomIndex + 1] == 0.5f && (*parsed)[lynx::harmlessCustomIndex + 524] == 0.25f);
  7328. auto old = blob;
  7329. old[0] = 3; // versions below 4 are not Harmless states we know
  7330. CHECK (! lynx::harmlessParams (old));
  7331. old = blob;
  7332. old.resize (300);
  7333. CHECK (! lynx::harmlessParams (old));
  7334. lynx::ChannelDef c;
  7335. c.instrument = lynx::InstrumentKind::harmless;
  7336. c.modelParams = *parsed;
  7337. c.modelParams[lynx::harmlessCustomFlagIndex] = 0.0f; // colour 0 (Saw): the custom table is not read
  7338. auto render = [] (const lynx::ChannelDef& def, int total, float gl, float gr, int offAt) {
  7339. auto inst = lynx::makeInstrument (lynx::InstrumentKind::harmless);
  7340. inst->configure (def, 120.0);
  7341. inst->prepare (44100.0);
  7342. std::vector<float> l ((std::size_t) total), r ((std::size_t) total);
  7343. inst->noteOn (60, 0.78125f);
  7344. for (int s = 0; s < total; s += 512)
  7345. {
  7346. if (s == offAt)
  7347. inst->noteOff (60);
  7348. inst->render (l.data() + s, r.data() + s, std::min (512, total - s), gl, gr);
  7349. }
  7350. return std::make_tuple (l, r, std::move (inst));
  7351. };
  7352. {
  7353. // reference model (REA round 32 hlmodel.py, C5 at FL velocity 100, channel volume 1, centre, released at 6144)
  7354. auto [l, r, inst] = render (c, 8192, 1.0f, 1.0f, 6144);
  7355. const std::tuple<int, float, float> golden[] {
  7356. { 0, 0.0f, 0.0f }, { 10, -0.02220994f, -0.06232700f }, { 100, 0.40623373f, 0.17308202f }, { 1000, -0.04091963f, -0.26821208f },
  7357. { 3000, 0.14519004f, 0.11027778f }, { 6000, 0.50411958f, 0.27901855f }, { 8191, 0.02117692f, -0.01466602f } };
  7358. for (const auto& [i, gl, gr] : golden)
  7359. CHECK (std::abs (l[(std::size_t) i] - gl) < 2e-6f && std::abs (r[(std::size_t) i] - gr) < 2e-6f);
  7360. // after the release the record fades out (below 1e-4, then 30 ms) and the instrument goes idle
  7361. std::vector<float> tail (44100), tailR (tail.size());
  7362. inst->render (tail.data(), tailR.data(), (int) tail.size(), 1.0f, 1.0f);
  7363. CHECK (inst->idle());
  7364. }
  7365. // FL's level law applied once: half the channel volume halves the output; full right pan silences the left side
  7366. const auto full = std::get<0> (render (c, 2048, 1.0f, 1.0f, -1));
  7367. const auto half = std::get<0> (render (c, 2048, 0.5f, 0.5f, -1));
  7368. CHECK (std::abs (half[100] - 0.5f * full[100]) < 1e-6f && std::abs (full[100]) > 0.1f);
  7369. auto mono = c;
  7370. mono.modelParams[25] = 0.0f; // no tremolo, no unison pan spread
  7371. mono.modelParams[65] = 1.0f;
  7372. const auto [pl, pr, pi] = render (mono, 2048, 0.0f, 1.41421356f, -1);
  7373. double el = 0.0, er = 0.0;
  7374. for (int i = 0; i < 2048; ++i)
  7375. el += (double) pl[(std::size_t) i] * pl[(std::size_t) i], er += (double) pr[(std::size_t) i] * pr[(std::size_t) i];
  7376. CHECK (el < 1e-10 * er && er > 1.0);
  7377. }
  7378. TEST (startup_sound)
  7379. {
  7380. // the splash's sound: the right length, finite, at its peak level, quiet before the whoosh swells,
  7381. // a landing "pop" at impactTime and a chime ringing after it
  7382. using namespace lynx::startup;
  7383. const auto sound = makeSound (48000.0);
  7384. CHECK (sound.left.size() == (std::size_t) (soundLength * 48000.0) && sound.right.size() == sound.left.size());
  7385. float peak = 0.0f;
  7386. bool finite = true;
  7387. for (std::size_t i = 0; i < sound.left.size(); ++i)
  7388. {
  7389. finite = finite && std::isfinite (sound.left[i]) && std::isfinite (sound.right[i]);
  7390. peak = std::max ({ peak, std::abs (sound.left[i]), std::abs (sound.right[i]) });
  7391. }
  7392. CHECK (finite && std::abs (peak - peakLevel) < 1.0e-4f);
  7393. auto rms = [&sound] (double from, double to) {
  7394. double e = 0.0;
  7395. const auto a = (std::size_t) (from * 48000.0), b = (std::size_t) (to * 48000.0);
  7396. for (auto i = a; i < b; ++i)
  7397. e += (double) sound.left[i] * sound.left[i];
  7398. return std::sqrt (e / (double) (b - a));
  7399. };
  7400. CHECK (rms (0.0, 0.05) < 0.2 * rms (impactTime - 0.05, impactTime)); // the whoosh swells
  7401. CHECK (rms (impactTime, impactTime + 0.05) > rms (impactTime - 0.05, impactTime)); // the landing
  7402. CHECK (rms (0.8, 1.0) > 0.005 && rms (soundLength - 0.02, soundLength) < rms (0.8, 1.0)); // chime rings, tail fades
  7403. CHECK (makeSound (48000.0).left == sound.left); // the same sound on every start
  7404. }
  7405. namespace
  7406. {
  7407. // little-endian byte writer for the state builders below
  7408. struct Bytes
  7409. {
  7410. std::vector<std::uint8_t> b;
  7411. void raw (const char* s, std::size_t n) { b.insert (b.end(), s, s + n); }
  7412. 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); }
  7413. void f32 (float v) { b.insert (b.end(), reinterpret_cast<const std::uint8_t*> (&v), reinterpret_cast<const std::uint8_t*> (&v) + 4); }
  7414. void zeros (std::size_t n) { b.insert (b.end(), n, 0); }
  7415. void bytes (const std::vector<std::uint8_t>& o) { b.insert (b.end(), o.begin(), o.end()); }
  7416. };
  7417. // A GMS state written from scratch (REA_rodada12 §1.1 layout, "Syn4"): oscillator waves that don't exist (silent
  7418. // tables, so the result does not depend on an FL installation), noise through the ladder with envelope and LFO,
  7419. // unison, slide, distortion, delay, reverb and the output EQ.
  7420. std::vector<std::uint8_t> gmsTestState()
  7421. {
  7422. std::array<float, 212> P {};
  7423. for (int i : { 1, 2, 44, 55, 56, 57, 58, 59, 60, 207, 208, 209, 210, 211 })
  7424. P[(std::size_t) i] = 0.5f;
  7425. P[0] = 0.75f, P[4] = 0.1f, P[5] = 0.4f, P[6] = 0.6f, P[7] = 0.3f, P[8] = 0.8f;
  7426. 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;
  7427. 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;
  7428. P[147] = 1.0f, P[117] = 0.3f, P[127] = 0.6f; // distortion
  7429. P[153] = 1.0f, P[123] = 0.5f, P[133] = 0.4f, P[143] = 0.4f; // delay (1/2 beat)
  7430. P[154] = 1.0f, P[124] = 0.6f, P[134] = 0.5f; // reverb
  7431. P[206] = 1.0f, P[207] = 0.7f, P[211] = 0.3f; // output EQ
  7432. Bytes preset;
  7433. preset.raw ("4nyS", 4);
  7434. for (const char* path : { "NoSuchDir\\NoWave A.wav", "NoSuchDir\\NoWave B.wav", "NoSuchDir\\NoWave C.wav", "", "", "", "" })
  7435. {
  7436. const auto n = std::strlen (path);
  7437. preset.raw (path, n);
  7438. preset.zeros (512 - n);
  7439. }
  7440. preset.i32 (0), preset.i32 (0), preset.i32 (0);
  7441. for (auto v : P)
  7442. preset.f32 (v);
  7443. preset.raw ("LYNX test", 9);
  7444. preset.zeros (512 - 9);
  7445. Bytes s;
  7446. s.raw ("SSLF", 4);
  7447. s.i32 ((std::int32_t) preset.b.size());
  7448. s.bytes (preset.b);
  7449. return s.b;
  7450. }
  7451. // A Morphine state written from scratch (REA_rodada16 §3 / REA_rodada39 §2.2 layout): generators A and B with a few
  7452. // frames each (A loops, PWM on A), C and D silent, a morph line A→B, four envelopes (Eg1 → pitch and velocity →
  7453. // amplitude through the matrix), the master ADSR and every plugin effect on.
  7454. std::vector<std::uint8_t> morphineTestState()
  7455. {
  7456. auto mbp = [] (int seed) {
  7457. Bytes b;
  7458. b.raw ("0PBM", 4);
  7459. for (int a = 0; a < 3; ++a)
  7460. for (int byte = 0; byte < 16; ++byte)
  7461. {
  7462. b.b.push_back (0xff);
  7463. for (int bit = 0; bit < 8; ++bit)
  7464. {
  7465. const auto k = byte * 8 + bit;
  7466. const float v = a == 0 ? std::cbrt (1.0f / (float) (k + 1 + seed * (k % 3))) * (k < 40 ? 1.0f : 0.2f)
  7467. : a == 1 ? 0.1f * (float) ((k * 7 + seed) % 11 - 5) / 5.0f
  7468. : 0.02f * (float) ((k * 5 + seed) % 7 - 3);
  7469. b.f32 (v);
  7470. }
  7471. }
  7472. return b.b;
  7473. };
  7474. auto msp = [&] (int frames, int seed, int loopMode) {
  7475. Bytes b;
  7476. b.raw ("0PSM", 4);
  7477. b.i32 (frames);
  7478. for (int f = 0; f < frames; ++f)
  7479. {
  7480. const auto m = mbp (seed + f);
  7481. b.i32 (20 + 7 * f), b.f32 (1.0f - 0.2f * (float) f), b.i32 ((std::int32_t) m.size());
  7482. b.bytes (m);
  7483. }
  7484. b.i32 (0x424);
  7485. b.i32 (10), b.i32 (40), b.i32 (0), b.i32 (loopMode);
  7486. b.f32 (0.45f), b.f32 (0.6f), b.f32 (0.5f), b.i32 (0);
  7487. for (int k = 0; k < 128; ++k)
  7488. b.f32 (0.3f);
  7489. for (int k = 0; k < 128; ++k)
  7490. b.f32 (1.0f);
  7491. return b.b;
  7492. };
  7493. auto mvc = [&] (int frames, int seed, int pwmMode) {
  7494. Bytes z;
  7495. z.raw ("0HZM", 4);
  7496. z.i32 (1);
  7497. const auto s = msp (frames, seed, 1);
  7498. z.i32 (128), z.f32 (frames > 1 ? 0.9f : 0.0f), z.i32 ((std::int32_t) s.size());
  7499. z.bytes (s);
  7500. Bytes b;
  7501. b.raw ("0CVM", 4);
  7502. b.i32 ((std::int32_t) z.b.size());
  7503. b.bytes (z.b);
  7504. 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);
  7505. return b.b;
  7506. };
  7507. Bytes p;
  7508. p.raw ("0roM", 4);
  7509. p.raw ("0RPM", 4);
  7510. for (const auto& g : { mvc (3, 1, 2), mvc (2, 7, 0), mvc (1, 3, 0), mvc (1, 5, 0) })
  7511. {
  7512. p.i32 ((std::int32_t) g.size());
  7513. p.bytes (g);
  7514. }
  7515. {
  7516. Bytes m;
  7517. m.raw ("0LMM", 4);
  7518. m.i32 (2), m.i32 (12);
  7519. m.f32 (0.0f), m.f32 (1.0f), m.i32 (60);
  7520. m.f32 (1.0f), m.f32 (1.0f), m.i32 (60);
  7521. m.i32 (0x54), m.i32 (0), m.i32 (0), m.i32 (0), m.i32 (0);
  7522. for (float v : { 1.0f, 0.8f, 0.0f, 0.0f, 0.5f, 0.4f, 0.5f, 0.5f })
  7523. m.f32 (v);
  7524. for (int k = 0; k < 4; ++k)
  7525. m.i32 (0);
  7526. m.f32 (0.5f), m.f32 (0.5f), m.f32 (0.5f), m.i32 (0);
  7527. p.i32 ((std::int32_t) m.b.size());
  7528. p.bytes (m.b);
  7529. }
  7530. {
  7531. Bytes d;
  7532. d.raw ("0DMM", 4);
  7533. d.i32 (4);
  7534. for (int e = 0; e < 4; ++e)
  7535. {
  7536. Bytes g;
  7537. g.raw ("0GEM", 4);
  7538. g.i32 (3), g.i32 (8);
  7539. g.f32 (0.0f), g.i32 (10), g.f32 (1.0f), g.i32 (40 + 10 * e), g.f32 (0.3f), g.i32 (50);
  7540. 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),
  7541. g.i32 (e == 0 ? 1 : 0);
  7542. d.i32 ((std::int32_t) g.b.size());
  7543. d.bytes (g.b);
  7544. }
  7545. d.i32 (0x94);
  7546. const int src[12] = { 5, 2 }, dst[12] = { 3, 1 };
  7547. const float amt[12] = { 0.56f, 0.7f };
  7548. for (int k = 0; k < 12; ++k)
  7549. d.i32 (src[k]);
  7550. for (int k = 0; k < 12; ++k)
  7551. d.i32 (dst[k]);
  7552. for (int k = 0; k < 12; ++k)
  7553. d.f32 (amt[k]);
  7554. p.i32 ((std::int32_t) d.b.size());
  7555. p.bytes (d.b);
  7556. }
  7557. {
  7558. 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
  7559. 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 …
  7560. 0.4f, 0.3f, 1.0f, 0.5f, 0.5f, 0.4f, 1.0f, 0.6f, 0.4f, 0.5f, // … delay, reverb, EQ …
  7561. 0.5f, 0.5f, 0.55f, 0.5f, 0.45f, 1.0f, 0.0f, 0.5f, 1.0f, 0.0f }; // EQ on, noise (muted)
  7562. Bytes g;
  7563. g.i32 (0x5c4);
  7564. for (auto v : A)
  7565. g.f32 (v);
  7566. g.zeros (0x5c4 - g.b.size());
  7567. p.bytes (g.b);
  7568. }
  7569. Bytes s;
  7570. s.raw ("SSLF", 4);
  7571. s.i32 ((std::int32_t) p.b.size());
  7572. s.bytes (p.b);
  7573. return s.b;
  7574. }
  7575. void dumpIfAsked (const char* var, const std::vector<std::uint8_t>& blob)
  7576. {
  7577. if (const char* path = std::getenv (var))
  7578. {
  7579. std::ofstream out (path, std::ios::binary);
  7580. out.write (reinterpret_cast<const char*> (blob.data()), (std::streamsize) blob.size());
  7581. }
  7582. }
  7583. } // namespace
  7584. TEST (dx10_engine)
  7585. {
  7586. // REA_rodada42: a Fruity DX10 state written from scratch (version 1: 22 raw parameters) against our reference model
  7587. // (dxmodel.py + dxproc.py, bit-identical to the installation's DLL), the channel processor, host levels and the
  7588. // instrument front-end
  7589. const std::int32_t P[22] = { 1000, 40000, 30000, 30000, 40000, 30000, 35000, 8000, 40000, 50000, 20000,
  7590. 25000, 15000, 30000, 20000, 10000, 20000, 30000, 5000, 30000, 20000, -1 };
  7591. std::vector<std::uint8_t> blob (4 + 22 * 4, 0);
  7592. blob[0] = 1;
  7593. std::memcpy (blob.data() + 4, P, sizeof (P));
  7594. CHECK (lynx::dx10StateUsable (blob) && lynx::dx10ProcessorNeutral (blob));
  7595. CHECK (lynx::dx10Param (blob, 21) == -1 && lynx::dx10Param (blob, 3) == 30000 && ! lynx::dx10Param (blob, 22));
  7596. CHECK (! lynx::dx10StateUsable (std::vector<std::uint8_t> (40, 0)));
  7597. {
  7598. auto bad = blob;
  7599. bad[0] = 3; // versions ≥ 3 are ignored by the plugin
  7600. CHECK (! lynx::dx10StateUsable (bad));
  7601. }
  7602. using N = lynx::dx10::RefNote;
  7603. const std::vector<N> notes { { 0, 60, 1.0, 0.8, 0.3, 0.0, 6144 }, { 2048, 67, 0.4, 1.0, -0.5, 25.0, 8192 }, { 3000, 40, 2.06, 0.6, 1.0, 0.0, -1 } };
  7604. struct Golden { std::vector<std::uint8_t> state; lynx::dx10::RefOptions opt; int rate; double el, er; std::tuple<int, float, float> at[6]; };
  7605. auto check = [&] (const Golden& g) {
  7606. const auto y = lynx::dx10::renderReference (g.state, notes, (double) g.rate, 16384, g.opt);
  7607. CHECK (y.size() == 2 * 16384);
  7608. if (y.size() != 2 * 16384)
  7609. return y;
  7610. double el = 0.0, er = 0.0;
  7611. for (std::size_t i = 0; i + 1 < y.size(); i += 2)
  7612. el += (double) y[i] * y[i], er += (double) y[i + 1] * y[i + 1];
  7613. CHECK (std::abs (el - g.el) <= 1e-7 * g.el && std::abs (er - g.er) <= 1e-7 * g.er);
  7614. for (const auto& [i, l, r] : g.at)
  7615. CHECK (std::abs (y[2 * (std::size_t) i] - l) <= 1e-7f * std::max (1e-16f, std::abs (l))
  7616. && std::abs (y[2 * (std::size_t) i + 1] - r) <= 1e-7f * std::max (1e-16f, std::abs (r)));
  7617. return y;
  7618. };
  7619. lynx::dx10::RefOptions plain, odd;
  7620. odd.block = 333, odd.maxPoly = 1;
  7621. check ({ blob, plain, 44100, 672.293115, 778.393071,
  7622. { { 100, -0.0943799689f, -0.154014125f }, { 1000, -0.0814286768f, -0.132879525f }, { 2500, 0.499493301f, 0.312498778f },
  7623. { 5000, -0.184045464f, 0.171641544f }, { 9000, -0.153369367f, -0.20805186f }, { 16383, -0.00441304967f, 0.200126961f } } });
  7624. // 48 kHz, odd host blocks, max polyphony 1 (the last note steals); the hard-right note keeps FL's x87 left gain
  7625. check ({ blob, odd, 48000, 122.232761, 493.320297,
  7626. { { 100, 0.0236493405f, 0.0385922194f }, { 1000, 0.189806491f, 0.309736073f }, { 2500, -0.425576478f, -0.176279545f },
  7627. { 5000, -3.54030076e-18f, -0.0578194074f }, { 9000, 1.37052479e-17f, 0.223831087f }, { 16383, 9.248742e-18f, 0.151048407f } } });
  7628. // the channel processor (§3): our own settings snapshot — pan LFO (triangle, delayed, faded in), volume envelope
  7629. // with tensions and LFO, cutoff envelope + square LFO, resonance LFO, pitch envelope, SVF LP ×2 (type 7)
  7630. auto record = [] (std::vector<std::uint8_t>& s, int k, std::initializer_list<std::pair<int, int>> fields) {
  7631. const std::int32_t neutral[17] = { 0, 0, 100, 20000, 20000, 30000, 50, 20000, 0, 100, 20000, 0, 32950, 0, 0, 0, 0 };
  7632. std::memcpy (s.data() + 0x44 * k, neutral, sizeof (neutral));
  7633. for (const auto& [i, v] : fields)
  7634. std::memcpy (s.data() + 0x44 * k + 4 * i, &v, 4);
  7635. };
  7636. auto settings = [] (std::vector<std::uint8_t>& s, std::int32_t modX, std::int32_t modY, std::int32_t type) {
  7637. std::memcpy (s.data() + 0x15c, &modX, 4);
  7638. std::memcpy (s.data() + 0x160, &modY, 4);
  7639. std::memcpy (s.data() + 0x168, &type, 4);
  7640. };
  7641. std::vector<std::uint8_t> snap (364, 0);
  7642. record (snap, 0, { { 9, 5000 }, { 10, 9000 }, { 11, -40 }, { 12, 15000 }, { 13, 1 } });
  7643. record (snap, 1, { { 0, 4 }, { 1, 1 }, { 3, 12000 }, { 4, 3000 }, { 5, 15000 }, { 6, 40 }, { 11, 30 }, { 12, 20000 }, { 14, 60 }, { 15, -90 }, { 16, -101 } });
  7644. record (snap, 2, { { 1, 1 }, { 3, 6000 }, { 4, 100 }, { 5, 16000 }, { 6, 20 }, { 8, -60 }, { 11, 20 }, { 12, 18000 }, { 13, 2 } });
  7645. record (snap, 3, { { 11, 40 }, { 12, 17000 } });
  7646. record (snap, 4, { { 1, 1 }, { 3, 5000 }, { 4, 100 }, { 5, 14000 }, { 6, 30 }, { 8, -700 } });
  7647. settings (snap, 140, 120, 7);
  7648. const auto withSnap = lynx::dx10StateWithSnapshot (blob, snap);
  7649. CHECK (withSnap.size() == 460 && withSnap[0] == 2 && ! lynx::dx10ProcessorNeutral (withSnap));
  7650. CHECK (lynx::dx10StateWithSnapshot (withSnap, std::vector<std::uint8_t> (364, 0)) == withSnap); // a v2 state keeps its own
  7651. lynx::dx10::RefOptions ticks;
  7652. ticks.tick = 230, ticks.ppq = 96, ticks.tempo = 120.0;
  7653. check ({ withSnap, ticks, 44100, 346.852062, 554.699375,
  7654. { { 100, -0.00162654708f, -0.00265428401f }, { 1000, 0.0310285408f, 0.0506339073f }, { 2500, -0.118068494f, -0.0915558636f },
  7655. { 5000, -0.297166437f, -0.256465197f }, { 9000, 0.199509233f, 0.166108996f }, { 16383, -0.00392446062f, 0.0410436988f } } });
  7656. // a volume envelope decaying to zero: the 10 ms end fade, then every voice is gone (silence from 14950 on)
  7657. std::vector<std::uint8_t> decay (364, 0);
  7658. for (int k = 0; k < 5; ++k)
  7659. record (decay, k, {});
  7660. record (decay, 1, { { 0, 4 }, { 1, 1 }, { 3, 9000 }, { 4, 100 }, { 5, 12000 }, { 6, 0 }, { 15, 50 }, { 16, -101 } });
  7661. settings (decay, 256, 0, 0);
  7662. auto ticks48 = ticks;
  7663. ticks48.block = 333;
  7664. const auto y = check ({ lynx::dx10StateWithSnapshot (blob, decay), ticks48, 48000, 338.361707, 350.520208,
  7665. { { 100, 0.000514116196f, 0.000838961045f }, { 1000, 0.0412623473f, 0.0673340634f }, { 2500, -0.141532451f, -0.156581759f },
  7666. { 5000, 0.382550895f, 0.23462519f }, { 7000, -0.189829409f, 0.144132584f }, { 9000, -0.13638559f, 0.142912149f } } });
  7667. bool silentTail = y.size() == 2 * 16384 && (y[2 * 14949] != 0.0f || y[2 * 14949 + 1] != 0.0f);
  7668. for (std::size_t i = 2 * 14950; i < y.size(); ++i)
  7669. silentTail = silentTail && y[i] == 0.0f;
  7670. CHECK (silentTail);
  7671. // the instrument: LYNX velocity v → Init.Vol = (11^(1.28·v) − 1)/10 and Final.Vol = channel volume × Init.Vol; channel
  7672. // gains √2·V·(cos, sin)((1 + p)π/4) → V, p; notes on block boundaries play like the reference renderer (neutral
  7673. // channel settings: the instrument's sequencer ticks change nothing; vibrato off, since the plugin-wide vibrato
  7674. // oscillator is stepped by each voice in turn, so its interleaving follows the host block layout, as in FL)
  7675. auto noVib = blob;
  7676. CHECK (lynx::dx10SetParam (noVib, 10, 0));
  7677. auto initVol = [] (double v) { return (double) (float) ((std::pow (11.0, 1.28 * v) - 1.0) / 10.0); }; // Init.Vol is a float
  7678. lynx::ChannelDef c;
  7679. c.instrument = lynx::InstrumentKind::dx10;
  7680. c.pluginState = noVib;
  7681. auto inst = lynx::makeInstrument (lynx::InstrumentKind::dx10);
  7682. inst->configure (c, 120.0);
  7683. inst->prepare (44100.0);
  7684. const float V = 0.6f, pan = 0.25f;
  7685. const auto gl = (float) (std::sqrt (2.0) * V * std::cos ((1.0 + pan) * 3.141592653589793 / 4.0));
  7686. const auto gr = (float) (std::sqrt (2.0) * V * std::sin ((1.0 + pan) * 3.141592653589793 / 4.0));
  7687. std::vector<float> l (16384), r (16384);
  7688. for (int s = 0; s < 16384; s += 512)
  7689. {
  7690. if (s == 0)
  7691. inst->noteOn (60, 0.78125f);
  7692. if (s == 2048)
  7693. {
  7694. inst->setNextNoteExpression (-0.5f, 25.0f);
  7695. inst->noteOn (67, 0.5f);
  7696. }
  7697. if (s == 6144)
  7698. inst->noteOff (60);
  7699. if (s == 8192)
  7700. inst->noteOff (67);
  7701. inst->render (l.data() + s, r.data() + s, 512, gl, gr);
  7702. }
  7703. // the channel level reaches the engine as FL's (recovered to float precision)
  7704. const auto Vr = std::sqrt (((double) gl * gl + (double) gr * gr) * 0.5);
  7705. const auto pr = std::atan2 ((double) gr, (double) gl) * (4.0 / 3.141592653589793) - 1.0;
  7706. const auto ref = lynx::dx10::renderReference (noVib, { { 0, 60, initVol (0.78125), Vr * initVol (0.78125), pr, 0.0, 6144 },
  7707. { 2048, 67, initVol (0.5), Vr * initVol (0.5), std::clamp (-0.5 + pr, -1.0, 1.0), 25.0, 8192 } },
  7708. 44100.0, 16384);
  7709. double worst = 0.0, peak = 0.0;
  7710. for (int i = 0; i < 16384; ++i)
  7711. 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]) }),
  7712. peak = std::max (peak, (double) std::abs (l[(std::size_t) i]));
  7713. CHECK (worst == 0.0 && peak > 0.05);
  7714. // the released voices end (DX10's own release) and the instrument goes idle
  7715. std::vector<float> tail (44100), tailR (tail.size());
  7716. for (int k = 0; k < 20 && ! inst->idle(); ++k)
  7717. inst->render (tail.data(), tailR.data(), (int) tail.size(), gl, gr);
  7718. CHECK (inst->idle());
  7719. // with the channel settings above the instrument follows FL's ticks: the cutoff envelope darkens the note
  7720. {
  7721. lynx::ChannelDef cs = c;
  7722. cs.pluginState = withSnap;
  7723. cs.modelParams = { 96.0f };
  7724. auto si = lynx::makeInstrument (lynx::InstrumentKind::dx10);
  7725. si->configure (cs, 120.0);
  7726. si->prepare (44100.0);
  7727. std::vector<float> sl (32768), sr (32768);
  7728. si->noteOn (48, 0.78125f);
  7729. for (int s = 0; s < 32768; s += 512)
  7730. si->render (sl.data() + s, sr.data() + s, 512, 1.0f, 1.0f);
  7731. double e1 = 0.0, e2 = 0.0;
  7732. bool finite = true;
  7733. for (int i = 0; i < 32768; ++i)
  7734. finite = finite && std::isfinite (sl[(std::size_t) i]), (i < 4096 ? e1 : e2) += (double) sl[(std::size_t) i] * sl[(std::size_t) i];
  7735. CHECK (finite && e1 > 1e-3 && e2 > 1e-3);
  7736. }
  7737. // parameter edits (the channel settings panel) write the raw integers, clamped to the knob ranges
  7738. auto edited = blob;
  7739. CHECK (lynx::dx10SetParam (edited, 21, 7) && lynx::dx10Param (edited, 21) == 3);
  7740. CHECK (lynx::dx10SetParam (edited, 12, 70000) && lynx::dx10Param (edited, 12) == 65536);
  7741. }
  7742. TEST (gms_engine)
  7743. {
  7744. const auto blob = gmsTestState();
  7745. dumpIfAsked ("LYNX_DUMP_GMS", blob);
  7746. CHECK (lynx::gmsStateUsable (blob));
  7747. CHECK (lynx::gmsWaveNames (blob) == std::vector<std::string> ({ "NoWave A", "NoWave B", "NoWave C" }));
  7748. CHECK (lynx::gmsParamOffset (blob, 12) == 8 + 4 + 7 * 512 + 12 + 4 * 12 && lynx::gmsParamOffset (blob, 212) < 0);
  7749. auto broken = blob;
  7750. broken[8] = 'X';
  7751. CHECK (! lynx::gmsStateUsable (broken));
  7752. CHECK (! lynx::gmsStateUsable (std::vector<std::uint8_t> (blob.begin(), blob.begin() + 2000)));
  7753. // golden samples of our round-39 model (gmsmodel.GmsPlugin, waves missing → silent tables, tempo 140, 44.1 kHz,
  7754. // host blocks of 512): C5 vel 100 0–30000, E5 vel 80 11025–40000, G5 vel 110 22050–52000 (Init.Vol law A)
  7755. auto iv = [] (double vel) { return (std::pow (11.0, vel / 100.0) - 1.0) / 10.0; };
  7756. const std::vector<lynx::gms::RefNote> notes = { { 0, 60, (float) iv (100), 1.0, 0.0, 0.0, 30000 },
  7757. { 11025, 64, (float) iv (80), 1.0, 0.0, 0.0, 40000 },
  7758. { 22050, 67, (float) iv (110), 1.0, 0.0, 0.0, 52000 } };
  7759. const auto y = lynx::gms::renderReference (blob, notes, 44100.0, 66150, "");
  7760. CHECK (y.size() == 2 * 66150u);
  7761. 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 } };
  7762. for (const auto& g : golden)
  7763. 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);
  7764. double e = 0.0;
  7765. for (auto v : y)
  7766. e += (double) v * v;
  7767. CHECK (std::abs (std::sqrt (e / (double) y.size()) - 0.0790270452795) < 1e-6);
  7768. // the instrument: same engine behind LYNX's channel gains (V = 1, centre → law A), velocity → Init.Vol
  7769. lynx::ChannelDef c;
  7770. c.instrument = lynx::InstrumentKind::gms;
  7771. c.pluginState = blob;
  7772. auto inst = lynx::makeInstrument (lynx::InstrumentKind::gms);
  7773. inst->configure (c, 140.0);
  7774. inst->prepare (44100.0);
  7775. std::vector<float> l (8192, 0.0f), r (8192, 0.0f);
  7776. for (int b = 0; b < 16; ++b)
  7777. {
  7778. if (b == 0)
  7779. inst->noteOn (60, 0.78125f);
  7780. if (b == 10)
  7781. inst->noteOff (60);
  7782. inst->render (l.data() + 512 * b, r.data() + 512 * b, 512, 1.0f, 1.0f);
  7783. }
  7784. 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, "");
  7785. double diff = 0.0, energy = 0.0;
  7786. for (int i = 0; i < 8192; ++i)
  7787. {
  7788. 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]) });
  7789. energy += (double) l[(std::size_t) i] * l[(std::size_t) i];
  7790. }
  7791. CHECK (diff == 0.0 && energy > 1e-3);
  7792. }
  7793. TEST (morphine_engine)
  7794. {
  7795. const auto blob = morphineTestState();
  7796. dumpIfAsked ("LYNX_DUMP_MORPHINE", blob);
  7797. CHECK (lynx::morphineStateUsable (blob));
  7798. CHECK (lynx::morphineNoiseName (blob).empty());
  7799. const auto at = lynx::morphineParamOffset (blob, 9);
  7800. CHECK (at > 0);
  7801. float a9 = 0.0f;
  7802. std::memcpy (&a9, blob.data() + at, 4);
  7803. CHECK (a9 == 0.2f && lynx::morphineParamOffset (blob, 40) < 0);
  7804. auto broken = blob;
  7805. broken[12] = 'X'; // the MPR0 tag
  7806. CHECK (! lynx::morphineStateUsable (broken));
  7807. CHECK (! lynx::morphineStateUsable (std::vector<std::uint8_t> (blob.begin(), blob.end() - 10)));
  7808. // golden samples of our round-39 model (mormodel.Synth, tempo 120, 44.1 kHz, host blocks of 512): keys 60/64/67,
  7809. // Init.Vol 1.0/0.5/2.0, note-offs at 30000/50000/70000
  7810. const std::vector<lynx::morphine::RefNote> notes = { { 0, 60, 1.0, 1.0, 0.0, 0.0, 30000 },
  7811. { 11025, 64, 0.5, 1.0, 0.0, 0.0, 50000 },
  7812. { 22050, 67, 2.0, 1.0, 0.0, 0.0, 70000 } };
  7813. const auto y = lynx::morphine::renderReference (blob, notes, 44100.0, 80000, "");
  7814. CHECK (y.size() == 2 * 80000u);
  7815. 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 } };
  7816. for (const auto& g : golden)
  7817. 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);
  7818. double e = 0.0;
  7819. for (auto v : y)
  7820. e += (double) v * v;
  7821. CHECK (std::abs (std::sqrt (e / (double) y.size()) - 0.18467099041) < 1e-6);
  7822. // the instrument: same engine behind LYNX's channel gains
  7823. lynx::ChannelDef c;
  7824. c.instrument = lynx::InstrumentKind::morphine;
  7825. c.pluginState = blob;
  7826. auto inst = lynx::makeInstrument (lynx::InstrumentKind::morphine);
  7827. inst->configure (c, 120.0);
  7828. inst->prepare (44100.0);
  7829. std::vector<float> l (8192, 0.0f), r (8192, 0.0f);
  7830. for (int b = 0; b < 16; ++b)
  7831. {
  7832. if (b == 0)
  7833. inst->noteOn (60, 0.78125f);
  7834. if (b == 10)
  7835. inst->noteOff (60);
  7836. inst->render (l.data() + 512 * b, r.data() + 512 * b, 512, 1.0f, 1.0f);
  7837. }
  7838. 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, "");
  7839. double diff = 0.0, energy = 0.0;
  7840. for (int i = 0; i < 8192; ++i)
  7841. {
  7842. 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]) });
  7843. energy += (double) l[(std::size_t) i] * l[(std::size_t) i];
  7844. }
  7845. CHECK (diff == 0.0 && energy > 1e-3);
  7846. }
  7847. namespace
  7848. {
  7849. // A MiniSynth state written from scratch (REA_rodada41 §1.1 layout: "SSLF" + the .flms preset)
  7850. std::vector<std::uint8_t> miniSynthTestState (const std::array<float, 43>& P)
  7851. {
  7852. const std::string name = "LYNX test";
  7853. Bytes body;
  7854. body.raw ("\x99" "FLS\r\n\x1a\n", 8);
  7855. body.raw ("HEAD", 4);
  7856. body.i32 (6 + 2 * (std::int32_t) name.size());
  7857. const std::uint16_t head[3] = { 1, 1, (std::uint16_t) name.size() };
  7858. body.raw (reinterpret_cast<const char*> (head), 6);
  7859. for (char ch : name)
  7860. body.raw (&ch, 1), body.zeros (1);
  7861. body.raw ("DATA", 4);
  7862. body.i32 (176);
  7863. body.raw ("0rev", 4);
  7864. for (auto v : P)
  7865. body.f32 (v);
  7866. Bytes s;
  7867. s.raw ("SSLF", 4);
  7868. s.i32 ((std::int32_t) body.b.size());
  7869. s.bytes (body.b);
  7870. return s.b;
  7871. }
  7872. std::array<float, 43> miniSynthDefaults()
  7873. {
  7874. return { 0.375f, 0.5f, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0.5f, 0, 0, 0.25f, 0.5f, 0, 1, 1, 0.07f, 0, 0, 0, 0, 0.7f, 0.5f, 1,
  7875. 0.5f, 0, 0.25f, 0.5f, 0.5f, 0, 0.11222222f, 0.4f, 0.1f, 1, 0.5f };
  7876. }
  7877. // a synthetic oscdata.dat (amplitudes 0.3/k, phases −π/2 + 0.001·(k − 1)): the test does not need an FL installation
  7878. std::string miniSynthTestOscdata()
  7879. {
  7880. const auto path = (std::filesystem::temp_directory_path() / "lynx_test_oscdata.dat").string();
  7881. std::vector<float> d (2048);
  7882. for (int h = 0; h < 1024; ++h)
  7883. d[(std::size_t) h] = (float) (0.3 / (h + 1)), d[1024 + (std::size_t) h] = (float) (-1.5707963267948966 + 0.001 * h);
  7884. std::ofstream out (path, std::ios::binary);
  7885. out.write (reinterpret_cast<const char*> (d.data()), 8192);
  7886. return path;
  7887. }
  7888. } // namespace
  7889. TEST (minisynth_engine)
  7890. {
  7891. auto A = miniSynthDefaults(), B = miniSynthDefaults();
  7892. // A: poly, SQR+SQR, noise, filter env/velocity/keytracking, LFO → cutoff, distortion + decimator, delay, chorus, phaser
  7893. const std::pair<int, float> a[] = { { 5, 0.45f }, { 6, 0.6f }, { 7, 0.4f }, { 8, 0.45f }, { 9, 0.6f }, { 10, 0.5f }, { 11, 0.7f },
  7894. { 12, 0.1f }, { 13, 0.4f }, { 14, 0.3f }, { 15, 0.5f }, { 16, 0.8f }, { 17, 0.6f }, { 18, 0.1f },
  7895. { 19, 0.5f }, { 20, 0.85f }, { 21, 0.05f }, { 22, 0.5f }, { 23, 0.6f }, { 24, 0.4f }, { 25, 1 },
  7896. { 26, 0.3f }, { 27, 0.1f }, { 28, 1 }, { 29, 0.4f }, { 30, 0.5f }, { 31, 0.6f }, { 32, 0.6f },
  7897. { 33, 1 }, { 34, 0.4f }, { 35, 0.6f }, { 36, 0.5f }, { 37, 1 }, { 38, 0.3f }, { 39, 0.6f },
  7898. { 40, 0.5f }, { 41, 0.7f }, { 42, 0.4f } };
  7899. // B: lead (legato glide), BELL, LFO → pitch
  7900. const std::pair<int, float> b[] = { { 0, 1 }, { 2, 0.4f }, { 5, 0.7f }, { 6, 0.3f }, { 7, 0.1f }, { 8, 0.6f }, { 9, 0.3f }, { 16, 0.7f },
  7901. { 17, 0.1f }, { 18, 0.5f }, { 19, 0.6f }, { 20, 0.7f }, { 22, 0.6f }, { 23, 0.5f }, { 24, 0.3f } };
  7902. for (const auto& [i, v] : a)
  7903. A[(std::size_t) i] = v;
  7904. for (const auto& [i, v] : b)
  7905. B[(std::size_t) i] = v;
  7906. const auto blobA = miniSynthTestState (A), blobB = miniSynthTestState (B);
  7907. dumpIfAsked ("LYNX_DUMP_MINISYNTH", blobA);
  7908. CHECK (lynx::miniSynthStateUsable (blobA) && lynx::miniSynthParams (blobA).size() == 43u && lynx::miniSynthParams (blobA)[26] == 0.3f);
  7909. CHECK (lynx::miniSynthParamOffset (blobA, 9) == 8 + 8 + 8 + 6 + 18 + 12 + 4 * 9 && lynx::miniSynthParamOffset (blobA, 43) < 0);
  7910. CHECK (! lynx::miniSynthStateUsable (std::vector<std::uint8_t> (blobA.begin(), blobA.begin() + 20)));
  7911. auto shortData = blobA;
  7912. shortData.resize (shortData.size() - 4 * 40); // only 3 parameters present: the rest keeps the defaults
  7913. CHECK (lynx::miniSynthParams (shortData)[20] == 0.5f && lynx::miniSynthParams (shortData)[1] == 0.5f);
  7914. // golden samples of our round-41 model (msmodel.Plugin on the same synthetic oscdata, 44.1 kHz, host blocks of 512,
  7915. // L = R = Final.Vol): C5 vel 100 0–30000, E5 vel 80 11025–40000, G5 vel 110 22050–52000 (Init.Vol law A)
  7916. const auto osc = miniSynthTestOscdata();
  7917. auto iv = [] (double vel) { return (std::pow (11.0, vel / 100.0) - 1.0) / 10.0; };
  7918. const std::vector<lynx::minisynth::RefNote> notes = { { 0, 60, iv (100), 1.0, 0.0, 0.0, 30000 },
  7919. { 11025, 64, iv (80), 1.0, 0.0, 0.0, 40000 },
  7920. { 22050, 67, iv (110), 1.0, 0.0, 0.0, 52000 } };
  7921. struct Golden { int i; float l, r; };
  7922. static const Golden goldenA[] = { { 100, 0.183149248f, -0.226551995f }, { 5000, -0.00842505973f, 0.254078597f }, { 15000, -0.180335894f, 0.0890596062f }, { 25000, 0.465151846f, 0.396314442f }, { 35000, 0.272939265f, 0.18288976f }, { 45000, -0.127651259f, -0.34875524f }, { 55000, -0.153043061f, -0.248885199f }, { 66000, -0.0197723396f, -0.0807986259f } };
  7923. static const Golden goldenB[] = { { 100, 0.175394624f, 0.175394624f }, { 5000, 0.0503161065f, 0.0503161065f }, { 15000, 0.0470628254f, 0.0470628254f }, { 25000, 0.0486912318f, 0.0486912318f }, { 35000, 0.021853026f, 0.021853026f }, { 45000, 0.0362072662f, 0.0362072662f }, { 55000, -0.000109080342f, -0.000109080342f }, { 66000, 0.0f, 0.0f } };
  7924. for (int which = 0; which < 2; ++which)
  7925. {
  7926. const auto y = lynx::minisynth::renderReference (which == 0 ? blobA : blobB, notes, 44100.0, 66150, osc);
  7927. CHECK (y.size() == 2 * 66150u);
  7928. if (y.size() != 2 * 66150u)
  7929. continue;
  7930. for (const auto& g : which == 0 ? std::vector (std::begin (goldenA), std::end (goldenA)) : std::vector (std::begin (goldenB), std::end (goldenB)))
  7931. CHECK (y[2 * (std::size_t) g.i] == g.l && y[2 * (std::size_t) g.i + 1] == g.r);
  7932. double e = 0.0;
  7933. for (auto v : y)
  7934. e += (double) v * v;
  7935. CHECK (std::abs (std::sqrt (e / (double) y.size()) - (which == 0 ? 0.315552434392 : 0.03926116287)) < 1e-9);
  7936. }
  7937. // missing oscdata.dat: silent tables, still finite
  7938. const auto silent = lynx::minisynth::renderReference (blobB, notes, 44100.0, 4096, "");
  7939. CHECK (silent.size() == 2 * 4096u && std::all_of (silent.begin(), silent.end(), [] (float v) { return std::isfinite (v) && std::abs (v) < 1.0f; }));
  7940. // the instrument: same engine behind LYNX's channel gains (V = 1, centre → law A), velocity → Init.Vol
  7941. lynx::ChannelDef c;
  7942. c.instrument = lynx::InstrumentKind::minisynth;
  7943. c.pluginState = blobA;
  7944. c.samplePath = osc;
  7945. auto inst = lynx::makeInstrument (lynx::InstrumentKind::minisynth);
  7946. inst->configure (c, 120.0);
  7947. inst->prepare (44100.0);
  7948. std::vector<float> l (8192, 0.0f), r (8192, 0.0f);
  7949. for (int k = 0; k < 16; ++k)
  7950. {
  7951. if (k == 0)
  7952. inst->noteOn (60, 0.78125f);
  7953. if (k == 10)
  7954. inst->noteOff (60);
  7955. inst->render (l.data() + 512 * k, r.data() + 512 * k, 512, 1.0f, 1.0f);
  7956. }
  7957. const auto ref = lynx::minisynth::renderReference (blobA, { { 0, 60, (std::pow (11.0, 1.28 * 0.78125) - 1.0) / 10.0, 1.0, 0.0, 0.0, 5120 } },
  7958. 44100.0, 8192, osc, 512, 120.0, 0, -1.0, true);
  7959. double diff = 0.0, energy = 0.0;
  7960. for (int i = 0; i < 8192; ++i)
  7961. {
  7962. 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]) });
  7963. energy += (double) l[(std::size_t) i] * l[(std::size_t) i];
  7964. }
  7965. CHECK (diff == 0.0 && energy > 1e-3 && ! inst->idle());
  7966. }
  7967. namespace
  7968. {
  7969. // A PoiZone state written from scratch (REA_rodada44 §1.3 layout, "Ver4" + 156 floats + name): pulse A synced to saw B,
  7970. // noise, envelope to the cutoff, triangle LFO to oscillator A's pitch, 3-voice unison, gate, chorus and tape delay.
  7971. std::vector<std::uint8_t> poizoneTestState()
  7972. {
  7973. std::array<float, 156> P {};
  7974. const std::pair<int, float> values[] = { { 0, 1.0f }, { 1, 0.7f }, { 2, 1.0f }, { 5, 0.6f }, { 6, 0.75f }, { 7, 0.2f }, { 8, 0.4f }, { 9, 0.1f },
  7975. { 10, 0.8f }, { 11, 0.3f }, { 12, 0.5f }, { 13, 0.4f }, { 14, 0.5f }, { 15, 0.5f }, { 16, 0.5f }, { 17, 0.5f },
  7976. { 18, 0.35f }, { 19, 0.6f }, { 20, 0.5f }, { 21, 0.3f }, { 22, 0.2f }, { 23, 0.6f }, { 24, 0.7f }, { 25, 0.5f },
  7977. { 26, 0.7f }, { 28, 0.6f }, { 29, 0.3f }, { 30, 0.8f }, { 31, 1.0f }, { 32, 0.3f }, { 33, 0.5f }, { 34, 0.5f },
  7978. { 35, 0.3f }, { 37, 1.0f }, { 38, 0.6f }, { 39, 1.0f }, { 40, 0.4f }, { 41, 0.5f }, { 42, 0.5f }, { 43, 0.5f },
  7979. { 47, 0.5f }, { 48, 0.3f }, { 67, 0.2f }, { 68, 0.5f }, { 75, 2.0f }, { 76, 15.0f }, { 77, 1.0f }, { 78, 1.0f },
  7980. { 79, 1.0f } };
  7981. for (const auto& [i, v] : values)
  7982. P[(std::size_t) i] = v;
  7983. for (int i = 49; i < 65; ++i)
  7984. P[(std::size_t) i] = (i - 49) % 3 != 2 ? 1.0f : 0.0f;
  7985. for (int i = 81; i < 155; ++i)
  7986. P[(std::size_t) i] = -1.0f;
  7987. std::vector<std::uint8_t> blob { 'S', 'S', 'L', 'F', 0xb4, 0x02, 0x00, 0x00, '4', 'r', 'e', 'V' };
  7988. blob.resize (12 + 4 * 156 + 64, 0);
  7989. std::memcpy (blob.data() + 12, P.data(), 4 * 156);
  7990. std::memcpy (blob.data() + 12 + 4 * 156, "LYNX test", 9);
  7991. return blob;
  7992. }
  7993. } // namespace
  7994. TEST (poizone_engine)
  7995. {
  7996. const auto blob = poizoneTestState();
  7997. CHECK (lynx::poizoneStateUsable (blob));
  7998. CHECK (lynx::poizoneParamOffset (blob, 18) == 12 + 4 * 18 && lynx::poizoneParamOffset (blob, 156) < 0);
  7999. CHECK (lynx::poizoneParam (blob, 75) == 2.0f && ! lynx::poizoneParam (blob, -1));
  8000. auto broken = blob;
  8001. broken[8] = 'X'; // the "Ver4" tag
  8002. CHECK (! lynx::poizoneStateUsable (broken));
  8003. CHECK (! lynx::poizoneStateUsable (std::vector<std::uint8_t> (blob.begin(), blob.begin() + 10)));
  8004. // golden samples of our round-44 model (pzmodel.Plugin, tempo 120, 44.1 kHz, host blocks of 512, L = R = Final.Vol):
  8005. // C5 vel 100 0–30000, E5 vel 80 11025–40000, G5 vel 110 22050–52000 (Init.Vol = (11^(vel/100) − 1)/10)
  8006. auto iv = [] (double vel) { return (std::pow (11.0, vel / 100.0) - 1.0) / 10.0; };
  8007. const std::vector<lynx::poizone::RefNote> notes = { { 0, 60, iv (100), 1.0, 0.0, 0.0, 30000 },
  8008. { 11025, 64, iv (80), 1.0, 0.0, 0.0, 40000 },
  8009. { 22050, 67, iv (110), 1.0, 0.0, 0.0, 52000 } };
  8010. const auto y = lynx::poizone::renderReference (blob, notes, 44100.0, 66150);
  8011. CHECK (y.size() == 2 * 66150u);
  8012. static const struct { int i; float l, r; } golden[] = { { 100, 0.0058150403f, 0.00038307323f }, { 5000, 0.01855834f, 0.09409425f }, { 15000, -0.01985861f, -0.013393694f }, { 25000, 0.121419534f, -0.12814318f }, { 35000, -0.09936376f, 0.034945987f }, { 45000, -0.09803468f, 0.05587045f }, { 55000, -0.07215294f, 0.02417629f }, { 66000, -0.007312033f, -0.047375992f } };
  8013. for (const auto& g : golden)
  8014. CHECK (std::abs (y[2 * (std::size_t) g.i] - g.l) < 1e-7f && std::abs (y[2 * (std::size_t) g.i + 1] - g.r) < 1e-7f);
  8015. double e = 0.0;
  8016. for (auto v : y)
  8017. e += (double) v * v;
  8018. CHECK (std::abs (std::sqrt (e / (double) y.size()) - 0.10990940878400073) < 1e-7);
  8019. // the instrument: same engine behind LYNX's channel gains (V = 1, centre → law A), velocity → Init.Vol
  8020. lynx::ChannelDef c;
  8021. c.instrument = lynx::InstrumentKind::poizone;
  8022. c.pluginState = blob;
  8023. auto inst = lynx::makeInstrument (lynx::InstrumentKind::poizone);
  8024. inst->configure (c, 120.0);
  8025. inst->prepare (44100.0);
  8026. std::vector<float> l (8192, 0.0f), r (8192, 0.0f);
  8027. for (int b = 0; b < 16; ++b)
  8028. {
  8029. if (b == 0)
  8030. inst->noteOn (60, 0.78125f);
  8031. if (b == 10)
  8032. inst->noteOff (60);
  8033. inst->render (l.data() + 512 * b, r.data() + 512 * b, 512, 1.0f, 1.0f);
  8034. }
  8035. const auto ref = lynx::poizone::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,
  8036. 512, 120.0, 0, true);
  8037. double diff = 0.0, energy = 0.0;
  8038. for (int i = 0; i < 8192; ++i)
  8039. {
  8040. 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]) });
  8041. energy += (double) l[(std::size_t) i] * l[(std::size_t) i];
  8042. }
  8043. CHECK (diff == 0.0 && energy > 1e-3);
  8044. }
  8045. // Workflow P2 (docs/WORKFLOW_FL.md)
  8046. #include "WorkflowP2Tests.inc"