tests.cpp 374 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972
  1. // Core tests (no JUCE). Usage: lynx_tests [folder-with-flp-files]
  2. #include <atomic>
  3. #include <cctype>
  4. #include <cmath>
  5. #include <cstdio>
  6. #include <cstring>
  7. #include <filesystem>
  8. #include <map>
  9. #include <set>
  10. #include <sstream>
  11. #include <fstream>
  12. #include <functional>
  13. #include <iterator>
  14. #include <string>
  15. #include <tuple>
  16. #include <vector>
  17. #include "core/Dither.h"
  18. #include "core/DrumSynthLive.h"
  19. #include "core/Effects.h"
  20. #include "core/Effector.h"
  21. #include "core/FlpImport.h"
  22. #include "core/FlEffects.h"
  23. #include "core/FlPatcher.h"
  24. #include "core/FlSamplers.h"
  25. #include "core/FlSynths.h"
  26. #include "core/Inflate.h"
  27. #include "core/WavPack.h"
  28. #include "core/FlWrapper.h"
  29. #include "core/Gms.h"
  30. #include "core/Harmless.h"
  31. #include "core/Harmor.h"
  32. #include "core/Morphine.h"
  33. #include "core/Ogun.h"
  34. #include "core/HarmlessFx.h"
  35. #include "core/MaximusFx.h"
  36. #include "core/LiveEventQueue.h"
  37. #include "core/RackRenderer.h"
  38. #include "core/Scheduler.h"
  39. #include "core/SnapshotExchange.h"
  40. #include "core/SoftClip.h"
  41. #include "core/Slicer.h"
  42. #include "core/SytrusEngine.h"
  43. #include "core/Templates.h"
  44. #include "core/Vocodex.h"
  45. #include "core/TimeStretch.h"
  46. #include "core/WorkerPool.h"
  47. #include "core/Song.h"
  48. #include "core/NoteEdit.h"
  49. #include "core/Recorder.h"
  50. #include "core/KeyMap.h"
  51. #include "core/RackOps.h"
  52. #include "core/ValueMath.h"
  53. #include "core/Workspace.h"
  54. #include "core/StartupSound.h"
  55. #include "flp/Flp.h"
  56. #include "ui/I18nData.h"
  57. namespace
  58. {
  59. int failures = 0;
  60. int checks = 0;
  61. std::vector<std::pair<const char*, std::function<void()>>>& registry()
  62. {
  63. static std::vector<std::pair<const char*, std::function<void()>>> r;
  64. return r;
  65. }
  66. struct Register
  67. {
  68. Register (const char* name, std::function<void()> fn) { registry().emplace_back (name, std::move (fn)); }
  69. };
  70. #define TEST(name) \
  71. static void name(); \
  72. static Register reg_##name (#name, name); \
  73. static void name()
  74. #define CHECK(cond) \
  75. do \
  76. { \
  77. ++checks; \
  78. if (! (cond)) \
  79. { \
  80. ++failures; \
  81. std::printf (" FAILED %s:%d: %s\n", __FILE__, __LINE__, #cond); \
  82. } \
  83. } while (false)
  84. std::string realFlpDir;
  85. // --- helpers for building synthetic .flp files -----------------------------
  86. struct FlpBuilder
  87. {
  88. std::vector<std::uint8_t> bytes;
  89. FlpBuilder (std::uint16_t ppq = 96)
  90. {
  91. put ("FLhd");
  92. u32 (6);
  93. u16 (0);
  94. u16 (1);
  95. u16 (ppq);
  96. put ("FLdt");
  97. u32 (0); // size is not used by the reader
  98. }
  99. void put (const char* s) { bytes.insert (bytes.end(), s, s + std::strlen (s)); }
  100. void u8 (std::uint8_t v) { bytes.push_back (v); }
  101. void u16 (std::uint16_t v) { u8 ((std::uint8_t) v); u8 ((std::uint8_t) (v >> 8)); }
  102. void u32 (std::uint32_t v) { u16 ((std::uint16_t) v); u16 ((std::uint16_t) (v >> 16)); }
  103. void varint (std::size_t n)
  104. {
  105. do
  106. {
  107. auto b = (std::uint8_t) (n & 0x7F);
  108. n >>= 7;
  109. u8 (n ? (std::uint8_t) (b | 0x80) : b);
  110. } while (n);
  111. }
  112. void data (std::uint8_t id, const std::vector<std::uint8_t>& payload)
  113. {
  114. u8 (id);
  115. varint (payload.size());
  116. bytes.insert (bytes.end(), payload.begin(), payload.end());
  117. }
  118. void ascii (std::uint8_t id, const std::string& s)
  119. {
  120. std::vector<std::uint8_t> p (s.begin(), s.end());
  121. p.push_back (0);
  122. data (id, p);
  123. }
  124. void utf16 (std::uint8_t id, const std::u16string& s)
  125. {
  126. std::vector<std::uint8_t> p;
  127. for (auto c : s)
  128. {
  129. p.push_back ((std::uint8_t) c);
  130. p.push_back ((std::uint8_t) (c >> 8));
  131. }
  132. p.push_back (0);
  133. p.push_back (0);
  134. data (id, p);
  135. }
  136. };
  137. std::vector<std::uint8_t> noteRecord (std::uint32_t pos, std::uint16_t channel, std::uint32_t len, std::uint16_t key,
  138. std::uint8_t velocity)
  139. {
  140. std::vector<std::uint8_t> r (24, 0);
  141. std::memcpy (&r[0], &pos, 4);
  142. std::memcpy (&r[6], &channel, 2);
  143. std::memcpy (&r[8], &len, 4);
  144. std::memcpy (&r[12], &key, 2);
  145. r[16] = 120;
  146. r[20] = 64;
  147. r[21] = velocity;
  148. return r;
  149. }
  150. } // namespace
  151. // ---------------------------------------------------------------------------
  152. // FLP
  153. TEST (flp_rejects_garbage)
  154. {
  155. std::vector<std::uint8_t> junk (64, 0x41);
  156. bool threw = false;
  157. try { flp::EventReader r (junk); } catch (const flp::Error&) { threw = true; }
  158. CHECK (threw);
  159. }
  160. TEST (flp_reads_size_classes_varint_and_extended_ids)
  161. {
  162. FlpBuilder b;
  163. b.u8 (0x15); b.u8 (2); // u8
  164. b.u8 (0x40); b.u16 (513); // u16
  165. b.u8 (0x9C); b.u32 (128500); // u32
  166. b.data (0xD5, std::vector<std::uint8_t> (300, 7)); // 2-byte varint
  167. b.u8 (0xAC); b.u32 (0xC0000100); b.varint (3); b.u8 (1); b.u8 (2); b.u8 (3); // extended ID
  168. flp::EventReader r (b.bytes);
  169. flp::Event e;
  170. CHECK (r.header().ppq == 96);
  171. CHECK (r.next (e) && e.id == 0x15 && e.value == 2);
  172. CHECK (r.next (e) && e.id == 0x40 && e.value == 513);
  173. CHECK (r.next (e) && e.id == 0x9C && e.value == 128500);
  174. CHECK (r.next (e) && e.id == 0xD5 && e.data.size() == 300 && e.data[299] == 7);
  175. CHECK (r.next (e) && e.id == 0xC0000100 && e.isData() && e.data.size() == 3 && e.data[2] == 3);
  176. CHECK (! r.next (e));
  177. }
  178. TEST (flp_truncated_file_throws)
  179. {
  180. FlpBuilder b;
  181. b.u8 (0x9C); b.u8 (1); // u32 with only 1 byte
  182. flp::EventReader r (b.bytes);
  183. flp::Event e;
  184. bool threw = false;
  185. try { r.next (e); } catch (const flp::Error&) { threw = true; }
  186. CHECK (threw);
  187. }
  188. TEST (flp_version_numbers)
  189. {
  190. CHECK (flp::parseVersionNumber ("25.2.5.5319") == 25002005u);
  191. CHECK (flp::parseVersionNumber ("20.99.3000.3031") == 20102000u);
  192. CHECK (flp::parseVersionNumber ("11.0.3") == 11000003u);
  193. }
  194. TEST (flp_playlist_record_size_by_version)
  195. {
  196. CHECK (flp::playlistRecordSize (12009003, 64) == 32);
  197. CHECK (flp::playlistRecordSize (21000000, 120) == 60);
  198. CHECK (flp::playlistRecordSize (25002005, 160) == 80);
  199. CHECK (flp::playlistRecordSize (25002005, 60) == 60); // size doesn't match the version -> tries the others
  200. CHECK (flp::playlistRecordSize (25002005, 7) == 0);
  201. }
  202. TEST (flp_parses_project_model)
  203. {
  204. FlpBuilder b (96);
  205. b.ascii (0xC7, "25.2.5.5319");
  206. b.u8 (0x9C); b.u32 (174500);
  207. b.utf16 (0xC2, u"Título");
  208. b.u8 (0x41); b.u16 (3);
  209. b.u8 (0x96); b.u32 (0x00A14547); // BGR in the file
  210. auto notes = noteRecord (96, 1, 48, 64, 100);
  211. auto n2 = noteRecord (0, 0, 0, 60, 128);
  212. notes.insert (notes.end(), n2.begin(), n2.end());
  213. b.data (0xE0, notes);
  214. b.u8 (0x40); b.u16 (0);
  215. b.u8 (0x15); b.u8 (0);
  216. b.utf16 (0xCB, u"Kick");
  217. {
  218. std::vector<std::uint8_t> levels (24, 0);
  219. const std::int32_t lv[] = { 3200, 12800, -150 };
  220. std::memcpy (levels.data(), lv, sizeof (lv));
  221. b.data (0xDB, levels);
  222. }
  223. b.u8 (0x68); b.u16 (5);
  224. b.u8 (0x40); b.u16 (1);
  225. b.u8 (0x15); b.u8 (2);
  226. b.utf16 (0xC9, u"FLEX");
  227. b.utf16 (0xCB, u"Lead");
  228. b.u8 (0x63); b.u16 (0);
  229. std::vector<std::uint8_t> item (80, 0);
  230. std::uint32_t pos = 384, len = 768;
  231. std::uint16_t base = 20480, idx = 20480 + 3, rv = 499 - 2;
  232. std::memcpy (&item[0], &pos, 4);
  233. std::memcpy (&item[4], &base, 2);
  234. std::memcpy (&item[6], &idx, 2);
  235. std::memcpy (&item[8], &len, 4);
  236. std::memcpy (&item[12], &rv, 2);
  237. b.data (0xE9, item);
  238. b.utf16 (0xCC, u"Drums");
  239. b.data (0xEC, std::vector<std::uint8_t> (12, 0));
  240. b.data (0xEC, std::vector<std::uint8_t> (12, 0));
  241. const auto p = flp::parseProject (b.bytes);
  242. CHECK (p.version == "25.2.5.5319");
  243. CHECK (std::abs (p.tempo - 174.5) < 1e-9);
  244. CHECK (p.title == "Título");
  245. CHECK (p.channels.size() == 2);
  246. CHECK (p.channels[0].name == "Kick" && p.channels[0].mixerTrack == 5);
  247. CHECK (p.channels[0].hasLevels && p.channels[0].pan == 3200 && p.channels[0].volume == 12800 && p.channels[0].pitchCents == -150);
  248. CHECK (p.channels[1].type == flp::ChannelType::instrument && p.channels[1].pluginName == "FLEX");
  249. CHECK (p.patterns.size() == 1 && p.patterns[0].index == 3);
  250. CHECK (p.patterns[0].colour && *p.patterns[0].colour == 0x4745A1);
  251. CHECK (p.patterns[0].notes.size() == 2 && p.patterns[0].notes[0].position == 0); // sorted
  252. CHECK (p.patterns[0].notes[1].key == 64 && p.patterns[0].notes[1].length == 48);
  253. CHECK (p.arrangements.size() == 1 && p.arrangements[0].items.size() == 1);
  254. const auto& it = p.arrangements[0].items[0];
  255. CHECK (it.kind == flp::PlaylistItem::Kind::pattern && it.index == 3 && it.track == 2 && it.position == 384);
  256. CHECK (p.mixer.size() == 2 && p.mixer[0].name == "Drums" && p.mixer[1].name.empty());
  257. CHECK (p.warnings.empty());
  258. }
  259. TEST (flp_fuzz_corrupted_files_do_not_crash)
  260. {
  261. if (realFlpDir.empty())
  262. return;
  263. // some real .flp files, corrupted in various ways: the parser may reject them (flp::Error), but
  264. // must never hang, read past the buffer or produce a Song with invalid indices
  265. std::vector<std::vector<std::uint8_t>> sources;
  266. for (auto& entry : std::filesystem::recursive_directory_iterator (realFlpDir))
  267. if (entry.path().extension() == ".flp" && sources.size() < 6 && std::filesystem::file_size (entry.path()) < 3'000'000)
  268. {
  269. std::ifstream in (entry.path(), std::ios::binary);
  270. sources.emplace_back ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  271. }
  272. std::uint32_t seed = 2024;
  273. auto rnd = [&] (std::uint32_t n) { seed = seed * 1664525u + 1013904223u; return n == 0 ? 0u : (seed >> 8) % n; };
  274. int parsed = 0, rejected = 0;
  275. for (int round = 0; round < 240 && ! sources.empty(); ++round)
  276. {
  277. auto bytes = sources[(std::size_t) rnd ((std::uint32_t) sources.size())];
  278. switch (round % 4)
  279. {
  280. case 0: bytes.resize (rnd ((std::uint32_t) bytes.size())); break; // truncated
  281. 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;
  282. case 2: // absurd event size
  283. for (int k = 0; k < 5; ++k)
  284. bytes[(std::size_t) rnd ((std::uint32_t) bytes.size())] = 0xFF;
  285. break;
  286. default: // shuffled block
  287. {
  288. const auto a = rnd ((std::uint32_t) bytes.size()), b = rnd ((std::uint32_t) bytes.size());
  289. std::reverse (bytes.begin() + std::min (a, b), bytes.begin() + std::max (a, b));
  290. break;
  291. }
  292. }
  293. try
  294. {
  295. const auto project = flp::parseProject (bytes);
  296. const auto song = lynx::importFlp (project);
  297. ++parsed;
  298. for (const auto& p : song.patterns)
  299. for (const auto& n : p.notes)
  300. CHECK (n.channel >= 0 && n.channel < (int) song.channels.size());
  301. for (const auto& c : song.playlist)
  302. CHECK (c.kind != lynx::ClipKind::pattern || (c.pattern >= 0 && c.pattern < (int) song.patterns.size()));
  303. }
  304. catch (const flp::Error&)
  305. {
  306. ++rejected;
  307. }
  308. }
  309. std::printf (" fuzz: %d imported, %d rejected\n", parsed, rejected);
  310. CHECK (parsed + rejected == 240);
  311. }
  312. TEST (plugin_state_decoders_survive_garbage)
  313. {
  314. // random blobs (varied sizes, including valid headers followed by garbage)
  315. std::uint32_t seed = 77;
  316. auto rnd = [&] { seed = seed * 1664525u + 1013904223u; return seed >> 8; };
  317. const char* plugins[] = { "Fruity Parametric EQ 2", "Fruity Limiter", "Fruity Reeverb 2", "Fruity Delay 2", "Fruity Delay 3",
  318. "Fruity Compressor", "Fruity Balance", "Fruity PanOMatic", "Fruity Stereo Shaper", "Fruity Phase Inverter" };
  319. int decoded = 0;
  320. for (int round = 0; round < 3000; ++round)
  321. {
  322. std::vector<std::uint8_t> blob ((std::size_t) (rnd() % 600));
  323. for (auto& b : blob)
  324. b = (std::uint8_t) rnd();
  325. if (blob.size() >= 4 && round % 3 == 0) // versions the readers accept
  326. {
  327. const std::uint32_t versions[] = { 8, 10001, 10000, 12, 14, 6, 1 };
  328. const auto v = versions[rnd() % 7];
  329. std::memcpy (blob.data(), &v, 4);
  330. }
  331. if (auto fx = lynx::effectFromFl (plugins[rnd() % 10], blob))
  332. {
  333. ++decoded;
  334. for (auto v : fx->params)
  335. CHECK (std::isfinite (v) && v >= 0.0f && v <= 1.0f);
  336. }
  337. lynx::SynthSettings synth;
  338. if (lynx::synthFrom3xOsc (blob, synth))
  339. for (const auto& o : synth.osc)
  340. CHECK (std::isfinite (o.level) && o.level >= 0.0f && o.level <= 1.0f);
  341. float harmlessGain = 1.0f;
  342. if (lynx::synthFromHarmless (blob, 120.0, synth, harmlessGain))
  343. CHECK (std::isfinite (harmlessGain) && std::isfinite (synth.cutoff) && std::isfinite (synth.attack));
  344. if (lynx::synthFromFruitKick (blob, synth))
  345. CHECK (std::isfinite (synth.decay) && std::isfinite (synth.pitchEnv.amount));
  346. if (lynx::synthFromGms (blob, 120.0, synth, harmlessGain) || lynx::synthFromHarmor (blob, synth, harmlessGain) || lynx::synthFromOgun (blob, synth, harmlessGain)
  347. || lynx::synthFromSakura (blob, synth) || lynx::synthFromKepler (blob, synth, harmlessGain))
  348. CHECK (std::isfinite (synth.cutoff) && std::isfinite (synth.attack) && std::isfinite (harmlessGain));
  349. if (auto sound = lynx::drumSynthLiveSound (blob))
  350. CHECK (sound->size() < 256);
  351. if (auto wave = lynx::waveTravellerSample (blob))
  352. CHECK (! wave->first.empty() && wave->second >= 0 && wave->second <= 127);
  353. lynx::synthFromBooBass (blob, synth);
  354. lynx::gmsStateUsable (blob); // (the exact engines' parsers reject garbage without crashing)
  355. lynx::morphineStateUsable (blob);
  356. if (lynx::synthFromPoiZone (blob, synth, harmlessGain) || lynx::synthFromBassDrum (blob, synth, harmlessGain) || lynx::synthFromToxic (blob, synth, harmlessGain)
  357. || lynx::synthFromMorphine (blob, synth, harmlessGain))
  358. CHECK (std::isfinite (synth.cutoff) && std::isfinite (harmlessGain));
  359. if (auto patch = lynx::drumpadPatchName (blob))
  360. CHECK (patch->size() <= 0x30 && std::isfinite (lynx::drumToneForName (*patch).decay));
  361. if (auto flex = lynx::flexPresetName (blob))
  362. CHECK ((! flex->first.empty() || ! flex->second.empty()) && flex->second.size() <= 1024);
  363. if (lynx::synthFromSytrus (blob, 120.0, synth, harmlessGain))
  364. CHECK (std::isfinite (synth.cutoff) && std::isfinite (synth.attack));
  365. if (lynx::synthFromDX10 (blob, synth))
  366. CHECK (std::isfinite (synth.decay) && std::isfinite (synth.release) && std::isfinite (synth.osc[1].level));
  367. if (blob.size() >= 4 && round % 5 == 0) // MiniSynth header followed by garbage
  368. {
  369. std::memcpy (blob.data(), "SSLF", 4);
  370. if (blob.size() > 220)
  371. {
  372. std::memcpy (blob.data() + 40, "DATA", 4);
  373. std::memcpy (blob.data() + 48, "0rev", 4);
  374. }
  375. }
  376. if (lynx::synthFromMiniSynth (blob, 120.0, synth))
  377. CHECK (std::isfinite (synth.cutoff) && std::isfinite (synth.decay) && std::isfinite (synth.attack));
  378. lynx::ForeignPlugin foreign;
  379. lynx::parseFlWrapper (blob, foreign);
  380. std::vector<std::uint8_t> component, controller;
  381. lynx::splitFlVst3State (blob, component, controller);
  382. }
  383. CHECK (decoded == 3000); // every known name yields an effect (default when the blob is unusable)
  384. }
  385. TEST (inflate_zlib)
  386. {
  387. // fixed Huffman with back-references
  388. const std::uint8_t fixed[] = { 0x78, 0xda, 0x4b, 0x4c, 0x4a, 0x4e, 0xc4, 0x86, 0x22, 0x00, 0x7c, 0x69, 0x09, 0x89 };
  389. const auto a = lynx::inflateZlib (fixed, sizeof (fixed));
  390. CHECK (a && std::string (a->begin(), a->end()) == "abcabcabcabcabcabcabcabcX");
  391. // stored (uncompressed) block
  392. const std::uint8_t stored[] = { 0x78, 0x01, 0x01, 0x03, 0x00, 0xfc, 0xff, 'L', 'Y', 'N', 0x00, 0x00, 0x00, 0x00 };
  393. const auto b = lynx::inflateZlib (stored, sizeof (stored));
  394. CHECK (b && std::string (b->begin(), b->end()) == "LYN");
  395. // truncated, bad header and size limit
  396. CHECK (! lynx::inflateZlib (fixed, 6));
  397. const std::uint8_t bad[] = { 0x12, 0x34, 0x00 };
  398. CHECK (! lynx::inflateZlib (bad, sizeof (bad)));
  399. CHECK (! lynx::inflateZlib (fixed, sizeof (fixed), false, 10));
  400. }
  401. TEST (fl_round15_effects_convert_known_values)
  402. {
  403. auto blob = [] (std::vector<std::int32_t> words) {
  404. std::vector<std::uint8_t> b (words.size() * 4);
  405. std::memcpy (b.data(), words.data(), b.size());
  406. return b;
  407. };
  408. // Frequency Shifter "+800 Hz": frequency 51542 in the 20 kHz range, 100% wet
  409. const auto fs = lynx::effectFromFl ("Frequency Shifter", blob ({ 4, 10000, 0, 51542, 0, 10000, 10000, 5000, 10000, 0, 5000, 0, 0 }));
  410. CHECK (fs && fs->kind == lynx::EffectKind::freqShift);
  411. if (fs)
  412. {
  413. const auto x = (fs->params[0] - 0.5) * 2.0;
  414. CHECK (std::abs (2000.0 * x * std::abs (x) - 800.0) < 10.0);
  415. CHECK (std::abs (fs->params[1] - 1.0f) < 1e-4f);
  416. }
  417. // Emphasis: input 0.0625 (= +1.5 dB) and ceiling 0.9308 (≈ −1.6 dB) -> limiter
  418. const auto em = lynx::effectFromFl ("Emphasis", blob ({ 8, 0, 0, 2, 1, 0, 0, 625, 10000, 10000, 9308, 0, 2, 7, 0 }));
  419. CHECK (em && em->kind == lynx::EffectKind::limiter && em->enabled);
  420. if (em)
  421. {
  422. CHECK (std::abs (em->params[1] * 24.0f - 1.5f) < 0.05f);
  423. CHECK (std::abs (em->params[0] * 12.0f - 12.0f + 1.6f) < 0.1f);
  424. }
  425. // Pitch Shifter +12 st, mix 100%
  426. 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 }));
  427. CHECK (ps && ps->kind == lynx::EffectKind::pitchShift && std::abs (ps->params[0] - (0.5f + 12.0f / 48.0f)) < 1e-4f);
  428. }
  429. TEST (frequency_shifter_moves_spectrum_by_hz)
  430. {
  431. auto fx = lynx::makeEffect (lynx::EffectKind::freqShift);
  432. fx->prepare (48000.0);
  433. auto slot = lynx::makeEffectSlot (lynx::EffectKind::freqShift);
  434. // +200 Hz: x·|x|·2000 = 200 -> x = sqrt(0.1)
  435. slot.params[0] = (float) (0.5 + std::sqrt (0.1) / 2.0);
  436. std::vector<float> l (48000), r (48000);
  437. for (int i = 0; i < 48000; ++i)
  438. l[(std::size_t) i] = r[(std::size_t) i] = (float) std::sin (2.0 * 3.141592653589793 * 1000.0 * i / 48000.0);
  439. for (int done = 0; done < 48000; done += 480)
  440. fx->process (l.data() + done, r.data() + done, 480, slot.params, 120.0);
  441. auto energy = [&] (double f) {
  442. const auto w = 2.0 * 3.141592653589793 * f / 48000.0, k = 2.0 * std::cos (w);
  443. double s1 = 0.0, s2 = 0.0;
  444. for (int i = 9600; i < 48000; ++i)
  445. {
  446. const auto s0 = l[(std::size_t) i] + k * s1 - s2;
  447. s2 = s1;
  448. s1 = s0;
  449. }
  450. return s1 * s1 + s2 * s2 - k * s1 * s2;
  451. };
  452. // the energy moves to 1200 Hz; little remains at 1000 and almost nothing at the image (800)
  453. CHECK (energy (1200.0) > 50.0 * energy (1000.0));
  454. CHECK (energy (1200.0) > 50.0 * energy (800.0));
  455. }
  456. TEST (pitch_shift_moves_frequency_keeps_length)
  457. {
  458. auto fx = lynx::makeEffect (lynx::EffectKind::pitchShift);
  459. fx->prepare (48000.0);
  460. auto slot = lynx::makeEffectSlot (lynx::EffectKind::pitchShift);
  461. auto crossingsAfter = [&] (float semitoneParam) {
  462. fx->reset();
  463. slot.params[0] = semitoneParam;
  464. std::vector<float> l (48000), r (48000);
  465. for (int i = 0; i < 48000; ++i)
  466. l[(std::size_t) i] = r[(std::size_t) i] = (float) std::sin (2.0 * 3.141592653589793 * 220.0 * i / 48000.0);
  467. for (int done = 0; done < 48000; done += 512)
  468. fx->process (l.data() + done, r.data() + done, std::min (512, 48000 - done), slot.params, 120.0);
  469. int crossings = 0;
  470. for (int i = 9600; i < 48000; ++i)
  471. crossings += (l[(std::size_t) i - 1] < 0.0f) != (l[(std::size_t) i] < 0.0f);
  472. for (auto v : l)
  473. CHECK (std::isfinite (v) && std::abs (v) < 1.6f);
  474. return crossings / 0.8 / 2.0; // cycles per second
  475. };
  476. CHECK (std::abs (crossingsAfter (0.5f) - 220.0) < 8.0); // 0 st
  477. CHECK (std::abs (crossingsAfter (0.5f + 12.0f / 48.0f) - 440.0) < 25.0); // +12 st
  478. CHECK (std::abs (crossingsAfter (0.5f - 12.0f / 48.0f) - 110.0) < 12.0); // −12 st
  479. }
  480. TEST (volume_gate_follows_bar_position)
  481. {
  482. auto fx = lynx::makeEffect (lynx::EffectKind::volumeGate);
  483. fx->prepare (48000.0);
  484. auto slot = lynx::makeEffectSlot (lynx::EffectKind::volumeGate);
  485. for (int i = 0; i < 32; ++i)
  486. slot.params[(std::size_t) i] = i < 16 ? 1.0f : 0.0f; // first two beats open, two closed
  487. slot.params[33] = slot.params[34] = 0.0f; // no smoothing
  488. // 120 BPM: one beat = 0.5 s = 24000 samples; the 4-beat bar starts at tick 0
  489. std::vector<float> l (96000, 1.0f), r (96000, 1.0f);
  490. fx->setSongPosition (0.0);
  491. for (int done = 0; done < 96000; done += 512)
  492. fx->process (l.data() + done, r.data() + done, std::min (512, 96000 - done), slot.params, 120.0);
  493. CHECK (l[10000] > 0.99f && l[40000] > 0.99f); // beats 1 and 2
  494. CHECK (l[60000] < 0.01f && l[90000] < 0.01f); // beats 3 and 4
  495. // starting mid-bar (beat 3): already closed
  496. std::vector<float> l2 (4800, 1.0f), r2 (4800, 1.0f);
  497. fx->reset();
  498. fx->setSongPosition (2.0 * lynx::ppq);
  499. fx->process (l2.data(), r2.data(), 4800, slot.params, 120.0);
  500. CHECK (l2[4000] < 0.01f);
  501. // mix 0: transparent
  502. slot.params[32] = 0.0f;
  503. std::vector<float> l3 (4800, 1.0f), r3 (4800, 1.0f);
  504. fx->setSongPosition (2.0 * lynx::ppq);
  505. fx->process (l3.data(), r3.data(), 4800, slot.params, 120.0);
  506. CHECK (l3[4000] > 0.99f);
  507. }
  508. TEST (patcher_branch_heads_follow_rea)
  509. {
  510. auto words = [] (std::vector<std::int32_t> v) {
  511. std::vector<std::uint8_t> b (v.size() * 4);
  512. std::memcpy (b.data(), v.data(), b.size());
  513. return b;
  514. };
  515. // Frequency Splitter, 2 bands, destinations 1/2/3, slope combo 3 (24 dB/oct), high send −6 dB
  516. std::vector<std::int32_t> fs (18, 0);
  517. fs[0] = 4;
  518. fs[1] = 32768;
  519. fs[3] = 3;
  520. fs[6] = 0;
  521. fs[11] = -600;
  522. fs[15] = 1;
  523. fs[16] = 2;
  524. fs[17] = 3;
  525. const auto split = words (fs);
  526. const auto low = lynx::patcherBranchHead ("Frequency Splitter", split, 1);
  527. CHECK (low.valid && low.slot && low.note.empty());
  528. if (low.slot)
  529. {
  530. // low band = just the Crossover low-pass, combo 3 (24 dB/oct)
  531. CHECK (low.slot->kind == lynx::EffectKind::crossover && low.slot->params[0] == 0.0f && low.slot->params[3] == 1.0f);
  532. CHECK (std::lround (low.slot->params[5] * 7.0f) == 3);
  533. }
  534. const auto mid = lynx::patcherBranchHead ("Frequency Splitter", split, 2);
  535. CHECK (mid.valid && mid.gain == 0.0f); // with 2 bands the mid is silent
  536. const auto high = lynx::patcherBranchHead ("Frequency Splitter", split, 3);
  537. CHECK (high.valid && std::abs (high.gain - std::pow (10.0f, -6.0f / 20.0f)) < 1e-4f);
  538. CHECK (! lynx::patcherBranchHead ("Frequency Splitter", split, 7).valid);
  539. // Stereo Shaper with identity matrix: the difference (destination 4) is zero
  540. const auto shaper = words ({ 3, 0, 12800, 12800, 0, 0, 0, 4, 0 });
  541. const auto diff = lynx::patcherBranchHead ("Fruity Stereo Shaper", shaper, 4);
  542. 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);
  543. CHECK (! lynx::patcherBranchHead ("Fruity Stereo Shaper", shaper, 2).valid);
  544. }
  545. TEST (parallel_container_sums_branches)
  546. {
  547. // two branches: dry with gain 0.5 and a utility that flips phase (matrix −1) with gain 0.5 -> silence
  548. auto slot = lynx::makeEffectSlot (lynx::EffectKind::parallel);
  549. lynx::EffectBranch dry;
  550. dry.gain = 0.5f;
  551. lynx::EffectBranch inverted;
  552. inverted.gain = 0.5f;
  553. auto flip = lynx::makeEffectSlot (lynx::EffectKind::utility);
  554. flip.params[2] = flip.params[5] = 0.25f; // (−1 + 2)/4
  555. inverted.chain.push_back (flip);
  556. slot.branches = { dry, inverted };
  557. auto fx = lynx::makeParallelEffect (slot);
  558. fx->prepare (48000.0);
  559. std::vector<float> l (9000, 0.8f), r (9000, -0.4f);
  560. fx->process (l.data(), r.data(), 9000, slot.params, 120.0);
  561. CHECK (std::abs (l[100]) < 1e-5f && std::abs (r[8999]) < 1e-5f);
  562. // only the dry branch with gain 2: doubles
  563. slot.branches = { lynx::EffectBranch { {}, 2.0f } };
  564. auto doubler = lynx::makeParallelEffect (slot);
  565. doubler->prepare (48000.0);
  566. std::fill (l.begin(), l.end(), 0.25f);
  567. doubler->process (l.data(), r.data(), 9000, slot.params, 120.0);
  568. CHECK (std::abs (l[5000] - 0.5f) < 1e-6f);
  569. }
  570. TEST (fl_controller_constant_outputs)
  571. {
  572. std::vector<std::int32_t> xy { 2, 32768, 0, 65536, 0, 16384, 0, 65536, 0, 1024, 256 };
  573. std::vector<std::uint8_t> blob (xy.size() * 4 + 8, 0);
  574. std::memcpy (blob.data(), xy.data(), xy.size() * 4);
  575. CHECK (std::abs (lynx::controllerConstantOutput ("Fruity X-Y Controller", blob, 0).value_or (-1.0f) - 0.5f) < 1e-4f);
  576. CHECK (std::abs (lynx::controllerConstantOutput ("Fruity X-Y Controller", blob, 1).value_or (-1.0f) - 0.25f) < 1e-4f);
  577. // Control Surface: version + group { 0x836: value 0.75, -, output 2 }
  578. std::vector<std::uint8_t> cs (4, 0);
  579. cs[0] = 1;
  580. auto chunk = [] (std::vector<std::uint8_t>& out, std::uint32_t id, const std::vector<std::uint8_t>& body) {
  581. const auto size = (std::uint64_t) body.size();
  582. out.insert (out.end(), reinterpret_cast<const std::uint8_t*> (&id), reinterpret_cast<const std::uint8_t*> (&id) + 4);
  583. out.insert (out.end(), reinterpret_cast<const std::uint8_t*> (&size), reinterpret_cast<const std::uint8_t*> (&size) + 8);
  584. out.insert (out.end(), body.begin(), body.end());
  585. };
  586. std::vector<std::uint8_t> value (12, 0);
  587. const float v = 0.75f;
  588. const std::int32_t out = 2;
  589. std::memcpy (value.data(), &v, 4);
  590. std::memcpy (value.data() + 8, &out, 4);
  591. std::vector<std::uint8_t> group;
  592. chunk (group, 0x836, value);
  593. chunk (cs, 0, group);
  594. CHECK (std::abs (lynx::controllerConstantOutput ("Control Surface", cs, 2).value_or (-1.0f) - 0.75f) < 1e-6f);
  595. CHECK (! lynx::controllerConstantOutput ("Control Surface", cs, 0).has_value());
  596. }
  597. TEST (flp_midi_out_notes_reach_wrapper_on_same_port)
  598. {
  599. auto record = [] (std::vector<std::uint8_t>& out, std::uint32_t id, std::vector<std::uint8_t> body) {
  600. const auto size = (std::uint64_t) body.size();
  601. out.insert (out.end(), reinterpret_cast<const std::uint8_t*> (&id), reinterpret_cast<const std::uint8_t*> (&id) + 4);
  602. out.insert (out.end(), reinterpret_cast<const std::uint8_t*> (&size), reinterpret_cast<const std::uint8_t*> (&size) + 8);
  603. out.insert (out.end(), body.begin(), body.end());
  604. };
  605. auto i32s = [] (std::vector<std::int32_t> v) {
  606. std::vector<std::uint8_t> b (v.size() * 4);
  607. std::memcpy (b.data(), v.data(), b.size());
  608. return b;
  609. };
  610. flp::Project p;
  611. flp::Channel midiOut;
  612. midiOut.index = 0;
  613. midiOut.type = flp::ChannelType::native;
  614. midiOut.pluginName = "MIDI Out";
  615. midiOut.pluginState = i32s ({ 7, 0, -1, -1, -1, 0, 3, 0 }); // channel 1, port 3 (@24)
  616. flp::Channel wrapper;
  617. wrapper.index = 1;
  618. wrapper.type = flp::ChannelType::native;
  619. wrapper.pluginName = "Fruity Wrapper";
  620. wrapper.pluginState = i32s ({ 9 });
  621. record (wrapper.pluginState, 0x32, i32s ({ 7 })); // VST3
  622. record (wrapper.pluginState, 0x01, i32s ({ 3, -1, 0, 0, 0 })); // input port 3
  623. p.channels = { midiOut, wrapper };
  624. flp::Pattern pattern;
  625. pattern.index = 1;
  626. flp::Note note;
  627. note.channel = 0;
  628. note.key = 64;
  629. note.length = 96;
  630. pattern.notes.push_back (note);
  631. p.patterns.push_back (pattern);
  632. const auto song = lynx::importFlp (p);
  633. CHECK (song.channels.size() == 2 && song.channels[0].muted);
  634. CHECK (song.channels[1].plugin.foreign.midiInPort == 3);
  635. int toWrapper = 0;
  636. for (const auto& pat : song.patterns)
  637. for (const auto& n : pat.notes)
  638. toWrapper += n.channel == 1 && n.key == 64;
  639. CHECK (toWrapper == 1);
  640. }
  641. TEST (flp_effect_automation_follows_slots_and_params)
  642. {
  643. // track 1: slot 0 with an effect that has no equivalent (dropped), slot 2 with Parametric EQ 2
  644. flp::Project p;
  645. flp::MixerInsert insert;
  646. insert.index = 1;
  647. insert.slots.push_back ({ 0, "Some Unknown FX", {} });
  648. insert.slots.push_back ({ 2, "Fruity Parametric EQ 2", {} });
  649. p.mixer.push_back (insert);
  650. auto clip = [&] (int index, std::uint32_t target) {
  651. flp::Channel c;
  652. c.index = index;
  653. c.type = flp::ChannelType::automationClip;
  654. c.automation = { { 0.0, 0.0 }, { 96.0, 1.0 } };
  655. p.channels.push_back (c);
  656. p.automationLinks.push_back ({ index, { target } });
  657. };
  658. 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; };
  659. clip (0, mixer (1, 2, 0x8000 + 7)); // EQ band 1 frequency
  660. clip (1, mixer (1, 2, 0x1F01)); // EQ slot mix
  661. clip (2, mixer (1, 0, 0x8000)); // parameter of the dropped effect
  662. clip (3, mixer (1, 2, 0x8000 + 21)); // band type: no equivalent
  663. const auto song = lynx::importFlp (p);
  664. CHECK (song.automations.size() == 4);
  665. CHECK (song.mixer[1].effects.size() == 1 && song.mixer[1].effects[0].kind == lynx::EffectKind::parametricEq);
  666. const auto& freq = song.automations[0];
  667. CHECK (freq.target.kind == lynx::AutomationTargetKind::effectParam && freq.target.index == 1 && freq.target.slot == 0);
  668. CHECK (freq.target.param == lynx::peq::param (0, 1));
  669. // FL's 0..1 (20 Hz..20 kHz) becomes our frequency scale
  670. CHECK (std::abs (freq.points.front().value - lynx::peq::hzValue (20.0)) < 1e-4f);
  671. CHECK (std::abs (freq.points.back().value - lynx::peq::hzValue (20000.0)) < 1e-4f);
  672. CHECK (song.automations[1].target.kind == lynx::AutomationTargetKind::effectMix && song.automations[1].target.slot == 0);
  673. CHECK (song.automations[2].target.kind == lynx::AutomationTargetKind::none);
  674. CHECK (song.automations[3].target.kind == lynx::AutomationTargetKind::none);
  675. // the automated mix is read/written through the target
  676. auto copy = song;
  677. CHECK (copy.setTargetValue (song.automations[1].target, 0.25f) && std::abs (copy.mixer[1].effects[0].mix - 0.25f) < 1e-6f);
  678. CHECK (std::abs (copy.targetValue (song.automations[1].target) - 0.25f) < 1e-6f);
  679. }
  680. TEST (flp_real_files)
  681. {
  682. if (realFlpDir.empty())
  683. {
  684. std::printf (" (skipped: pass a folder with .flp files as argument)\n");
  685. return;
  686. }
  687. int files = 0, withNotes = 0, withPlaylist = 0, automations = 0, automationsWithTarget = 0, sends = 0;
  688. int threeOsc = 0, threeOscDecoded = 0, wrapped = 0, wrappedParsed = 0, markers = 0, signatures = 0, trackEqs = 0;
  689. int harmless = 0, harmlessDecoded = 0, harmlessParsed = 0, harmlessKind = 0, sytrus = 0, sytrusDecoded = 0, sytrusEngine = 0, sytrusRendered = 0,
  690. sytrusSounding = 0;
  691. int harmor = 0, harmorUsable = 0, harmorKind = 0, harmorSounding = 0;
  692. int gms = 0, gmsUsable = 0, gmsKind = 0, gmsSounding = 0, morphine = 0, morphineUsable = 0, morphineKind = 0, morphineSounding = 0, demoGoldens = 0;
  693. int ogun = 0, ogunUsable = 0, ogunKind = 0, ogunSounding = 0;
  694. std::map<std::string, std::pair<int, int>> generators; // GMS/Ogun/Autogun/Sakura/DrumSynth: channels, decoded
  695. int ogunTrumpet = 0; // Ogun channels whose spectrum matches the REA "Trumpet" reference
  696. int peqSlots = 0, peqShaped = 0, reverbs = 0, reverbsDryless = 0, reverbsLowCut = 0;
  697. int dwChannels = 0, dwZones = 0, fpcKits = 0, padChannels = 0, padNotes = 0;
  698. int harmlessCompWanted = 0, harmlessCompLoaded = 0; // Harmless rack compressors / presets read from the installation
  699. int maximusSlots = 0, maximusExact = 0, sgzSlots = 0, sgzExact = 0, vocodexSlots = 0, vocodexWithData = 0; // REA_rodada40
  700. // import with the installation's samples (realFlpDir is ...\Data): for DirectWave/FPC
  701. lynx::FlpImportOptions withFiles;
  702. const auto flRoot = std::filesystem::path (realFlpDir).parent_path().string();
  703. withFiles.roots = { flRoot, realFlpDir, "" };
  704. withFiles.fileExists = [] (const std::string& path) {
  705. auto local = path;
  706. std::replace (local.begin(), local.end(), '\\', '/');
  707. return std::filesystem::exists (local);
  708. };
  709. withFiles.readFile = [] (const std::string& path) {
  710. auto local = path;
  711. std::replace (local.begin(), local.end(), '\\', '/');
  712. std::ifstream in (local, std::ios::binary);
  713. return std::vector<std::uint8_t> ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  714. };
  715. int embeddedSaved = 0;
  716. withFiles.saveEmbedded = [&embeddedSaved] (const std::vector<std::uint8_t>& wav, const std::string&) {
  717. ++embeddedSaved;
  718. return wav.size() > 44 ? std::string ("embutido.wav") : std::string();
  719. };
  720. int slicedChannels = 0, flKeysChannels = 0;
  721. for (auto& entry : std::filesystem::recursive_directory_iterator (realFlpDir))
  722. {
  723. if (entry.path().extension() != ".flp")
  724. continue;
  725. std::ifstream in (entry.path(), std::ios::binary);
  726. std::vector<std::uint8_t> bytes ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  727. ++files;
  728. try
  729. {
  730. const auto p = flp::parseProject (bytes);
  731. CHECK (! p.version.empty());
  732. CHECK (p.tempo > 10.0 && p.tempo < 1000.0);
  733. const auto song = lynx::importFlp (p);
  734. CHECK (! song.patterns.empty());
  735. {
  736. const auto full = lynx::importFlp (p, withFiles);
  737. bool hasFpc = false;
  738. for (const auto& c : p.channels)
  739. hasFpc = hasFpc || c.pluginName == "FPC";
  740. // GMS and Morphine (REA_rodada39): every state plays on the exact engine (GMS with its waves from the
  741. // installation) and sounds; two demo channels match golden samples of our round-39 models
  742. for (const auto& c : p.channels)
  743. {
  744. if (c.pluginName == "GMS")
  745. ++gms, gmsUsable += lynx::gmsStateUsable (c.pluginState) ? 1 : 0;
  746. if (c.pluginName == "Morphine")
  747. ++morphine, morphineUsable += lynx::morphineStateUsable (c.pluginState) ? 1 : 0;
  748. }
  749. const auto file = entry.path().filename().string();
  750. for (const auto& c : full.channels)
  751. {
  752. const auto isGms = c.instrument == lynx::InstrumentKind::gms, isMorphine = c.instrument == lynx::InstrumentKind::morphine;
  753. if (! isGms && ! isMorphine)
  754. continue;
  755. (isGms ? gmsKind : morphineKind)++;
  756. auto iv = [] (double vel) { return (std::pow (11.0, vel / 100.0) - 1.0) / 10.0; };
  757. const auto golden = (isGms && c.name == "GMS" && file.find ("Song For You") != std::string::npos)
  758. || (isMorphine && c.name == "Morphine" && file.find ("SHINE") != std::string::npos);
  759. std::vector<float> y;
  760. if (isGms)
  761. y = lynx::gms::renderReference (c.pluginState,
  762. { { 0, 60, (float) iv (100), 1.0, 0.0, 0.0, 30000 }, { 11025, 64, (float) iv (80), 1.0, 0.0, 0.0, 40000 },
  763. { 22050, 67, (float) iv (110), 1.0, 0.0, 0.0, 52000 }, { 60000, 48, (float) iv (127), 1.0, 0.0, 0.0, 70000 } },
  764. 44100.0, golden ? 88200 : 22050, c.samplePath);
  765. else
  766. 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 } },
  767. 44100.0, golden ? 100000 : 22050, c.samplePath);
  768. double e = 0.0;
  769. bool finite = ! y.empty();
  770. for (auto v : y)
  771. finite = finite && std::isfinite (v), e += (double) v * v;
  772. CHECK (finite);
  773. (isGms ? gmsSounding : morphineSounding) += e > 1e-6 ? 1 : 0;
  774. if (golden && ! y.empty())
  775. {
  776. // our model, same events (GMS: tempo 140; Morphine: tempo 120), state as saved, 44.1 kHz
  777. const auto rms = std::sqrt (e / (double) y.size());
  778. CHECK (std::abs (rms - (isGms ? 0.213602668574 : 0.0673606448152)) < 1e-5);
  779. 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 } },
  780. 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 } };
  781. for (const auto& g : isGms ? std::vector (std::begin (gmsAt), std::end (gmsAt)) : std::vector (std::begin (morAt), std::end (morAt)))
  782. 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);
  783. ++demoGoldens;
  784. }
  785. }
  786. for (const auto& c : full.channels)
  787. {
  788. if (c.instrument == lynx::InstrumentKind::harmless && c.modelParams.size() >= (std::size_t) lynx::harmlessParamCount
  789. && c.modelParams[(std::size_t) lynx::harmlessComboIndex + 3] > 0.5f)
  790. {
  791. ++harmlessCompWanted;
  792. harmlessCompLoaded += c.modelParams.size() > (std::size_t) lynx::harmlessCompIndex + 1000 ? 1 : 0;
  793. }
  794. flKeysChannels += c.zones.size() == 30 && c.zones.front().path.find ("CHANGPIANO") != std::string::npos ? 1 : 0;
  795. if (c.sampler.slices.size() >= 4)
  796. {
  797. ++slicedChannels;
  798. CHECK (std::is_sorted (c.sampler.slices.begin(), c.sampler.slices.end()));
  799. CHECK (c.sampler.slices.back() < 1.0f);
  800. }
  801. if (! c.zones.empty() && c.name.find (" - ") == std::string::npos)
  802. {
  803. ++dwChannels;
  804. dwZones += (int) c.zones.size();
  805. }
  806. padChannels += c.name.find (" - ") != std::string::npos && c.instrument == lynx::InstrumentKind::sampler ? 1 : 0;
  807. }
  808. fpcKits += hasFpc;
  809. // Maximus / Soundgoodizer become the exact engine (REA_rodada40); Vocodex carries SG.dat (and its
  810. // carrier's Sytrus preset) read from the installation
  811. for (const auto& insert : p.mixer)
  812. for (const auto& slot : insert.slots)
  813. {
  814. maximusSlots += slot.plugin == "Maximus";
  815. sgzSlots += slot.plugin == "Soundgoodizer";
  816. vocodexSlots += slot.plugin == "Vocodex";
  817. }
  818. for (const auto& t : full.mixer)
  819. for (const auto& fx : t.effects)
  820. {
  821. if (fx.kind == lynx::EffectKind::maximus)
  822. {
  823. const auto blob = lynx::maximusfx::unpack (fx.state);
  824. CHECK (blob && lynx::maximusfx::presetOf (*blob) != nullptr);
  825. if (blob)
  826. (blob->build == lynx::hlfx::MaximusBuild::soundgoodizer ? sgzExact : maximusExact) += 1;
  827. }
  828. if (fx.kind == lynx::EffectKind::vocodex)
  829. vocodexWithData += ! lynx::vocodex::splitInstallData (fx.state).second.sgDat.empty();
  830. }
  831. for (const auto& pat : full.patterns)
  832. for (const auto& n : pat.notes)
  833. {
  834. CHECK (n.channel >= 0 && n.channel < (int) full.channels.size());
  835. padNotes += full.channels[(std::size_t) n.channel].name.find (" - ") != std::string::npos ? 1 : 0;
  836. }
  837. }
  838. const auto peqDefaults = lynx::makeEffectSlot (lynx::EffectKind::parametricEq).params;
  839. for (const auto& t : song.mixer)
  840. for (const auto& fx : t.effects)
  841. {
  842. if (fx.kind == lynx::EffectKind::parametricEq)
  843. {
  844. ++peqSlots;
  845. peqShaped += fx.params != peqDefaults;
  846. for (double hz : { 50.0, 1000.0, 10000.0 })
  847. CHECK (std::isfinite (lynx::peq::responseDb (fx.params, 48000.0, hz)));
  848. }
  849. if (fx.kind == lynx::EffectKind::reverb)
  850. {
  851. ++reverbs;
  852. reverbsDryless += fx.params[4] < 0.01f;
  853. reverbsLowCut += fx.params[5] > 0.0f;
  854. }
  855. }
  856. for (const auto& t : song.mixer)
  857. if (t.eq.active())
  858. {
  859. ++trackEqs;
  860. for (std::size_t b = 0; b < 3; ++b)
  861. CHECK (t.eq.hz[b] >= 10.0f && t.eq.hz[b] <= 16000.0f && std::abs (t.eq.gainDb[b]) <= 18.0f);
  862. }
  863. for (const auto& a : song.arrangements)
  864. for (const auto& m : a.markers)
  865. {
  866. ++markers;
  867. signatures += m.isSignature();
  868. CHECK (m.tick >= 0);
  869. }
  870. // Fruity Wrapper (channels and mixer slots): every blob in the demos is read
  871. auto countWrapper = [&] (const std::string& plugin, const std::vector<std::uint8_t>& state) {
  872. if (plugin != "Fruity Wrapper")
  873. return;
  874. ++wrapped;
  875. lynx::ForeignPlugin f;
  876. wrappedParsed += lynx::parseFlWrapper (state, f) && f.format != lynx::ForeignPlugin::Format::none && ! f.name.empty();
  877. };
  878. for (const auto& c : p.channels)
  879. countWrapper (c.pluginName, c.pluginState);
  880. for (const auto& insert : p.mixer)
  881. for (const auto& slot : insert.slots)
  882. countWrapper (slot.plugin, slot.state);
  883. // Harmless: every state in the demos becomes a synth, with finite values
  884. for (const auto& c : p.channels)
  885. if (c.pluginName == "Harmless")
  886. {
  887. ++harmless;
  888. lynx::SynthSettings hs;
  889. float g = 1.0f;
  890. if (lynx::synthFromHarmless (c.pluginState, 128.0, hs, g))
  891. {
  892. ++harmlessDecoded;
  893. CHECK (std::isfinite (g) && hs.cutoff >= 20.0f && hs.cutoff <= 20000.0f && std::isfinite (hs.decay) && std::isfinite (hs.release));
  894. }
  895. if (const auto hp = lynx::harmlessParams (c.pluginState))
  896. harmlessParsed += (int) hp->size() == lynx::harmlessParamCount ? 1 : 0;
  897. }
  898. for (const auto& c : song.channels)
  899. harmlessKind += c.instrument == lynx::InstrumentKind::harmless ? 1 : 0;
  900. // Harmor: every state in the demos plays on the exact engine (REA_rodada34) and sounds, with finite samples
  901. for (const auto& c : p.channels)
  902. if (c.pluginName == "Harmor")
  903. {
  904. ++harmor;
  905. harmorUsable += lynx::harmorStateUsable (c.pluginState) ? 1 : 0;
  906. }
  907. for (const auto& c : song.channels)
  908. if (c.instrument == lynx::InstrumentKind::harmor)
  909. {
  910. ++harmorKind;
  911. 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);
  912. double e = 0.0;
  913. bool finite = ! y.empty();
  914. for (auto v : y)
  915. finite = finite && std::isfinite (v), e += (double) v * v;
  916. CHECK (finite);
  917. harmorSounding += e > 1e-6 ? 1 : 0;
  918. }
  919. // Ogun: every state in the demos plays on the exact engine (REA_rodada37) and sounds, with finite samples
  920. for (const auto& c : p.channels)
  921. if (c.pluginName == "Ogun")
  922. {
  923. ++ogun;
  924. ogunUsable += lynx::ogunStateUsable (c.pluginState) ? 1 : 0;
  925. }
  926. for (const auto& c : song.channels)
  927. if (c.instrument == lynx::InstrumentKind::ogun)
  928. {
  929. ++ogunKind;
  930. 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 },
  931. { 2000, 67, 0.6, 1.0, 0.0, 0.0, 0.0, 0.0, 0.5, 8000 } }, 44100.0, 11025);
  932. double e = 0.0;
  933. bool finite = ! y.empty();
  934. for (auto v : y)
  935. finite = finite && std::isfinite (v), e += (double) v * v;
  936. CHECK (finite);
  937. ogunSounding += e > 1e-6 ? 1 : 0;
  938. }
  939. // Sytrus: every state in the demos (zlib + 10 units) decodes, with finite values
  940. for (const auto& c : p.channels)
  941. if (c.pluginName == "Sytrus")
  942. {
  943. ++sytrus;
  944. lynx::SynthSettings ss;
  945. float g = 1.0f;
  946. // the Sytrus engine (REA_rodada31) reads every demo state; the first 24 play a short note (render settings)
  947. if (lynx::sytrus::stateUsable (c.pluginState))
  948. {
  949. ++sytrusEngine;
  950. if (sytrusRendered < 24)
  951. {
  952. ++sytrusRendered;
  953. lynx::sytrus::Engine e;
  954. e.prepare (44100.0, true, 512);
  955. e.setPatch (lynx::sytrus::parsePatch (c.pluginState));
  956. lynx::sytrus::NoteParams note;
  957. e.noteOn (note);
  958. std::vector<float> l (8192), r (8192);
  959. e.render (l.data(), r.data(), 8192, 0.551f, 0.0f);
  960. bool finite = true;
  961. double energy = 0.0;
  962. for (std::size_t k = 0; k < l.size(); ++k)
  963. finite = finite && std::isfinite (l[k]) && std::isfinite (r[k]), energy += (double) l[k] * l[k];
  964. CHECK (finite);
  965. sytrusSounding += energy > 1e-6;
  966. }
  967. }
  968. if (lynx::synthFromSytrus (c.pluginState, 128.0, ss, g))
  969. {
  970. ++sytrusDecoded;
  971. CHECK (std::isfinite (g) && ss.cutoff >= 20.0f && ss.cutoff <= 20000.0f && std::isfinite (ss.attack) && std::isfinite (ss.decay)
  972. && std::isfinite (ss.release) && ss.sustain >= 0.0f && ss.sustain <= 1.0f && std::isfinite (ss.filterEnv.amount));
  973. for (const auto& o : ss.osc)
  974. CHECK (o.level >= 0.0f && o.level <= 1.0f && o.octave >= -3 && o.octave <= 3);
  975. }
  976. }
  977. // round 12 generators
  978. for (const auto& c : p.channels)
  979. {
  980. lynx::SynthSettings gs;
  981. float g = 1.0f;
  982. int decoded = -1;
  983. if (c.pluginName == "Harmor")
  984. {
  985. decoded = lynx::synthFromHarmor (c.pluginState, gs, g);
  986. if (decoded)
  987. {
  988. // REA_rodada25 §4: most resonant settings stay below Q ≈ 3, a few saturate
  989. CHECK (gs.resonance >= 0.0f && gs.resonance <= 1.0f);
  990. static int resonant = 0, strong = 0, total = 0;
  991. resonant += gs.resonance > 0.0f;
  992. strong += gs.resonance > 0.9f;
  993. if (++total % 50 == 0)
  994. std::printf (" Harmor resonance: %d with a peak, %d with Q > ~5 (of %d)\n", resonant, strong, total);
  995. }
  996. static int saw = 0, square = 0, other = 0, total = 0;
  997. if (decoded && std::any_of (gs.osc.begin(), gs.osc.end(), [] (const lynx::SynthOscillator& o) { return o.wave == lynx::Waveform::spectral; }))
  998. {
  999. auto isSaw = true, isSquare = true;
  1000. for (int n = 1; n <= 16; ++n)
  1001. {
  1002. isSaw = isSaw && std::abs (gs.spectrum[(std::size_t) n - 1] - 1.0f / n) < 1e-3f;
  1003. isSquare = isSquare && std::abs (gs.spectrum[(std::size_t) n - 1] - (n % 2 == 1 ? 1.1535f / n : 0.0f)) < 2e-3f;
  1004. }
  1005. ++(isSaw ? saw : isSquare ? square : other);
  1006. if (++total % 20 == 0 || total == 100)
  1007. std::printf (" Harmor spectrum: %d saw, %d square, %d other (of %d)\n", saw, square, other, total);
  1008. }
  1009. }
  1010. else if (c.pluginName == "GMS")
  1011. decoded = lynx::synthFromGms (c.pluginState, 128.0, gs, g);
  1012. else if (c.pluginName == "Ogun" || c.pluginName == "Autogun")
  1013. {
  1014. decoded = lynx::synthFromOgun (c.pluginState, gs, g);
  1015. // REA_rodada24 §1.9: the "Trumpet" preset (richness 7, no seeds) has partials 0.9087, 0.8610,
  1016. // 0.8151… at the fixed seed-3 phases 0.919, 0.380, 0.130
  1017. if (decoded && gs.osc[0].wave == lynx::Waveform::spectral)
  1018. {
  1019. CHECK (std::all_of (gs.spectrum.begin(), gs.spectrum.end(), [] (float a) { return std::isfinite (a) && a >= 0.0f; }));
  1020. static constexpr float trumpet[3] { 0.9087f, 0.8610f, 0.8151f }, phases[3] { 0.919f, 0.380f, 0.130f };
  1021. auto match = true;
  1022. for (std::size_t k = 0; k < 3; ++k)
  1023. match = match && std::abs (gs.spectrum[k] * 2.0f / 3.14159265f - trumpet[k]) < 1e-3f && std::abs (gs.spectrumPhase[k] - phases[k]) < 1e-3f;
  1024. ogunTrumpet += match ? 1 : 0;
  1025. }
  1026. }
  1027. else if (c.pluginName == "Sakura")
  1028. decoded = lynx::synthFromSakura (c.pluginState, gs);
  1029. else if (c.pluginName == "Kepler")
  1030. decoded = lynx::synthFromKepler (c.pluginState, gs, g);
  1031. else if (c.pluginName == "Wave Traveller")
  1032. decoded = lynx::waveTravellerSample (c.pluginState).has_value() ? 2 : 0;
  1033. else if (c.pluginName == "PoiZone")
  1034. decoded = lynx::synthFromPoiZone (c.pluginState, gs, g);
  1035. else if (c.pluginName == "BassDrum")
  1036. decoded = lynx::synthFromBassDrum (c.pluginState, gs, g);
  1037. else if (c.pluginName == "Toxic Biohazard")
  1038. decoded = lynx::synthFromToxic (c.pluginState, gs, g);
  1039. else if (c.pluginName == "Morphine")
  1040. decoded = lynx::synthFromMorphine (c.pluginState, gs, g);
  1041. else if (c.pluginName == "BooBass")
  1042. decoded = lynx::synthFromBooBass (c.pluginState, gs);
  1043. else if (c.pluginName == "Drumpad" || c.pluginName == "DrumPad")
  1044. decoded = lynx::drumpadPatchName (c.pluginState).has_value() ? 2 : 0;
  1045. else if (c.pluginName == "Fruity Envelope Controller" && c.pluginState.size() >= 4 && c.pluginState[2] >= 6) // v >= 6
  1046. decoded = lynx::parseEnvelopeController (c.pluginState).has_value() ? 2 : 0;
  1047. else if (c.pluginName == "FLEX")
  1048. decoded = lynx::flexPresetName (c.pluginState).has_value() ? 2 : 0;
  1049. else if (c.pluginName == "Fruity DrumSynth Live")
  1050. decoded = lynx::drumSynthLiveParams (c.pluginState).has_value() ? 2 : 0;
  1051. if (decoded < 0)
  1052. continue;
  1053. auto& counter = generators[c.pluginName];
  1054. ++counter.first;
  1055. counter.second += decoded != 0;
  1056. if (decoded == 1 && c.pluginName != "Fruity DrumSynth Live")
  1057. {
  1058. CHECK (std::isfinite (g) && g >= 0.0f && gs.cutoff >= 20.0f && gs.cutoff <= 20000.0f && gs.sustain >= 0.0f && gs.sustain <= 1.0f);
  1059. 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));
  1060. for (const auto& o : gs.osc)
  1061. CHECK (o.level >= 0.0f && o.level <= 4.0f && std::isfinite (o.detune) && std::isfinite (o.pan));
  1062. }
  1063. }
  1064. // 3x Osc: every state in the demos decodes, with levels summing to at most 1
  1065. for (const auto& c : p.channels)
  1066. if (c.pluginName == "3x Osc")
  1067. {
  1068. ++threeOsc;
  1069. lynx::SynthSettings s;
  1070. if (lynx::synthFrom3xOsc (c.pluginState, s))
  1071. {
  1072. ++threeOscDecoded;
  1073. // with AM, osc 3 is the modulation depth and is left out of the sum
  1074. const auto sum = s.osc[0].level + s.osc[1].level + (s.am ? 0.0f : s.osc[2].level);
  1075. CHECK (sum <= 1.001f && s.osc[2].level <= 1.0f);
  1076. for (const auto& o : s.osc)
  1077. CHECK (o.octave >= -2 && o.octave <= 2 && std::abs (o.semitones) <= 11 && std::abs (o.pan) <= 1.0f);
  1078. }
  1079. }
  1080. for (auto& pat : p.patterns)
  1081. if (! pat.notes.empty())
  1082. {
  1083. ++withNotes;
  1084. break;
  1085. }
  1086. for (auto& a : p.arrangements)
  1087. for (auto& item : a.items)
  1088. CHECK (item.track >= 0 && item.track < 500);
  1089. for (auto& clip : song.playlist)
  1090. {
  1091. CHECK (clip.pattern >= 0 && clip.pattern < (int) song.patterns.size());
  1092. CHECK (clip.length > 0 && clip.offset >= 0);
  1093. if (clip.kind == lynx::ClipKind::automation)
  1094. CHECK (clip.automation >= 0 && clip.automation < (int) song.automations.size());
  1095. }
  1096. for (auto& a : song.automations)
  1097. {
  1098. ++automations;
  1099. automationsWithTarget += a.target.kind != lynx::AutomationTargetKind::none;
  1100. CHECK (a.isLive() || ! a.points.empty());
  1101. for (std::size_t i = 1; i < a.points.size(); ++i)
  1102. CHECK (a.points[i].tick >= a.points[i - 1].tick);
  1103. }
  1104. // imported routing has no cycles and valid destinations
  1105. CHECK (song.mixerOrder().size() + 1 == song.mixer.size());
  1106. for (auto& t : song.mixer)
  1107. for (auto& s : t.sends)
  1108. {
  1109. ++sends;
  1110. CHECK (s.target > 0 && s.target < (int) song.mixer.size());
  1111. }
  1112. if (! song.playlist.empty())
  1113. ++withPlaylist;
  1114. }
  1115. catch (const flp::Error& e)
  1116. {
  1117. ++failures;
  1118. std::printf (" FAILED %s: %s\n", entry.path().string().c_str(), e.what());
  1119. }
  1120. }
  1121. CHECK (threeOscDecoded == threeOsc);
  1122. std::printf (" Harmless: %d channels, %d decoded\n", harmless, harmlessDecoded);
  1123. std::printf (" Sytrus: %d channels, %d decoded, %d by the engine (%d of %d rendered sound)\n", sytrus, sytrusDecoded, sytrusEngine,
  1124. sytrusSounding, sytrusRendered);
  1125. CHECK (sytrusEngine == sytrus);
  1126. CHECK (sytrusSounding >= sytrusRendered * 3 / 4);
  1127. for (const auto& [name, counter] : generators)
  1128. {
  1129. std::printf (" %s: %d channels, %d decoded\n", name.c_str(), counter.first, counter.second);
  1130. CHECK (counter.second == counter.first);
  1131. }
  1132. std::printf (" Ogun spectra matching the Trumpet reference: %d\n", ogunTrumpet);
  1133. CHECK (ogunTrumpet >= 1);
  1134. // demo Gross Beat: the volume slot becomes the gate (those using an envelope slot get steps < 1)
  1135. {
  1136. int vocodexes = 0, vocodexSides = 0;
  1137. int lovePhilterLinks[4] {}; // live links: cutoff, resonance; inside containers: cutoff, resonance
  1138. int embeddedZones = 0, lovePhilters = 0, lovePhiltersRead = 0, lovePhiltersConverted = 0, gates = 0, shaped = 0, effectors = 0, patchers = 0, serial = 0, parallel = 0, generatorPatchers = 0;
  1139. for (const auto& entry : std::filesystem::recursive_directory_iterator (std::filesystem::path (realFlpDir) / "Demo projects"))
  1140. if (entry.path().extension() == ".flp")
  1141. {
  1142. std::ifstream in (entry.path(), std::ios::binary);
  1143. const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1144. try
  1145. {
  1146. const auto project = flp::parseProject (file);
  1147. for (const auto& insert : project.mixer)
  1148. for (const auto& slot : insert.slots)
  1149. if (slot.plugin == "Gross Beat")
  1150. {
  1151. const auto fx = lynx::effectFromFl (slot.plugin, slot.state);
  1152. CHECK (fx && fx->kind == lynx::EffectKind::volumeGate);
  1153. ++gates;
  1154. if (fx && std::any_of (fx->params.begin(), fx->params.begin() + 32, [] (float v) { return v < 0.99f; }))
  1155. ++shaped;
  1156. }
  1157. else if (slot.plugin == "Fruity Love Philter")
  1158. {
  1159. ++lovePhilters;
  1160. lovePhiltersRead += lynx::parseLovePhilter (slot.state).has_value();
  1161. if (const auto conv = lynx::lovePhilterEffects (slot.state))
  1162. {
  1163. ++lovePhiltersConverted;
  1164. CHECK (! conv->slots.empty());
  1165. for (const auto& fx : conv->slots)
  1166. for (auto v : fx.params)
  1167. CHECK (std::isfinite (v) && v >= 0.0f && v <= 1.0f);
  1168. for (const auto& fx : conv->slots)
  1169. for (const auto& link : fx.links)
  1170. {
  1171. const auto& chain = fx.branches[(std::size_t) link.branch].chain;
  1172. CHECK (link.source < (int) chain.size() && chain[(std::size_t) link.target].kind == lynx::EffectKind::parametricEq);
  1173. lovePhilterLinks[2 + (link.param == lynx::peq::param (0, 3) ? 1 : 0)]++;
  1174. }
  1175. for (const auto& link : conv->links)
  1176. {
  1177. lovePhilterLinks[link.param == lynx::peq::param (0, 3) ? 1 : 0]++;
  1178. CHECK (link.curve.size() == 33);
  1179. for (auto v : link.curve)
  1180. CHECK (std::isfinite (v) && v >= 0.0f && v <= 1.0f);
  1181. }
  1182. }
  1183. }
  1184. else if (slot.plugin == "Vocodex")
  1185. {
  1186. const auto v = lynx::vocodexEffect (slot.state);
  1187. CHECK (v.has_value());
  1188. vocodexes += v.has_value();
  1189. vocodexSides += v && (v->modIn > 0 || v->carIn > 0);
  1190. }
  1191. else if (slot.plugin == "Effector")
  1192. effectors += lynx::effectFromFl (slot.plugin, slot.state).has_value();
  1193. else if (slot.plugin == "Patcher")
  1194. {
  1195. const auto graph = lynx::parsePatcher (slot.state);
  1196. CHECK (graph.has_value());
  1197. ++patchers;
  1198. if (graph && ! graph->serialChain.empty())
  1199. ++serial;
  1200. if (graph && graph->serialChain.empty() && graph->audio)
  1201. ++parallel;
  1202. }
  1203. for (const auto& c : project.channels)
  1204. if (c.pluginName == "DirectWave")
  1205. if (const auto program = lynx::directWaveProgram (c.pluginState))
  1206. for (const auto& wav : program->embeddedWav)
  1207. if (! wav.empty())
  1208. {
  1209. ++embeddedZones;
  1210. CHECK (wav.size() > 44 && std::memcmp (wav.data(), "RIFF", 4) == 0);
  1211. }
  1212. for (const auto& c : project.channels)
  1213. if (c.pluginName == "Patcher")
  1214. {
  1215. const auto graph = lynx::parsePatcher (c.pluginState);
  1216. CHECK (graph.has_value());
  1217. generatorPatchers += graph && graph->mainGenerator >= 0;
  1218. }
  1219. }
  1220. catch (const flp::Error&) {}
  1221. }
  1222. std::printf (" Gross Beat: %d slots, %d with gate; Effector: %d converted; Love Philter: %d, %d read\n", gates, shaped, effectors,
  1223. lovePhilters, lovePhiltersRead);
  1224. CHECK (lovePhiltersRead == lovePhilters && lovePhiltersConverted == lovePhilters);
  1225. std::printf (" Vocodex: %d converted, %d with side inputs\n", vocodexes, vocodexSides);
  1226. CHECK (vocodexes >= 9);
  1227. std::printf (" Love Philter live links: %d cutoff, %d resonance; in multi-unit containers: %d cutoff, %d resonance\n",
  1228. lovePhilterLinks[0], lovePhilterLinks[1], lovePhilterLinks[2], lovePhilterLinks[3]);
  1229. CHECK (lovePhilterLinks[2] + lovePhilterLinks[3] > 0);
  1230. std::printf (" DirectWave: %d zones with embedded audio\n", embeddedZones);
  1231. CHECK (embeddedZones == 12);
  1232. std::printf (" Patcher: %d in the mixer (%d serial, %d reduced to serial/parallel), %d as instrument with generator\n", patchers, serial,
  1233. parallel, generatorPatchers);
  1234. CHECK (gates == 0 || shaped > 0);
  1235. }
  1236. // Envelope Controller "Basic Sidechain" (Future House): drops on the note and returns to ~1 within ~1/3 s
  1237. {
  1238. const auto path = std::filesystem::path (realFlpDir) / "Demo projects" / "Demo songs" / "Asher Postman - Future House.flp";
  1239. if (std::filesystem::exists (path))
  1240. {
  1241. std::ifstream in (path, std::ios::binary);
  1242. const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1243. const auto song = lynx::importFlp (flp::parseProject (file));
  1244. const lynx::ChannelDef* controller = nullptr;
  1245. for (const auto& c : song.channels)
  1246. if (c.instrument == lynx::InstrumentKind::controller)
  1247. controller = &c;
  1248. CHECK (controller != nullptr);
  1249. if (controller != nullptr)
  1250. {
  1251. auto inst = lynx::makeInstrument (lynx::InstrumentKind::controller);
  1252. inst->prepare (48000.0);
  1253. inst->configure (*controller, song.bpm);
  1254. std::vector<float> l (480), r (480);
  1255. inst->render (l.data(), r.data(), 480, 1.0f, 1.0f);
  1256. inst->noteOn (60, 1.0f);
  1257. inst->render (l.data(), r.data(), 480, 1.0f, 1.0f); // 10 ms
  1258. const auto ducked = inst->controlOutput (0);
  1259. for (int i = 0; i < 100; ++i) // +1 s
  1260. inst->render (l.data(), r.data(), 480, 1.0f, 1.0f);
  1261. const auto recovered = inst->controlOutput (0);
  1262. std::printf (" Envelope Controller (Basic Sidechain): %.2f on the note, %.2f after 1 s\n", ducked, recovered);
  1263. CHECK (ducked < 0.3f && recovered > 0.9f);
  1264. }
  1265. }
  1266. }
  1267. // mutation fuzz: real states with flipped and truncated bytes must not crash the readers
  1268. {
  1269. std::map<std::string, std::vector<std::uint8_t>> samples; // one real blob per plugin
  1270. for (const auto& entry : std::filesystem::recursive_directory_iterator (std::filesystem::path (realFlpDir) / "Demo projects"))
  1271. {
  1272. if (entry.path().extension() != ".flp")
  1273. continue;
  1274. std::ifstream in (entry.path(), std::ios::binary);
  1275. const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1276. try
  1277. {
  1278. const auto project = flp::parseProject (file);
  1279. for (const auto& c : project.channels)
  1280. if (! c.pluginState.empty())
  1281. samples.emplace (c.pluginName, c.pluginState);
  1282. for (const auto& insert : project.mixer)
  1283. for (const auto& slot : insert.slots)
  1284. if (! slot.state.empty())
  1285. samples.emplace (slot.plugin, slot.state);
  1286. }
  1287. catch (const flp::Error&) {}
  1288. }
  1289. std::uint32_t seed = 12345;
  1290. auto rnd = [&seed] { seed = seed * 1664525u + 1013904223u; return seed >> 8; };
  1291. int mutations = 0;
  1292. for (const auto& [name, original] : samples)
  1293. for (int round = 0; round < 40; ++round)
  1294. {
  1295. auto blob = original;
  1296. if (round % 4 == 3 && ! blob.empty())
  1297. blob.resize (rnd() % blob.size()); // truncated
  1298. else
  1299. for (int k = 0; k < 1 + (int) (rnd() % 8) && ! blob.empty(); ++k)
  1300. blob[rnd() % blob.size()] = (std::uint8_t) rnd();
  1301. ++mutations;
  1302. lynx::SynthSettings synth;
  1303. float gain = 1.0f;
  1304. lynx::synthFromSytrus (blob, 120.0, synth, gain);
  1305. lynx::synthFromHarmor (blob, synth, gain);
  1306. lynx::synthFromGms (blob, 120.0, synth, gain);
  1307. lynx::synthFromOgun (blob, synth, gain);
  1308. lynx::synthFromMorphine (blob, synth, gain);
  1309. lynx::synthFromKepler (blob, synth, gain);
  1310. lynx::synthFromPoiZone (blob, synth, gain);
  1311. lynx::synthFromToxic (blob, synth, gain);
  1312. lynx::synthFromBassDrum (blob, synth, gain);
  1313. lynx::synthFromHarmless (blob, 120.0, synth, gain);
  1314. lynx::harmlessParams (blob);
  1315. if (lynx::harmorStateUsable (blob))
  1316. lynx::harmorFallbacks (blob);
  1317. lynx::parseEnvelopeController (blob);
  1318. lynx::parseKeyboardController (blob);
  1319. lynx::parseLovePhilter (blob);
  1320. lynx::parsePatcher (blob);
  1321. lynx::effectFromFl (name, blob);
  1322. lynx::fpcPads (blob);
  1323. lynx::directWaveProgram (blob);
  1324. CHECK (std::isfinite (gain) && std::isfinite (synth.cutoff));
  1325. }
  1326. std::printf (" mutation fuzz: %d blobs from %d plugins\n", mutations, (int) samples.size());
  1327. }
  1328. // WavPack (.wv) samples from FL packs: all decode, with finite, non-silent audio
  1329. {
  1330. int files = 0, decoded = 0, audible = 0;
  1331. double seconds = 0.0;
  1332. for (const auto& entry : std::filesystem::recursive_directory_iterator (std::filesystem::path (realFlpDir) / "Patches" / "Packs"))
  1333. if (entry.path().extension() == ".wv")
  1334. {
  1335. std::ifstream in (entry.path(), std::ios::binary);
  1336. const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1337. ++files;
  1338. lynx::DecodedAudio audio;
  1339. if (! lynx::decodeWavPack (file.data(), file.size(), audio))
  1340. continue;
  1341. ++decoded;
  1342. float peak = 0.0f;
  1343. bool finite = true;
  1344. for (const auto& ch : audio.channels)
  1345. for (auto v : ch)
  1346. {
  1347. finite = finite && std::isfinite (v);
  1348. peak = std::max (peak, std::abs (v));
  1349. }
  1350. CHECK (finite && peak <= 4.0f);
  1351. audible += peak > 1e-4f;
  1352. seconds += (double) audio.channels[0].size() / audio.sampleRate;
  1353. }
  1354. std::printf (" WavPack: %d .wv files, %d decoded, %d audible, %.0f s of audio\n", files, decoded, audible, seconds);
  1355. CHECK (decoded == files);
  1356. }
  1357. // native GMS presets (.gmsynth = the contents of 0xD5 without the "SSLF")
  1358. int gmsPresets = 0, gmsDecoded = 0;
  1359. const auto gmsFolder = std::filesystem::path (realFlpDir) / "Patches" / "Plugin presets" / "Generators" / "GMS";
  1360. if (std::filesystem::exists (gmsFolder))
  1361. for (const auto& entry : std::filesystem::recursive_directory_iterator (gmsFolder))
  1362. if (entry.path().extension() == ".gmsynth")
  1363. {
  1364. std::ifstream in (entry.path(), std::ios::binary);
  1365. std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1366. std::vector<std::uint8_t> blob { 'S', 'S', 'L', 'F' };
  1367. const auto n = (std::uint32_t) file.size();
  1368. blob.insert (blob.end(), reinterpret_cast<const std::uint8_t*> (&n), reinterpret_cast<const std::uint8_t*> (&n) + 4);
  1369. blob.insert (blob.end(), file.begin(), file.end());
  1370. lynx::SynthSettings gs;
  1371. float g = 1.0f;
  1372. ++gmsPresets;
  1373. if (lynx::synthFromGms (blob, 120.0, gs, g))
  1374. {
  1375. ++gmsDecoded;
  1376. CHECK (std::isfinite (g) && gs.cutoff >= 20.0f && std::isfinite (gs.pitchEnv.amount) && std::isfinite (gs.lfo[lynx::lfoPitch].period));
  1377. }
  1378. }
  1379. std::printf (" GMS presets: %d, %d decoded\n", gmsPresets, gmsDecoded);
  1380. // the synth's "FL presets" button: Sytrus/Harmor .fst and .gmsynth become synth settings
  1381. int presetFiles = 0, presetsRead = 0;
  1382. for (const auto* name : { "Sytrus", "Harmor", "GMS", "Harmless", "Ogun", "Sakura", "Fruit Kick", "Fruity DX10", "MiniSynth", "Kepler",
  1383. "PoiZone", "Toxic Biohazard", "BassDrum" })
  1384. {
  1385. const auto folder = std::filesystem::path (realFlpDir) / "Patches" / "Plugin presets" / "Generators" / name;
  1386. if (! std::filesystem::exists (folder))
  1387. continue;
  1388. for (const auto& entry : std::filesystem::recursive_directory_iterator (folder))
  1389. if (entry.path().extension() == ".fst" || entry.path().extension() == ".gmsynth")
  1390. {
  1391. std::ifstream in (entry.path(), std::ios::binary);
  1392. const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1393. ++presetFiles;
  1394. presetsRead += lynx::synthFromFlPreset (file).has_value();
  1395. }
  1396. }
  1397. std::printf (" FL synth presets: %d files, %d read\n", presetFiles, presetsRead);
  1398. CHECK (presetsRead >= presetFiles * 95 / 100);
  1399. CHECK (gmsDecoded == gmsPresets);
  1400. CHECK (sytrusDecoded == sytrus);
  1401. CHECK (harmlessDecoded == harmless && harmless > 100);
  1402. std::printf (" Harmless: %d states parsed for the engine, %d channels imported as Harmless\n", harmlessParsed, harmlessKind);
  1403. CHECK (harmlessParsed == harmless && harmlessKind >= harmless);
  1404. std::printf (" Harmor: %d channels, %d states usable by the engine, %d imported as Harmor (%d sounding)\n", harmor, harmorUsable, harmorKind, harmorSounding);
  1405. CHECK (harmorUsable == harmor && harmor > 90 && harmorKind >= harmor && harmorSounding >= harmorKind * 9 / 10);
  1406. 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",
  1407. gms, gmsUsable, gmsKind, gmsSounding, morphine, morphineUsable, morphineKind, morphineSounding, demoGoldens);
  1408. CHECK (gmsUsable == gms && gms >= 9 && gmsKind == gms && gmsSounding == gmsKind);
  1409. CHECK (morphineUsable == morphine && morphine >= 7 && morphineKind == morphine && morphineSounding == morphineKind && demoGoldens == 2);
  1410. std::printf (" Ogun: %d channels, %d states usable by the engine, %d imported as Ogun (%d sounding)\n", ogun, ogunUsable, ogunKind, ogunSounding);
  1411. CHECK (ogunUsable == ogun && ogun >= 20 && ogunKind >= ogun && ogunSounding >= ogunKind * 9 / 10);
  1412. std::printf (" Harmless rack compressor: %d of %d presets read from the installation\n", harmlessCompLoaded, harmlessCompWanted);
  1413. CHECK (harmlessCompLoaded == harmlessCompWanted && harmlessCompWanted > 100);
  1414. std::printf (" Maximus: %d of %d slots on the exact engine; Soundgoodizer: %d of %d; Vocodex with SG.dat: %d of %d\n", maximusExact,
  1415. maximusSlots, sgzExact, sgzSlots, vocodexWithData, vocodexSlots);
  1416. // REA_rodada40 §6: in Demo projects the 4 states left on the approximation use the Frequency Splitter linear-phase
  1417. // option; the other Data folders add states with options not decoded
  1418. CHECK (maximusSlots - maximusExact <= 16 && maximusExact >= 97 && sgzExact == sgzSlots && sgzSlots > 90);
  1419. CHECK (vocodexWithData == vocodexSlots && vocodexSlots >= 10);
  1420. // 3x Osc channel presets shipped with FL (.fst): all become synth settings
  1421. int presets = 0, presetsDecoded = 0;
  1422. const auto presetDir = std::filesystem::path (realFlpDir) / "Patches" / "Channel presets" / "3x Osc";
  1423. if (std::filesystem::is_directory (presetDir))
  1424. for (auto& entry : std::filesystem::directory_iterator (presetDir))
  1425. if (entry.path().extension() == ".fst")
  1426. {
  1427. ++presets;
  1428. std::ifstream in (entry.path(), std::ios::binary);
  1429. std::vector<std::uint8_t> bytes ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  1430. if (auto synth = lynx::synthFromFlPreset (bytes))
  1431. {
  1432. ++presetsDecoded;
  1433. CHECK (synth->osc[0].level + synth->osc[1].level + (synth->am ? 0.0f : synth->osc[2].level) <= 1.001f);
  1434. }
  1435. }
  1436. std::printf (" %d 3x Osc presets, %d read\n", presets, presetsDecoded);
  1437. CHECK (presetsDecoded == presets);
  1438. // FL effect presets that become built-in effects
  1439. int fxPresets = 0, fxDecoded = 0;
  1440. for (auto kind : { lynx::EffectKind::parametricEq, lynx::EffectKind::limiter, lynx::EffectKind::reverb, lynx::EffectKind::delay,
  1441. lynx::EffectKind::utility })
  1442. for (const auto& plugin : lynx::flPluginsForEffect (kind))
  1443. {
  1444. const auto dir = std::filesystem::path (realFlpDir) / "Patches" / "Plugin presets" / "Effects" / plugin;
  1445. if (! std::filesystem::is_directory (dir))
  1446. continue;
  1447. for (auto& entry : std::filesystem::recursive_directory_iterator (dir))
  1448. if (entry.path().extension() == ".fst")
  1449. {
  1450. ++fxPresets;
  1451. std::ifstream in (entry.path(), std::ios::binary);
  1452. std::vector<std::uint8_t> bytes ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  1453. fxDecoded += lynx::effectFromFlPreset (bytes).has_value();
  1454. }
  1455. }
  1456. std::printf (" %d FL effect presets, %d read\n", fxPresets, fxDecoded);
  1457. CHECK (fxDecoded == fxPresets);
  1458. CHECK (wrappedParsed == wrapped);
  1459. std::printf (" %d plugins in Fruity Wrapper, %d read\n", wrapped, wrappedParsed);
  1460. std::printf (" %d markers, %d time signature changes, %d tracks with EQ\n", markers, signatures, trackEqs);
  1461. std::printf (" %d parametric EQs (%d with FL settings), %d reverbs (%d without dry)\n", peqSlots, peqShaped, reverbs, reverbsDryless);
  1462. std::printf (" DirectWave: %d channels, %d zones; FPC: %d projects, %d pad channels, %d pad notes\n", dwChannels, dwZones, fpcKits,
  1463. padChannels, padNotes);
  1464. CHECK (dwZones > 1000 && padChannels > 250 && padNotes > 500);
  1465. std::printf (" sliced channels (Slicer/Slicex): %d; embedded WAVs saved: %d\n", slicedChannels, embeddedSaved);
  1466. CHECK (slicedChannels >= 25 && embeddedSaved >= 10); // without decoding Ogg here, some loops have no duration
  1467. std::printf (" FL Keys (Grand Piano, 30 zones): %d channels\n", flKeysChannels);
  1468. CHECK (flKeysChannels >= 8);
  1469. CHECK (peqSlots > 1000 && peqShaped > 900 && reverbsDryless > 20 && reverbsLowCut > 250);
  1470. CHECK (markers > 300 && signatures > 60);
  1471. std::printf (" %d 3x Osc channels, %d decoded\n", threeOsc, threeOscDecoded);
  1472. std::printf (" %d .flp files read, %d with notes, %d with playlist, %d automations (%d with target), %d sends\n",
  1473. files, withNotes, withPlaylist, automations, automationsWithTarget, sends);
  1474. CHECK (files > 0);
  1475. CHECK (automations > 0 && sends > 0);
  1476. }
  1477. // ---------------------------------------------------------------------------
  1478. // Sequencer
  1479. TEST (pattern_toggle_step_and_length)
  1480. {
  1481. lynx::Pattern p;
  1482. CHECK (! p.hasStep (0, 4));
  1483. p.toggleStep (0, 4);
  1484. CHECK (p.hasStep (0, 4));
  1485. CHECK (p.notes.size() == 1 && p.notes[0].start == 4 * lynx::ticksPerStep);
  1486. CHECK (p.effectiveLength (4) == 4 * lynx::ppq); // one bar
  1487. p.toggleStep (1, 20); // second bar
  1488. CHECK (p.effectiveLength (4) == 8 * lynx::ppq);
  1489. p.toggleStep (0, 4);
  1490. CHECK (! p.hasStep (0, 4) && p.notes.size() == 1);
  1491. }
  1492. TEST (scheduler_places_events_at_exact_samples)
  1493. {
  1494. lynx::Pattern p;
  1495. p.toggleStep (0, 0);
  1496. p.toggleStep (0, 4); // tick 960 = 1 beat
  1497. const double sr = 48000.0, bpm = 120.0; // 1 beat = 0.5 s = 24000 samples
  1498. const auto tps = lynx::ticksPerSample (bpm, sr);
  1499. lynx::EventBuffer ev;
  1500. lynx::schedulePatternLoop (p, p.effectiveLength (4), 23900.0 * tps, 512, tps, ev);
  1501. // the beat-2 note starts at sample 24000 -> offset 100 in this block
  1502. int ons = 0;
  1503. for (auto& e : ev)
  1504. if (e.type == lynx::NoteEvent::Type::on)
  1505. {
  1506. ++ons;
  1507. CHECK (e.sampleOffset == 100);
  1508. }
  1509. CHECK (ons == 1);
  1510. }
  1511. TEST (scheduler_wraps_the_loop)
  1512. {
  1513. lynx::Pattern p;
  1514. p.toggleStep (2, 0);
  1515. const auto len = p.effectiveLength (4); // 3840 ticks
  1516. const double sr = 48000.0;
  1517. const auto tps = lynx::ticksPerSample (120.0, sr);
  1518. lynx::EventBuffer ev;
  1519. // block that crosses the loop end: starts 10 samples before
  1520. const auto start = (double) len - 10.0 * tps;
  1521. lynx::schedulePatternLoop (p, len, start, 64, tps, ev);
  1522. bool found = false;
  1523. for (auto& e : ev)
  1524. if (e.type == lynx::NoteEvent::Type::on && e.channel == 2)
  1525. {
  1526. found = true;
  1527. CHECK (e.sampleOffset == 10);
  1528. }
  1529. CHECK (found);
  1530. }
  1531. TEST (scheduler_off_before_on_at_same_sample)
  1532. {
  1533. lynx::Pattern p;
  1534. lynx::Note a;
  1535. a.start = 0; a.length = 240; a.channel = 0;
  1536. lynx::Note b = a;
  1537. b.start = 240;
  1538. p.notes = { a, b };
  1539. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  1540. lynx::EventBuffer ev;
  1541. lynx::schedulePatternLoop (p, p.effectiveLength (4), 200.0, 4000, tps, ev);
  1542. CHECK (ev.size() >= 2);
  1543. CHECK (ev[0].type == lynx::NoteEvent::Type::off);
  1544. CHECK (ev[1].type == lynx::NoteEvent::Type::on);
  1545. CHECK (ev[0].sampleOffset == ev[1].sampleOffset);
  1546. }
  1547. TEST (snapshot_exchange_hands_over_and_recycles)
  1548. {
  1549. struct Counted
  1550. {
  1551. int value;
  1552. int* alive;
  1553. Counted (int v, int* a) : value (v), alive (a) { ++*alive; }
  1554. ~Counted() { --*alive; }
  1555. };
  1556. int alive = 0;
  1557. {
  1558. lynx::SnapshotExchange<Counted> x;
  1559. CHECK (x.acquire() == nullptr);
  1560. x.publish (std::make_unique<Counted> (1, &alive));
  1561. CHECK (x.acquire()->value == 1);
  1562. x.publish (std::make_unique<Counted> (2, &alive));
  1563. x.publish (std::make_unique<Counted> (3, &alive)); // 2 was never read: freed immediately
  1564. CHECK (alive == 2);
  1565. CHECK (x.acquire()->value == 3);
  1566. CHECK (alive == 2); // 1 was returned, but only the UI frees it
  1567. x.collectGarbage();
  1568. CHECK (alive == 1);
  1569. // without collection, the return slots fill up and the audio side holds on to the current one
  1570. for (int i = 0; i < 20; ++i)
  1571. {
  1572. x.publish (std::make_unique<Counted> (10 + i, &alive));
  1573. CHECK (x.acquire() != nullptr);
  1574. }
  1575. }
  1576. CHECK (alive == 0);
  1577. }
  1578. TEST (rack_renderer_makes_sound_and_reuses_instruments)
  1579. {
  1580. auto song = lynx::Song::makeDefault();
  1581. song.bpm = 120.0;
  1582. const double sr = 48000.0;
  1583. auto state = lynx::RackState::build (song, nullptr, sr);
  1584. lynx::RackRenderer r;
  1585. r.prepare (sr);
  1586. std::vector<float> l (512), rr (512);
  1587. double tick = 0.0;
  1588. float peak = 0.0f;
  1589. int kicks = 0;
  1590. for (int block = 0; block < 93; ++block) // 47616 samples: just before 1 s
  1591. {
  1592. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  1593. for (auto& e : r.lastEvents())
  1594. if (e.type == lynx::NoteEvent::Type::on && e.channel == 0)
  1595. ++kicks;
  1596. for (int i = 0; i < 512; ++i)
  1597. {
  1598. CHECK (std::isfinite (l[(std::size_t) i]));
  1599. peak = std::max (peak, std::abs (l[(std::size_t) i]));
  1600. }
  1601. tick += 512 * lynx::ticksPerSample (song.bpm, sr);
  1602. }
  1603. CHECK (peak > 0.1f && peak < 4.0f);
  1604. CHECK (kicks == 2); // 120 BPM: beats at 0 and 0.5 s
  1605. // editing the song keeps the instruments of channels whose type didn't change
  1606. song.channels[4].instrument = lynx::InstrumentKind::kick;
  1607. auto next = lynx::RackState::build (song, state.get(), sr);
  1608. CHECK (next->instruments[0] == state->instruments[0]);
  1609. CHECK (next->instruments[4] != state->instruments[4]);
  1610. // stopping silences the synth and triggers no new notes
  1611. r.process (next.get(), false, tick, 512, l.data(), rr.data());
  1612. CHECK (r.lastEvents().size() == 0);
  1613. }
  1614. TEST (flp_import_maps_channels_and_rescales)
  1615. {
  1616. flp::Project p;
  1617. p.header.ppq = 96;
  1618. p.tempo = 150.0;
  1619. p.channels = { { 0, flp::ChannelType::sampler, "Kick 808", "", "", 1 },
  1620. { 1, flp::ChannelType::audioClip, "Vocal", "", "", 2 },
  1621. { 2, flp::ChannelType::instrument, "Lead", "FLEX", "", 3 } };
  1622. flp::Pattern pat;
  1623. pat.index = 1;
  1624. flp::Note n;
  1625. n.position = 96;
  1626. n.length = 0;
  1627. n.channel = 2;
  1628. n.key = 72;
  1629. n.velocity = 64;
  1630. pat.notes.push_back (n);
  1631. p.patterns.push_back (pat);
  1632. const auto s = lynx::importFlp (p);
  1633. CHECK (s.bpm == 150.0);
  1634. CHECK (s.channels.size() == 3); // audio clip channels stay in the rack, as in FL
  1635. CHECK (s.channels[0].instrument == lynx::InstrumentKind::kick);
  1636. CHECK (s.channels[1].instrument == lynx::InstrumentKind::audioClip);
  1637. CHECK (s.channels[2].instrument == lynx::InstrumentKind::synth);
  1638. CHECK (s.patterns.size() == 1);
  1639. CHECK (s.patterns[0].notes[0].start == lynx::ppq); // 96 @ PPQ 96 = 1 beat
  1640. CHECK (s.patterns[0].notes[0].channel == 2);
  1641. CHECK (s.patterns[0].notes[0].length == lynx::ticksPerStep); // step note
  1642. CHECK (std::abs (s.patterns[0].notes[0].velocity - 0.5f) < 1e-6f);
  1643. }
  1644. TEST (live_queue_is_fifo_and_bounded)
  1645. {
  1646. lynx::LiveEventQueue q;
  1647. lynx::NoteEvent e;
  1648. CHECK (! q.pop (e));
  1649. for (int i = 0; i < 10; ++i)
  1650. {
  1651. lynx::NoteEvent in;
  1652. in.key = i;
  1653. CHECK (q.push (in));
  1654. }
  1655. for (int i = 0; i < 10; ++i)
  1656. CHECK (q.pop (e) && e.key == i);
  1657. int pushed = 0;
  1658. while (q.push (e))
  1659. ++pushed;
  1660. CHECK (pushed == (int) lynx::LiveEventQueue::capacity - 1); // one slot stays free to tell full from empty
  1661. }
  1662. TEST (sampler_plays_pitched_one_shot)
  1663. {
  1664. // 1000-frame ramp sample: the position can be measured from the amplitude
  1665. auto data = std::make_shared<lynx::SampleData>();
  1666. data->sampleRate = 48000.0;
  1667. for (int i = 0; i < 1000; ++i)
  1668. data->left.push_back (1.0f);
  1669. auto sampler = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  1670. sampler->prepare (48000.0);
  1671. std::vector<float> l (2048, 0.0f), r (2048, 0.0f);
  1672. sampler->noteOn (60, 1.0f);
  1673. sampler->noteOff (60); // one-shot: noteOff doesn't cut
  1674. sampler->render (l.data(), r.data(), 2048, 1.0f, 1.0f);
  1675. int sounding = 0;
  1676. for (auto s : l)
  1677. sounding += s > 0.5f;
  1678. CHECK (sounding >= 995 && sounding <= 1000); // plays the whole sample at the original pitch
  1679. std::fill (l.begin(), l.end(), 0.0f);
  1680. sampler->noteOn (72, 1.0f); // one octave up: half the duration
  1681. sampler->render (l.data(), r.data(), 2048, 1.0f, 1.0f);
  1682. sounding = 0;
  1683. for (auto s : l)
  1684. sounding += s > 0.5f;
  1685. CHECK (sounding >= 495 && sounding <= 500);
  1686. CHECK (r[10] > 0.5f); // mono goes to both sides
  1687. auto silent = lynx::makeInstrument (lynx::InstrumentKind::sampler, nullptr);
  1688. silent->prepare (48000.0);
  1689. silent->noteOn (60, 1.0f);
  1690. std::fill (l.begin(), l.end(), 0.0f);
  1691. silent->render (l.data(), r.data(), 64, 1.0f, 1.0f);
  1692. CHECK (l[0] == 0.0f);
  1693. }
  1694. TEST (rack_live_notes_and_sample_provider)
  1695. {
  1696. lynx::Song song;
  1697. lynx::ChannelDef c;
  1698. c.name = "Smp";
  1699. c.instrument = lynx::InstrumentKind::sampler;
  1700. c.samplePath = "a.wav";
  1701. song.channels.push_back (c);
  1702. song.patterns.emplace_back();
  1703. int loads = 0;
  1704. auto provider = [&] (const std::string& path) -> std::shared_ptr<const lynx::SampleData> {
  1705. ++loads;
  1706. CHECK (path == "a.wav");
  1707. auto d = std::make_shared<lynx::SampleData>();
  1708. d->left.assign (4800, 0.5f);
  1709. return d;
  1710. };
  1711. auto state = lynx::RackState::build (song, nullptr, 48000.0, provider);
  1712. CHECK (loads == 1);
  1713. lynx::RackRenderer renderer;
  1714. renderer.prepare (48000.0);
  1715. lynx::LiveEventQueue live;
  1716. lynx::NoteEvent on;
  1717. on.channel = 0;
  1718. on.velocity = 1.0f;
  1719. live.push (on);
  1720. std::vector<float> l (256), r (256);
  1721. renderer.process (state.get(), false, 0.0, 256, l.data(), r.data(), &live); // stopped, but the live note plays
  1722. CHECK (l[0] > 0.1f);
  1723. // same sample: reused; different sample: reloaded
  1724. auto same = lynx::RackState::build (song, state.get(), 48000.0, provider);
  1725. CHECK (loads == 1 && same->instruments[0] == state->instruments[0]);
  1726. song.channels[0].samplePath = "b.wav";
  1727. auto other = lynx::RackState::build (song, state.get(), 48000.0, [&] (const std::string&) { ++loads; return nullptr; });
  1728. CHECK (loads == 2 && other->instruments[0] != state->instruments[0]);
  1729. }
  1730. TEST (flp_paths_resolve_and_samplers_import)
  1731. {
  1732. lynx::FlPathRoots roots { "C:\\FL", "C:\\FL\\Data", "D:\\User" };
  1733. CHECK (lynx::resolveFlPath ("%FLStudioFactoryData%\\Data\\x.wav", roots) == "C:\\FL\\Data\\x.wav");
  1734. CHECK (lynx::resolveFlPath ("%FLStudioData%\\Patches\\y.wav", roots) == "C:\\FL\\Data\\Patches\\y.wav");
  1735. CHECK (lynx::resolveFlPath ("%FLStudioUserData%\\z.wav", roots) == "D:\\User\\z.wav");
  1736. CHECK (lynx::resolveFlPath ("E:\\abs.wav", roots) == "E:\\abs.wav");
  1737. CHECK (lynx::resolveFlPath ("%FLStudioUserData%\\z.wav", {}) == "");
  1738. flp::Project p;
  1739. p.channels = { { 0, flp::ChannelType::sampler, "Kick", "", "%FLStudioData%\\k.wav", 1 },
  1740. { 1, flp::ChannelType::sampler, "Hat", "", "%FLStudioData%\\missing.wav", 1 } };
  1741. lynx::FlpImportOptions options;
  1742. options.roots = roots;
  1743. options.fileExists = [] (const std::string& path) { return path == "C:\\FL\\Data\\k.wav"; };
  1744. const auto s = lynx::importFlp (p, options);
  1745. CHECK (s.channels[0].instrument == lynx::InstrumentKind::sampler);
  1746. CHECK (s.channels[0].samplePath == "C:\\FL\\Data\\k.wav");
  1747. CHECK (s.channels[1].instrument == lynx::InstrumentKind::hat); // no file: built-in instrument
  1748. }
  1749. TEST (soft_clip_is_transparent_below_knee_and_bounded)
  1750. {
  1751. float s[] = { 0.5f, -0.89f, 1.5f, -3.0f, 0.95f };
  1752. lynx::softClip (s, 5);
  1753. CHECK (s[0] == 0.5f && s[1] == -0.89f);
  1754. CHECK (s[2] > 0.9f && s[2] <= 1.0f);
  1755. CHECK (s[3] < -0.9f && s[3] >= -1.0f);
  1756. CHECK (s[4] > 0.9f && s[4] < 0.95f);
  1757. }
  1758. TEST (song_scheduler_plays_clips_with_offset_and_cut)
  1759. {
  1760. lynx::Song s;
  1761. s.channels.resize (1);
  1762. auto& p = s.patterns.emplace_back();
  1763. for (int step : { 0, 4, 8, 12 }) // one note per beat
  1764. p.toggleStep (0, step);
  1765. // clip at bar 2 playing only the second half of the pattern (beats 3 and 4)
  1766. lynx::Clip c;
  1767. c.pattern = 0;
  1768. c.start = 4 * lynx::ppq;
  1769. c.length = 2 * lynx::ppq;
  1770. c.offset = 2 * lynx::ppq;
  1771. s.playlist.push_back (c);
  1772. CHECK (s.songLength() == 8 * lynx::ppq);
  1773. const double sr = 48000.0;
  1774. const auto tps = lynx::ticksPerSample (120.0, sr); // 1 beat = 24000 samples
  1775. lynx::EventBuffer ev;
  1776. // whole song in a single block (8 beats = 192000 samples)
  1777. lynx::scheduleSong (s, 0.0, 192000, tps, ev);
  1778. std::vector<int> ons;
  1779. for (auto& e : ev)
  1780. if (e.type == lynx::NoteEvent::Type::on)
  1781. ons.push_back (e.sampleOffset);
  1782. CHECK (ons.size() == 2);
  1783. CHECK (ons.size() == 2 && ons[0] == 4 * 24000 && ons[1] == 5 * 24000);
  1784. // crossing the loop: bar 1 is empty, so nothing at the start of the second pass
  1785. ev.clear();
  1786. lynx::scheduleSong (s, 8.0 * lynx::ppq - 100 * tps, 200, tps, ev);
  1787. CHECK (ev.size() == 0);
  1788. // a note longer than the clip is cut at the clip end
  1789. p.notes[3].length = 4 * lynx::ppq;
  1790. ev.clear();
  1791. lynx::scheduleSong (s, 0.0, 192000, tps, ev);
  1792. int lastOff = -1;
  1793. for (auto& e : ev)
  1794. if (e.type == lynx::NoteEvent::Type::off)
  1795. lastOff = std::max (lastOff, e.sampleOffset);
  1796. CHECK (lastOff == 6 * 24000);
  1797. }
  1798. TEST (remove_pattern_fixes_clips)
  1799. {
  1800. lynx::Song s;
  1801. s.patterns.resize (3);
  1802. s.currentPattern = 2;
  1803. s.playlist = { { 0, 0, 0, 100, 0 }, { 1, 0, 100, 100, 0 }, { 2, 1, 0, 100, 0 } };
  1804. s.removePattern (1);
  1805. CHECK (s.patterns.size() == 2);
  1806. CHECK (s.playlist.size() == 2 && s.playlist[1].pattern == 1);
  1807. CHECK (s.currentPattern == 1);
  1808. }
  1809. TEST (flp_import_3x_osc_state_and_channel_filter)
  1810. {
  1811. // new 3x Osc patch (version 14): osc 2 mix 64 coarse -12, osc 3 mix 32 coarse -24
  1812. std::vector<std::uint8_t> blob (460, 0);
  1813. auto put = [&] (std::size_t off, std::int32_t v) {
  1814. for (int b = 0; b < 4; ++b)
  1815. blob[off + (std::size_t) b] = (std::uint8_t) ((std::uint32_t) v >> (8 * b));
  1816. };
  1817. put (0x00, 14);
  1818. put (0x08, 3); // osc 1 saw
  1819. put (0x10, 7); // osc 1 fine +7
  1820. put (0x04, -32); // osc 1 pan -0.5
  1821. put (0x1C, 64); // osc 2 mix
  1822. put (0x28, -12); // osc 2 coarse
  1823. put (0x38, 32); // osc 3 mix
  1824. put (0x40, 2); // osc 3 square
  1825. put (0x44, -19); // osc 3 coarse: -1 octave and -7 semitones
  1826. lynx::SynthSettings s;
  1827. CHECK (lynx::synthFrom3xOsc (blob, s));
  1828. 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);
  1829. CHECK (s.osc[0].wave == lynx::Waveform::saw && s.osc[0].detune == 7.0f && s.osc[0].pan == -0.5f);
  1830. CHECK (s.osc[1].wave == lynx::Waveform::sine && s.osc[1].octave == -1 && s.osc[1].semitones == 0);
  1831. CHECK (s.osc[2].wave == lynx::Waveform::square && s.osc[2].octave == -1 && s.osc[2].semitones == -7);
  1832. CHECK (! lynx::synthFrom3xOsc (std::vector<std::uint8_t> (40, 0), s));
  1833. // channel filter: open by default; LP with Mod X 128 ~ 2.71 kHz; Fast LP with Mod X 128 ~ 280 Hz
  1834. float hz = 0.0f, res = 1.0f;
  1835. int mode = -1;
  1836. lynx::synthFilterFromChannel (256, 0, 0, hz, res, mode);
  1837. CHECK (hz >= 19999.0f && res == 0.0f);
  1838. lynx::synthFilterFromChannel (128, 0, 1, hz, res, mode);
  1839. CHECK (std::abs (hz - 2710.0f) < 30.0f && res == 0.0f);
  1840. lynx::synthFilterFromChannel (128, 0, 0, hz, res, mode);
  1841. CHECK (hz > 240.0f && hz < 320.0f);
  1842. lynx::synthFilterFromChannel (128, 256, 1, hz, res, mode);
  1843. CHECK (res > 0.8f);
  1844. CHECK (mode == 0);
  1845. lynx::synthFilterFromChannel (64, 0, 3, hz, res, mode); // high-pass at ~840 Hz
  1846. CHECK (mode == 2 && std::abs (hz - 840.0f) < 40.0f);
  1847. lynx::synthFilterFromChannel (128, 0, 2, hz, res, mode); // band-pass
  1848. CHECK (mode == 1);
  1849. }
  1850. TEST (synth_pitch_and_filter_envelopes)
  1851. {
  1852. auto render = [] (const lynx::SynthSettings& s, int frames) {
  1853. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  1854. inst->prepare (48000.0);
  1855. lynx::ChannelDef c;
  1856. c.synth = s;
  1857. inst->configure (c, 120.0);
  1858. inst->noteOn (45, 1.0f); // A2 = 110 Hz
  1859. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  1860. inst->render (l.data(), r.data(), frames, 1.0f, 1.0f);
  1861. return l;
  1862. };
  1863. auto crossings = [] (const std::vector<float>& b, int from, int to) {
  1864. int n = 0;
  1865. for (int i = from + 1; i < to; ++i)
  1866. n += (b[(std::size_t) i - 1] < 0.0f) != (b[(std::size_t) i] < 0.0f);
  1867. return n;
  1868. };
  1869. // 3x Osc "kick": sine with a +24 st pitch envelope falling fast
  1870. lynx::SynthSettings kick;
  1871. kick.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  1872. kick.cutoff = 20000.0f;
  1873. kick.pitchEnv = { 24.0f, 0.0f, 0.0f, 0.05f, 0.0f, 0.05f };
  1874. const auto k = render (kick, 48000);
  1875. const auto early = crossings (k, 0, 2400); // first 50 ms: well above 110 Hz
  1876. const auto late = crossings (k, 24000, 48000); // then back to 110 Hz (~110 crossings in 0.5 s)
  1877. CHECK (early > 20); // +24 st ramp over 50 ms: ~2.2x the average frequency (11 crossings without envelope)
  1878. CHECK (std::abs (late - 110) < 4);
  1879. // cutoff envelope: saw closed at 200 Hz opens +5 octaves on attack and closes again
  1880. lynx::SynthSettings pluck;
  1881. pluck.cutoff = 200.0f;
  1882. pluck.filterEnv = { 5.0f, 0.0f, 0.0f, 0.1f, 0.0f, 0.1f };
  1883. const auto p = render (pluck, 48000);
  1884. auto hf = [&] (int from, int to) { // energy of the difference (highs)
  1885. double e = 0.0;
  1886. for (int i = from + 1; i < to; ++i)
  1887. e += std::pow ((double) p[(std::size_t) i] - p[(std::size_t) i - 1], 2.0);
  1888. return e;
  1889. };
  1890. CHECK (hf (0, 2400) > 4.0 * hf (40000, 42400));
  1891. // Toxic Biohazard's envelope (REA_rodada33 §2): exponential towards 5 clipped at 1, so the cutoff is still near
  1892. // its base early in the attack, fully open at A = 0.2 s and back down after the exponential decay
  1893. lynx::SynthSettings toxic = pluck;
  1894. toxic.filterEnv = { 5.0f, 0.2f, 0.0f, 0.1f, 0.0f, 0.1f, 1 };
  1895. const auto t = render (toxic, 48000);
  1896. auto thf = [&] (int from, int to) {
  1897. double e = 0.0;
  1898. for (int i = from + 1; i < to; ++i)
  1899. e += std::pow ((double) t[(std::size_t) i] - t[(std::size_t) i - 1], 2.0);
  1900. return e;
  1901. };
  1902. CHECK (thf (9000, 9600) > 4.0 * thf (300, 900));
  1903. CHECK (thf (9000, 9600) > 4.0 * thf (40000, 40600));
  1904. }
  1905. TEST (synth_mono_reuses_the_sounding_voice)
  1906. {
  1907. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  1908. inst->prepare (48000.0);
  1909. lynx::ChannelDef c;
  1910. c.synth.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  1911. c.synth.cutoff = 20000.0f;
  1912. c.synth.mono = true;
  1913. inst->configure (c, 120.0);
  1914. std::vector<float> l (48000), r (48000);
  1915. inst->noteOn (57, 1.0f);
  1916. inst->render (l.data(), r.data(), 4800, 1.0f, 1.0f);
  1917. inst->noteOn (69, 1.0f); // A4 takes over the A3 voice: only one note sounding
  1918. inst->render (l.data() + 4800, r.data() + 4800, 43200, 1.0f, 1.0f);
  1919. int crossings = 0;
  1920. float peak = 0.0f;
  1921. for (std::size_t i = 24001; i < 48000; ++i)
  1922. {
  1923. crossings += (l[i - 1] < 0.0f) != (l[i] < 0.0f);
  1924. peak = std::max (peak, std::abs (l[i]));
  1925. }
  1926. CHECK (std::abs (crossings - 440) < 4); // 0.5 s of 440 Hz, without the A3 underneath
  1927. CHECK (peak < 0.35f); // one voice (0.3 level), not two summed
  1928. // no click on the handover: the jump between neighbouring samples stays sine-sized
  1929. float jump = 0.0f;
  1930. for (std::size_t i = 4790; i < 4810; ++i)
  1931. jump = std::max (jump, std::abs (l[i] - l[i - 1]));
  1932. CHECK (jump < 0.05f);
  1933. }
  1934. TEST (synth_porta_glides_and_am_modulates)
  1935. {
  1936. auto make = [] (const lynx::SynthSettings& s) {
  1937. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  1938. inst->prepare (48000.0);
  1939. lynx::ChannelDef c;
  1940. c.synth = s;
  1941. inst->configure (c, 120.0);
  1942. return inst;
  1943. };
  1944. auto crossings = [] (const std::vector<float>& b, std::size_t from, std::size_t to) {
  1945. int n = 0;
  1946. for (auto i = from + 1; i < to; ++i)
  1947. n += (b[i - 1] < 0.0f) != (b[i] < 0.0f);
  1948. return n;
  1949. };
  1950. // mono + 1-beat porta (0.5 s at 120 BPM): from A3 to A4, halfway ~E4 (329.6 Hz)
  1951. lynx::SynthSettings s;
  1952. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  1953. s.cutoff = 20000.0f;
  1954. s.mono = true;
  1955. s.porta = true;
  1956. s.portaBeats = 1.0f;
  1957. auto inst = make (s);
  1958. std::vector<float> l (96000), r (96000);
  1959. inst->noteOn (57, 1.0f);
  1960. inst->render (l.data(), r.data(), 4800, 1.0f, 1.0f);
  1961. inst->noteOn (69, 1.0f);
  1962. inst->render (l.data() + 4800, r.data() + 4800, 91200, 1.0f, 1.0f);
  1963. const auto middle = crossings (l, 4800 + 12000 - 2400, 4800 + 12000 + 2400); // 0.1 s around 0.25 s
  1964. CHECK (std::abs (middle - 66) < 6); // ~330 Hz * 0.1 s * 2
  1965. CHECK (std::abs (crossings (l, 48000, 96000) - 880) < 4); // reached A4 (1 s = 880 crossings)
  1966. // AM: osc 3 at level 1.0, slow sine, modulates osc 1 (the average level drops, the sum doesn't gain osc 3)
  1967. lynx::SynthSettings am;
  1968. am.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  1969. am.osc[2] = { lynx::Waveform::sine, -3, 0.0f, 1.0f };
  1970. am.cutoff = 20000.0f;
  1971. am.am = true;
  1972. auto modulated = make (am);
  1973. modulated->noteOn (69, 1.0f);
  1974. std::fill (l.begin(), l.end(), 0.0f);
  1975. modulated->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  1976. float peak = 0.0f;
  1977. for (std::size_t i = 4800; i < 48000; ++i)
  1978. peak = std::max (peak, std::abs (l[i]));
  1979. CHECK (peak > 0.45f && peak < 0.65f); // 0.3 · (1 + 1) at most: (1 − o3) goes up to 2
  1980. }
  1981. TEST (channel_lfo_vibrato_and_tremolo)
  1982. {
  1983. auto render = [] (const lynx::SynthSettings& s) {
  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 (69, 1.0f);
  1990. std::vector<float> l (48000), r (48000);
  1991. inst->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  1992. return l;
  1993. };
  1994. lynx::SynthSettings s;
  1995. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  1996. s.cutoff = 20000.0f;
  1997. // tremolo: 100% volume LFO at 4 Hz (0.25 s period) -> the amplitude envelope goes from ~0 to ~2x
  1998. auto tremolo = s;
  1999. tremolo.lfo[lynx::lfoVolume] = { 1.0f, 0.25f, false, 0, 0.0f, 0.0f };
  2000. const auto t = render (tremolo);
  2001. float lowest = 1.0f, highest = 0.0f;
  2002. for (std::size_t w = 4800; w + 480 <= 48000; w += 480) // 10 ms windows (4.4 cycles of 440 Hz)
  2003. {
  2004. float peak = 0.0f;
  2005. for (auto i = w; i < w + 480; ++i)
  2006. peak = std::max (peak, std::abs (t[i]));
  2007. lowest = std::min (lowest, peak);
  2008. highest = std::max (highest, peak);
  2009. }
  2010. CHECK (lowest < 0.08f && highest > 0.5f);
  2011. // synced vibrato: ±1 semitone, 1-beat period (0.5 s at 120 BPM); the average stays at 440 Hz
  2012. auto vibrato = s;
  2013. vibrato.lfo[lynx::lfoPitch] = { 1.0f, 1.0f, true, 0, 0.0f, 0.0f };
  2014. const auto v = render (vibrato);
  2015. int crossings = 0;
  2016. for (std::size_t i = 1; i < 48000; ++i)
  2017. crossings += (v[i - 1] < 0.0f) != (v[i] < 0.0f);
  2018. CHECK (std::abs (crossings - 880) < 12);
  2019. int firstQuarter = 0; // first quarter of the cycle: rising sine -> higher than 440
  2020. for (std::size_t i = 1; i < 6000; ++i)
  2021. firstQuarter += (v[i - 1] < 0.0f) != (v[i] < 0.0f);
  2022. CHECK (firstQuarter > 112);
  2023. }
  2024. TEST (sampler_porta_glides_from_previous_note)
  2025. {
  2026. auto data = std::make_shared<lynx::SampleData>();
  2027. data->sampleRate = 48000.0;
  2028. data->left.resize (96000);
  2029. for (std::size_t i = 0; i < data->left.size(); ++i)
  2030. data->left[i] = 0.5f * (float) std::sin (6.283185307 * 220.0 * (double) i / 48000.0);
  2031. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  2032. inst->prepare (48000.0);
  2033. lynx::ChannelDef c;
  2034. c.sampler.cut = true;
  2035. c.sampler.porta = true;
  2036. c.sampler.portaBeats = 1.0f; // 0.5 s at 120 BPM
  2037. inst->configure (c, 120.0);
  2038. std::vector<float> l (24000), r (24000);
  2039. inst->noteOn (60, 1.0f);
  2040. inst->render (l.data(), r.data(), 2400, 1.0f, 1.0f);
  2041. inst->noteOn (72, 1.0f); // one octave up: starts at 220 Hz and rises
  2042. std::fill (l.begin(), l.end(), 0.0f);
  2043. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  2044. auto crossings = [&] (std::size_t from, std::size_t to) {
  2045. int n = 0;
  2046. for (auto i = from + 1; i < to; ++i)
  2047. n += (l[i - 1] < 0.0f) != (l[i] < 0.0f);
  2048. return n;
  2049. };
  2050. const auto start = crossings (600, 2400); // 37.5 ms still near 220 Hz: ~17 crossings (440 Hz would give 33)
  2051. const auto end = crossings (21600, 24000); // 50 ms at the end of the glide: near 440 Hz (~44; 220 Hz would give 22)
  2052. CHECK (start < 22);
  2053. CHECK (end > 36);
  2054. }
  2055. TEST (zoned_sampler_picks_zone_by_key_and_velocity)
  2056. {
  2057. auto sine = [] (double hz, float amp) {
  2058. auto d = std::make_shared<lynx::SampleData>();
  2059. d->sampleRate = 48000.0;
  2060. d->left.resize (48000);
  2061. for (std::size_t i = 0; i < d->left.size(); ++i)
  2062. d->left[i] = amp * (float) std::sin (6.283185307 * hz * (double) i / 48000.0);
  2063. return d;
  2064. };
  2065. // lows: 220 Hz sine recorded as A3 (57), up to key 69; highs: 880 Hz as A5 (81)
  2066. // hard layer on the highs: same tuning, louder
  2067. std::vector<lynx::LoadedZone> zones {
  2068. { { "graves.wav", 57, 0, 69, 0, 127, 0.0f, 1.0f }, sine (220.0, 0.5f) },
  2069. { { "agudos.wav", 81, 70, 127, 0, 99, 0.0f, 1.0f }, sine (880.0, 0.25f) },
  2070. { { "agudos forte.wav", 81, 70, 127, 100, 127, 0.0f, 1.0f }, sine (880.0, 0.9f) },
  2071. };
  2072. auto inst = lynx::makeZonedSampler (zones);
  2073. inst->prepare (48000.0);
  2074. inst->configure (lynx::ChannelDef {}, 120.0);
  2075. auto play = [&] (int key, float velocity) {
  2076. inst->allNotesOff();
  2077. std::vector<float> l (24000), r (24000);
  2078. inst->render (l.data(), r.data(), 2000, 1.0f, 1.0f); // let the old voices die out
  2079. std::fill (l.begin(), l.end(), 0.0f);
  2080. inst->noteOn (key, velocity);
  2081. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  2082. int crossings = 0;
  2083. float peak = 0.0f;
  2084. for (std::size_t i = 1; i < 24000; ++i)
  2085. {
  2086. crossings += (l[i - 1] < 0.0f) != (l[i] < 0.0f);
  2087. peak = std::max (peak, std::abs (l[i]));
  2088. }
  2089. return std::pair { crossings, peak };
  2090. };
  2091. const auto low = play (69, 0.5f); // A4 from root A3: 440 Hz -> 440 crossings in 0.5 s
  2092. CHECK (std::abs (low.first - 440) < 4);
  2093. const auto soft = play (81, 0.5f); // high zone at the root: 880 Hz
  2094. CHECK (std::abs (soft.first - 880) < 6);
  2095. const auto hard = play (81, 0.95f); // high velocity: hard layer
  2096. CHECK (hard.second > soft.second * 2.0f);
  2097. // overlapping layers round-robin: two identical zones at different levels, notes alternate
  2098. auto rr = lynx::makeZonedSampler ({ { { "a.wav", 60 }, sine (440.0, 0.2f) }, { { "b.wav", 60 }, sine (440.0, 0.8f) } });
  2099. rr->prepare (48000.0);
  2100. rr->configure (lynx::ChannelDef {}, 120.0);
  2101. float peaks[2] {};
  2102. for (int k = 0; k < 2; ++k)
  2103. {
  2104. rr->allNotesOff();
  2105. std::vector<float> l (4800), r (4800);
  2106. rr->render (l.data(), r.data(), 2000, 1.0f, 1.0f);
  2107. std::fill (l.begin(), l.end(), 0.0f);
  2108. rr->noteOn (60, 1.0f);
  2109. rr->render (l.data(), r.data(), 4800, 1.0f, 1.0f);
  2110. for (auto v : l)
  2111. peaks[k] = std::max (peaks[k], std::abs (v));
  2112. }
  2113. CHECK (std::abs (peaks[0] - peaks[1]) > 0.3f);
  2114. }
  2115. TEST (zoned_sampler_loops_while_held)
  2116. {
  2117. // 0.1 s sample with a loop in the middle: holding the note it keeps sounding well past the end of the file;
  2118. // on release, it leaves the loop and ends
  2119. auto data = std::make_shared<lynx::SampleData>();
  2120. data->sampleRate = 48000.0;
  2121. data->left.resize (4800);
  2122. for (std::size_t i = 0; i < data->left.size(); ++i)
  2123. data->left[i] = 0.5f * (float) std::sin (6.283185307 * 480.0 * (double) i / 48000.0); // 100 frames per cycle
  2124. lynx::SampleZone zone { "loop.wav", 60 };
  2125. zone.loopStart = 1000;
  2126. zone.loopEnd = 3000;
  2127. zone.loopMode = 2;
  2128. auto inst = lynx::makeZonedSampler ({ { zone, data } });
  2129. inst->prepare (48000.0);
  2130. lynx::ChannelDef c;
  2131. c.sampler.release = 0.01f;
  2132. inst->configure (c, 120.0);
  2133. inst->noteOn (60, 1.0f);
  2134. std::vector<float> l (48000), r (48000);
  2135. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f); // 0.5 s held
  2136. float held = 0.0f;
  2137. for (std::size_t i = 20000; i < 24000; ++i)
  2138. held = std::max (held, std::abs (l[i]));
  2139. CHECK (held > 0.3f);
  2140. inst->noteOff (60);
  2141. inst->render (l.data() + 24000, r.data() + 24000, 24000, 1.0f, 1.0f);
  2142. float after = 0.0f;
  2143. for (std::size_t i = 40000; i < 48000; ++i)
  2144. after = std::max (after, std::abs (l[i]));
  2145. CHECK (after == 0.0f);
  2146. }
  2147. TEST (global_lfo_follows_song_position)
  2148. {
  2149. // global volume LFO (1-beat period): a note mid-cycle starts mid-wave; the
  2150. // same note with a per-note LFO starts at phase 0
  2151. auto first = [] (bool global, double songTicks) {
  2152. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  2153. inst->prepare (48000.0);
  2154. lynx::ChannelDef c;
  2155. c.synth.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  2156. c.synth.cutoff = 20000.0f;
  2157. c.synth.lfo[lynx::lfoVolume] = { 1.0f, 1.0f, true, 2, 0.0f, 0.0f, global }; // pulse: +1 in the first half
  2158. inst->configure (c, 120.0);
  2159. inst->setSongPosition (songTicks);
  2160. inst->noteOn (69, 1.0f);
  2161. std::vector<float> l (4800), r (4800);
  2162. inst->render (l.data(), r.data(), 4800, 1.0f, 1.0f);
  2163. float peak = 0.0f;
  2164. for (std::size_t i = 2400; i < 4800; ++i)
  2165. peak = std::max (peak, std::abs (l[i]));
  2166. return peak;
  2167. };
  2168. // mid-cycle (phase 0.6) the pulse is at −1: volume ~0; per note (phase 0) it is at +1: ~2x
  2169. const auto globalLate = first (true, 0.6 * lynx::ppq);
  2170. const auto perNote = first (false, 0.6 * lynx::ppq);
  2171. CHECK (globalLate < 0.05f);
  2172. CHECK (perNote > 0.4f);
  2173. }
  2174. TEST (sampler_channel_filter_darkens_and_bypasses_when_open)
  2175. {
  2176. // white noise in the sampler: with a 300 Hz cutoff the energy drops a lot; open passes unchanged
  2177. auto data = std::make_shared<lynx::SampleData>();
  2178. data->sampleRate = 48000.0;
  2179. data->left.resize (48000);
  2180. std::uint32_t seed = 7;
  2181. for (auto& v : data->left)
  2182. {
  2183. seed = seed * 1664525u + 1013904223u;
  2184. v = ((float) (seed >> 8) / 16777216.0f - 0.5f);
  2185. }
  2186. data->right = data->left;
  2187. auto energy = [&] (float cutoff) {
  2188. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  2189. inst->prepare (48000.0);
  2190. lynx::ChannelDef c;
  2191. c.sampler.cutoff = cutoff;
  2192. inst->configure (c, 120.0);
  2193. inst->noteOn (60, 1.0f);
  2194. std::vector<float> l (24000), r (24000);
  2195. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  2196. double e = 0.0;
  2197. for (auto v : l)
  2198. e += (double) v * v;
  2199. return e;
  2200. };
  2201. const auto open = energy (20000.0f), dark = energy (300.0f);
  2202. {
  2203. // high-pass at 10 kHz: also removes most of the noise energy, but from the other side
  2204. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  2205. inst->prepare (48000.0);
  2206. lynx::ChannelDef hp;
  2207. hp.sampler.cutoff = 10000.0f;
  2208. hp.sampler.filterType = 2;
  2209. inst->configure (hp, 120.0);
  2210. inst->noteOn (60, 1.0f);
  2211. std::vector<float> l (24000), r (24000);
  2212. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  2213. double e = 0.0, lowE = 0.0;
  2214. float lp = 0.0f;
  2215. for (auto v : l)
  2216. {
  2217. e += (double) v * v;
  2218. lp += 0.01f * (v - lp); // crude low-pass: almost nothing should remain below
  2219. lowE += (double) lp * lp;
  2220. }
  2221. CHECK (e > 10.0 && e < 0.7 * energy (20000.0f));
  2222. CHECK (lowE < e * 0.01);
  2223. }
  2224. CHECK (open > 100.0);
  2225. CHECK (dark < open * 0.05);
  2226. // +12 st pitch envelope with sustain 1: the sample runs at double speed
  2227. // and ends in half the time (1 s of sample -> 0.5 s)
  2228. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  2229. inst->prepare (48000.0);
  2230. lynx::ChannelDef c;
  2231. c.sampler.pitchEnv = { 12.0f, 0.0f, 0.0f, 0.1f, 1.0f, 0.1f };
  2232. inst->configure (c, 120.0);
  2233. inst->noteOn (60, 1.0f);
  2234. std::vector<float> l (48000), r (48000);
  2235. inst->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  2236. float tail = 0.0f, body = 0.0f;
  2237. for (std::size_t i = 20000; i < 23000; ++i)
  2238. body = std::max (body, std::abs (l[i]));
  2239. for (std::size_t i = 25000; i < 48000; ++i)
  2240. tail = std::max (tail, std::abs (l[i]));
  2241. CHECK (body > 0.1f);
  2242. CHECK (tail == 0.0f);
  2243. }
  2244. TEST (synth_oscillator_pan_and_semitones)
  2245. {
  2246. auto render = [] (lynx::SynthSettings s, std::vector<float>& l, std::vector<float>& r) {
  2247. auto synth = lynx::makeInstrument (lynx::InstrumentKind::synth);
  2248. synth->prepare (48000.0);
  2249. lynx::ChannelDef c;
  2250. c.synth = s;
  2251. synth->configure (c, 120.0);
  2252. synth->noteOn (69, 1.0f);
  2253. l.assign (24000, 0.0f);
  2254. r.assign (24000, 0.0f);
  2255. synth->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  2256. };
  2257. lynx::SynthSettings s;
  2258. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f, 7, 1.0f }; // a fifth up, fully right
  2259. s.cutoff = 20000.0f;
  2260. std::vector<float> l, r;
  2261. render (s, l, r);
  2262. float peakL = 0.0f, peakR = 0.0f;
  2263. int crossings = 0;
  2264. for (std::size_t i = 4800; i < 24000; ++i)
  2265. {
  2266. peakL = std::max (peakL, std::abs (l[i]));
  2267. peakR = std::max (peakR, std::abs (r[i]));
  2268. crossings += (r[i - 1] < 0.0f) != (r[i] < 0.0f);
  2269. }
  2270. CHECK (peakL < 1e-4f && peakR > 0.1f);
  2271. // 440 * 2^(7/12) = 659.3 Hz; 0.4 s = 263.7 cycles = ~527 crossings
  2272. CHECK (std::abs (crossings - 527) < 6);
  2273. }
  2274. TEST (fl_wrapper_state_parses_records_and_vst3_state)
  2275. {
  2276. // Fruity Wrapper blob (version 12): VST3 generator type, class ID, name, path and state
  2277. std::vector<std::uint8_t> blob;
  2278. 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))); };
  2279. auto record = [&] (std::vector<std::uint8_t>& b, std::uint32_t id, const std::vector<std::uint8_t>& payload) {
  2280. u32 (b, id);
  2281. u32 (b, (std::uint32_t) payload.size());
  2282. u32 (b, 0);
  2283. b.insert (b.end(), payload.begin(), payload.end());
  2284. };
  2285. auto bytes = [] (const std::string& s) { return std::vector<std::uint8_t> (s.begin(), s.end()); };
  2286. std::vector<std::uint8_t> vst3State;
  2287. u32 (vst3State, 1);
  2288. record (vst3State, 1, std::vector<std::uint8_t> (64, 0));
  2289. record (vst3State, 3, bytes ("COMPONENTE"));
  2290. record (vst3State, 2, bytes ("CONTROLADOR"));
  2291. // record 4: 3 slots → ParamIDs 700, −1 (empty), 0xFFFFFF01
  2292. std::vector<std::uint8_t> slots;
  2293. for (auto v : { 3u, 700u, 0xFFFFFFFFu, 0xFFFFFF01u })
  2294. u32 (slots, v);
  2295. record (vst3State, 4, slots);
  2296. u32 (blob, 12);
  2297. record (blob, 0x01, std::vector<std::uint8_t> (20, 0xFF));
  2298. record (blob, 0x32, { 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });
  2299. std::vector<std::uint8_t> cid;
  2300. for (int i = 0; i < 16; ++i)
  2301. cid.push_back ((std::uint8_t) (0xA0 + i));
  2302. record (blob, 0x34, cid);
  2303. record (blob, 0x36, bytes ("Surge XT"));
  2304. record (blob, 0x37, bytes ("C:/Program Files/Common Files/VST3/Surge XT.vst3"));
  2305. record (blob, 0x35, vst3State);
  2306. lynx::ForeignPlugin p;
  2307. CHECK (lynx::parseFlWrapper (blob, p));
  2308. CHECK (p.format == lynx::ForeignPlugin::Format::vst3);
  2309. CHECK (p.hasClassId && p.classId[0] == 0xA0 && p.classId[15] == 0xAF);
  2310. CHECK (p.name == "Surge XT" && p.path.find ("Surge XT.vst3") != std::string::npos);
  2311. std::vector<std::uint8_t> component, controller;
  2312. CHECK (lynx::splitFlVst3State (p.state, component, controller));
  2313. CHECK (component == bytes ("COMPONENTE") && controller == bytes ("CONTROLADOR"));
  2314. const auto saved = lynx::flVst3ParamSlots (p.state);
  2315. CHECK (saved == (std::vector<std::int32_t> { 700, -1, (std::int32_t) 0xFFFFFF01u }));
  2316. // FL's slot assignment: saved slots keep their ParamID wherever it now sits; the empty slot stays empty;
  2317. // a vanished ParamID (0xFFFFFF01) leaves its slot dead; parameters without a slot get slots 3, 4… in list order
  2318. const auto positions = lynx::flVst3SlotPositions (saved, { 5u, 700u, 9u });
  2319. CHECK (positions == (std::vector<int> { 1, -1, -1, 0, 2 }));
  2320. CHECK (lynx::flVst3SlotPositions ({}, { 5u, 6u }) == (std::vector<int> { 0, 1 })); // new instance: slot = position
  2321. // version out of range or no type: not a usable wrapper
  2322. blob[0] = 13;
  2323. CHECK (! lynx::parseFlWrapper (blob, p));
  2324. CHECK (! lynx::parseFlWrapper ({ 12, 0, 0, 0 }, p));
  2325. }
  2326. TEST (schedule_index_matches_full_scan)
  2327. {
  2328. // random song (long notes, swing, clips with offset); indexed scheduling must yield
  2329. // exactly the same events as the full scan, including in the block that wraps around
  2330. lynx::Song s = lynx::Song::makeDefault();
  2331. s.swing = 0.6f;
  2332. std::uint32_t seed = 12345;
  2333. auto rnd = [&] (int n) { seed = seed * 1664525u + 1013904223u; return (int) ((seed >> 8) % (std::uint32_t) n); };
  2334. s.patterns.resize (3);
  2335. for (auto& p : s.patterns)
  2336. {
  2337. p.notes.clear();
  2338. for (int i = 0; i < 60; ++i)
  2339. {
  2340. lynx::Note n;
  2341. n.start = rnd (16 * lynx::ppq);
  2342. n.length = rnd (5) == 0 ? rnd (12 * lynx::ppq) + 1 : rnd (lynx::ppq) + 1;
  2343. n.channel = rnd (4);
  2344. n.key = 40 + rnd (40);
  2345. n.slide = rnd (20) == 0;
  2346. p.notes.push_back (n);
  2347. }
  2348. p.sortNotes();
  2349. }
  2350. s.playlist.clear();
  2351. for (int i = 0; i < 12; ++i)
  2352. {
  2353. lynx::Clip c;
  2354. c.pattern = rnd (3);
  2355. c.track = rnd (4);
  2356. c.start = rnd (40) * lynx::ppq;
  2357. c.length = (rnd (12) + 1) * lynx::ppq;
  2358. c.offset = rnd (4) * lynx::ppq;
  2359. s.playlist.push_back (c);
  2360. }
  2361. s.mode = lynx::PlayMode::song;
  2362. const auto index = lynx::makeScheduleIndex (s);
  2363. const auto tps = lynx::ticksPerSample (140.0, 48000.0);
  2364. const auto loop = (double) s.songLength();
  2365. int mismatches = 0, events = 0;
  2366. for (int block = 0; block < 400; ++block)
  2367. {
  2368. const auto start = block == 0 ? loop - 100.0 * tps : (double) rnd ((int) loop * 2);
  2369. const auto samples = 64 + rnd (24000); // up to ~1 beat per block
  2370. lynx::EventBuffer a, b;
  2371. lynx::scheduleSong (s, start, samples, tps, a, false, nullptr);
  2372. lynx::scheduleSong (s, start, samples, tps, b, false, &index);
  2373. events += a.size();
  2374. if (a.size() != b.size())
  2375. {
  2376. ++mismatches;
  2377. continue;
  2378. }
  2379. for (int i = 0; i < a.size(); ++i)
  2380. {
  2381. const auto& x = *(a.begin() + i);
  2382. const auto& y = *(b.begin() + i);
  2383. mismatches += x.sampleOffset != y.sampleOffset || x.type != y.type || x.key != y.key || x.channel != y.channel;
  2384. }
  2385. }
  2386. CHECK (events > 500);
  2387. CHECK (mismatches == 0);
  2388. }
  2389. TEST (mixer_track_eq_defaults_and_boost)
  2390. {
  2391. // FL defaults: 90 Hz, 1.5 kHz and 8 kHz; peak Q 0.632; shelf slope 0.607
  2392. lynx::TrackEq eq;
  2393. CHECK (std::abs (lynx::TrackEq::peakQ (eq.width[1]) - 0.632) < 0.01);
  2394. CHECK (std::abs (lynx::TrackEq::shelfSlope (eq.width[0]) - 0.607) < 0.01);
  2395. CHECK (! eq.active());
  2396. // +12 dB peak at 1.5 kHz on a track: a 1.5 kHz sine rises ~4x
  2397. lynx::Song song = lynx::Song::makeDefault();
  2398. song.mixer[1].eq.gainDb[1] = 12.0f;
  2399. for (auto& c : song.channels)
  2400. c.mixerTrack = 1;
  2401. song.channels[4].instrument = lynx::InstrumentKind::synth;
  2402. song.channels[4].synth = {};
  2403. song.channels[4].synth.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  2404. song.channels[4].synth.cutoff = 20000.0f;
  2405. auto render = [] (const lynx::Song& s) {
  2406. auto state = lynx::RackState::build (s, nullptr, 48000.0);
  2407. lynx::RackRenderer renderer;
  2408. renderer.prepare (48000.0);
  2409. lynx::LiveEventQueue live;
  2410. lynx::NoteEvent on; // 1.5 kHz ~ key 90.6: use 91 (1568 Hz), still within the wide peak
  2411. on.channel = 4;
  2412. on.key = 91;
  2413. on.velocity = 1.0f;
  2414. live.push (on);
  2415. std::vector<float> l (24000), r (24000);
  2416. for (int pos = 0; pos < 24000; pos += 480)
  2417. renderer.process (state.get(), false, 0.0, 480, l.data() + pos, r.data() + pos, pos == 0 ? &live : nullptr);
  2418. float peak = 0.0f;
  2419. for (std::size_t i = 12000; i < 24000; ++i)
  2420. peak = std::max (peak, std::abs (l[i]));
  2421. return peak;
  2422. };
  2423. const auto boosted = render (song);
  2424. song.mixer[1].eq.gainDb[1] = 0.0f;
  2425. const auto flat = render (song);
  2426. CHECK (flat > 0.01f);
  2427. CHECK (boosted / flat > 3.0f && boosted / flat < 4.2f);
  2428. }
  2429. TEST (bars_follow_time_signature_markers)
  2430. {
  2431. lynx::Song song;
  2432. song.beatsPerBar = 4;
  2433. const auto bar4 = (std::int64_t) lynx::ppq * 4;
  2434. auto bars = song.barsBetween (0, bar4 * 3);
  2435. CHECK (bars.size() == 3 && bars[2].tick == bar4 * 2 && bars[2].number == 3);
  2436. // 7/4 from bar 3, and 3/4 in the middle of a 7 bar (cuts and restarts)
  2437. song.addMarker ({ bar4 * 2, "Verso", 7, 4 });
  2438. song.addMarker ({ bar4, "Nome só", 0, 4 });
  2439. const auto seven = (std::int64_t) lynx::ppq * 7;
  2440. song.addMarker ({ bar4 * 2 + seven + lynx::ppq * 2, "", 3, 4 });
  2441. bars = song.barsBetween (0, bar4 * 2 + seven * 2);
  2442. CHECK (bars.size() >= 5);
  2443. CHECK (bars[1].length == bar4 && bars[2].tick == bar4 * 2 && bars[2].length == seven);
  2444. CHECK (bars[3].length == lynx::ppq * 2); // cut short by the change
  2445. CHECK (bars[4].length == lynx::ppq * 3 && bars[4].number == 5);
  2446. CHECK (song.markers()[0].name == "Nome só"); // sorted by tick
  2447. // from far away: starts at the right bar without losing the numbering
  2448. const auto far = song.barsBetween (lynx::ppq * 3000, lynx::ppq * 3001);
  2449. CHECK (far.size() == 1 && far[0].length == lynx::ppq * 3);
  2450. CHECK (song.barAt (lynx::ppq * 3000).number == far[0].number);
  2451. CHECK ((lynx::ppq * 3000 - far[0].tick) < far[0].length);
  2452. }
  2453. TEST (split_drum_channel_moves_notes_to_pads)
  2454. {
  2455. lynx::Song song = lynx::Song::makeDefault();
  2456. const auto channels = (int) song.channels.size();
  2457. song.patterns[0].notes.clear();
  2458. song.patterns[0].notes.push_back ({ 0, 240, 1, 36, 0.9f }); // kit kick (channel 1)
  2459. song.patterns[0].notes.push_back ({ 240, 240, 1, 38, 0.8f }); // snare
  2460. song.patterns[0].notes.push_back ({ 480, 240, 1, 50, 0.8f }); // key without a pad: dropped
  2461. song.patterns[0].notes.push_back ({ 480, 240, 3, 60, 0.8f }); // other channel: shifts by 1 position
  2462. lynx::Automation a;
  2463. a.target = { lynx::AutomationTargetKind::channelVolume, 3, 0, 0 };
  2464. song.automations.push_back (a);
  2465. std::vector<lynx::DrumPad> pads (2);
  2466. pads[0].name = "Kick";
  2467. pads[0].key = 36;
  2468. pads[0].layers = { { "kick.wav" } };
  2469. pads[1].name = "Snare";
  2470. pads[1].key = 38;
  2471. pads[1].layers = { { "snare soft.wav", 60, 0, 127, 0, 90 }, { "snare hard.wav", 60, 0, 127, 91, 127 } };
  2472. pads[1].cutGroup = 2;
  2473. pads[1].cutBy = 2;
  2474. lynx::splitDrumChannel (song, 1, pads);
  2475. CHECK ((int) song.channels.size() == channels + 1);
  2476. CHECK (song.channels[1].samplePath == "kick.wav" && song.channels[1].instrument == lynx::InstrumentKind::sampler);
  2477. CHECK (song.channels[2].zones.size() == 2 && song.channels[2].cutGroup == song.channels[2].cutBy && song.channels[2].cutGroup != 0);
  2478. const auto& notes = song.patterns[0].notes;
  2479. CHECK (notes.size() == 3);
  2480. CHECK (notes[0].channel == 1 && notes[0].key == 60);
  2481. CHECK (notes[1].channel == 2 && notes[1].key == 60);
  2482. CHECK (notes[2].channel == 4); // the old channel 3
  2483. CHECK (song.automations[0].target.index == 4);
  2484. }
  2485. TEST (flp_import_brings_playlist)
  2486. {
  2487. flp::Project p;
  2488. p.header.ppq = 96;
  2489. p.channels = { { 0, flp::ChannelType::sampler, "Kick", "", "", 1 } };
  2490. flp::Pattern empty;
  2491. empty.index = 1;
  2492. flp::Pattern full;
  2493. full.index = 2;
  2494. flp::Note n;
  2495. n.channel = 0;
  2496. full.notes.push_back (n);
  2497. p.patterns = { empty, full };
  2498. flp::Arrangement a;
  2499. flp::PlaylistItem item;
  2500. item.kind = flp::PlaylistItem::Kind::pattern;
  2501. item.index = 2;
  2502. item.position = 384;
  2503. item.length = 192;
  2504. item.track = 3;
  2505. item.patternStartTick = 96;
  2506. a.items.push_back (item);
  2507. item.index = 1; // empty pattern: discarded
  2508. a.items.push_back (item);
  2509. item.kind = flp::PlaylistItem::Kind::channelClip; // audio: not supported yet
  2510. a.items.push_back (item);
  2511. p.arrangements.push_back (a);
  2512. const auto s = lynx::importFlp (p);
  2513. CHECK (s.mode == lynx::PlayMode::song);
  2514. CHECK (s.playlist.size() == 1);
  2515. CHECK (s.playlist[0].pattern == 0 && s.playlist[0].track == 3);
  2516. CHECK (s.playlist[0].start == 4 * lynx::ppq && s.playlist[0].length == 2 * lynx::ppq && s.playlist[0].offset == lynx::ppq);
  2517. }
  2518. TEST (rack_releases_notes_on_position_jump)
  2519. {
  2520. lynx::Song s;
  2521. lynx::ChannelDef c;
  2522. c.instrument = lynx::InstrumentKind::synth;
  2523. s.channels.push_back (c);
  2524. auto& p = s.patterns.emplace_back();
  2525. lynx::Note n;
  2526. n.start = 0;
  2527. n.length = 4 * lynx::ppq; // long note
  2528. p.notes.push_back (n);
  2529. s.bpm = 120.0;
  2530. auto state = lynx::RackState::build (s, nullptr, 48000.0);
  2531. lynx::RackRenderer r;
  2532. r.prepare (48000.0);
  2533. std::vector<float> l (512), rr (512);
  2534. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  2535. double tick = 0.0;
  2536. for (int i = 0; i < 20; ++i, tick += 512 * tps)
  2537. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  2538. // jump to tick 2000 (mid-note, no new "on"): the synth must go silent
  2539. for (int i = 0; i < 40; ++i)
  2540. r.process (state.get(), true, 2000.0 + i * 512 * tps, 512, l.data(), rr.data());
  2541. float tail = 0.0f;
  2542. for (auto v : l)
  2543. tail = std::max (tail, std::abs (v));
  2544. CHECK (tail < 0.001f);
  2545. }
  2546. namespace
  2547. {
  2548. // Two samplers with a constant 0.5 signal on different inserts; returns the output peak.
  2549. float juce_db (float gain)
  2550. {
  2551. return 20.0f * std::log10 (gain);
  2552. }
  2553. float renderMixerCase (const std::function<void (lynx::Song&)>& tweak, lynx::MeterBank* meters = nullptr)
  2554. {
  2555. lynx::Song s;
  2556. s.mixer = lynx::Song::defaultMixer (4);
  2557. for (int i = 0; i < 2; ++i)
  2558. {
  2559. lynx::ChannelDef c;
  2560. c.instrument = lynx::InstrumentKind::sampler;
  2561. c.samplePath = "dc";
  2562. c.volume = 1.0f;
  2563. c.mixerTrack = i + 1;
  2564. s.channels.push_back (c);
  2565. }
  2566. s.patterns.emplace_back();
  2567. tweak (s);
  2568. auto provider = [] (const std::string&) {
  2569. auto d = std::make_shared<lynx::SampleData>();
  2570. d->left.assign (48000, 0.5f);
  2571. return std::shared_ptr<const lynx::SampleData> (d);
  2572. };
  2573. auto state = lynx::RackState::build (s, nullptr, 48000.0, provider);
  2574. lynx::RackRenderer r;
  2575. r.prepare (48000.0, 256);
  2576. lynx::LiveEventQueue live;
  2577. for (int ch = 0; ch < 2; ++ch)
  2578. {
  2579. lynx::NoteEvent on;
  2580. on.channel = ch;
  2581. on.velocity = 1.0f;
  2582. live.push (on);
  2583. }
  2584. std::vector<float> l (1000), rr (1000); // larger than the mixer block: tests the chunking
  2585. r.process (state.get(), false, 0.0, 1000, l.data(), rr.data(), &live, meters);
  2586. return std::max (std::abs (l[999]), std::abs (rr[999]));
  2587. }
  2588. } // namespace
  2589. TEST (mixer_routes_mutes_solos_and_meters)
  2590. {
  2591. // two 0.5 channels summed on the Master at 0 dB
  2592. CHECK (std::abs (renderMixerCase ([] (lynx::Song&) {}) - 1.0f) < 1e-4f);
  2593. // insert 1 muted: only channel 2 remains
  2594. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.mixer[1].muted = true; }) - 0.5f) < 1e-4f);
  2595. // solo on insert 2: same
  2596. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.mixer[2].solo = true; }) - 0.5f) < 1e-4f);
  2597. // FL fader curve: 0.8 = 0 dB, max ≈ +5.6 dB, half travel ≈ -12.7 dB
  2598. CHECK (std::abs (lynx::faderGain (0.8f) - 1.0f) < 1e-5f);
  2599. CHECK (std::abs (juce_db (lynx::faderGain (1.0f)) - 5.59f) < 0.05f);
  2600. CHECK (lynx::faderGain (0.0f) == 0.0f);
  2601. // Master fader at max
  2602. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.mixer[0].volume = 1.0f; }) - lynx::faderGain (1.0f)) < 1e-4f);
  2603. // both channels on the same insert, insert fader at 0.4
  2604. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) {
  2605. s.channels[1].mixerTrack = 1;
  2606. s.mixer[1].volume = 0.4f;
  2607. }) - lynx::faderGain (0.4f)) < 1e-4f);
  2608. // a route outside the mixer falls to the last existing insert, without crashing
  2609. CHECK (renderMixerCase ([] (lynx::Song& s) { s.channels[0].mixerTrack = 100; }) > 0.9f);
  2610. // no mixer: everything straight to the output at 0 dB
  2611. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.mixer.clear(); }) - 1.0f) < 1e-4f);
  2612. lynx::MeterBank meters;
  2613. renderMixerCase ([] (lynx::Song&) {}, &meters);
  2614. CHECK (std::abs (meters.takePeak (1, 0) - 0.5f) < 1e-4f);
  2615. CHECK (std::abs (meters.takePeak (0, 1) - 1.0f) < 1e-4f);
  2616. CHECK (meters.takePeak (1, 0) == 0.0f); // reading resets
  2617. CHECK (meters.takePeak (3, 0) == 0.0f); // insert with no channel
  2618. }
  2619. TEST (next_free_insert_and_flp_mixer_import)
  2620. {
  2621. auto s = lynx::Song::makeDefault();
  2622. CHECK (s.mixer.size() == 17 && s.mixer[0].name == "Master");
  2623. CHECK (s.nextFreeInsert() == 6); // the 5 default channels take 1..5
  2624. flp::Project p;
  2625. p.channels = { { 0, flp::ChannelType::sampler, "Kick", "", "", 30 } };
  2626. p.mixer = { { 0, "" }, { 30, "Drums" } };
  2627. const auto song = lynx::importFlp (p);
  2628. CHECK (song.channels[0].mixerTrack == 30);
  2629. CHECK (song.mixer.size() == 31);
  2630. CHECK (song.mixer[30].name == "Drums" && song.mixer[0].name == "Master");
  2631. }
  2632. namespace
  2633. {
  2634. float runEffectOnSine (lynx::EffectKind kind, const std::function<void (lynx::EffectSlot&)>& tweak, double hz, float amp,
  2635. int frames = 48000)
  2636. {
  2637. auto fx = lynx::makeEffect (kind);
  2638. fx->prepare (48000.0);
  2639. auto slot = lynx::makeEffectSlot (kind);
  2640. tweak (slot);
  2641. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  2642. for (int i = 0; i < frames; ++i)
  2643. l[(std::size_t) i] = r[(std::size_t) i] = amp * (float) std::sin (6.283185307 * hz * i / 48000.0);
  2644. for (int i = 0; i < frames; i += 480)
  2645. fx->process (l.data() + i, r.data() + i, std::min (480, frames - i), slot.params, 120.0);
  2646. float peak = 0.0f;
  2647. for (int i = frames / 2; i < frames; ++i) // second half: already settled
  2648. {
  2649. CHECK (std::isfinite (l[(std::size_t) i]));
  2650. peak = std::max (peak, std::abs (l[(std::size_t) i]));
  2651. }
  2652. return peak;
  2653. }
  2654. } // namespace
  2655. TEST (parametric_eq_bands_and_response)
  2656. {
  2657. // default: transparent
  2658. auto slot = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  2659. CHECK (std::abs (lynx::peq::responseDb (slot.params, 48000.0, 1000.0)) < 0.01);
  2660. CHECK (std::abs (runEffectOnSine (lynx::EffectKind::parametricEq, [] (auto&) {}, 1000.0, 0.5f) - 0.5f) < 0.005f);
  2661. // +12 dB peak at 1 kHz on band 4: the response and the signal agree
  2662. auto boost = [] (lynx::EffectSlot& s) {
  2663. s.params[(std::size_t) lynx::peq::param (3, 1)] = lynx::peq::hzValue (1000.0);
  2664. s.params[(std::size_t) lynx::peq::param (3, 2)] = lynx::peq::gainValue (12.0);
  2665. };
  2666. boost (slot);
  2667. CHECK (std::abs (lynx::peq::responseDb (slot.params, 48000.0, 1000.0) - 12.0) < 0.2);
  2668. CHECK (std::abs (lynx::peq::responseDb (slot.params, 48000.0, 100.0)) < 1.0);
  2669. const auto peak = runEffectOnSine (lynx::EffectKind::parametricEq, boost, 1000.0, 0.1f);
  2670. CHECK (std::abs (peak - 0.1f * std::pow (10.0f, 12.0f / 20.0f)) < 0.01f);
  2671. // low cut at 48 dB/oct at 200 Hz: 50 Hz (2 octaves below) drops ~96 dB; 2 kHz passes
  2672. auto cut = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  2673. cut.params[(std::size_t) lynx::peq::param (0, 0)] = lynx::peq::typeValue (lynx::peq::BandType::lowCut);
  2674. cut.params[(std::size_t) lynx::peq::param (0, 1)] = lynx::peq::hzValue (200.0);
  2675. cut.params[(std::size_t) lynx::peq::param (0, 3)] = lynx::peq::qValue (0.70710678); // Butterworth
  2676. cut.params[(std::size_t) (lynx::peq::slopeParam + 0)] = 1.0f;
  2677. CHECK (lynx::peq::responseDb (cut.params, 48000.0, 50.0) < -80.0);
  2678. CHECK (std::abs (lynx::peq::responseDb (cut.params, 48000.0, 200.0) + 3.0) < 0.5); // -3 dB at the cutoff (Butterworth)
  2679. CHECK (std::abs (lynx::peq::responseDb (cut.params, 48000.0, 2000.0)) < 0.1);
  2680. // round-trip conversions
  2681. CHECK (std::abs (lynx::peq::hz (lynx::peq::hzValue (440.0)) - 440.0) < 0.5);
  2682. CHECK (std::abs (lynx::peq::q (lynx::peq::qValue (2.5)) - 2.5) < 0.01);
  2683. CHECK (lynx::peq::type (lynx::peq::typeValue (lynx::peq::BandType::notch)) == lynx::peq::BandType::notch);
  2684. }
  2685. TEST (fl_parametric_eq2_state_maps_to_bands)
  2686. {
  2687. // v8 blob: band 1 low cut at 100 Hz "Steep 8", band 4 peak +6 dB at 1 kHz, output −3 dB
  2688. std::vector<std::uint8_t> blob (354, 0);
  2689. auto put = [&] (std::size_t off, std::int32_t v) { std::memcpy (blob.data() + off, &v, 4); };
  2690. put (0, 8);
  2691. auto param = [&] (int i, std::int32_t v) { put (4 + 4 * (std::size_t) i, v); };
  2692. auto hzRaw = [] (double hz) { return (std::int32_t) std::lround (std::log (hz / 20.0) / std::log (1000.0) * 65536.0); };
  2693. for (int b = 0; b < 7; ++b)
  2694. param (21 + b, 0); // all off
  2695. param (21 + 0, 3); // high pass (= low cut)
  2696. param (7 + 0, hzRaw (100.0));
  2697. param (14 + 0, 40124); // default width -> Q ~0.68
  2698. param (28 + 0, -3); // Steep 8 -> 4 biquads
  2699. param (21 + 3, 6); // peaking
  2700. param (7 + 3, hzRaw (1000.0));
  2701. param (3, 600); // +6 dB
  2702. param (14 + 3, 25412);
  2703. param (35, -300); // main level −3 dB
  2704. put (0x13E, 0x7F);
  2705. const auto slot = lynx::effectFromFl ("Fruity Parametric EQ 2", blob);
  2706. CHECK (slot.has_value() && slot->kind == lynx::EffectKind::parametricEq);
  2707. const auto& p = slot->params;
  2708. CHECK (lynx::peq::type (p[(std::size_t) lynx::peq::param (0, 0)]) == lynx::peq::BandType::lowCut);
  2709. CHECK (lynx::peq::slopeStages (p[(std::size_t) lynx::peq::slopeParam]) == 4);
  2710. CHECK (lynx::peq::type (p[(std::size_t) lynx::peq::param (3, 0)]) == lynx::peq::BandType::peak);
  2711. CHECK (lynx::peq::type (p[(std::size_t) lynx::peq::param (1, 0)]) == lynx::peq::BandType::off);
  2712. CHECK (std::abs (lynx::peq::responseDb (p, 48000.0, 1000.0) - 3.0) < 0.3); // +6 from the peak −3 from the output
  2713. CHECK (lynx::peq::responseDb (p, 48000.0, 30.0) < -40.0); // 48 dB/oct below 100 Hz
  2714. CHECK (std::abs (lynx::peq::responseDb (p, 48000.0, 8000.0) + 3.0) < 0.3);
  2715. // a band muted by the mask doesn't sound
  2716. put (0x13E, 0x7F & ~(1 << 3));
  2717. const auto muted = lynx::effectFromFl ("Fruity Parametric EQ 2", blob);
  2718. CHECK (lynx::peq::type (muted->params[(std::size_t) lynx::peq::param (3, 0)]) == lynx::peq::BandType::off);
  2719. }
  2720. TEST (reverb_low_cut_and_predelay)
  2721. {
  2722. // impulse: with 100 ms predelay the wet only starts later; with a 3 kHz low cut a
  2723. // 100 Hz sine barely enters the reverb
  2724. auto run = [] (const std::function<void (lynx::EffectSlot&)>& tweak, double hz, bool impulse) {
  2725. auto fx = lynx::makeEffect (lynx::EffectKind::reverb);
  2726. fx->prepare (48000.0);
  2727. auto slot = lynx::makeEffectSlot (lynx::EffectKind::reverb);
  2728. slot.params[4] = 0.0f; // wet only
  2729. slot.params[3] = 1.0f;
  2730. tweak (slot);
  2731. std::vector<float> l (48000), r (48000);
  2732. for (int i = 0; i < 48000; ++i)
  2733. 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);
  2734. for (int i = 0; i < 48000; i += 480)
  2735. fx->process (l.data() + i, r.data() + i, 480, slot.params, 120.0);
  2736. return l;
  2737. };
  2738. const auto delayed = run ([] (auto& s) { s.params[7] = 0.1f; }, 0.0, true);
  2739. float early = 0.0f, later = 0.0f;
  2740. for (std::size_t i = 0; i < 4800; ++i)
  2741. early = std::max (early, std::abs (delayed[i]));
  2742. for (std::size_t i = 4800; i < 24000; ++i)
  2743. later = std::max (later, std::abs (delayed[i]));
  2744. CHECK (early == 0.0f && later > 0.0f);
  2745. 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; };
  2746. const auto open = energy (run ([] (auto&) {}, 100.0, false));
  2747. const auto cut = energy (run ([] (auto& s) { s.params[5] = 1.0f; }, 100.0, false));
  2748. CHECK (cut < open * 0.01);
  2749. }
  2750. TEST (utility_effect_and_fl_stereo_tools)
  2751. {
  2752. // transparent by default; balance fully right silences the left
  2753. CHECK (std::abs (runEffectOnSine (lynx::EffectKind::utility, [] (auto&) {}, 440.0, 0.5f) - 0.5f) < 0.001f);
  2754. CHECK (runEffectOnSine (lynx::EffectKind::utility, [] (auto& s) { s.params[1] = 1.0f; }, 440.0, 0.5f) < 0.001f);
  2755. // Stereo Shaper in "mono": each output = 0.5 L + 0.5 R
  2756. std::vector<std::uint8_t> blob (36, 0);
  2757. auto put = [&] (std::size_t off, std::int32_t v) { std::memcpy (blob.data() + off, &v, 4); };
  2758. put (4, 6400); put (8, 6400); put (12, 6400); put (16, 6400);
  2759. const auto slot = lynx::effectFromFl ("Fruity Stereo Shaper", blob);
  2760. CHECK (slot && slot->kind == lynx::EffectKind::utility);
  2761. auto fx = lynx::makeEffect (lynx::EffectKind::utility);
  2762. float l = 1.0f, r = 0.0f;
  2763. fx->process (&l, &r, 1, slot->params, 120.0);
  2764. CHECK (std::abs (l - 0.5f) < 1e-4f && std::abs (r - 0.5f) < 1e-4f);
  2765. // Balance: volume 256 = 0 dB, pan −128 = fully left
  2766. std::vector<std::uint8_t> bal (8, 0);
  2767. std::int32_t pan = -128, vol = 256;
  2768. std::memcpy (bal.data(), &pan, 4);
  2769. std::memcpy (bal.data() + 4, &vol, 4);
  2770. const auto b = lynx::effectFromFl ("Fruity Balance", bal);
  2771. l = 0.5f; r = 0.5f;
  2772. fx->process (&l, &r, 1, b->params, 120.0);
  2773. CHECK (std::abs (l - 0.5f) < 1e-3f && std::abs (r) < 1e-4f);
  2774. }
  2775. TEST (effects_eq_compressor_behave)
  2776. {
  2777. // EQ at default is transparent
  2778. CHECK (std::abs (runEffectOnSine (lynx::EffectKind::eq, [] (auto&) {}, 1000.0, 0.5f) - 0.5f) < 0.01f);
  2779. // +18 dB on the lows: 60 Hz rises a lot, 5 kHz barely
  2780. CHECK (runEffectOnSine (lynx::EffectKind::eq, [] (auto& s) { s.params[0] = 1.0f; }, 60.0, 0.05f) > 0.3f);
  2781. CHECK (runEffectOnSine (lynx::EffectKind::eq, [] (auto& s) { s.params[0] = 1.0f; }, 5000.0, 0.05f) < 0.06f);
  2782. // compressor: threshold -20 dB, ratio 20:1 flattens a 0 dBFS signal to near the threshold
  2783. const auto squashed = runEffectOnSine (lynx::EffectKind::compressor, [] (auto& s) {
  2784. s.params[0] = 40.0f / 60.0f;
  2785. s.params[1] = 1.0f;
  2786. }, 200.0, 1.0f);
  2787. CHECK (squashed < 0.2f && squashed > 0.05f);
  2788. // a signal below the threshold passes intact
  2789. CHECK (std::abs (runEffectOnSine (lynx::EffectKind::compressor, [] (auto& s) { s.params[0] = 1.0f; }, 200.0, 0.3f) - 0.3f) < 0.01f);
  2790. }
  2791. TEST (effects_delay_echoes_on_tempo_and_reverb_has_tail)
  2792. {
  2793. auto delay = lynx::makeEffect (lynx::EffectKind::delay);
  2794. delay->prepare (48000.0);
  2795. auto slot = lynx::makeEffectSlot (lynx::EffectKind::delay);
  2796. slot.params[0] = 3.5f / 8.0f; // index 3 = 1/4 = 0.5 s at 120 BPM
  2797. slot.params[1] = 0.0f; // no feedback: a single echo
  2798. slot.params[2] = 1.0f;
  2799. slot.params[4] = 0.0f; // no damping
  2800. std::vector<float> l (48000, 0.0f), r (48000, 0.0f);
  2801. l[0] = r[0] = 1.0f;
  2802. delay->process (l.data(), r.data(), 48000, slot.params, 120.0);
  2803. CHECK (std::abs (l[24000] - 1.0f) < 1e-4f);
  2804. CHECK (std::abs (l[12000]) < 1e-6f);
  2805. auto reverb = lynx::makeEffect (lynx::EffectKind::reverb);
  2806. reverb->prepare (48000.0);
  2807. auto rs = lynx::makeEffectSlot (lynx::EffectKind::reverb);
  2808. rs.params[3] = 1.0f;
  2809. std::fill (l.begin(), l.end(), 0.0f);
  2810. std::fill (r.begin(), r.end(), 0.0f);
  2811. l[0] = r[0] = 1.0f;
  2812. reverb->process (l.data(), r.data(), 48000, rs.params, 120.0);
  2813. float tail = 0.0f;
  2814. for (int i = 4800; i < 9600; ++i) // between 100 and 200 ms after the impulse
  2815. tail = std::max (tail, std::abs (l[(std::size_t) i]));
  2816. CHECK (tail > 1e-4f && tail < 1.0f);
  2817. CHECK (lynx::formatEffectParam (lynx::EffectKind::delay, 0, slot.params[0], 120.0) == "1/4 (500 ms)");
  2818. }
  2819. TEST (rack_runs_insert_effects_and_reuses_them)
  2820. {
  2821. // an insert with EQ at -inf doesn't exist; we use the EQ output at -18 dB to see the effect act
  2822. const auto quiet = renderMixerCase ([] (lynx::Song& s) {
  2823. auto eq = lynx::makeEffectSlot (lynx::EffectKind::eq);
  2824. eq.params[4] = 0.0f; // output -18 dB
  2825. s.mixer[1].effects.push_back (eq);
  2826. });
  2827. CHECK (quiet > 0.55f && quiet < 0.6f); // 0.5 from channel 2 + 0.5 * 0.126 from channel 1
  2828. const auto bypassed = renderMixerCase ([] (lynx::Song& s) {
  2829. auto eq = lynx::makeEffectSlot (lynx::EffectKind::eq);
  2830. eq.params[4] = 0.0f;
  2831. eq.enabled = false;
  2832. s.mixer[1].effects.push_back (eq);
  2833. });
  2834. CHECK (std::abs (bypassed - 1.0f) < 1e-4f);
  2835. auto s = lynx::Song::makeDefault();
  2836. s.mixer[2].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::reverb));
  2837. auto a = lynx::RackState::build (s, nullptr, 48000.0);
  2838. s.mixer[2].effects[0].params[0] = 0.9f; // turning a knob doesn't recreate the effect
  2839. auto b = lynx::RackState::build (s, a.get(), 48000.0);
  2840. CHECK (b->effects[2][0] == a->effects[2][0]);
  2841. s.mixer[2].effects[0] = lynx::makeEffectSlot (lynx::EffectKind::delay);
  2842. auto c = lynx::RackState::build (s, b.get(), 48000.0);
  2843. CHECK (c->effects[2][0] != b->effects[2][0]);
  2844. }
  2845. TEST (audio_clips_trigger_cut_and_resume)
  2846. {
  2847. lynx::Song s;
  2848. s.bpm = 120.0; // 1 beat = 0.5 s = 24000 samples at 48 kHz
  2849. lynx::ChannelDef c;
  2850. c.instrument = lynx::InstrumentKind::audioClip;
  2851. c.samplePath = "ramp";
  2852. c.volume = 1.0f;
  2853. s.channels.push_back (c);
  2854. s.patterns.emplace_back();
  2855. lynx::Clip clip;
  2856. clip.kind = lynx::ClipKind::audio;
  2857. clip.channel = 0;
  2858. clip.start = lynx::ppq; // starts at beat 2
  2859. clip.length = 2 * lynx::ppq; // lasts 2 beats
  2860. clip.offset = lynx::ppq; // skips the first beat of the audio
  2861. s.playlist.push_back (clip);
  2862. s.mode = lynx::PlayMode::song;
  2863. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  2864. lynx::EventBuffer ev;
  2865. lynx::scheduleSong (s, 0.0, 4 * 24000, tps, ev);
  2866. CHECK (ev.size() == 2);
  2867. CHECK (ev[0].type == lynx::NoteEvent::Type::on && ev[0].sampleOffset == 24000 && std::abs (ev[0].startSeconds - 0.5) < 1e-9);
  2868. CHECK (ev[1].type == lynx::NoteEvent::Type::off && ev[1].sampleOffset == 3 * 24000);
  2869. // seek to the middle of the clip (beat 2.5): with resume, starts at the block's first sample
  2870. ev.clear();
  2871. lynx::scheduleSong (s, 1.5 * lynx::ppq, 256, tps, ev, true);
  2872. CHECK (ev.size() == 1 && ev[0].sampleOffset == 0 && std::abs (ev[0].startSeconds - 0.75) < 1e-9);
  2873. ev.clear();
  2874. lynx::scheduleSong (s, 1.5 * lynx::ppq, 256, tps, ev, false);
  2875. CHECK (ev.size() == 0);
  2876. // sample whose value = position in seconds: lets us check where playback started
  2877. auto provider = [] (const std::string&) {
  2878. auto d = std::make_shared<lynx::SampleData>();
  2879. d->sampleRate = 48000.0;
  2880. for (int i = 0; i < 48000 * 3; ++i)
  2881. d->left.push_back ((float) i / 48000.0f);
  2882. return std::shared_ptr<const lynx::SampleData> (d);
  2883. };
  2884. auto state = lynx::RackState::build (s, nullptr, 48000.0, provider);
  2885. lynx::RackRenderer r;
  2886. r.prepare (48000.0, 512);
  2887. std::vector<float> l (256), rr (256);
  2888. // first block already playing mid-clip
  2889. r.process (state.get(), true, 1.5 * lynx::ppq, 256, l.data(), rr.data());
  2890. CHECK (std::abs (l[0] - 0.75f) < 0.001f);
  2891. // the clip ends at beat 3: after the short fade, silence (the sample would still have audio)
  2892. double tick = 3.0 * lynx::ppq - 10 * tps;
  2893. r.process (state.get(), false, tick, 256, l.data(), rr.data()); // stops (fade)
  2894. for (int i = 0; i < 4; ++i)
  2895. r.process (state.get(), false, tick, 256, l.data(), rr.data());
  2896. CHECK (std::abs (l[255]) < 1e-6f);
  2897. }
  2898. TEST (remove_channel_fixes_notes_and_audio_clips)
  2899. {
  2900. lynx::Song s;
  2901. s.channels.resize (3);
  2902. s.patterns.resize (1);
  2903. s.patterns[0].notes = { { 0, 240, 0, 60, 1.0f }, { 0, 240, 1, 60, 1.0f }, { 0, 240, 2, 60, 1.0f } };
  2904. lynx::Clip a;
  2905. a.kind = lynx::ClipKind::audio;
  2906. a.channel = 1;
  2907. a.length = 100;
  2908. lynx::Clip b = a;
  2909. b.channel = 2;
  2910. s.playlist = { a, b };
  2911. s.removeChannel (1);
  2912. CHECK (s.channels.size() == 2);
  2913. CHECK (s.patterns[0].notes.size() == 2 && s.patterns[0].notes[1].channel == 1);
  2914. CHECK (s.playlist.size() == 1 && s.playlist[0].channel == 1);
  2915. }
  2916. TEST (flp_import_audio_clips_with_offsets)
  2917. {
  2918. flp::Project p;
  2919. p.header.ppq = 96;
  2920. p.tempo = 120.0;
  2921. p.channels = { { 0, flp::ChannelType::audioClip, "Vocal", "", "%FLStudioData%\\v.wav", 2 },
  2922. { 1, flp::ChannelType::audioClip, "Loop", "", "%FLStudioData%\\l.wav", 3 } };
  2923. flp::Arrangement arr;
  2924. flp::PlaylistItem beats; // offset in beats: end - start = duration in beats
  2925. beats.kind = flp::PlaylistItem::Kind::channelClip;
  2926. beats.index = 0;
  2927. beats.position = 192;
  2928. beats.length = 384; // 4 beats
  2929. beats.startOffset = 2.0f;
  2930. beats.endOffset = 6.0f;
  2931. flp::PlaylistItem ms = beats; // offset in ms: 4 beats at 120 BPM = 2000 ms
  2932. ms.index = 1;
  2933. ms.startOffset = 500.0f;
  2934. ms.endOffset = 2500.0f;
  2935. arr.items = { beats, ms };
  2936. p.arrangements.push_back (arr);
  2937. lynx::FlpImportOptions options;
  2938. options.roots = { "C:\\FL", "C:\\FL\\Data", "" };
  2939. options.fileExists = [] (const std::string&) { return true; };
  2940. const auto s = lynx::importFlp (p, options);
  2941. CHECK (s.channels.size() == 2 && s.channels[0].instrument == lynx::InstrumentKind::audioClip);
  2942. CHECK (s.channels[0].samplePath == "C:\\FL\\Data\\v.wav");
  2943. CHECK (s.playlist.size() == 2);
  2944. CHECK (s.playlist[0].kind == lynx::ClipKind::audio && s.playlist[0].start == 2 * lynx::ppq);
  2945. CHECK (s.playlist[0].offset == 2 * lynx::ppq);
  2946. CHECK (s.playlist[1].offset == lynx::ppq); // 500 ms at 120 BPM = 1 beat
  2947. CHECK (s.mode == lynx::PlayMode::song);
  2948. }
  2949. TEST (plugin_factories_create_reuse_and_fallback)
  2950. {
  2951. lynx::Song s;
  2952. s.mixer = lynx::Song::defaultMixer (2);
  2953. lynx::ChannelDef c;
  2954. c.instrument = lynx::InstrumentKind::plugin;
  2955. c.plugin.id = "VST3-Synth-123";
  2956. c.mixerTrack = 1;
  2957. s.channels.push_back (c);
  2958. lynx::ChannelDef missing = c;
  2959. missing.plugin.id = "VST3-Ausente-0";
  2960. s.channels.push_back (missing);
  2961. lynx::EffectSlot fx;
  2962. fx.kind = lynx::EffectKind::plugin;
  2963. fx.plugin.id = "VST3-Reverb-9";
  2964. s.mixer[1].effects.push_back (fx);
  2965. s.patterns.emplace_back();
  2966. int instrumentsMade = 0, effectsMade = 0;
  2967. lynx::RackState::Factories f;
  2968. f.pluginInstruments = [&] (const lynx::PluginRef& ref, double) -> std::shared_ptr<lynx::Instrument> {
  2969. if (ref.id != "VST3-Synth-123")
  2970. return nullptr;
  2971. ++instrumentsMade;
  2972. auto synth = lynx::makeInstrument (lynx::InstrumentKind::synth);
  2973. synth->prepare (48000.0);
  2974. return synth;
  2975. };
  2976. f.pluginEffects = [&] (const lynx::PluginRef&, double) -> std::shared_ptr<lynx::Effect> {
  2977. ++effectsMade;
  2978. auto eq = lynx::makeEffect (lynx::EffectKind::eq);
  2979. eq->prepare (48000.0);
  2980. return eq;
  2981. };
  2982. auto a = lynx::RackState::build (s, nullptr, 48000.0, f);
  2983. CHECK (instrumentsMade == 1 && effectsMade == 1);
  2984. CHECK (a->instruments.size() == 2 && a->instruments[1] != nullptr); // missing: muted, but it exists
  2985. // changing the saved state doesn't recreate; swapping the plugin does
  2986. s.channels[0].plugin.state = "abc";
  2987. auto b = lynx::RackState::build (s, a.get(), 48000.0, f);
  2988. CHECK (instrumentsMade == 1 && b->instruments[0] == a->instruments[0] && b->effects[1][0] == a->effects[1][0]);
  2989. s.mixer[1].effects[0].plugin.id = "VST3-Outro-1";
  2990. auto c2 = lynx::RackState::build (s, b.get(), 48000.0, f);
  2991. CHECK (effectsMade == 2);
  2992. // rendering with a missing plugin and a plugin slot breaks nothing
  2993. lynx::RackRenderer r;
  2994. r.prepare (48000.0, 256);
  2995. lynx::LiveEventQueue live;
  2996. lynx::NoteEvent on;
  2997. on.channel = 0;
  2998. on.velocity = 1.0f;
  2999. live.push (on);
  3000. on.channel = 1;
  3001. live.push (on);
  3002. std::vector<float> l (256), rr (256);
  3003. r.process (c2.get(), false, 0.0, 256, l.data(), rr.data(), &live);
  3004. float peak = 0.0f;
  3005. for (auto v : l)
  3006. {
  3007. CHECK (std::isfinite (v));
  3008. peak = std::max (peak, std::abs (v));
  3009. }
  3010. CHECK (peak > 0.0f);
  3011. }
  3012. TEST (export_song_adds_silent_tail_and_never_restarts)
  3013. {
  3014. auto s = lynx::Song::makeDefault();
  3015. s.playlist.clear();
  3016. std::int64_t length = 0;
  3017. auto pat = lynx::makeExportSong (s, true, lynx::ppq * 8, length); // empty Playlist: uses the pattern
  3018. CHECK (length == lynx::ppq * 4);
  3019. CHECK (pat.mode == lynx::PlayMode::song && pat.playlist.size() == 2);
  3020. CHECK (pat.songLength() >= length + lynx::ppq * 8);
  3021. // no new notes after the song ends, only silence until the end of the tail
  3022. lynx::EventBuffer events;
  3023. const auto tps = lynx::ticksPerSample (pat.bpm, 48000.0);
  3024. int onsAfterEnd = 0, onsBefore = 0;
  3025. for (double tick = 0.0; tick < (double) (length + lynx::ppq * 8); tick += 512 * tps)
  3026. {
  3027. events.clear();
  3028. lynx::scheduleSong (pat, tick, 512, tps, events);
  3029. for (const auto& e : events)
  3030. if (e.type == lynx::NoteEvent::Type::on)
  3031. (tick + e.sampleOffset * tps >= (double) length ? onsAfterEnd : onsBefore)++;
  3032. }
  3033. CHECK (onsBefore == (int) s.patterns[0].notes.size());
  3034. CHECK (onsAfterEnd == 0);
  3035. // with Playlist: the end is the last clip's, without rounding
  3036. s.playlist.push_back ({ 0, 0, lynx::ppq * 2, lynx::ppq * 3, 0 });
  3037. auto song = lynx::makeExportSong (s, true, 0, length);
  3038. CHECK (length == lynx::ppq * 5 && song.playlist.size() == 1);
  3039. song = lynx::makeExportSong (s, false, 0, length);
  3040. CHECK (length == lynx::ppq * 4 && song.playlist[0].start == 0);
  3041. }
  3042. TEST (note_edit_selection_operations)
  3043. {
  3044. namespace ne = lynx::noteedit;
  3045. lynx::Pattern p;
  3046. p.notes = { { 0, 240, 0, 60 }, { 480, 240, 0, 64 }, { 960, 480, 1, 67 } };
  3047. // sorting keeps the indices in step
  3048. p.notes[0].start = 1200;
  3049. std::vector<int> tracked { 0, 2 };
  3050. ne::sortTracking (p, tracked);
  3051. CHECK (p.notes[2].start == 1200 && p.notes[(std::size_t) tracked[0]].start == 1200);
  3052. CHECK (p.notes[(std::size_t) tracked[1]].key == 67);
  3053. // group move respects the limits
  3054. std::int64_t dt = -5000;
  3055. int dk = 100;
  3056. ne::move (p, { 0, 1 }, dt, dk);
  3057. CHECK (dt == -480 && dk == 127 - 67 && p.notes[0].start == 0 && p.notes[1].key == 127);
  3058. // duplicate: right after the selection, rounded to the grid
  3059. lynx::Pattern q;
  3060. q.notes = { { 0, 240, 0, 60 }, { 240, 300, 0, 62 } }; // 540-tick selection
  3061. const auto added = ne::duplicate (q, { 0, 1 }, 960);
  3062. CHECK (added.size() == 2 && q.notes[(std::size_t) added[0]].start == 960 && q.notes[(std::size_t) added[1]].start == 1200);
  3063. // paste onto another channel with an offset
  3064. const auto pasted = ne::paste (q, ne::copy (q, { 1 }), 100, 3);
  3065. CHECK (pasted.size() == 1 && q.notes.back().channel == 3 && q.notes.back().start == 340);
  3066. // quantize rounds to the nearest
  3067. q.notes[0].start = 130;
  3068. q.notes[1].start = 100;
  3069. ne::quantize (q, { 0, 1 }, 240);
  3070. CHECK (q.notes[0].start == 240 && q.notes[1].start == 0);
  3071. // remove several (order and duplicates don't matter)
  3072. const auto before = q.notes.size();
  3073. ne::remove (q, { 1, 0, 1 });
  3074. CHECK (q.notes.size() == before - 2);
  3075. }
  3076. TEST (note_edit_quick_operations)
  3077. {
  3078. namespace ne = lynx::noteedit;
  3079. const std::int64_t step = lynx::ticksPerStep, bar = lynx::ppq * 4;
  3080. // split: only strictly inside; the tail is appended and does not slide again
  3081. lynx::Pattern p;
  3082. p.notes = { { 0, 4 * step, 0, 60 } };
  3083. p.notes[0].slide = true;
  3084. CHECK (ne::split (p, 0, 0) == -1 && ne::split (p, 0, 4 * step) == -1);
  3085. CHECK (ne::split (p, 0, step) == 1 && p.notes[0].length == step && p.notes[1].start == step && p.notes[1].length == 3 * step
  3086. && ! p.notes[1].slide);
  3087. // chop to grid: a 2.5-step note from half a step becomes 3 pieces cut on the step lines
  3088. lynx::Pattern c;
  3089. c.notes = { { step / 2, step * 5 / 2, 0, 60 }, { 0, step, 1, 50 } };
  3090. const auto pieces = ne::chop (c, { 0, 1 }, step);
  3091. CHECK (pieces.size() == 4 && c.notes.size() == 4);
  3092. CHECK (c.notes[0].length == step / 2 && c.notes[2].start == step && c.notes[2].length == step && c.notes[3].start == 2 * step
  3093. && c.notes[3].length == step);
  3094. // join: touching and overlapping notes of the same key and channel merge; others stay
  3095. lynx::Pattern j;
  3096. j.notes = { { 0, step, 0, 60 }, { step, step, 0, 60 }, { step * 3 / 2, step * 2, 0, 60 }, { 5 * step, step, 0, 60 },
  3097. { step, step, 0, 62 }, { step, step, 1, 60 } };
  3098. CHECK (ne::join (j, { 0, 1, 2, 3, 4, 5 }) == 2 && j.notes.size() == 4);
  3099. CHECK (j.notes[0].start == 0 && j.notes[0].length == step * 7 / 2);
  3100. // legato: each note reaches the next start (a chord ends together); the last keeps its length
  3101. lynx::Pattern l;
  3102. l.notes = { { 0, 10, 0, 60 }, { 0, 10, 0, 64 }, { step, 10, 0, 62 }, { 3 * step, 10, 0, 65 }, { step, 10, 1, 40 } };
  3103. ne::legato (l, { 0, 1, 2, 3, 4 });
  3104. CHECK (l.notes[0].length == step && l.notes[1].length == step && l.notes[2].length == 2 * step && l.notes[3].length == 10
  3105. && l.notes[4].length == 10);
  3106. // shrink to grid and full quantise (start and end)
  3107. ne::shrinkToGrid (l, { 3 }, step / 2);
  3108. CHECK (l.notes[3].length == step / 2);
  3109. lynx::Pattern q;
  3110. q.notes = { { 10, step - 30, 0, 60 }, { step + 100, 20, 0, 60 } };
  3111. ne::quantizeFull (q, { 0, 1 }, step);
  3112. CHECK (q.notes[0].start == 0 && q.notes[0].length == step && q.notes[1].start == step && q.notes[1].length == step);
  3113. // rotate inside the bar, wrapping
  3114. lynx::Pattern r;
  3115. r.notes = { { 0, step, 0, 60 }, { bar - step, step, 0, 62 } };
  3116. ne::rotate (r, { 0, 1 }, step, bar, 1);
  3117. CHECK (r.notes[0].start == step && r.notes[1].start == 0);
  3118. ne::rotate (r, { 0, 1 }, step, bar, -2);
  3119. CHECK (r.notes[0].start == bar - step && r.notes[1].start == bar - 2 * step);
  3120. r.notes.push_back ({ bar + step, step, 0, 64 }); // alone in the second bar: wraps inside that bar
  3121. ne::rotate (r, { 2 }, step, bar, -2);
  3122. CHECK (r.notes[2].start == 2 * bar - step);
  3123. }
  3124. TEST (note_edit_grid_and_time_text)
  3125. {
  3126. namespace ne = lynx::noteedit;
  3127. const std::int64_t step = lynx::ticksPerStep, bar = lynx::ppq * 4;
  3128. CHECK (ne::snapDown (250.0, step) == step && ne::snapDown (-1.0, step) == -step && ne::snapDown (17.9, 1) == 17);
  3129. CHECK (ne::snapNearest (1000.0, { 400, 1100, 980 }, 50.0, step) == 980);
  3130. CHECK (ne::snapNearest (1000.0, { 400 }, 50.0, step) == 960); // too far: falls back to the grid
  3131. // screen grid: 24 px per step shows steps; zoomed out it climbs to beats, bars and bar multiples
  3132. CHECK (ne::screenStep (24.0 / step, bar) == step);
  3133. CHECK (ne::screenStep (96.0 / bar, bar) == lynx::ppq);
  3134. CHECK (ne::screenStep (8.0 / bar, bar) == 2 * bar);
  3135. CHECK (ne::screenStep (200.0 / step, bar) == step / 4);
  3136. CHECK (ne::formatTime (0, 4) == "1:1:0" && ne::formatTime (bar + 5 * step + 7, 4) == "2:6:7");
  3137. CHECK (ne::formatTime (step * 2, 4, true) == "0:2:0");
  3138. std::int64_t t = 0;
  3139. CHECK (ne::parseTime ("2:6:7", 4, t) && t == bar + 5 * step + 7);
  3140. CHECK (ne::parseTime ("3", 4, t) && t == 2 * bar);
  3141. CHECK (ne::parseTime ("0:2:0", 4, t, true) && t == 2 * step);
  3142. CHECK (! ne::parseTime ("0:1:0", 4, t) && ! ne::parseTime ("1:17:0", 4, t) && ! ne::parseTime ("1:1:240", 4, t)
  3143. && ! ne::parseTime ("a", 4, t) && ! ne::parseTime ("", 4, t));
  3144. CHECK (ne::parseTime ("1:12:0", 3, t) && ! ne::parseTime ("1:13:0", 3, t)); // 3/4: 12 steps per bar
  3145. }
  3146. TEST (playlist_clip_edges_and_time_selection)
  3147. {
  3148. namespace ne = lynx::noteedit;
  3149. const std::int64_t beat = lynx::ppq;
  3150. // left-edge trim: content stays in place, cannot reveal what is before the content's start
  3151. lynx::Clip c { 0, 0, 4 * beat, 4 * beat, beat };
  3152. ne::trimStart (c, 5 * beat, beat);
  3153. CHECK (c.start == 5 * beat && c.offset == 2 * beat && c.length == 3 * beat);
  3154. ne::trimStart (c, 0, beat);
  3155. CHECK (c.start == 3 * beat && c.offset == 0 && c.length == 5 * beat);
  3156. ne::trimStart (c, 100 * beat, beat);
  3157. CHECK (c.length == beat && c.end() == 8 * beat);
  3158. // slip moves the content, not the clip
  3159. lynx::Clip s { 0, 0, 0, 2 * beat, beat };
  3160. ne::slip (s, beat / 2);
  3161. CHECK (s.offset == beat / 2 && s.start == 0 && s.length == 2 * beat);
  3162. ne::slip (s, beat);
  3163. CHECK (s.offset == 0);
  3164. ne::slip (s, -3 * beat);
  3165. CHECK (s.offset == 3 * beat);
  3166. // insert / delete time across all tracks, markers included
  3167. std::vector<lynx::Clip> clips { { 0, 0, 0, 2 * beat, 0 }, { 0, 1, 4 * beat, 2 * beat, 0 }, { 0, 2, beat, 6 * beat, 0 } };
  3168. std::vector<lynx::Marker> markers { { 5 * beat, "A" }, { beat / 2, "B" } };
  3169. ne::insertTime (clips, markers, 2 * beat, 4 * beat);
  3170. CHECK (clips[0].start == 0 && clips[1].start == 8 * beat && clips[2].start == beat && markers[0].tick == 9 * beat
  3171. && markers[1].tick == beat / 2);
  3172. std::vector<lynx::Clip> d { { 0, 0, 0, 2 * beat, 0 }, // before: kept
  3173. { 0, 1, 3 * beat, beat, 0 }, // inside: deleted
  3174. { 0, 2, beat, 6 * beat, 0 }, // spans the cut: head + tail
  3175. { 0, 3, 3 * beat, 4 * beat, 0 }, // tail outside: trimmed and moved
  3176. { 0, 4, 8 * beat, beat, 0 } }; // after: moved left
  3177. std::vector<lynx::Marker> dm { { 3 * beat, "in" }, { 9 * beat, "after" } };
  3178. ne::deleteTime (d, dm, 2 * beat, 5 * beat);
  3179. CHECK (d.size() == 5);
  3180. CHECK (d[1].track == 2 && d[1].start == beat && d[1].length == beat);
  3181. CHECK (d[2].track == 2 && d[2].start == 2 * beat && d[2].offset == 4 * beat && d[2].length == 2 * beat);
  3182. CHECK (d[3].track == 3 && d[3].start == 2 * beat && d[3].offset == 2 * beat && d[3].length == 2 * beat);
  3183. CHECK (d[4].start == 5 * beat && dm.size() == 1 && dm[0].tick == 6 * beat);
  3184. // time selection: overlapping clips; Ctrl+B repeats what starts inside it after itself
  3185. std::vector<lynx::Clip> r { { 0, 0, 0, beat, 0 }, { 0, 1, beat, 2 * beat, 0 }, { 0, 0, 4 * beat, beat, 0 } };
  3186. CHECK ((ne::clipsInTime (r, beat / 2, 2 * beat) == std::vector<int> { 0, 1 }));
  3187. const auto added = ne::repeatTime (r, 0, 4 * beat, {});
  3188. CHECK (added.size() == 2 && r[3].start == 4 * beat && r[4].start == 5 * beat && r[4].track == 1);
  3189. CHECK (ne::repeatTime (r, 0, 2 * beat, { 2 }).size() == 1 && r.back().start == 6 * beat);
  3190. }
  3191. TEST (recorder_builds_notes_in_pattern_and_song_mode)
  3192. {
  3193. auto song = lynx::Song::makeDefault();
  3194. const auto loop = song.patterns[0].effectiveLength (4); // 1 bar = 3840
  3195. lynx::NoteRecorder r;
  3196. r.add (song, { 100.0, 4, 60, 0.5f, true }); // no take: ignored
  3197. CHECK (r.takeFinished().empty());
  3198. r.begin (loop);
  3199. r.add (song, { 4000.0, 4, 60, 0.5f, true }); // second loop pass
  3200. r.add (song, { 4480.0, 4, 60, 0.0f, false });
  3201. r.add (song, { 5000.0, 4, 64, 0.9f, true }); // held until stop
  3202. r.end (song, 5240.0);
  3203. const auto notes = r.takeFinished();
  3204. CHECK (notes.size() == 2);
  3205. CHECK (notes[0].start == 4000 - 3840 && notes[0].length == 480 && notes[0].velocity == 0.5f && notes[0].channel == 4);
  3206. CHECK (notes[1].key == 64 && notes[1].start == 5000 - 3840 && notes[1].length == 240);
  3207. // song mode: position inside the current pattern's clip (with offset)
  3208. song.mode = lynx::PlayMode::song;
  3209. song.playlist = { { 0, 0, 7680, 3840, 960 } };
  3210. CHECK (lynx::patternPositionForTick (song, 7680.0 + 100.0, loop) == 1060);
  3211. CHECK (lynx::patternPositionForTick (song, 100.0, loop) == 100); // outside the clip: like loop
  3212. }
  3213. TEST (automation_curve_and_playback)
  3214. {
  3215. lynx::Automation a;
  3216. a.points = { { 0, 0.0f }, { 960, 1.0f }, { 1920, 0.5f, 0.0f } };
  3217. CHECK (a.valueAt (-10.0) == 0.0f && a.valueAt (480.0) == 0.5f && a.valueAt (5000.0) == 0.5f);
  3218. CHECK (a.length() == 1920);
  3219. a.points[0].tension = 1.0f; // curve: starts slow
  3220. CHECK (a.valueAt (480.0) < 0.2f && a.valueAt (480.0) > 0.0f);
  3221. // automated Master: silence in the first bar, sound in the second, and the last value
  3222. // keeps applying after the automation clip ends
  3223. auto song = lynx::Song::makeDefault();
  3224. song.bpm = 120.0;
  3225. song.mode = lynx::PlayMode::song;
  3226. const auto bar = (std::int64_t) lynx::ppq * 4;
  3227. for (int b = 0; b < 3; ++b)
  3228. song.playlist.push_back ({ 0, 0, bar * b, bar, 0 });
  3229. lynx::Automation master;
  3230. master.target = { lynx::AutomationTargetKind::mixerVolume, 0 };
  3231. master.points = { { 0, 0.0f }, { bar - 1, 0.0f }, { bar, 0.8f } };
  3232. song.automations.push_back (master);
  3233. lynx::Clip ac;
  3234. ac.kind = lynx::ClipKind::automation;
  3235. ac.automation = 0;
  3236. ac.track = 1;
  3237. ac.length = bar + bar / 2;
  3238. song.playlist.push_back (ac);
  3239. const double sr = 48000.0;
  3240. auto state = lynx::RackState::build (song, nullptr, sr);
  3241. CHECK (state->hasAutomation && state->mixerVolumeAuto[0] == 0 && state->automationClips[0].size() == 1);
  3242. lynx::RackRenderer r;
  3243. r.prepare (sr, 512);
  3244. std::vector<float> l (512), rr (512);
  3245. const auto tps = lynx::ticksPerSample (song.bpm, sr);
  3246. float peakBar1 = 0.0f, peakBar2 = 0.0f, peakBar3 = 0.0f;
  3247. for (double tick = 0.0; tick < (double) (bar * 3); tick += 512 * tps)
  3248. {
  3249. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  3250. auto& peak = tick < (double) bar - 512 * tps ? peakBar1 : tick < (double) bar * 2 ? peakBar2 : peakBar3;
  3251. for (auto v : l)
  3252. peak = std::max (peak, std::abs (v));
  3253. }
  3254. CHECK (peakBar1 < 1.0e-6f);
  3255. CHECK (peakBar2 > 0.05f);
  3256. CHECK (peakBar3 > 0.05f); // after the clip: keeps the last value
  3257. // target removed: automation disappears from the tables
  3258. song.removeChannel (0);
  3259. song.automations[0].target = { lynx::AutomationTargetKind::channelVolume, 0 };
  3260. song.removeChannel (0);
  3261. CHECK (song.automations[0].target.kind == lynx::AutomationTargetKind::none);
  3262. song.removeAutomation (0);
  3263. CHECK (song.automations.empty() && song.playlist.size() == 3);
  3264. }
  3265. TEST (mixer_sends_between_inserts)
  3266. {
  3267. // insert 1 goes only to 3; 3 goes to the Master: same sum (0.5 + 0.5)
  3268. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.setRoute (1, 3, true); s.setRoute (1, 0, false); }) - 1.0f) < 1e-4f);
  3269. // send at 50% and muted destination
  3270. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.setRoute (1, 3, true, 0.5f); s.setRoute (1, 0, false); }) - 0.75f) < 1e-4f);
  3271. 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);
  3272. // going to the Master and to 3: the signal doubles
  3273. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.setRoute (1, 3, true); }) - 1.5f) < 1e-4f);
  3274. // solo on 3 lets what reaches it sound (insert 1), but not 2
  3275. 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);
  3276. // solo on 1 lets the path to the Master (3) sound
  3277. 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);
  3278. // order and cycles
  3279. auto song = lynx::Song::makeDefault();
  3280. song.setRoute (4, 2, true);
  3281. song.setRoute (2, 1, true);
  3282. CHECK (! song.canRoute (1, 4) && ! song.canRoute (1, 2) && song.canRoute (1, 5));
  3283. song.setRoute (1, 4, true); // ignored: would create a cycle
  3284. CHECK (! song.routes (1, 4));
  3285. const auto order = song.mixerOrder();
  3286. const auto pos = [&] (int t) { return std::find (order.begin(), order.end(), t) - order.begin(); };
  3287. CHECK ((int) order.size() == (int) song.mixer.size() - 1);
  3288. CHECK (pos (4) < pos (2) && pos (2) < pos (1));
  3289. song.setRoute (4, 2, false);
  3290. CHECK (! song.routes (4, 2) && song.routes (4, 0));
  3291. }
  3292. namespace
  3293. {
  3294. // Test effect: delays the signal by `latency` samples and reports that latency (like a lookahead plugin).
  3295. class LatentEffect final : public lynx::Effect
  3296. {
  3297. public:
  3298. explicit LatentEffect (int samples) : latency (samples), line (samples) {}
  3299. void prepare (double) noexcept override {}
  3300. void reset() noexcept override {}
  3301. void process (float* l, float* r, int n, const lynx::EffectParams&, double) noexcept override { line.process (l, r, n); }
  3302. int latencySamples() const noexcept override { return latency; }
  3303. private:
  3304. int latency;
  3305. lynx::DelayLine line;
  3306. };
  3307. } // namespace
  3308. TEST (delay_line_mix_into_matches_process_and_drains_tail)
  3309. {
  3310. // mixInto = process over source*level, added to the destination; in stretches that cross the ring
  3311. lynx::DelayLine a (37), b (37);
  3312. std::vector<float> sl (300), sr (300), dl (300, 0.5f), dr (300, -0.5f), xl (300), xr (300);
  3313. for (int i = 0; i < 300; ++i)
  3314. {
  3315. sl[(std::size_t) i] = (float) std::sin (i * 0.1);
  3316. sr[(std::size_t) i] = (float) std::cos (i * 0.07);
  3317. }
  3318. for (int start = 0; start < 300; start += 100)
  3319. {
  3320. b.mixInto (sl.data() + start, sr.data() + start, 0.25f, dl.data() + start, dr.data() + start, 100);
  3321. for (int i = start; i < start + 100; ++i)
  3322. {
  3323. xl[(std::size_t) i] = sl[(std::size_t) i] * 0.25f;
  3324. xr[(std::size_t) i] = sr[(std::size_t) i] * 0.25f;
  3325. }
  3326. a.process (xl.data() + start, xr.data() + start, 100);
  3327. }
  3328. float worst = 0.0f;
  3329. for (int i = 0; i < 300; ++i)
  3330. worst = std::max ({ worst, std::abs (dl[(std::size_t) i] - 0.5f - xl[(std::size_t) i]),
  3331. std::abs (dr[(std::size_t) i] + 0.5f - xr[(std::size_t) i]) });
  3332. CHECK (worst < 1e-6f);
  3333. // silenced source: the tail still in the line comes out, then nothing remains
  3334. std::vector<float> tl (64, 0.0f), tr (64, 0.0f);
  3335. b.mixInto (nullptr, nullptr, 1.0f, tl.data(), tr.data(), 64);
  3336. CHECK (std::abs (tl[0] - sl[263] * 0.25f) < 1e-6f);
  3337. std::vector<float> zl (64, 0.0f), zr (64, 0.0f);
  3338. b.mixInto (nullptr, nullptr, 1.0f, zl.data(), zr.data(), 64);
  3339. CHECK (*std::max_element (zl.begin(), zl.end()) == 0.0f && *std::min_element (zl.begin(), zl.end()) == 0.0f);
  3340. }
  3341. TEST (limiter_lookahead_holds_ceiling_on_bursts)
  3342. {
  3343. // short bursts over a low floor: the sliding maximum must see each peak before it leaves
  3344. auto fx = lynx::makeEffect (lynx::EffectKind::limiter);
  3345. fx->prepare (48000.0);
  3346. auto slot = lynx::makeEffectSlot (lynx::EffectKind::limiter);
  3347. slot.params[2] = 0.0f; // 10 ms release
  3348. std::vector<float> l (48000), r (48000);
  3349. std::uint32_t seed = 1;
  3350. for (int i = 0; i < 48000; ++i)
  3351. {
  3352. seed = seed * 1664525u + 1013904223u;
  3353. const auto noise = ((float) (seed >> 8) / 16777216.0f - 0.5f) * 0.1f;
  3354. l[(std::size_t) i] = noise + ((i % 9973) < 3 ? 3.0f : 0.0f);
  3355. r[(std::size_t) i] = -noise;
  3356. }
  3357. for (int i = 0; i < 48000; i += 333)
  3358. fx->process (l.data() + i, r.data() + i, std::min (333, 48000 - i), slot.params, 120.0);
  3359. float peak = 0.0f, quiet = 0.0f;
  3360. for (int i = 0; i < 48000; ++i)
  3361. peak = std::max (peak, std::abs (l[(std::size_t) i]));
  3362. for (int i = 9973 * 2 + 2000; i < 9973 * 2 + 2400; ++i) // 40 ms after the burst the gain has already recovered
  3363. quiet = std::max (quiet, std::abs (r[(std::size_t) i]));
  3364. const auto ceiling = 1.0f; // the default ceiling is at 0 dBFS or below
  3365. CHECK (peak <= ceiling + 1e-5f);
  3366. CHECK (quiet > 0.03f);
  3367. }
  3368. TEST (pdc_aligns_paths_through_latent_effects)
  3369. {
  3370. // plan: channel 0 -> insert 1 (effect of 100) -> insert 3; channel 1 -> insert 2 -> Master
  3371. lynx::Song s;
  3372. s.mixer = lynx::Song::defaultMixer (4);
  3373. s.channels.resize (3);
  3374. s.channels[0].mixerTrack = 1;
  3375. s.channels[1].mixerTrack = 2;
  3376. s.channels[2].mixerTrack = 3;
  3377. s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::eq));
  3378. s.setRoute (1, 3, true);
  3379. s.setRoute (1, 0, false);
  3380. auto plan = lynx::computePdc (s, { 0, 0, 30 }, { {}, { 100 } });
  3381. CHECK (plan.inAlign[1] == 0 && plan.outLat[1] == 100);
  3382. CHECK (plan.inAlign[3] == 100 && plan.channelDelay[2] == 70); // instrument of 30 on insert 3
  3383. CHECK (plan.sendDelay[1][1] == 0); // the slowest path isn't delayed
  3384. CHECK (plan.sendDelay[2][0] == 100 && plan.sendDelay[3][0] == 0 && plan.total == 100);
  3385. // bypass zeroes the slot's latency
  3386. s.mixer[1].effects[0].enabled = false;
  3387. CHECK (lynx::computePdc (s, { 0, 0, 30 }, { {}, { 100 } }).total == 30);
  3388. // rendered: two impulses played together come out together
  3389. lynx::Song r;
  3390. r.mixer = lynx::Song::defaultMixer (2);
  3391. for (int i = 0; i < 2; ++i)
  3392. {
  3393. lynx::ChannelDef c;
  3394. c.instrument = lynx::InstrumentKind::sampler;
  3395. c.samplePath = "impulso";
  3396. c.volume = 1.0f;
  3397. c.mixerTrack = i + 1;
  3398. r.channels.push_back (c);
  3399. }
  3400. r.patterns.emplace_back();
  3401. lynx::EffectSlot fx;
  3402. fx.kind = lynx::EffectKind::plugin;
  3403. fx.plugin.id = "latente";
  3404. r.mixer[1].effects.push_back (fx);
  3405. lynx::RackState::Factories f;
  3406. f.samples = [] (const std::string&) {
  3407. auto d = std::make_shared<lynx::SampleData>();
  3408. d->left.assign (64, 0.0f);
  3409. d->left[0] = 1.0f;
  3410. return std::shared_ptr<const lynx::SampleData> (d);
  3411. };
  3412. f.pluginEffects = [] (const lynx::PluginRef&, double) -> std::shared_ptr<lynx::Effect> { return std::make_shared<LatentEffect> (100); };
  3413. auto state = lynx::RackState::build (r, nullptr, 48000.0, f);
  3414. CHECK (state->pdc.total == 100 && state->sendDelays[2][0] != nullptr && state->sendDelays[2][0]->length() == 100);
  3415. lynx::RackRenderer renderer;
  3416. renderer.prepare (48000.0, 256);
  3417. lynx::LiveEventQueue live;
  3418. for (int ch = 0; ch < 2; ++ch)
  3419. {
  3420. lynx::NoteEvent on;
  3421. on.channel = ch;
  3422. on.key = 60;
  3423. on.velocity = 1.0f;
  3424. live.push (on);
  3425. }
  3426. std::vector<float> l (256), rr (256);
  3427. renderer.process (state.get(), false, 0.0, 256, l.data(), rr.data(), &live);
  3428. int first = -1;
  3429. for (int i = 0; i < 256 && first < 0; ++i)
  3430. if (std::abs (l[(std::size_t) i]) > 0.01f)
  3431. first = i;
  3432. CHECK (first == 100 && std::abs (l[100] - 2.0f) < 1e-3f); // both impulses arrive together, summed
  3433. // editing without changing latencies reuses the lines
  3434. r.channels[0].volume = 0.5f;
  3435. auto next = lynx::RackState::build (r, state.get(), 48000.0, f);
  3436. CHECK (next->sendDelays[2][0] == state->sendDelays[2][0]);
  3437. }
  3438. TEST (mixer_mute_fades_instead_of_clicking)
  3439. {
  3440. lynx::Song s;
  3441. s.mixer = lynx::Song::defaultMixer (2);
  3442. lynx::ChannelDef c;
  3443. c.instrument = lynx::InstrumentKind::sampler;
  3444. c.samplePath = "dc";
  3445. c.volume = 1.0f;
  3446. c.mixerTrack = 1;
  3447. s.channels.push_back (c);
  3448. s.patterns.emplace_back();
  3449. auto provider = [] (const std::string&) {
  3450. auto d = std::make_shared<lynx::SampleData>();
  3451. d->left.assign (48000, 0.5f);
  3452. return std::shared_ptr<const lynx::SampleData> (d);
  3453. };
  3454. auto on = lynx::RackState::build (s, nullptr, 48000.0, provider);
  3455. s.mixer[1].muted = true;
  3456. auto off = lynx::RackState::build (s, on.get(), 48000.0, provider);
  3457. lynx::RackRenderer r;
  3458. r.prepare (48000.0, 256);
  3459. lynx::LiveEventQueue live;
  3460. lynx::NoteEvent note;
  3461. note.velocity = 1.0f;
  3462. live.push (note);
  3463. std::vector<float> l (256), rr (256);
  3464. r.process (on.get(), false, 0.0, 256, l.data(), rr.data(), &live);
  3465. CHECK (std::abs (l[255] - 0.5f) < 1e-3f);
  3466. r.process (off.get(), false, 0.0, 256, l.data(), rr.data());
  3467. CHECK (l[0] > 0.45f && l[128] > 0.2f && l[128] < 0.3f && std::abs (l[255]) < 1e-6f); // ramp down to zero
  3468. r.process (off.get(), false, 0.0, 256, l.data(), rr.data());
  3469. CHECK (std::abs (l[0]) < 1e-9f);
  3470. }
  3471. TEST (dither_quantizes_to_lsb_grid_with_small_error)
  3472. {
  3473. lynx::Dither d (16);
  3474. std::vector<float> x (4800);
  3475. for (std::size_t i = 0; i < x.size(); ++i)
  3476. x[i] = 0.25f * std::sin ((float) i * 0.05f);
  3477. auto y = x;
  3478. d.process (y.data(), (int) y.size(), 0);
  3479. double errorSum = 0.0;
  3480. bool onGrid = true;
  3481. for (std::size_t i = 0; i < x.size(); ++i)
  3482. {
  3483. const auto steps = y[i] * 32768.0f;
  3484. onGrid = onGrid && std::abs (steps - std::round (steps)) < 1e-3f;
  3485. errorSum += std::abs (y[i] - x[i]);
  3486. }
  3487. CHECK (onGrid);
  3488. CHECK (errorSum / (double) x.size() < 4.0 / 32768.0); // a few LSBs of noise on average
  3489. }
  3490. TEST (parallel_rendering_matches_sequential)
  3491. {
  3492. // 32 channels (worth parallelizing), inserts with chained sends
  3493. auto song = lynx::Song::makeDefault();
  3494. song.mixer = lynx::Song::defaultMixer (16);
  3495. for (int i = 5; i < 32; ++i)
  3496. {
  3497. lynx::ChannelDef c;
  3498. c.instrument = i % 2 ? lynx::InstrumentKind::synth : lynx::InstrumentKind::hat;
  3499. c.mixerTrack = 1 + i % 12;
  3500. c.volume = 0.3f;
  3501. song.channels.push_back (c);
  3502. for (int step = i % 4; step < 16; step += 3)
  3503. song.patterns[0].notes.push_back ({ (std::int64_t) step * lynx::ticksPerStep, 200, i, 48 + i, 0.7f });
  3504. }
  3505. song.patterns[0].sortNotes();
  3506. song.setRoute (3, 7, true, 0.6f);
  3507. song.setRoute (7, 9, true, 0.5f);
  3508. song.setRoute (2, 9, true);
  3509. song.mixer[9].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::reverb));
  3510. auto seqState = lynx::RackState::build (song, nullptr, 48000.0);
  3511. auto parState = lynx::RackState::build (song, nullptr, 48000.0);
  3512. CHECK (parState->parallel && parState->mixerLayers.size() == 3);
  3513. lynx::WorkerPool pool (3);
  3514. lynx::RackRenderer seq, par;
  3515. seq.prepare (48000.0, 512);
  3516. par.prepare (48000.0, 512);
  3517. par.setWorkerPool (&pool);
  3518. std::vector<float> l1 (512), r1 (512), l2 (512), r2 (512);
  3519. const auto tps = lynx::ticksPerSample (song.bpm, 48000.0);
  3520. bool same = true;
  3521. float peak = 0.0f;
  3522. for (int block = 0; block < 200; ++block)
  3523. {
  3524. seq.process (seqState.get(), true, block * 512 * tps, 512, l1.data(), r1.data());
  3525. par.process (parState.get(), true, block * 512 * tps, 512, l2.data(), r2.data());
  3526. same = same && l1 == l2 && r1 == r2;
  3527. for (auto v : l1)
  3528. peak = std::max (peak, std::abs (v));
  3529. }
  3530. CHECK (same);
  3531. CHECK (peak > 0.05f);
  3532. // the pool handles many small rounds in a row
  3533. std::atomic<int> sum { 0 };
  3534. auto add = [&sum] (int i) { sum.fetch_add (i + 1); };
  3535. for (int round = 0; round < 2000; ++round)
  3536. pool.parallelFor (5, add);
  3537. CHECK (sum.load() == 2000 * 15);
  3538. }
  3539. TEST (arrangements_switch_and_keep_clip_indices)
  3540. {
  3541. auto s = lynx::Song::makeDefault();
  3542. s.patterns.emplace_back().name = "B";
  3543. s.playlist = { { 1, 0, 0, 960, 0 } };
  3544. s.loopEnd = 960;
  3545. CHECK (s.arrangements.size() == 1 && s.currentArrangement == 0);
  3546. const auto second = s.addArrangement ("Versão curta", true);
  3547. CHECK (second == 1 && s.currentArrangement == 1 && s.playlist.size() == 1 && s.loopEnd == 960);
  3548. s.playlist.push_back ({ 0, 1, 960, 960, 0 });
  3549. s.loopEnd = 0;
  3550. s.selectArrangement (0);
  3551. CHECK (s.playlist.size() == 1 && s.loopEnd == 960 && s.arrangements[1].clips.size() == 2);
  3552. // removing pattern 0 fixes the clips stored in the other arrangement
  3553. s.removePattern (0);
  3554. CHECK (s.playlist.size() == 1 && s.playlist[0].pattern == 0);
  3555. CHECK (s.arrangements[1].clips.size() == 1 && s.arrangements[1].clips[0].pattern == 0);
  3556. s.removeArrangement (0);
  3557. CHECK (s.arrangements.size() == 1 && s.currentArrangement == 0 && s.playlist.size() == 1 && s.loopEnd == 0);
  3558. }
  3559. namespace
  3560. {
  3561. // Test effect that inverts the signal and counts how many times it processed.
  3562. class CountingInverter final : public lynx::Effect
  3563. {
  3564. public:
  3565. void prepare (double) noexcept override {}
  3566. void reset() noexcept override {}
  3567. void process (float* l, float* r, int n, const lynx::EffectParams&, double) noexcept override
  3568. {
  3569. ++calls;
  3570. for (int i = 0; i < n; ++i)
  3571. {
  3572. l[i] = -l[i];
  3573. r[i] = -r[i];
  3574. }
  3575. }
  3576. int calls = 0;
  3577. };
  3578. } // namespace
  3579. TEST (keyboard_controller_outputs_key_value)
  3580. {
  3581. std::vector<std::uint8_t> blob (554, 0);
  3582. const std::uint32_t version = 3;
  3583. std::memcpy (blob.data(), &version, 4);
  3584. const float key60 = 0.7f, off = 0.2f;
  3585. std::memcpy (blob.data() + 12 + 60 * 4, &key60, 4);
  3586. std::memcpy (blob.data() + 548, &off, 4);
  3587. blob[552] = 1; // auto release
  3588. lynx::ChannelDef c;
  3589. c.instrument = lynx::InstrumentKind::controller;
  3590. c.controllerState = blob;
  3591. auto inst = lynx::makeInstrument (lynx::InstrumentKind::controller);
  3592. inst->prepare (48000.0);
  3593. inst->configure (c, 120.0);
  3594. std::vector<float> l (64), r (64);
  3595. inst->noteOn (60, 1.0f);
  3596. inst->render (l.data(), r.data(), 64, 1.0f, 1.0f);
  3597. CHECK (std::abs (inst->controlOutput (0) - 0.7f) < 1e-6f);
  3598. inst->noteOff (60);
  3599. CHECK (std::abs (inst->controlOutput (0) - 0.2f) < 1e-6f);
  3600. }
  3601. TEST (envelope_controller_ducks_on_each_note)
  3602. {
  3603. // a unipolar articulator like "Basic Sidechain": base 0.05, drops to 0 on the note and rises to 1 in 0.3 s
  3604. lynx::ControllerArticulator a;
  3605. a.envOn = true;
  3606. a.base = 0.05f;
  3607. a.envLevel = 1.0f;
  3608. a.count = 3;
  3609. a.time = { 0.0f, 0.2f, 0.3f };
  3610. a.level = { 0.0f, 0.75f, 1.0f };
  3611. CHECK (std::abs (lynx::controllerValue (a, 0.0, -1.0) - 0.05f) < 1e-4f);
  3612. CHECK (std::abs (lynx::controllerValue (a, 0.1, -1.0) - 0.425f) < 1e-3f);
  3613. CHECK (lynx::controllerValue (a, 1.0, -1.0) > 0.99f); // no sustain: runs to the end and stays
  3614. a.sustain = 1;
  3615. CHECK (std::abs (lynx::controllerValue (a, 1.0, -1.0) - 0.8f) < 1e-3f); // held at sustain
  3616. CHECK (lynx::controllerValue (a, 1.0, 0.5) > 0.99f); // released: continues to the end
  3617. a.bipolar = true;
  3618. a.base = 0.5f;
  3619. a.sustain = -1;
  3620. CHECK (std::abs (lynx::controllerValue (a, 0.0, -1.0) - 0.0f) < 1e-4f); // bipolar: 0.5 + (0 − 0.5)
  3621. }
  3622. TEST (peak_controller_drives_live_automation)
  3623. {
  3624. // track 1: source (DC 0.5) with Peak Controller; track 2: DC 0.5 with volume linked to the controller
  3625. auto render = [] (bool linked) {
  3626. lynx::Song s;
  3627. s.mixer = lynx::Song::defaultMixer (2);
  3628. for (int t = 1; t <= 2; ++t)
  3629. {
  3630. lynx::ChannelDef c;
  3631. c.instrument = lynx::InstrumentKind::sampler;
  3632. c.samplePath = "dc";
  3633. c.volume = 1.0f;
  3634. c.mixerTrack = t;
  3635. s.channels.push_back (c);
  3636. }
  3637. s.patterns.emplace_back();
  3638. auto peak = lynx::makeEffectSlot (lynx::EffectKind::peakController);
  3639. peak.params[0] = 1.0f; // base 1
  3640. peak.params[1] = 0.0f; // amount −1: 1 − peak
  3641. peak.params[2] = 0.5f; // no tension
  3642. s.mixer[1].effects.push_back (peak);
  3643. if (linked)
  3644. {
  3645. lynx::Automation a;
  3646. a.name = "Peak";
  3647. a.target = { lynx::AutomationTargetKind::mixerVolume, 2 };
  3648. a.source = { 1, 0, 0 };
  3649. s.automations.push_back (a);
  3650. }
  3651. lynx::RackState::Factories f;
  3652. f.samples = [] (const std::string&) {
  3653. auto d = std::make_shared<lynx::SampleData>();
  3654. d->left.assign (48000, 0.5f);
  3655. return std::shared_ptr<const lynx::SampleData> (d);
  3656. };
  3657. auto state = lynx::RackState::build (s, nullptr, 48000.0, f);
  3658. lynx::RackRenderer r;
  3659. r.prepare (48000.0, 512);
  3660. lynx::LiveEventQueue live;
  3661. for (int ch = 0; ch < 2; ++ch)
  3662. {
  3663. lynx::NoteEvent on;
  3664. on.channel = ch;
  3665. on.velocity = 1.0f;
  3666. live.push (on);
  3667. }
  3668. std::vector<float> l (4800), rr (4800);
  3669. r.process (state.get(), false, 0.0, 4800, l.data(), rr.data(), &live);
  3670. return l[4000];
  3671. };
  3672. const auto free = render (false), ducked = render (true);
  3673. CHECK (std::isfinite (ducked) && ducked > 0.0f);
  3674. CHECK (ducked < free - 0.05f); // the 0.5 peak on track 1 lowers track 2's volume
  3675. }
  3676. TEST (effect_slot_dry_wet_and_smart_disable)
  3677. {
  3678. lynx::Song s;
  3679. s.mixer = lynx::Song::defaultMixer (1);
  3680. lynx::ChannelDef c;
  3681. c.instrument = lynx::InstrumentKind::sampler;
  3682. c.samplePath = "dc";
  3683. c.volume = 1.0f;
  3684. c.mixerTrack = 1;
  3685. s.channels.push_back (c);
  3686. s.patterns.emplace_back();
  3687. lynx::EffectSlot fx;
  3688. fx.kind = lynx::EffectKind::plugin;
  3689. fx.plugin.id = "inversor";
  3690. fx.mix = 0.25f; // 75% dry (+0.5) and 25% wet (-0.5) = +0.25
  3691. s.mixer[1].effects.push_back (fx);
  3692. auto inverter = std::make_shared<CountingInverter>();
  3693. lynx::RackState::Factories f;
  3694. f.samples = [] (const std::string&) {
  3695. auto d = std::make_shared<lynx::SampleData>();
  3696. d->left.assign (4800, 0.5f);
  3697. return std::shared_ptr<const lynx::SampleData> (d);
  3698. };
  3699. f.pluginEffects = [inverter] (const lynx::PluginRef&, double) -> std::shared_ptr<lynx::Effect> { return inverter; };
  3700. auto state = lynx::RackState::build (s, nullptr, 48000.0, f);
  3701. lynx::RackRenderer r;
  3702. r.prepare (48000.0, 512);
  3703. lynx::LiveEventQueue live;
  3704. lynx::NoteEvent on;
  3705. on.velocity = 1.0f;
  3706. live.push (on);
  3707. std::vector<float> l (480), rr (480);
  3708. r.process (state.get(), false, 0.0, 480, l.data(), rr.data(), &live);
  3709. CHECK (std::abs (l[100] - 0.25f) < 1e-4f);
  3710. // after the sample ends: 4 s of silence and the plugin stops being called
  3711. for (int i = 0; i < 100 * 6; ++i) // 6 s
  3712. r.process (state.get(), false, 0.0, 480, l.data(), rr.data());
  3713. const auto callsAfterSilence = inverter->calls;
  3714. for (int i = 0; i < 100; ++i)
  3715. r.process (state.get(), false, 0.0, 480, l.data(), rr.data());
  3716. CHECK (inverter->calls == callsAfterSilence);
  3717. CHECK (callsAfterSilence < 100 * 6);
  3718. // sound again: processing resumes in the same block
  3719. live.push (on);
  3720. r.process (state.get(), false, 0.0, 480, l.data(), rr.data(), &live);
  3721. CHECK (inverter->calls == callsAfterSilence + 1 && std::abs (l[100] - 0.25f) < 1e-4f);
  3722. }
  3723. TEST (swing_delays_offbeat_sixteenths)
  3724. {
  3725. CHECK (lynx::swingDelay (0, 1.0f) == 0);
  3726. CHECK (lynx::swingDelay (lynx::ticksPerStep, 1.0f) == lynx::ticksPerStep / 2);
  3727. CHECK (lynx::swingDelay (lynx::ticksPerStep * 2, 1.0f) == 0);
  3728. CHECK (lynx::swingDelay (lynx::ticksPerStep + 10, 1.0f) == (lynx::ticksPerStep - 20) / 2); // off the grid: triangular weight (FL)
  3729. CHECK (lynx::swingDelay (lynx::ticksPerStep, 1.0f, 0.5f) == lynx::ticksPerStep / 4); // channel mix
  3730. CHECK (lynx::swingDelay (lynx::ticksPerStep * 3, 0.5f) == lynx::ticksPerStep / 4);
  3731. lynx::Pattern p;
  3732. p.notes = { { 0, 100, 0, 60 }, { lynx::ticksPerStep, 100, 0, 62 } };
  3733. lynx::EventBuffer ev;
  3734. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  3735. lynx::schedulePatternLoop (p, p.effectiveLength (4), 0.0, 12000, tps, ev, 1.0f);
  3736. int onOffset = -1;
  3737. for (auto& e : ev)
  3738. if (e.type == lynx::NoteEvent::Type::on && e.key == 62)
  3739. onOffset = e.sampleOffset;
  3740. CHECK (onOffset == (int) std::floor ((lynx::ticksPerStep * 1.5) / tps));
  3741. }
  3742. TEST (sampler_settings_pitch_reverse_envelope_cut)
  3743. {
  3744. auto ramp = std::make_shared<lynx::SampleData>();
  3745. for (int i = 0; i < 48000; ++i)
  3746. ramp->left.push_back ((float) i / 48000.0f); // ramp: the value tells where the read position is
  3747. ramp->sampleRate = 48000.0;
  3748. auto play = [&] (const lynx::SamplerSettings& s, int key, int frames, bool releaseAfterHalf) {
  3749. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  3750. inst->prepare (48000.0);
  3751. lynx::ChannelDef c;
  3752. c.sampler = s;
  3753. inst->configure (c, 120.0);
  3754. inst->noteOn (key, 1.0f);
  3755. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  3756. inst->render (l.data(), r.data(), frames / 2, 1.0f, 1.0f);
  3757. if (releaseAfterHalf)
  3758. inst->noteOff (key);
  3759. inst->render (l.data() + frames / 2, r.data() + frames / 2, frames - frames / 2, 1.0f, 1.0f);
  3760. return l;
  3761. };
  3762. // +12 semitones: reads twice as fast
  3763. lynx::SamplerSettings up;
  3764. up.pitch = 12.0f;
  3765. CHECK (std::abs (play (up, 60, 1000, false)[999] - 2.0f * 999.0f / 48000.0f) < 1e-3f);
  3766. // reversed: starts from the end
  3767. lynx::SamplerSettings back;
  3768. back.reverse = true;
  3769. CHECK (play (back, 60, 100, false)[10] > 0.99f);
  3770. // 10 ms attack: starts silent and reaches full level
  3771. lynx::SamplerSettings slow;
  3772. slow.attack = 0.01f;
  3773. const auto a = play (slow, 60, 2000, false);
  3774. CHECK (a[10] < 0.2f * (10.0f / 48000.0f) + 1e-6f && std::abs (a[1500] - 1500.0f / 48000.0f) < 1e-4f);
  3775. // 5 ms release: gone right after release; without release it plays in full
  3776. lynx::SamplerSettings rel;
  3777. rel.release = 0.005f;
  3778. CHECK (play (rel, 60, 2000, true)[1999] == 0.0f);
  3779. CHECK (play (lynx::SamplerSettings {}, 60, 2000, true)[1999] > 0.0f);
  3780. // cut itself: the second note cuts the first (one voice remains)
  3781. lynx::SamplerSettings cut;
  3782. cut.cut = true;
  3783. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  3784. inst->prepare (48000.0);
  3785. lynx::ChannelDef cutChannel;
  3786. cutChannel.sampler = cut;
  3787. inst->configure (cutChannel, 120.0);
  3788. inst->noteOn (60, 1.0f);
  3789. std::vector<float> l (2000), r (2000);
  3790. inst->render (l.data(), r.data(), 1000, 1.0f, 1.0f);
  3791. inst->noteOn (60, 1.0f);
  3792. std::fill (l.begin(), l.end(), 0.0f);
  3793. inst->render (l.data(), r.data(), 2000, 1.0f, 1.0f);
  3794. CHECK (std::abs (l[1999] - 1999.0f / 48000.0f) < 1e-4f); // only the new note
  3795. }
  3796. TEST (playlist_split_and_track_mute)
  3797. {
  3798. lynx::Clip c { 0, 3, 960, 3840, 480 };
  3799. const auto rest = lynx::splitClip (c, 2000);
  3800. CHECK (c.start == 960 && c.length == 1040 && c.offset == 480);
  3801. CHECK (rest.start == 2000 && rest.length == 2800 && rest.offset == 480 + 1040 && rest.track == 3);
  3802. auto s = lynx::Song::makeDefault();
  3803. s.mode = lynx::PlayMode::song;
  3804. s.playlist = { { 0, 0, 0, 3840, 0 } };
  3805. lynx::EventBuffer ev;
  3806. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  3807. lynx::scheduleSong (s, 0.0, 48000, tps, ev);
  3808. CHECK (ev.size() > 0);
  3809. s.playlistTracks.resize (1);
  3810. s.playlistTracks[0].muted = true;
  3811. ev.clear();
  3812. lynx::scheduleSong (s, 0.0, 48000, tps, ev);
  3813. CHECK (ev.size() == 0);
  3814. }
  3815. TEST (note_pan_pitch_and_mute)
  3816. {
  3817. lynx::Pattern p;
  3818. lynx::Note a { 0, 240, 0, 60 };
  3819. a.pan = -1.0f;
  3820. a.finePitch = 50.0f;
  3821. lynx::Note b { 240, 240, 0, 62 };
  3822. b.muted = true;
  3823. p.notes = { a, b };
  3824. lynx::EventBuffer ev;
  3825. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  3826. lynx::schedulePatternLoop (p, p.effectiveLength (4), 0.0, 48000, tps, ev);
  3827. int ons = 0;
  3828. for (auto& e : ev)
  3829. if (e.type == lynx::NoteEvent::Type::on)
  3830. {
  3831. ++ons;
  3832. CHECK (e.key == 60 && e.pan == -1.0f && e.cents == 50.0f);
  3833. }
  3834. CHECK (ons == 1); // the muted one doesn't play
  3835. // note pan in the sampler: fully left
  3836. auto dc = std::make_shared<lynx::SampleData>();
  3837. dc->left.assign (4800, 0.5f);
  3838. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, dc);
  3839. inst->prepare (48000.0);
  3840. inst->setNextNoteExpression (-1.0f, 0.0f);
  3841. inst->noteOn (60, 1.0f);
  3842. std::vector<float> l (100), r (100);
  3843. inst->render (l.data(), r.data(), 100, 1.0f, 1.0f);
  3844. CHECK (l[50] > 0.6f && std::abs (r[50]) < 1e-6f);
  3845. }
  3846. TEST (tempo_automation_changes_speed_and_duration)
  3847. {
  3848. auto song = lynx::Song::makeDefault();
  3849. song.bpm = 120.0;
  3850. song.mode = lynx::PlayMode::song;
  3851. const auto bar = (std::int64_t) lynx::ppq * 4;
  3852. song.playlist = { { 0, 0, 0, bar, 0 }, { 0, 0, bar, bar, 0 } };
  3853. lynx::Automation tempo;
  3854. tempo.target = { lynx::AutomationTargetKind::tempo, 0 };
  3855. const auto v120 = lynx::valueFromTempo (120.0), v240 = lynx::valueFromTempo (240.0);
  3856. tempo.points = { { 0, v120 }, { bar - 1, v120 }, { bar, v240 } }; // step: 120 -> 240 at bar 2
  3857. song.automations.push_back (tempo);
  3858. lynx::Clip clip;
  3859. clip.kind = lynx::ClipKind::automation;
  3860. clip.automation = 0;
  3861. clip.track = 1;
  3862. clip.length = bar * 2;
  3863. song.playlist.push_back (clip);
  3864. CHECK (std::abs (song.tempoAt (100.0) - 120.0) < 0.01 && std::abs (song.tempoAt ((double) bar + 100.0) - 240.0) < 0.01);
  3865. // 1 bar at 120 (2 s) + 1 at 240 (1 s)
  3866. CHECK (std::abs (song.secondsForTicks (bar * 2) - 3.0) < 0.01);
  3867. auto state = lynx::RackState::build (song, nullptr, 48000.0);
  3868. CHECK (state->tempoAutomation == 0);
  3869. lynx::RackRenderer r;
  3870. r.prepare (48000.0, 512);
  3871. std::vector<float> l (512), rr (512);
  3872. r.process (state.get(), true, 10.0, 512, l.data(), rr.data());
  3873. CHECK (std::abs (r.currentBpm() - 120.0) < 0.01);
  3874. r.process (state.get(), true, (double) bar + 10.0, 512, l.data(), rr.data());
  3875. CHECK (std::abs (r.currentBpm() - 240.0) < 0.01);
  3876. }
  3877. TEST (bounce_insert_song_and_apply)
  3878. {
  3879. auto s = lynx::Song::makeDefault();
  3880. s.setRoute (3, 7, true, 0.5f);
  3881. s.mixer[0].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::reverb));
  3882. s.mixer[2].solo = true;
  3883. const auto b = lynx::makeBounceSong (s, 3);
  3884. CHECK (b.mixer[3].solo && ! b.mixer[2].solo && b.mixer[3].toMaster && b.mixer[3].sends.empty());
  3885. CHECK (b.mixer[0].effects.empty() && b.mode == lynx::PlayMode::song);
  3886. const auto audible = b.soloAudible();
  3887. CHECK (audible[3] && ! audible[1] && ! audible[7]);
  3888. const auto channels = s.channels.size();
  3889. const auto inserts = s.mixer.size();
  3890. const auto created = lynx::applyBounce (s, 3, "C:/x.wav", 3840);
  3891. CHECK (created == (int) inserts && s.mixer.size() == inserts + 1 && s.mixer[3].muted);
  3892. CHECK (s.mixer[(std::size_t) created].sends.size() == 1 && s.mixer[(std::size_t) created].sends[0].target == 7);
  3893. CHECK (s.channels.size() == channels + 1 && s.channels.back().mixerTrack == created);
  3894. CHECK (s.playlist.back().kind == lynx::ClipKind::audio && s.playlist.back().length == 3840);
  3895. }
  3896. TEST (mixer_stereo_separation_phase_swap)
  3897. {
  3898. lynx::MixerTrack t;
  3899. std::vector<float> l { 1.0f }, r { 0.0f };
  3900. t.stereo = 1.0f; // mono
  3901. lynx::RackRenderer::applyStereoForTest (t, l.data(), r.data(), 1);
  3902. CHECK (std::abs (l[0] - 0.5f) < 1e-6f && std::abs (r[0] - 0.5f) < 1e-6f);
  3903. l = { 1.0f };
  3904. r = { 0.0f };
  3905. t.stereo = -1.0f; // doubled side: 1.5 L - 0.5 R
  3906. lynx::RackRenderer::applyStereoForTest (t, l.data(), r.data(), 1);
  3907. CHECK (std::abs (l[0] - 1.5f) < 1e-6f && std::abs (r[0] + 0.5f) < 1e-6f);
  3908. l = { 1.0f };
  3909. r = { 0.25f };
  3910. t.stereo = 0.0f;
  3911. t.swapChannels = true;
  3912. t.invertPhase = true;
  3913. lynx::RackRenderer::applyStereoForTest (t, l.data(), r.data(), 1);
  3914. CHECK (l[0] == -0.25f && r[0] == -1.0f);
  3915. }
  3916. TEST (effects_limiter_filter_distortion_chorus)
  3917. {
  3918. const double sr = 48000.0;
  3919. auto sine = [] (float hz, float amp, int n) {
  3920. std::vector<float> v ((std::size_t) n);
  3921. for (int i = 0; i < n; ++i)
  3922. v[(std::size_t) i] = amp * std::sin (2.0f * 3.14159265f * hz * (float) i / 48000.0f);
  3923. return v;
  3924. };
  3925. auto peak = [] (const std::vector<float>& v, int from) {
  3926. float p = 0.0f;
  3927. for (std::size_t i = (std::size_t) from; i < v.size(); ++i)
  3928. p = std::max (p, std::abs (v[i]));
  3929. return p;
  3930. };
  3931. // limiter: +12 dB on a 0.9 sine never exceeds the ceiling (-1 dB) and reports the latency
  3932. auto lim = lynx::makeEffect (lynx::EffectKind::limiter);
  3933. lim->prepare (sr);
  3934. auto slot = lynx::makeEffectSlot (lynx::EffectKind::limiter);
  3935. slot.params[0] = 11.0f / 12.0f; // -1 dB
  3936. slot.params[1] = 0.5f; // +12 dB
  3937. auto l = sine (100.0f, 0.9f, 48000), r = l;
  3938. lim->process (l.data(), r.data(), 48000, slot.params, 120.0);
  3939. CHECK (peak (l, 0) <= std::pow (10.0f, -1.0f / 20.0f) + 1e-4f);
  3940. CHECK (peak (l, 4800) > 0.8f);
  3941. CHECK (lim->latencySamples() == 72);
  3942. // low-pass filter at 500 Hz knocks down an 8 kHz sine
  3943. auto lp = lynx::makeEffect (lynx::EffectKind::filter);
  3944. lp->prepare (sr);
  3945. auto fs = lynx::makeEffectSlot (lynx::EffectKind::filter);
  3946. fs.params[1] = std::log (500.0f / 20.0f) / std::log (1000.0f);
  3947. l = sine (8000.0f, 1.0f, 9600);
  3948. r = l;
  3949. lp->process (l.data(), r.data(), 9600, fs.params, 120.0);
  3950. CHECK (peak (l, 4800) < 0.05f);
  3951. // distortion and chorus: finite, audible output
  3952. for (auto kind : { lynx::EffectKind::distortion, lynx::EffectKind::chorus })
  3953. {
  3954. auto fx = lynx::makeEffect (kind);
  3955. fx->prepare (sr);
  3956. auto ps = lynx::makeEffectSlot (kind);
  3957. l = sine (220.0f, 0.5f, 9600);
  3958. r = l;
  3959. fx->process (l.data(), r.data(), 9600, ps.params, 120.0);
  3960. bool finite = true;
  3961. for (auto v : l)
  3962. finite = finite && std::isfinite (v);
  3963. CHECK (finite && peak (l, 2400) > 0.1f && peak (l, 0) < 2.0f);
  3964. }
  3965. }
  3966. TEST (slide_notes_glide_without_retrigger)
  3967. {
  3968. // sampler with a ramp: the read speed doubles after a one-octave slide
  3969. auto ramp = std::make_shared<lynx::SampleData>();
  3970. for (int i = 0; i < 96000; ++i)
  3971. ramp->left.push_back ((float) i / 96000.0f);
  3972. ramp->sampleRate = 48000.0;
  3973. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  3974. inst->prepare (48000.0);
  3975. inst->noteOn (60, 1.0f);
  3976. std::vector<float> l (2000), r (2000);
  3977. inst->render (l.data(), r.data(), 1000, 1.0f, 1.0f);
  3978. const auto stepBefore = l[999] - l[998];
  3979. inst->slideTo (72, 0.0f, 100.0f);
  3980. std::fill (l.begin(), l.end(), 0.0f);
  3981. inst->render (l.data(), r.data(), 1000, 1.0f, 1.0f);
  3982. const auto stepAfter = l[999] - l[998];
  3983. CHECK (std::abs (stepAfter / stepBefore - 2.0f) < 0.01f);
  3984. // the sequencer sends "slide" (no off) for the slide note
  3985. lynx::Pattern p;
  3986. lynx::Note base { 0, 960, 0, 48 };
  3987. lynx::Note glide { 480, 240, 0, 55 };
  3988. glide.slide = true;
  3989. p.notes = { base, glide };
  3990. lynx::EventBuffer ev;
  3991. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  3992. lynx::schedulePatternLoop (p, p.effectiveLength (4), 0.0, 30000, tps, ev);
  3993. int ons = 0, offs = 0, slides = 0;
  3994. for (auto& e : ev)
  3995. {
  3996. ons += e.type == lynx::NoteEvent::Type::on;
  3997. offs += e.type == lynx::NoteEvent::Type::off;
  3998. if (e.type == lynx::NoteEvent::Type::slide)
  3999. {
  4000. ++slides;
  4001. CHECK (e.key == 55 && std::abs (e.slideSamples - 240.0f / (float) tps) < 1.0f);
  4002. }
  4003. }
  4004. CHECK (ons == 1 && offs == 1 && slides == 1);
  4005. }
  4006. TEST (synth_fm_phase_modulation)
  4007. {
  4008. auto render = [] (const lynx::SynthSettings& s) {
  4009. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  4010. inst->prepare (48000.0);
  4011. lynx::ChannelDef c;
  4012. c.synth = s;
  4013. inst->configure (c, 120.0);
  4014. inst->noteOn (69, 1.0f); // 440 Hz
  4015. std::vector<float> l (48000), r (48000);
  4016. inst->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  4017. return l;
  4018. };
  4019. // energy (Goertzel) at frequency f over frames [from, to)
  4020. auto energy = [] (const std::vector<float>& x, double f, int from, int to) {
  4021. const auto w = 2.0 * 3.141592653589793 * f / 48000.0, k = 2.0 * std::cos (w);
  4022. double s1 = 0.0, s2 = 0.0;
  4023. for (int i = from; i < to; ++i)
  4024. {
  4025. const auto s0 = x[(std::size_t) i] + k * s1 - s2;
  4026. s2 = s1;
  4027. s1 = s0;
  4028. }
  4029. return s1 * s1 + s2 * s2 - k * s1 * s2;
  4030. };
  4031. lynx::SynthSettings plain;
  4032. plain.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  4033. plain.osc[2] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  4034. plain.cutoff = 20000.0f;
  4035. auto fm = plain;
  4036. fm.fm = 1.0f;
  4037. const auto a = render (plain), b = render (fm);
  4038. // no FM: osc 3 adds (same pitch) and there's no 2nd harmonic; with FM the sidebands appear
  4039. CHECK (energy (a, 880.0, 4800, 24000) < 1e-3 * energy (a, 440.0, 4800, 24000));
  4040. CHECK (energy (b, 880.0, 4800, 24000) > 0.1 * energy (b, 440.0, 4800, 24000));
  4041. CHECK (energy (b, 1320.0, 4800, 24000) > 0.01 * energy (b, 440.0, 4800, 24000));
  4042. for (auto v : b)
  4043. CHECK (std::isfinite (v) && std::abs (v) < 1.0f);
  4044. // index decaying to 0: the start is bright, the end is nearly a sine again
  4045. auto decaying = fm;
  4046. decaying.fmDecay = 0.1f;
  4047. decaying.fmSustain = 0.0f;
  4048. const auto c = render (decaying);
  4049. const auto early = energy (c, 880.0, 0, 2400) / energy (c, 440.0, 0, 2400);
  4050. const auto late = energy (c, 880.0, 36000, 48000) / energy (c, 440.0, 36000, 48000);
  4051. CHECK (early > 0.05 && late < 1e-3);
  4052. }
  4053. TEST (synth_three_oscillators_adsr_filter)
  4054. {
  4055. auto render = [] (const lynx::SynthSettings& s, int frames, int releaseAt) {
  4056. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  4057. inst->prepare (48000.0);
  4058. lynx::ChannelDef c;
  4059. c.synth = s;
  4060. inst->configure (c, 120.0);
  4061. inst->noteOn (69, 1.0f); // A4 = 440 Hz
  4062. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  4063. inst->render (l.data(), r.data(), releaseAt, 1.0f, 1.0f);
  4064. inst->noteOff (69);
  4065. inst->render (l.data() + releaseAt, r.data() + releaseAt, frames - releaseAt, 1.0f, 1.0f);
  4066. return l;
  4067. };
  4068. auto peakIn = [] (const std::vector<float>& v, int from, int to) {
  4069. float p = 0.0f;
  4070. for (int i = from; i < to; ++i)
  4071. p = std::max (p, std::abs (v[(std::size_t) i]));
  4072. return p;
  4073. };
  4074. // default: sounds and fades after the release
  4075. const lynx::SynthSettings standard;
  4076. const auto a = render (standard, 48000, 24000);
  4077. CHECK (peakIn (a, 1000, 20000) > 0.05f && peakIn (a, 40000, 48000) < 1e-3f);
  4078. // pure sine with an open filter: zero-crossing count gives ~440 Hz
  4079. lynx::SynthSettings sine;
  4080. sine.osc[0].wave = lynx::Waveform::sine;
  4081. sine.cutoff = 20000.0f;
  4082. const auto b = render (sine, 48000, 47000);
  4083. int crossings = 0;
  4084. for (int i = 4800; i < 4800 + 48000 / 2; ++i)
  4085. crossings += (b[(std::size_t) i - 1] < 0.0f) != (b[(std::size_t) i] < 0.0f);
  4086. CHECK (std::abs (crossings - 440) < 6); // half a second = 220 cycles = 440 crossings
  4087. float sinePeak = 0.0f;
  4088. for (int i = 4800; i < 9600; ++i)
  4089. sinePeak = std::max (sinePeak, std::abs (b[(std::size_t) i]));
  4090. CHECK (sinePeak > 0.2f && sinePeak < 0.35f); // 0.3 level, approximated sine without clipping
  4091. // second oscillator an octave up adds energy; sustain 0 makes the note decay on its own
  4092. lynx::SynthSettings two = sine;
  4093. two.osc[1] = { lynx::Waveform::sine, 1, 0.0f, 1.0f };
  4094. two.sustain = 0.0f;
  4095. two.decay = 0.1f;
  4096. const auto c = render (two, 48000, 47000);
  4097. CHECK (peakIn (c, 100, 2000) > peakIn (b, 100, 2000) && peakIn (c, 30000, 40000) < 1e-3f);
  4098. }
  4099. TEST (set_target_value_round_trips)
  4100. {
  4101. auto s = lynx::Song::makeDefault();
  4102. s.mixer[2].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay));
  4103. const lynx::AutomationTarget targets[] = {
  4104. { lynx::AutomationTargetKind::channelVolume, 1 }, { lynx::AutomationTargetKind::channelPan, 2 },
  4105. { lynx::AutomationTargetKind::mixerVolume, 3 }, { lynx::AutomationTargetKind::mixerPan, 0 },
  4106. { lynx::AutomationTargetKind::effectParam, 2, 0, 1 }, { lynx::AutomationTargetKind::tempo, 0 },
  4107. };
  4108. for (const auto& t : targets)
  4109. {
  4110. CHECK (s.setTargetValue (t, 0.25f));
  4111. CHECK (std::abs (s.targetValue (t) - 0.25f) < 1e-5f);
  4112. }
  4113. CHECK (! s.setTargetValue ({ lynx::AutomationTargetKind::channelParam, 0, 0, 3 }, 0.5f)); // lives in the plugin
  4114. }
  4115. TEST (cut_groups_stretch_and_envelope_import)
  4116. {
  4117. // open hat (cut by 1) is cut when the closed one (group 1) plays
  4118. lynx::Song s;
  4119. s.mixer = lynx::Song::defaultMixer (2);
  4120. for (int i = 0; i < 2; ++i)
  4121. {
  4122. lynx::ChannelDef c;
  4123. c.instrument = lynx::InstrumentKind::sampler;
  4124. c.samplePath = "dc";
  4125. c.volume = 1.0f;
  4126. c.mixerTrack = i + 1;
  4127. s.channels.push_back (c);
  4128. }
  4129. s.channels[0].cutBy = 1; // open
  4130. s.channels[1].cutGroup = 1; // closed
  4131. auto& p = s.patterns.emplace_back();
  4132. p.notes = { { 0, 100, 0, 60 }, { 960, 100, 1, 60 } };
  4133. auto provider = [] (const std::string&) {
  4134. auto d = std::make_shared<lynx::SampleData>();
  4135. d->left.assign (96000, 0.5f);
  4136. return std::shared_ptr<const lynx::SampleData> (d);
  4137. };
  4138. auto state = lynx::RackState::build (s, nullptr, 48000.0, provider);
  4139. CHECK (state->hasCutGroups && state->cutTargets[1].size() == 1 && state->cutTargets[1][0] == 0);
  4140. lynx::RackRenderer r;
  4141. r.prepare (48000.0, 512);
  4142. std::vector<float> l (512), rr (512);
  4143. const auto tps = lynx::ticksPerSample (s.bpm, 48000.0);
  4144. float afterCut = 0.0f;
  4145. for (double tick = 0.0; tick < 960.0 * 3; tick += 512 * tps)
  4146. {
  4147. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  4148. if (tick > 960.0 * 2) // the closed one continues; the open one has stopped
  4149. afterCut = std::max (afterCut, std::abs (l[256]));
  4150. }
  4151. CHECK (std::abs (afterCut - 0.5f * 0.78f) < 0.01f); // only the closed one (default velocity 0.78)
  4152. // resampling stretch: 1 s of sample stretched to 4 beats at 120 BPM = 2 s
  4153. auto ramp = std::make_shared<lynx::SampleData>();
  4154. for (int i = 0; i < 48000; ++i)
  4155. ramp->left.push_back ((float) i / 48000.0f);
  4156. ramp->sampleRate = 48000.0;
  4157. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  4158. inst->prepare (48000.0);
  4159. lynx::ChannelDef c;
  4160. c.sampler.stretchBeats = 4.0f;
  4161. inst->configure (c, 120.0);
  4162. inst->noteOn (72, 1.0f); // the note pitch doesn't change the speed
  4163. std::vector<float> a (48000), b (48000);
  4164. inst->render (a.data(), b.data(), 48000, 1.0f, 1.0f);
  4165. CHECK (std::abs (a[47999] - 0.5f) < 0.01f); // after 1 s it has read half
  4166. // FL envelope time: 32950 = 2 s; < 101 = 0
  4167. CHECK (std::abs (flp::Channel::envelopeTime (32950) - 2.0) < 0.01 && flp::Channel::envelopeTime (50) == 0.0);
  4168. }
  4169. TEST (time_stretch_keeps_pitch)
  4170. {
  4171. lynx::SampleData sine;
  4172. sine.sampleRate = 48000.0;
  4173. for (int i = 0; i < 48000; ++i)
  4174. sine.left.push_back (0.5f * std::sin (2.0f * 3.14159265f * 440.0f * (float) i / 48000.0f));
  4175. auto crossingsPerSecond = [] (const lynx::SampleData& d) {
  4176. int c = 0;
  4177. const auto n = (int) d.frames();
  4178. for (int i = 4800; i < n - 4800; ++i)
  4179. c += (d.left[(std::size_t) i - 1] < 0.0f) != (d.left[(std::size_t) i] < 0.0f);
  4180. return (double) c / ((double) (n - 9600) / d.sampleRate);
  4181. };
  4182. for (double ratio : { 2.0, 0.5, 1.37 })
  4183. {
  4184. const auto out = lynx::timeStretch (sine, ratio);
  4185. CHECK (std::abs ((double) out->frames() - 48000.0 * ratio) < 2.0);
  4186. CHECK (std::abs (crossingsPerSecond (*out) - 880.0) < 15.0); // 440 Hz stays 440 Hz
  4187. float peak = 0.0f;
  4188. for (std::size_t i = 4800; i + 4800 < out->frames(); ++i)
  4189. peak = std::max (peak, std::abs (out->left[i]));
  4190. CHECK (peak > 0.4f && peak < 0.6f); // no gaps or clipping in the overlap
  4191. }
  4192. }
  4193. TEST (sampler_region_start_and_end)
  4194. {
  4195. auto ramp = std::make_shared<lynx::SampleData>();
  4196. for (int i = 0; i < 10000; ++i)
  4197. ramp->left.push_back ((float) i / 10000.0f);
  4198. ramp->sampleRate = 48000.0;
  4199. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  4200. inst->prepare (48000.0);
  4201. lynx::ChannelDef c;
  4202. c.sampler.regionStart = 0.25f;
  4203. c.sampler.regionEnd = 0.5f;
  4204. inst->configure (c, 120.0);
  4205. inst->noteOn (60, 1.0f);
  4206. std::vector<float> l (6000), r (6000);
  4207. inst->render (l.data(), r.data(), 6000, 1.0f, 1.0f);
  4208. CHECK (std::abs (l[0] - 0.25f) < 0.001f); // starts at the beginning of the slice
  4209. CHECK (l[2400] > 0.48f && l[2600] == 0.0f); // and stops at its end
  4210. }
  4211. TEST (arpeggiator_plays_held_chord_in_steps)
  4212. {
  4213. auto song = lynx::Song::makeDefault();
  4214. song.bpm = 120.0;
  4215. song.patterns[0].notes.clear();
  4216. for (int key : { 60, 64, 67 })
  4217. song.patterns[0].notes.push_back ({ 0, lynx::ppq * 4, 4, key, 0.8f }); // chord held for 1 bar
  4218. song.channels[4].arp.direction = 1; // up
  4219. song.channels[4].arp.stepBeats = 0.25f;
  4220. auto state = lynx::RackState::build (song, nullptr, 48000.0);
  4221. CHECK (state->arpeggiators[4] != nullptr && state->arpeggiators[0] == nullptr);
  4222. // the arpeggiator generates the notes; we count what it hands to the instrument
  4223. auto& arp = *state->arpeggiators[4];
  4224. const auto tps = lynx::ticksPerSample (song.bpm, 48000.0);
  4225. std::vector<int> keys;
  4226. lynx::EventBuffer ev;
  4227. for (double tick = 0.0; tick < lynx::ppq * 2.0; tick += 512 * tps)
  4228. {
  4229. ev.clear();
  4230. lynx::schedulePatternLoop (song.patterns[0], song.patterns[0].effectiveLength (4), tick, 512, tps, ev);
  4231. int in = 0, out = 0;
  4232. for (auto& e : ev)
  4233. if (e.channel == 4)
  4234. arp.input[(std::size_t) in++] = e;
  4235. arp.process (4, arp.input.data(), in, tick, tps, 512, song.channels[4].arp, arp.output.data(), out);
  4236. for (int i = 0; i < out; ++i)
  4237. if (arp.output[(std::size_t) i].type == lynx::NoteEvent::Type::on)
  4238. keys.push_back (arp.output[(std::size_t) i].key);
  4239. }
  4240. // 2 beats = 8 sixteenth steps: 60 64 67 60 64 67 60 64
  4241. CHECK (keys.size() >= 8); // the last block goes slightly past 2 beats
  4242. const int expected[] = { 60, 64, 67, 60, 64, 67, 60, 64 };
  4243. for (std::size_t i = 0; i < keys.size() && i < 8; ++i)
  4244. CHECK (keys[i] == expected[i]);
  4245. // actually rendering also makes sound
  4246. lynx::RackRenderer r;
  4247. r.prepare (48000.0, 512);
  4248. std::vector<float> l (512), rr (512);
  4249. float peak = 0.0f;
  4250. for (double tick = 0.0; tick < lynx::ppq; tick += 512 * tps)
  4251. {
  4252. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  4253. for (auto v : l)
  4254. peak = std::max (peak, std::abs (v));
  4255. }
  4256. CHECK (peak > 0.01f);
  4257. }
  4258. TEST (audio_clip_fades_and_gain)
  4259. {
  4260. lynx::Song s;
  4261. s.bpm = 120.0;
  4262. s.mode = lynx::PlayMode::song;
  4263. s.mixer = lynx::Song::defaultMixer (1);
  4264. lynx::ChannelDef c;
  4265. c.instrument = lynx::InstrumentKind::audioClip;
  4266. c.samplePath = "dc";
  4267. c.volume = 1.0f;
  4268. c.mixerTrack = 1;
  4269. s.channels.push_back (c);
  4270. s.patterns.emplace_back();
  4271. lynx::Clip clip;
  4272. clip.kind = lynx::ClipKind::audio;
  4273. clip.channel = 0;
  4274. clip.length = lynx::ppq * 4; // 2 s at 120 BPM
  4275. clip.fadeIn = lynx::ppq; // 0.5 s
  4276. clip.fadeOut = lynx::ppq;
  4277. clip.gain = 0.5f;
  4278. s.playlist.push_back (clip);
  4279. auto provider = [] (const std::string&) {
  4280. auto d = std::make_shared<lynx::SampleData>();
  4281. d->left.assign (48000 * 4, 1.0f);
  4282. return std::shared_ptr<const lynx::SampleData> (d);
  4283. };
  4284. auto state = lynx::RackState::build (s, nullptr, 48000.0, provider);
  4285. lynx::RackRenderer r;
  4286. r.prepare (48000.0, 512);
  4287. std::vector<float> all;
  4288. std::vector<float> l (512), rr (512);
  4289. const auto tps = lynx::ticksPerSample (s.bpm, 48000.0);
  4290. for (double tick = 0.0; tick < lynx::ppq * 4.0; tick += 512 * tps)
  4291. {
  4292. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  4293. all.insert (all.end(), l.begin(), l.end());
  4294. }
  4295. CHECK (all[100] < 0.01f); // fade-in start
  4296. CHECK (std::abs (all[12000] - 0.25f) < 0.02f); // fade-in midpoint: half of 0.5
  4297. CHECK (std::abs (all[48000] - 0.5f) < 0.01f); // body: the clip gain
  4298. CHECK (std::abs (all[96000 - 12000] - 0.25f) < 0.02f); // fade-out midpoint
  4299. }
  4300. TEST (slicer_detects_hits_and_plays_slices_by_key)
  4301. {
  4302. // 4 hits (decaying noise) every 0.25 s
  4303. lynx::SampleData loop;
  4304. loop.sampleRate = 48000.0;
  4305. loop.left.assign (48000, 0.0f);
  4306. lynx::Noise noise;
  4307. for (int hit = 0; hit < 4; ++hit)
  4308. for (int i = 0; i < 6000; ++i)
  4309. loop.left[(std::size_t) (hit * 12000 + i)] = noise.next() * 0.8f * std::exp (-(float) i / 1500.0f);
  4310. const auto slices = lynx::detectSlices (loop, 0.5f);
  4311. CHECK (slices.size() == 4);
  4312. for (std::size_t i = 0; i < slices.size(); ++i)
  4313. CHECK (std::abs (slices[i] - 0.25f * (float) i) < 0.01f);
  4314. // key 61 plays the second slice, which starts at 0.25 and ends before 0.5
  4315. auto ramp = std::make_shared<lynx::SampleData>();
  4316. for (int i = 0; i < 48000; ++i)
  4317. ramp->left.push_back ((float) i / 48000.0f);
  4318. ramp->sampleRate = 48000.0;
  4319. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  4320. inst->prepare (48000.0);
  4321. lynx::ChannelDef c;
  4322. c.sampler.slices = slices;
  4323. inst->configure (c, 120.0);
  4324. inst->noteOn (61, 1.0f);
  4325. std::vector<float> l (20000), r (20000);
  4326. inst->render (l.data(), r.data(), 20000, 1.0f, 1.0f);
  4327. CHECK (std::abs (l[0] - 0.25f) < 0.01f && l[11000] > 0.45f && l[13000] == 0.0f);
  4328. }
  4329. TEST (project_templates_render_sound)
  4330. {
  4331. const auto names = lynx::templateNames();
  4332. CHECK (names.size() == 4);
  4333. for (int t = 1; t < (int) names.size(); ++t)
  4334. {
  4335. auto song = lynx::makeTemplate (t);
  4336. auto state = lynx::RackState::build (song, nullptr, 48000.0);
  4337. lynx::RackRenderer r;
  4338. r.prepare (48000.0, 512);
  4339. std::vector<float> l (512), rr (512);
  4340. const auto tps = lynx::ticksPerSample (song.bpm, 48000.0);
  4341. float peak = 0.0f;
  4342. for (double tick = 0.0; tick < lynx::ppq * 4.0; tick += 512 * tps)
  4343. {
  4344. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  4345. for (auto v : l)
  4346. peak = std::max (peak, std::abs (v));
  4347. }
  4348. CHECK (peak > 0.05f && peak < 4.0f);
  4349. }
  4350. CHECK (lynx::makeTemplate (0).patterns[0].notes.empty());
  4351. }
  4352. // --- interface translations (resources/i18n) -------------------------------------------------------
  4353. namespace i18ntest
  4354. {
  4355. std::string readFile (const std::filesystem::path& path)
  4356. {
  4357. std::ifstream in (path, std::ios::binary);
  4358. return { std::istreambuf_iterator<char> (in), std::istreambuf_iterator<char>() };
  4359. }
  4360. std::string unescape (const std::string& s)
  4361. {
  4362. std::string out;
  4363. for (std::size_t i = 0; i < s.size(); ++i)
  4364. {
  4365. if (s[i] == '\\' && i + 1 < s.size())
  4366. {
  4367. const auto n = s[++i];
  4368. out += n == 'n' ? '\n' : n == 't' ? '\t' : n;
  4369. }
  4370. else
  4371. out += s[i];
  4372. }
  4373. return out;
  4374. }
  4375. // reads a quoted string starting at s[pos] == '"'; returns the raw (escaped) contents and moves pos past the closing quote
  4376. bool quoted (const std::string& s, std::size_t& pos, std::string& raw)
  4377. {
  4378. if (pos >= s.size() || s[pos] != '"')
  4379. return false;
  4380. raw.clear();
  4381. for (++pos; pos < s.size() && s[pos] != '"' && s[pos] != '\n'; ++pos)
  4382. {
  4383. if (s[pos] == '\\' && pos + 1 < s.size())
  4384. raw += s[pos++];
  4385. raw += s[pos];
  4386. }
  4387. if (pos >= s.size() || s[pos] != '"')
  4388. return false;
  4389. ++pos;
  4390. return true;
  4391. }
  4392. // JUCE LocalisedStrings format: "english" = "translation"; duplicates are reported in `duplicates`
  4393. std::map<std::string, std::string> parseTable (const std::string& text, std::vector<std::string>& duplicates)
  4394. {
  4395. std::map<std::string, std::string> table;
  4396. std::istringstream lines (text);
  4397. std::string line;
  4398. while (std::getline (lines, line))
  4399. {
  4400. std::size_t pos = line.find_first_not_of (" \t");
  4401. std::string key, value;
  4402. if (pos == std::string::npos || ! quoted (line, pos, key))
  4403. continue;
  4404. pos = line.find ('"', pos);
  4405. if (pos == std::string::npos || ! quoted (line, pos, value))
  4406. value.clear();
  4407. const auto k = unescape (key);
  4408. if (table.count (k) != 0)
  4409. duplicates.push_back (k);
  4410. table[k] = unescape (value);
  4411. }
  4412. return table;
  4413. }
  4414. // string literals passed to tr() / TR_NOOP() in the sources (adjacent literals are concatenated)
  4415. std::map<std::string, std::string> sourceKeys (const std::filesystem::path& srcDir)
  4416. {
  4417. std::map<std::string, std::string> keys;
  4418. for (const auto& entry : std::filesystem::recursive_directory_iterator (srcDir))
  4419. {
  4420. const auto ext = entry.path().extension().string();
  4421. if (! entry.is_regular_file() || (ext != ".cpp" && ext != ".h"))
  4422. continue;
  4423. // drop // comment lines (they may quote tr ("...") as an example)
  4424. std::string text, line;
  4425. std::istringstream in (readFile (entry.path()));
  4426. while (std::getline (in, line))
  4427. {
  4428. const auto first = line.find_first_not_of (" \t");
  4429. text += (first != std::string::npos && line.compare (first, 2, "//") == 0) ? std::string() : line;
  4430. text += '\n';
  4431. }
  4432. auto isIdent = [] (char c) { return std::isalnum ((unsigned char) c) || c == '_'; };
  4433. for (const std::string name : { "tr", "TR_NOOP" })
  4434. for (auto at = text.find (name); at != std::string::npos; at = text.find (name, at + 1))
  4435. {
  4436. if ((at > 0 && isIdent (text[at - 1])) || isIdent (text[at + name.size()]))
  4437. continue;
  4438. auto pos = text.find_first_not_of (" \t\n", at + name.size());
  4439. if (pos == std::string::npos || text[pos] != '(')
  4440. continue;
  4441. pos = text.find_first_not_of (" \t\n", pos + 1);
  4442. std::string key, raw;
  4443. bool any = false;
  4444. while (pos != std::string::npos && quoted (text, pos, raw))
  4445. {
  4446. key += raw;
  4447. any = true;
  4448. pos = text.find_first_not_of (" \t\n", pos);
  4449. }
  4450. if (any)
  4451. keys.emplace (unescape (key), entry.path().filename().string());
  4452. }
  4453. }
  4454. return keys;
  4455. }
  4456. std::set<std::string> placeholders (const std::string& s)
  4457. {
  4458. std::set<std::string> found;
  4459. for (auto open = s.find ('{'); open != std::string::npos; open = s.find ('{', open + 1))
  4460. if (const auto close = s.find ('}', open); close != std::string::npos && close - open <= 3)
  4461. found.insert (s.substr (open, close - open + 1));
  4462. return found;
  4463. }
  4464. } // namespace i18ntest
  4465. TEST (translations_cover_every_ui_string)
  4466. {
  4467. using namespace i18ntest;
  4468. const auto text = readFile ("resources/i18n/pt-BR.txt");
  4469. CHECK (! text.empty());
  4470. std::vector<std::string> duplicates;
  4471. const auto table = parseTable (text, duplicates);
  4472. CHECK (table.size() > 300);
  4473. CHECK (duplicates.empty());
  4474. for (const auto& d : duplicates)
  4475. std::printf (" duplicate pt-BR entry: \"%s\"\n", d.c_str());
  4476. const auto keys = sourceKeys ("src");
  4477. CHECK (keys.size() > 300);
  4478. int missing = 0;
  4479. for (const auto& [key, file] : keys)
  4480. if (auto it = table.find (key); it == table.end() || it->second.empty())
  4481. {
  4482. ++missing;
  4483. std::printf (" no pt-BR translation for \"%s\" (%s)\n", key.c_str(), file.c_str());
  4484. }
  4485. CHECK (missing == 0);
  4486. // no empty values, and every {n} placeholder survives the translation
  4487. int empty = 0, badPlaceholders = 0;
  4488. for (const auto& [english, portuguese] : table)
  4489. {
  4490. empty += portuguese.empty() ? 1 : 0;
  4491. if (placeholders (english) != placeholders (portuguese))
  4492. {
  4493. ++badPlaceholders;
  4494. std::printf (" placeholders differ: \"%s\"\n", english.c_str());
  4495. }
  4496. }
  4497. CHECK (empty == 0);
  4498. CHECK (badPlaceholders == 0);
  4499. }
  4500. TEST (translations_embedded_table_is_up_to_date)
  4501. {
  4502. // src/ui/I18nData.h must be regenerated (tools/make_i18n.py) whenever the .txt changes
  4503. const auto text = i18ntest::readFile ("resources/i18n/pt-BR.txt");
  4504. CHECK (text.size() == sizeof (lynx::i18n::data::ptBR));
  4505. CHECK (std::memcmp (text.data(), lynx::i18n::data::ptBR, std::min (text.size(), sizeof (lynx::i18n::data::ptBR))) == 0);
  4506. }
  4507. // --- workflow shell: pattern/channel operations, key map, workspace layout, control math -------------
  4508. TEST (workflow_pattern_navigation_and_insert)
  4509. {
  4510. auto song = lynx::Song::makeDefault();
  4511. song.patterns.resize (3);
  4512. song.patterns[1].name = "B";
  4513. song.patterns[2].name = "C";
  4514. song.patterns[2].notes.push_back ({});
  4515. song.currentPattern = 0;
  4516. CHECK (lynx::stepPattern (song, 1) == 1 && lynx::stepPattern (song, -1) == 0 && lynx::stepPattern (song, 10) == 2);
  4517. // pattern 0 has the default notes, 1 is empty, 2 has a note
  4518. CHECK (! lynx::isPatternEmpty (song.patterns[0]) && lynx::isPatternEmpty (song.patterns[1]));
  4519. CHECK (lynx::findNextEmptyPattern (song, 0) == 1 && lynx::findNextEmptyPattern (song, 1) == -1);
  4520. CHECK (lynx::gotoNextEmptyPattern (song) == 1 && song.currentPattern == 1);
  4521. song.patterns[1].notes.push_back ({});
  4522. const auto before = song.patterns.size();
  4523. CHECK (lynx::gotoNextEmptyPattern (song) == (int) before && song.patterns.size() == before + 1);
  4524. CHECK (song.patterns.back().name == "Pattern 1" || song.patterns.back().name.rfind ("Pattern ", 0) == 0);
  4525. // insert keeps Playlist clips on their patterns
  4526. lynx::Clip clip;
  4527. clip.pattern = 2;
  4528. song.playlist = { clip };
  4529. song.arrangements.push_back ({ "Other", { clip }, 0, 0, {} });
  4530. CHECK (lynx::insertPattern (song, 1, "New") == 1 && song.currentPattern == 1);
  4531. CHECK (song.patterns[1].name == "New" && song.patterns[1].notes.empty() && song.patterns[3].name == "C");
  4532. CHECK (song.playlist[0].pattern == 3 && song.arrangements[1].clips[0].pattern == 3);
  4533. }
  4534. TEST (workflow_split_pattern_by_channel)
  4535. {
  4536. auto song = lynx::Song::makeDefault();
  4537. song.patterns.resize (1);
  4538. auto& p = song.patterns[0];
  4539. p.name = "Beat";
  4540. p.notes.clear();
  4541. for (int i = 0; i < 4; ++i)
  4542. p.notes.push_back ({ (std::int64_t) i * lynx::ticksPerStep, lynx::ticksPerStep, i % 2 == 0 ? 0 : 2, 60 });
  4543. song.channels[2].colour = 0xff112233;
  4544. lynx::Clip clip;
  4545. clip.pattern = 0;
  4546. song.playlist = { clip };
  4547. const auto created = lynx::splitPatternByChannel (song, 0);
  4548. CHECK (created == 2 && song.patterns.size() == 3);
  4549. CHECK (song.patterns[0].notes.size() == 4); // the original is unchanged
  4550. CHECK (song.patterns[1].name == "Beat - " + song.channels[0].name && song.patterns[1].notes.size() == 2);
  4551. CHECK (song.patterns[2].colour == 0xff112233u && song.patterns[2].notes.size() == 2 && song.patterns[2].notes[0].channel == 2);
  4552. CHECK (song.playlist[0].pattern == 0);
  4553. CHECK (lynx::splitPatternByChannel (song, 99) == 0);
  4554. }
  4555. TEST (workflow_channel_selection)
  4556. {
  4557. lynx::ChannelSelection s;
  4558. s.selectOnly (2);
  4559. s.toggle (5);
  4560. s.toggle (0);
  4561. CHECK ((s.rows == std::vector<int> { 0, 2, 5 }) && s.contains (5) && ! s.contains (3));
  4562. s.toggle (2);
  4563. CHECK ((s.rows == std::vector<int> { 0, 5 }));
  4564. s.selectOnly (3);
  4565. s.extendTo (6);
  4566. CHECK ((s.rows == std::vector<int> { 3, 4, 5, 6 }));
  4567. s.extendTo (1);
  4568. CHECK ((s.rows == std::vector<int> { 1, 2, 3 }));
  4569. s.selectOnly (4);
  4570. s.toggle (4); // the last one stays
  4571. CHECK ((s.rows == std::vector<int> { 4 }));
  4572. s.selectAll (3);
  4573. CHECK ((s.rows == std::vector<int> { 0, 1, 2 }));
  4574. s.rows = { 7, 9 };
  4575. s.clamp (5);
  4576. CHECK (s.rows.size() == 1 && s.rows[0] < 5);
  4577. }
  4578. TEST (workflow_move_clone_insert_channels)
  4579. {
  4580. auto song = lynx::Song::makeDefault();
  4581. const auto names = [&] {
  4582. std::vector<std::string> n;
  4583. for (const auto& c : song.channels)
  4584. n.push_back (c.name);
  4585. return n;
  4586. };
  4587. const auto original = names();
  4588. const auto count = (int) song.channels.size();
  4589. CHECK (count >= 4);
  4590. // references that must follow their channel
  4591. song.patterns[0].notes.push_back ({ 0, 240, 1, 64 });
  4592. lynx::Automation a;
  4593. a.target = { lynx::AutomationTargetKind::channelVolume, 1 };
  4594. song.automations.push_back (a);
  4595. song.midiLinks.push_back ({ 7, -1, { lynx::AutomationTargetKind::channelPan, 3 } });
  4596. lynx::Clip audio;
  4597. audio.kind = lynx::ClipKind::audio;
  4598. audio.channel = 3;
  4599. song.playlist.push_back (audio);
  4600. std::vector<int> selection { 1, 3 };
  4601. CHECK (lynx::moveChannels (song, selection, -1));
  4602. CHECK ((selection == std::vector<int> { 0, 2 }));
  4603. CHECK (song.channels[0].name == original[1] && song.channels[1].name == original[0] && song.channels[2].name == original[3]
  4604. && song.channels[3].name == original[2]);
  4605. CHECK (song.automations[0].target.index == 0 && song.midiLinks[0].target.index == 2 && song.playlist.back().channel == 2);
  4606. CHECK (std::any_of (song.patterns[0].notes.begin(), song.patterns[0].notes.end(),
  4607. [] (const lynx::Note& n) { return n.channel == 0 && n.key == 64; }));
  4608. CHECK (! lynx::moveChannels (song, selection, -1)); // the block is at the top
  4609. CHECK (lynx::moveChannels (song, selection, 1) && (selection == std::vector<int> { 1, 3 }) && names() == original);
  4610. // clone: settings, not notes, right below, with a new name
  4611. song.channels[1].volume = 0.33f;
  4612. const auto notesBefore = song.patterns[0].notes.size();
  4613. const auto clone = lynx::cloneChannel (song, 1);
  4614. CHECK (clone == 2 && (int) song.channels.size() == count + 1);
  4615. CHECK (song.channels[2].name == original[1] + " #2" && song.channels[2].volume == 0.33f);
  4616. CHECK (song.patterns[0].notes.size() == notesBefore);
  4617. CHECK (song.channels[3].name == original[2] && song.automations[0].target.index == 1);
  4618. CHECK (lynx::cloneChannel (song, 1) == 2 && song.channels[2].name == original[1] + " #3");
  4619. // remove several
  4620. CHECK (lynx::removeChannels (song, { 2, 3, 2 }) == 2 && (int) song.channels.size() == count);
  4621. CHECK (names() == original);
  4622. }
  4623. TEST (workflow_send_channels_to_free_inserts)
  4624. {
  4625. auto song = lynx::Song::makeDefault();
  4626. for (auto& c : song.channels)
  4627. c.mixerTrack = 0;
  4628. song.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay)); // not free: has effects
  4629. song.channels[0].mixerTrack = 2; // not free: used
  4630. song.setRoute (5, 3, true); // 3 is not free: receives a send
  4631. CHECK (! lynx::isInsertFree (song, 1) && ! lynx::isInsertFree (song, 2) && ! lynx::isInsertFree (song, 3) && lynx::isInsertFree (song, 4));
  4632. song.channels[1].colour = 0xff445566;
  4633. const auto tracks = lynx::sendChannelsToFreeInserts (song, { 1, 2 });
  4634. CHECK ((tracks == std::vector<int> { 4, 5 }) || (tracks == std::vector<int> { 4, 6 }));
  4635. CHECK (song.channels[1].mixerTrack == 4 && song.mixer[4].name == song.channels[1].name && song.mixer[4].colour == 0xff445566u);
  4636. CHECK (song.mixer[(std::size_t) tracks[1]].name == song.channels[2].name);
  4637. // with no free insert left, a new one is added at the end
  4638. auto full = lynx::Song::makeDefault();
  4639. full.mixer = lynx::Song::defaultMixer (1);
  4640. full.channels[0].mixerTrack = 1;
  4641. const auto added = lynx::sendChannelsToFreeInserts (full, { 1 });
  4642. CHECK (added.size() == 1 && added[0] == 2 && full.mixer.size() == 3 && full.channels[1].mixerTrack == 2);
  4643. }
  4644. TEST (workflow_palette_random_colour)
  4645. {
  4646. const auto& palette = lynx::lynxPalette();
  4647. for (std::uint32_t seed = 0; seed < 50; ++seed)
  4648. {
  4649. const auto current = palette[seed % palette.size()];
  4650. const auto c = lynx::randomPaletteColour (current, seed);
  4651. CHECK (c != current && std::find (palette.begin(), palette.end(), c) != palette.end());
  4652. }
  4653. }
  4654. TEST (workflow_key_map)
  4655. {
  4656. using namespace lynx::keys;
  4657. KeyMap map;
  4658. const auto global = Context::global, rack = Context::channelRack;
  4659. CHECK (map.find ({ space, none }, global, true) == "transport.playStop");
  4660. CHECK (map.find ({ space, ctrl }, global, true) == "transport.pause");
  4661. CHECK (map.find ({ f6, none }, global, true) == "panel.channelRack");
  4662. CHECK (map.find ({ f8, alt }, global, false) == "panel.browser");
  4663. CHECK (map.find ({ insert, ctrl | shift }, global, false) == "pattern.insert");
  4664. CHECK (map.find ({ numpadPlus, none }, rack, true) == "pattern.next");
  4665. // panel context: only while focused
  4666. CHECK (map.find ({ 'L', ctrl }, rack, true) == "rack.sendToInserts");
  4667. CHECK (map.find ({ 'L', ctrl }, global, true).empty());
  4668. CHECK (map.find ({ up, alt }, rack, false) == "rack.moveUp");
  4669. // typing piano: note keys play, other plain keys only for whilePiano actions; chords always work
  4670. CHECK (KeyMap::playsNote ({ 'Z', none }, true) && ! KeyMap::playsNote ({ 'Z', none }, false) && ! KeyMap::playsNote ({ 'Z', ctrl }, true));
  4671. CHECK (map.find ({ 'L', none }, global, true) == "transport.toggleMode");
  4672. CHECK (map.find ({ '1', none }, rack, false) == "rack.mute1" && map.find ({ '0', none }, rack, false) == "rack.mute10");
  4673. CHECK (map.find ({ '1', none }, rack, true).empty()); // a plain digit is not a shortcut while the piano is on
  4674. CHECK (map.find ({ '2', ctrl }, rack, true) == "rack.solo2");
  4675. CHECK (typingPianoNote ('Z') == 60 && typingPianoNote ('q') == 72 && typingPianoNote ('P') == 88 && typingPianoNote ('L') == -1);
  4676. CHECK (map.conflicts().empty());
  4677. // chord text
  4678. CHECK (toString ({ f4, ctrl | shift }) == "Ctrl+Shift+F4" && toString ({ numpadMinus, none }) == "Numpad -");
  4679. CHECK (parseChord ("Shift+Ctrl+Ins") == (Chord { insert, ctrl | shift }));
  4680. CHECK (parseChord ("alt+up") == (Chord { up, alt }) && parseChord ("k") == (Chord { 'K', none }));
  4681. CHECK (parseChord ("Numpad +") == (Chord { numpadPlus, none }) && ! parseChord ("F13") && ! parseChord ("Ctrl+"));
  4682. for (const auto& a : actions())
  4683. for (const auto& c : a.defaults)
  4684. CHECK (parseChord (toString (c)) == c);
  4685. // JSON overrides
  4686. std::vector<std::string> errors;
  4687. CHECK (map.loadJson (R"({ "pattern.next": "Ctrl+Right", "rack.clone": ["Alt+D", "Ctrl+D"], "help.shortcuts": "", "nope": "F1", "file.open": "Hyper+Q" })", &errors));
  4688. CHECK (errors.size() == 2);
  4689. CHECK (map.find ({ right, ctrl }, global, false) == "pattern.next" && map.find ({ numpadPlus, none }, global, false).empty());
  4690. CHECK (map.find ({ 'D', ctrl }, rack, false) == "rack.clone" && map.find ({ f1, none }, global, false).empty());
  4691. map.setChords ("pattern.previous", { { right, ctrl } });
  4692. CHECK (map.conflicts().size() == 1);
  4693. KeyMap reloaded;
  4694. CHECK (reloaded.loadJson (map.toJson()) && reloaded.chordsFor ("rack.clone") == map.chordsFor ("rack.clone"));
  4695. CHECK (! map.loadJson ("[1, 2]") && ! map.loadJson ("{\"a\": }"));
  4696. map.resetToDefaults();
  4697. CHECK (map.find ({ numpadPlus, none }, global, false) == "pattern.next");
  4698. }
  4699. TEST (workflow_workspace_layout)
  4700. {
  4701. using namespace lynx::workspace;
  4702. auto l = Layout::makeDefault (1280, 620);
  4703. // every visible panel is inside the desktop; the default shows Browser, Playlist and Channel Rack
  4704. for (const auto& p : l.panels)
  4705. CHECK (p.bounds.x >= 0 && p.bounds.y >= 0 && p.bounds.right() <= 1280 && p.bounds.bottom() <= 620 && p.bounds.w >= minWidth);
  4706. CHECK (l[Panel::browser].visible && l[Panel::playlist].visible && l[Panel::channelRack].visible);
  4707. CHECK (! l[Panel::pianoRoll].visible && ! l[Panel::mixer].visible);
  4708. CHECK (l[Panel::playlist].bounds.x == l[Panel::browser].bounds.right() && l[Panel::playlist].bounds.right() == 1280);
  4709. CHECK (l.isFrontmost (Panel::channelRack) && l.focused == Panel::channelRack);
  4710. // toggle: show+focus, focus, hide
  4711. CHECK (l.toggle (Panel::mixer) && l.focused == Panel::mixer && l.isFrontmost (Panel::mixer));
  4712. CHECK (l.toggle (Panel::channelRack) && l.focused == Panel::channelRack && l.isFrontmost (Panel::channelRack));
  4713. CHECK (! l.toggle (Panel::channelRack) && ! l[Panel::channelRack].visible && l.focused == Panel::mixer);
  4714. l.toggleMaximised (Panel::playlist);
  4715. CHECK (l[Panel::playlist].maximised && l.focused == Panel::playlist);
  4716. // save and load at another size: positions scale
  4717. l[Panel::mixer].detached = true;
  4718. l[Panel::mixer].windowBounds = { 100, 50, 900, 500 };
  4719. const auto text = l.serialise();
  4720. const auto big = Layout::parse (text, 2560, 1240);
  4721. CHECK (big.has_value());
  4722. if (big)
  4723. {
  4724. CHECK ((*big)[Panel::playlist].maximised && (*big)[Panel::mixer].detached && (*big)[Panel::mixer].windowBounds.w == 900);
  4725. CHECK (std::abs ((*big)[Panel::playlist].bounds.x - 2 * l[Panel::playlist].bounds.x) <= 1);
  4726. CHECK (big->order == l.order && big->focused == l.focused);
  4727. }
  4728. 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));
  4729. // resize keeps panels inside and edges glued to the border
  4730. l.resize (1000, 500);
  4731. CHECK (l[Panel::playlist].bounds.right() == 1000 && l[Panel::browser].bounds.bottom() == 500);
  4732. for (const auto& p : l.panels)
  4733. CHECK (p.bounds.right() <= 1000 && p.bounds.bottom() <= 500);
  4734. // off-screen panels come back
  4735. l[Panel::pianoRoll].bounds = { 5000, -300, 400, 300 };
  4736. CHECK (l.bringBackOffscreen() == 1 && l[Panel::pianoRoll].bounds.x + 400 <= 1000 && l[Panel::pianoRoll].bounds.y == 0);
  4737. // snapping: to the desktop, to another panel, and resizing one edge
  4738. CHECK ((snap ({ 5, 6, 200, 100 }, {}, 1000, 500) == Rect { 0, 0, 200, 100 }));
  4739. CHECK ((snap ({ 304, 50, 200, 100 }, { { 0, 0, 300, 400 } }, 1000, 500) == Rect { 300, 50, 200, 100 }));
  4740. CHECK ((snap ({ 304, 50, 200, 100 }, { { 0, 0, 300, 400 } }, 1000, 500, 2) == Rect { 304, 50, 200, 100 })); // out of range
  4741. CHECK ((snap ({ 100, 100, 195, 100 }, { { 300, 0, 300, 400 } }, 1000, 500, 8, right) == Rect { 100, 100, 200, 100 }));
  4742. CHECK ((snap ({ 100, 100, 195, 100 }, { { 300, 1000, 300, 400 } }, 2000, 2000, 8, right) == Rect { 100, 100, 195, 100 })); // not facing
  4743. }
  4744. TEST (workflow_control_math)
  4745. {
  4746. using namespace lynx::controls;
  4747. CHECK (std::abs (dragValue (0.5, 75, 0, 1, 150, false) - 1.0) < 1e-9);
  4748. CHECK (std::abs (dragValue (0.5, 75, 0, 1, 150, true) - 0.55) < 1e-9);
  4749. CHECK (dragValue (0.5, -1000, -1, 1, 150, false) == -1.0);
  4750. 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);
  4751. CHECK (wheelValue (3, 1, 0, 10, true, 1) == 4.0); // integer controls move at least one step
  4752. CHECK (std::abs (snapToInterval (0.234, 0, 0.1) - 0.2) < 1e-9);
  4753. CHECK (tempoDrag (130.0, 8, false, false) == 132.0 && tempoDrag (130.0, -3, false, false) == 130.0);
  4754. CHECK (std::abs (tempoDrag (130.0, 25, true, false) - 130.25) < 1e-9);
  4755. CHECK (std::abs (tempoDrag (130.0, 8, false, true) - 130.2) < 1e-9);
  4756. CHECK (tempoDrag (520.0, 400, false, false) == lynx::maxTempo && halfTempo (15.0) == lynx::minTempo && doubleTempo (130.0) == 260.0);
  4757. TapTempo tap;
  4758. CHECK (! tap.tap (1000.0));
  4759. CHECK (tap.tap (1500.0) == 120.0);
  4760. CHECK (tap.tap (2000.0) == 120.0 && tap.count() == 3);
  4761. CHECK (std::abs (*tap.tap (2400.0) - 128.57) < 0.01); // average of 500, 500, 400 ms
  4762. CHECK (! tap.tap (9000.0) && tap.count() == 1); // a long pause starts over
  4763. }
  4764. int main (int argc, char** argv)
  4765. {
  4766. if (argc > 1)
  4767. realFlpDir = argv[1];
  4768. const char* only = std::getenv ("LYNX_TEST"); // run only the tests whose name contains this
  4769. for (auto& [name, fn] : registry())
  4770. {
  4771. if (only != nullptr && std::strstr (name, only) == nullptr)
  4772. continue;
  4773. std::printf ("%s\n", name);
  4774. fn();
  4775. }
  4776. std::printf ("\n%d checks, %d failures\n", checks, failures);
  4777. return failures == 0 ? 0 : 1;
  4778. }
  4779. TEST (synth_cutoff_keytrack)
  4780. {
  4781. // the cutoff follows the note from key 48 (130.81 Hz), like Harmor's "Key to filter frequency"
  4782. auto rms = [] (float keyTrack, int key) {
  4783. lynx::SynthSettings s;
  4784. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  4785. s.cutoff = 130.81f;
  4786. s.keyTrack = keyTrack;
  4787. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  4788. inst->prepare (48000.0);
  4789. lynx::ChannelDef c;
  4790. c.synth = s;
  4791. inst->configure (c, 120.0);
  4792. inst->noteOn (key, 1.0f);
  4793. std::vector<float> l (24000), r (24000);
  4794. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  4795. double e = 0.0;
  4796. for (int i = 4800; i < 24000; ++i)
  4797. e += (double) l[(std::size_t) i] * l[(std::size_t) i];
  4798. return std::sqrt (e / 19200.0);
  4799. };
  4800. const auto fixed = rms (0.0f, 72), tracked = rms (1.0f, 72);
  4801. CHECK (tracked > 4.0 * fixed); // 2 octaves up: without keytrack the low-pass cuts
  4802. CHECK (std::abs (rms (1.0f, 48) - rms (0.0f, 48)) < 0.05 * rms (0.0f, 48)); // unchanged at the reference key
  4803. }
  4804. namespace
  4805. {
  4806. std::vector<float> renderSynthNote (const lynx::SynthSettings& s, int key, int frames)
  4807. {
  4808. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  4809. inst->prepare (48000.0);
  4810. lynx::ChannelDef c;
  4811. c.synth = s;
  4812. inst->configure (c, 120.0);
  4813. inst->noteOn (key, 1.0f);
  4814. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  4815. inst->render (l.data(), r.data(), frames, 1.0f, 1.0f);
  4816. return l;
  4817. }
  4818. double goertzel (const std::vector<float>& x, double f, int from, int to)
  4819. {
  4820. const auto w = 2.0 * 3.141592653589793 * f / 48000.0, k = 2.0 * std::cos (w);
  4821. double s1 = 0.0, s2 = 0.0;
  4822. for (int i = from; i < to; ++i)
  4823. {
  4824. const auto s0 = x[(std::size_t) i] + k * s1 - s2;
  4825. s2 = s1;
  4826. s1 = s0;
  4827. }
  4828. return s1 * s1 + s2 * s2 - k * s1 * s2;
  4829. }
  4830. } // namespace
  4831. TEST (synth_pitch_sweep_ring_and_bands)
  4832. {
  4833. lynx::SynthSettings sine;
  4834. sine.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  4835. sine.cutoff = 20000.0f;
  4836. // sweep: starts at f·(1 + sweep) and returns to f (time constant s = 10 ms; s⁴ falls 4× faster)
  4837. auto sweep = sine;
  4838. sweep.sweep = 1.0f;
  4839. sweep.sweepTime = 0.01f;
  4840. const auto a = renderSynthNote (sweep, 69, 24000);
  4841. auto crossings = [] (const std::vector<float>& x, int to) {
  4842. int n = 0;
  4843. for (int i = 1; i < to; ++i)
  4844. n += (x[(std::size_t) i - 1] < 0.0f) != (x[(std::size_t) i] < 0.0f);
  4845. return n;
  4846. };
  4847. CHECK (crossings (a, 480) > 1.3 * crossings (renderSynthNote (sine, 69, 480), 480)); // 10 ms: much higher
  4848. CHECK (goertzel (a, 440.0, 12000, 24000) > 100.0 * goertzel (a, 880.0, 12000, 24000));
  4849. // ring with |a| = 1: carrier 440 × modulator 110 -> only 330 and 550, no 440
  4850. auto ring = sine;
  4851. ring.am = ring.ring = true;
  4852. ring.osc[2] = { lynx::Waveform::sine, -2, 0.0f, 1.0f };
  4853. const auto b = renderSynthNote (ring, 69, 24000);
  4854. CHECK (goertzel (b, 330.0, 4800, 24000) > 100.0 * goertzel (b, 440.0, 4800, 24000));
  4855. CHECK (goertzel (b, 550.0, 4800, 24000) > 100.0 * goertzel (b, 440.0, 4800, 24000));
  4856. // 3 bands: muting the high knocks down a 4 kHz note and barely touches an 80 Hz one
  4857. auto bands = sine;
  4858. bands.bandGain = { 1.0f, 1.0f, 0.0f };
  4859. auto rms = [] (const std::vector<float>& x) {
  4860. double e = 0.0;
  4861. for (std::size_t i = 4800; i < x.size(); ++i)
  4862. e += (double) x[i] * x[i];
  4863. return std::sqrt (e / (double) (x.size() - 4800));
  4864. };
  4865. CHECK (rms (renderSynthNote (bands, 107, 24000)) < 0.3 * rms (renderSynthNote (sine, 107, 24000)));
  4866. CHECK (rms (renderSynthNote (bands, 28, 24000)) > 0.85 * rms (renderSynthNote (sine, 28, 24000)));
  4867. }
  4868. TEST (love_philter_map_evaluation)
  4869. {
  4870. lynx::LovePhilterMap line { { { 0.0, 0.0 }, { 1.0, 1.0 } } };
  4871. CHECK (std::abs (lynx::lovePhilterMapAt (line, 0.5) - 0.5) < 1e-9);
  4872. CHECK (std::abs (lynx::lovePhilterMapAt (line, 1.0) - 1.0) < 1e-9);
  4873. // steps (Δx = 0): 1 until 0.4375, ramp to 0 at 0.5, then 0
  4874. lynx::LovePhilterMap steps { { { 0.0, 1.0 }, { 0.4375, 1.0 }, { 0.0625, 0.0 }, { 0.5, 0.0 } } };
  4875. CHECK (lynx::lovePhilterMapAt (steps, 0.27) == 1.0);
  4876. CHECK (lynx::lovePhilterMapAt (steps, 0.75) == 0.0);
  4877. CHECK (std::abs (lynx::lovePhilterMapAt (steps, 0.46875) - 0.5) < 1e-9);
  4878. CHECK (lynx::lovePhilterMapAt ({}, 0.3) == 1.0);
  4879. }
  4880. TEST (lofi_holds_and_quantizes)
  4881. {
  4882. auto fx = lynx::makeEffect (lynx::EffectKind::lofi);
  4883. fx->prepare (48000.0);
  4884. auto slot = lynx::makeEffectSlot (lynx::EffectKind::lofi);
  4885. slot.params[0] = 0.5f; // 128·0.125 + 1 = 17 samples
  4886. slot.params[1] = 1.0f; // 65536/2049 ≈ 32 levels
  4887. std::vector<float> l (170), r (170);
  4888. for (std::size_t i = 0; i < l.size(); ++i)
  4889. l[i] = r[i] = 0.9f * (float) std::sin (0.05 * (double) i);
  4890. const auto original = l;
  4891. fx->process (l.data(), r.data(), 170, slot.params, 120.0);
  4892. for (int i = 0; i < 17; ++i)
  4893. CHECK (l[(std::size_t) i] == l[0]);
  4894. CHECK (l[17] != l[16]);
  4895. const auto step = 2.0f * 2049.0f / 65536.0f;
  4896. for (auto v : l)
  4897. CHECK (std::abs (v / step - std::round (v / step)) < 1e-3f);
  4898. CHECK (std::abs (l[0] - original[0]) <= step);
  4899. CHECK (lynx::formatEffectParam (lynx::EffectKind::lofi, 1, 0.0f, 120.0) == "16.0 bits");
  4900. }
  4901. namespace
  4902. {
  4903. lynx::EffectParams effectorParams (int type, float x, float y)
  4904. {
  4905. auto slot = lynx::makeEffectSlot (lynx::EffectKind::effector);
  4906. slot.params[0] = (float) type / 11.0f;
  4907. slot.params[3] = x;
  4908. slot.params[4] = y;
  4909. return slot.params;
  4910. }
  4911. } // namespace
  4912. TEST (effector_algorithms)
  4913. {
  4914. CHECK (lynx::effector::typeOf (8.0f / 11.0f) == 8);
  4915. CHECK (std::string (lynx::effector::typeName (11)) == "Ring");
  4916. CHECK (std::abs (lynx::effector::rateBeats (0.5f, 0.0f) - 0.75) < 1e-9); // trunc(8·0.5 + 0.5) = 4 -> 3/4
  4917. CHECK (std::abs (lynx::effector::rateBeats (1.0f, 0.5f) - 2.0) < 1e-9); // 8 × (1 − 0.5)²
  4918. auto run = [] (const lynx::EffectParams& p, std::vector<float> in, double bpm = 120.0) {
  4919. auto fx = lynx::makeEffect (lynx::EffectKind::effector);
  4920. fx->prepare (48000.0);
  4921. fx->setSongPosition (0.0);
  4922. auto r = in;
  4923. fx->process (in.data(), r.data(), (int) in.size(), p, bpm);
  4924. return in;
  4925. };
  4926. // Distort with Y = 1 (everything goes to the cascade): 0.5 comes out 0.5 (compensation G = 0.5/F(0.5))
  4927. {
  4928. auto p = effectorParams (0, 0.5f, 1.0f);
  4929. const auto out = run (p, std::vector<float> (4800, 0.5f));
  4930. CHECK (std::abs (out.back() - 0.5f) < 1e-3f);
  4931. const auto small = run (p, std::vector<float> (4800, 0.05f));
  4932. CHECK (small.back() > 0.45f && small.back() < 0.5f); // saturates near ±0.5
  4933. }
  4934. // Ring: DC 1 becomes the carrier sine, 2^(8.7·0 + 5) = 32 Hz -> 32 cycles per second
  4935. {
  4936. auto p = effectorParams (11, 0.0f, 0.0f);
  4937. const auto out = run (p, std::vector<float> (48000, 1.0f));
  4938. int crossings = 0;
  4939. for (std::size_t i = 4800; i < out.size(); ++i)
  4940. crossings += (out[i - 1] < 0.0f) != (out[i] < 0.0f);
  4941. CHECK (crossings >= 56 && crossings <= 60); // 0.9 s × 32 Hz × 2
  4942. }
  4943. // Trancer, Y = 0: at the start of the period the gain drops to zero; X = 1 returns only at the end of the period
  4944. {
  4945. auto p = effectorParams (8, 1.0f, 0.0f);
  4946. p[5] = 1.0f; // 8/1 = 8 beats = 4 s at 120 BPM
  4947. const auto out = run (p, std::vector<float> (48000, 1.0f));
  4948. CHECK (out[100] > 0.3f); // still rising on the "and" (1% of the period = 40 ms)
  4949. CHECK (out[24000] < 0.05f); // 0.5 s: trough
  4950. }
  4951. // Reverb with Wet = 0: the dry passes intact
  4952. {
  4953. auto p = effectorParams (6, 0.5f, 0.5f);
  4954. p[2] = 0.0f;
  4955. std::vector<float> in (4800);
  4956. for (std::size_t i = 0; i < in.size(); ++i)
  4957. in[i] = (float) std::sin (0.01 * (double) i);
  4958. const auto out = run (p, in);
  4959. for (std::size_t i = 0; i < in.size(); ++i)
  4960. CHECK (std::abs (out[i] - in[i]) < 1e-6f);
  4961. }
  4962. // Delay: the echo arrives after the Mod Rate period (1/4 beat at 120 BPM = 125 ms), at level X²
  4963. {
  4964. auto p = effectorParams (5, 0.7f, 0.5f);
  4965. p[5] = 1.0f / 8.0f; // index 1 = 1/4
  4966. std::vector<float> in (12000, 0.0f);
  4967. in[0] = 1.0f;
  4968. const auto out = run (p, in);
  4969. CHECK (std::abs (out[6000] - 0.49f) < 0.02f);
  4970. CHECK (std::abs (out[3000]) < 1e-6f);
  4971. }
  4972. // Stutter: repeats the recorded start every period
  4973. {
  4974. auto p = effectorParams (9, 0.0f, 0.0f);
  4975. p[5] = 0.0f; // 1/8 beat = 62.5 ms = 3000 samples
  4976. std::vector<float> in (9000);
  4977. for (std::size_t i = 0; i < in.size(); ++i)
  4978. in[i] = (float) i / 9000.0f;
  4979. const auto out = run (p, in);
  4980. CHECK (std::abs (out[3000 + 500] - in[500]) < 0.01f); // after the crossfade, it's the start again
  4981. CHECK (std::abs (out[1000] - in[1000]) < 1e-6f);
  4982. }
  4983. }
  4984. TEST (crossover_linkwitz_riley_sums_flat)
  4985. {
  4986. // low band + high band of the same crossover: sum with magnitude 1 (Linkwitz-Riley; for 12 and 36 dB the HP is inverted)
  4987. for (const auto combo : { 1, 3, 4, 5, 6, 7 })
  4988. for (const auto testHz : { 200.0, 1000.0, 5000.0 })
  4989. {
  4990. auto run = [&] (bool high) {
  4991. auto fx = lynx::makeEffect (lynx::EffectKind::crossover);
  4992. fx->prepare (48000.0);
  4993. auto slot = lynx::makeEffectSlot (lynx::EffectKind::crossover);
  4994. const auto value = (float) (std::log2 (1000.0 / 30.0) / 9.0589);
  4995. slot.params[high ? 0 : 3] = 1.0f;
  4996. slot.params[high ? 1 : 4] = value;
  4997. slot.params[high ? 2 : 5] = (float) combo / 7.0f;
  4998. std::vector<float> l (24000), r (24000);
  4999. for (std::size_t i = 0; i < l.size(); ++i)
  5000. l[i] = r[i] = (float) std::sin (2.0 * 3.141592653589793 * testHz * (double) i / 48000.0);
  5001. fx->process (l.data(), r.data(), 24000, slot.params, 120.0);
  5002. return l;
  5003. };
  5004. const auto low = run (false), high = run (true);
  5005. double peak = 0.0;
  5006. for (std::size_t i = 12000; i < low.size(); ++i)
  5007. peak = std::max (peak, (double) std::abs (low[i] + high[i]));
  5008. CHECK (std::abs (peak - 1.0) < 0.02);
  5009. }
  5010. // 96 dB/oct: two octaves above the cutoff the low-pass is already below −150 dB... in practice, very low
  5011. auto fx = lynx::makeEffect (lynx::EffectKind::crossover);
  5012. fx->prepare (48000.0);
  5013. auto slot = lynx::makeEffectSlot (lynx::EffectKind::crossover);
  5014. slot.params[3] = 1.0f;
  5015. slot.params[4] = (float) (std::log2 (500.0 / 30.0) / 9.0589);
  5016. slot.params[5] = 1.0f;
  5017. std::vector<float> l (24000), r (24000);
  5018. for (std::size_t i = 0; i < l.size(); ++i)
  5019. l[i] = r[i] = (float) std::sin (2.0 * 3.141592653589793 * 2000.0 * (double) i / 48000.0);
  5020. fx->process (l.data(), r.data(), 24000, slot.params, 120.0);
  5021. float peak = 0.0f;
  5022. for (std::size_t i = 12000; i < l.size(); ++i)
  5023. peak = std::max (peak, std::abs (l[i]));
  5024. CHECK (peak < 1e-4f);
  5025. }
  5026. TEST (rhythm_gain_and_autopan)
  5027. {
  5028. // 1-beat gate: 1 → 0 at 0.5 beat (linear) → 1 at the end; at 120 BPM 1 beat = 24000 samples at 48 kHz
  5029. auto slot = lynx::makeEffectSlot (lynx::EffectKind::rhythmGain);
  5030. slot.params[0] = 1.0f / 64.0f;
  5031. slot.params[1] = 3.0f / 12.0f;
  5032. const float pts[3][3] = { { 0.0f, 1.0f, 0.5f }, { 0.5f, 0.0f, 0.5f }, { 1.0f, 1.0f, 0.5f } };
  5033. for (int k = 0; k < 3; ++k)
  5034. for (int j = 0; j < 3; ++j)
  5035. slot.params[(std::size_t) (2 + 3 * k + j)] = pts[k][j];
  5036. auto fx = lynx::makeEffect (lynx::EffectKind::rhythmGain);
  5037. fx->prepare (48000.0);
  5038. fx->setSongPosition (960.0 * 2.0); // beat 2: phase 0
  5039. std::vector<float> l (24000, 1.0f), r (24000, 1.0f);
  5040. fx->process (l.data(), r.data(), 24000, slot.params, 120.0);
  5041. CHECK (std::abs (l[0] - 1.0f) < 1e-3f);
  5042. CHECK (std::abs (l[6000] - 0.5f) < 1e-3f);
  5043. CHECK (l[12000] < 1e-3f);
  5044. CHECK (std::abs (l[18000] - 0.5f) < 1e-3f);
  5045. // positive tension: changes quickly at the start of the segment
  5046. CHECK (lynx::effectInfo (lynx::EffectKind::rhythmGain).params.size() == 39);
  5047. // auto-pan: 1-beat period, full depth; start phase 0.75 -> W = 0 rising (pan centered)
  5048. auto pan = lynx::makeEffectSlot (lynx::EffectKind::autoPan);
  5049. pan.params[0] = 1.0f / 64.0f;
  5050. pan.params[1] = 1.0f;
  5051. auto ap = lynx::makeEffect (lynx::EffectKind::autoPan);
  5052. ap->prepare (48000.0);
  5053. ap->setSongPosition (0.0);
  5054. std::vector<float> a (24000, 1.0f), b (24000, 1.0f);
  5055. ap->process (a.data(), b.data(), 24000, pan.params, 120.0);
  5056. CHECK (std::abs (a[0] - 1.0f) < 1e-3f && std::abs (b[0] - 1.0f) < 1e-3f);
  5057. CHECK (a[6000] < 0.01f && std::abs (b[6000] - 1.0f) < 1e-3f); // ¼ cycle later: fully right
  5058. }
  5059. TEST (vocoder_side_inputs_split_modulator_and_carrier)
  5060. {
  5061. // "Side inputs" mode (Vocodex): modulator from side input 1 (noise in the first half), carrier from side input 2
  5062. // (saw), own input silent → the output follows the side modulator; with input 1 silent, the output is silent
  5063. auto slot = lynx::makeEffectSlot (lynx::EffectKind::vocoder);
  5064. slot.params[16] = 1.0f;
  5065. auto fx = lynx::makeEffect (lynx::EffectKind::vocoder);
  5066. fx->prepare (48000.0);
  5067. std::vector<float> modL (48000), car (48000), l (48000, 0.0f), r (48000, 0.0f);
  5068. std::uint32_t seed = 1;
  5069. for (std::size_t i = 0; i < modL.size(); ++i)
  5070. {
  5071. seed = seed * 1664525u + 1013904223u;
  5072. modL[i] = i < 24000 ? ((float) (seed >> 8) / 16777216.0f - 0.5f) : 0.0f;
  5073. car[i] = (float) (2.0 * std::fmod ((double) i * 220.0 / 48000.0, 1.0) - 1.0) * 0.5f;
  5074. }
  5075. for (int done = 0; done < 48000; done += 480)
  5076. {
  5077. fx->setSidechain (modL.data() + done, modL.data() + done);
  5078. fx->setSidechain2 (car.data() + done, car.data() + done);
  5079. fx->process (l.data() + done, r.data() + done, 480, slot.params, 120.0);
  5080. }
  5081. auto rms = [&] (int from, int to) {
  5082. double e = 0.0;
  5083. for (int i = from; i < to; ++i)
  5084. e += (double) l[(std::size_t) i] * l[(std::size_t) i];
  5085. return std::sqrt (e / (to - from));
  5086. };
  5087. CHECK (rms (6000, 20000) > 0.01);
  5088. CHECK (rms (40000, 48000) < 0.1 * rms (6000, 20000));
  5089. // the side modulator configured but silent: nothing comes out (the own input is not used instead)
  5090. std::vector<float> a (4800, 0.3f), b (4800, 0.3f);
  5091. for (int done = 0; done < 4800; done += 480)
  5092. {
  5093. fx->setSidechain (nullptr, nullptr);
  5094. fx->setSidechain2 (car.data() + done, car.data() + done);
  5095. fx->process (a.data() + done, b.data() + done, 480, slot.params, 120.0);
  5096. }
  5097. CHECK (std::abs (a[4700]) < 0.05f);
  5098. }
  5099. TEST (vocoder_follows_modulator)
  5100. {
  5101. // modulator (L) plays only in the first half; carrier (R) is a continuous saw: the wet follows the modulator
  5102. auto slot = lynx::makeEffectSlot (lynx::EffectKind::vocoder);
  5103. auto fx = lynx::makeEffect (lynx::EffectKind::vocoder);
  5104. fx->prepare (48000.0);
  5105. std::vector<float> l (48000), r (48000);
  5106. std::uint32_t seed = 1;
  5107. for (std::size_t i = 0; i < l.size(); ++i)
  5108. {
  5109. seed = seed * 1664525u + 1013904223u;
  5110. l[i] = i < 24000 ? ((float) (seed >> 8) / 16777216.0f - 0.5f) : 0.0f;
  5111. r[i] = (float) (2.0 * std::fmod ((double) i * 220.0 / 48000.0, 1.0) - 1.0) * 0.5f;
  5112. }
  5113. fx->process (l.data(), r.data(), 48000, slot.params, 120.0);
  5114. auto rms = [&] (int from, int to) {
  5115. double e = 0.0;
  5116. for (int i = from; i < to; ++i)
  5117. e += (double) l[(std::size_t) i] * l[(std::size_t) i];
  5118. return std::sqrt (e / (to - from));
  5119. };
  5120. CHECK (rms (6000, 20000) > 0.01);
  5121. CHECK (rms (40000, 48000) < 0.1 * rms (6000, 20000)); // modulator silent: the vocoder fades out (100 ms release)
  5122. for (std::size_t i = 0; i < l.size(); ++i)
  5123. CHECK (l[i] == r[i] && std::isfinite (l[i])); // mono output
  5124. }
  5125. // Vocodex (REA_rodada35): a synthetic state in FL's layout (version 8, 13 maps, 20 parameters, the 0x24 block,
  5126. // 13 map-axis bytes, tone, notes)
  5127. struct VocodexSpec
  5128. {
  5129. // Wet, SG, ModVol, ModHP, CarVol, CarLP, CarNoise, CarNoiseHP, Hold, Att, AttCurve, Rel, RelCurve, Freeze, BW,
  5130. // Flatness, ModBW, ModPitch, FatPitch, FatPan
  5131. 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 };
  5132. std::array<std::int32_t, 7> block { 0, 2, 0, 24, 1, 1, 2 }; // hold mode, order, unison, bands, draft field, ModIn, CarIn
  5133. 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
  5134. std::vector<std::uint8_t> bytes() const
  5135. {
  5136. std::vector<std::uint8_t> d;
  5137. 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); };
  5138. auto i32 = [&] (std::int32_t v) { put (&v, 4); };
  5139. i32 (8 << 16);
  5140. for (int m = 0; m < 13; ++m)
  5141. {
  5142. const double y0 = m == 8 ? 0.1429 : (m == 3 || m == 4 || m == 11) ? 0.0 : 0.5;
  5143. const double y1 = m == 8 ? 0.9918 : y0;
  5144. i32 (1), i32 (0), i32 (2);
  5145. for (const auto& [dx, y] : { std::pair { 0.0, y0 }, std::pair { 1.0, y1 } })
  5146. {
  5147. put (&dx, 8), put (&y, 8);
  5148. i32 (0), i32 (0); // tension (f32 0), flags
  5149. }
  5150. const std::array<std::uint8_t, 20> tail {};
  5151. put (tail.data(), tail.size());
  5152. }
  5153. for (auto v : params)
  5154. i32 (v);
  5155. for (auto v : block)
  5156. i32 (v);
  5157. put (flags.data(), flags.size());
  5158. const std::array<std::uint8_t, 13> axis {};
  5159. put (axis.data(), axis.size());
  5160. d.push_back (3), put ("PWM", 3);
  5161. i32 (1), i32 (60);
  5162. return d;
  5163. }
  5164. };
  5165. std::vector<float> vocodexSaw (int n, double hz, double fs)
  5166. {
  5167. std::vector<float> out ((std::size_t) n);
  5168. for (int i = 0; i < n; ++i)
  5169. out[(std::size_t) i] = (float) (2.0 * std::fmod (i * hz / fs, 1.0) - 1.0) * 0.4f;
  5170. return out;
  5171. }
  5172. TEST (vocodex_state_parse_and_conversion)
  5173. {
  5174. VocodexSpec spec;
  5175. spec.block = { 1, 3, 2, 40, 0, 2, 1 };
  5176. spec.params[17] = -1200;
  5177. const auto raw = spec.bytes();
  5178. const auto s = lynx::vocodex::parseState (raw);
  5179. CHECK (s.has_value());
  5180. if (! s)
  5181. return;
  5182. CHECK (s->version == 8 && s->holdMode == 1 && s->order == 3 && s->unison == 2 && s->bands == 40);
  5183. CHECK (s->draft() && s->modIn == 2 && s->carIn == 1 && s->minTimes && s->subtractiveGate && ! s->lrEncoding);
  5184. CHECK (s->params[lynx::vocodex::modPitch] == -1200 && s->params[lynx::vocodex::carLp] == 65536);
  5185. 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);
  5186. CHECK (s->tone == "PWM" && s->notes.size() == 1 && s->notes[0] == 60);
  5187. const auto v = lynx::vocodexEffect (raw);
  5188. CHECK (v && v->slot.kind == lynx::EffectKind::vocodex && v->slot.state == raw && v->modIn == 2 && v->carIn == 1 && v->notes.empty());
  5189. spec.block[6] = -1; // internal synth carrier: not available yet → reported
  5190. spec.params[1] = 150; // Soundgoodizer stage
  5191. const auto w = lynx::vocodexEffect (spec.bytes());
  5192. CHECK (w && w->carIn == -1 && w->notes.size() == 2);
  5193. CHECK (! lynx::vocodex::parseState ({ 1, 2, 3 }).has_value());
  5194. }
  5195. TEST (vocodex_vocodes_side_inputs)
  5196. {
  5197. // modulator on side input 1 (noise in the first half), carrier on side input 2 (saw), own input silent: the
  5198. // output follows the modulator's envelope and fades after it stops
  5199. VocodexSpec spec;
  5200. lynx::EffectSlot slot = lynx::makeEffectSlot (lynx::EffectKind::vocodex);
  5201. slot.state = spec.bytes();
  5202. auto fx = lynx::makeEffect (slot);
  5203. fx->prepare (48000.0);
  5204. CHECK (fx->latencySamples() == 0);
  5205. const auto car = vocodexSaw (48000, 110.0, 48000.0);
  5206. std::vector<float> mod (48000), l (48000, 0.0f), r (48000, 0.0f);
  5207. std::uint32_t seed = 7;
  5208. for (std::size_t i = 0; i < mod.size(); ++i)
  5209. {
  5210. seed = seed * 1664525u + 1013904223u;
  5211. mod[i] = i < 24000 ? ((float) (seed >> 8) / 16777216.0f - 0.5f) : 0.0f;
  5212. }
  5213. for (int done = 0; done < 48000; done += 512)
  5214. {
  5215. const int n = std::min (512, 48000 - done);
  5216. fx->setSidechain (mod.data() + done, mod.data() + done);
  5217. fx->setSidechain2 (car.data() + done, car.data() + done);
  5218. fx->process (l.data() + done, r.data() + done, n, slot.params, 120.0);
  5219. }
  5220. auto rms = [&] (int from, int to) {
  5221. double e = 0.0;
  5222. for (int i = from; i < to; ++i)
  5223. e += (double) l[(std::size_t) i] * l[(std::size_t) i] + (double) r[(std::size_t) i] * r[(std::size_t) i];
  5224. return std::sqrt (e / (2.0 * (to - from)));
  5225. };
  5226. CHECK (rms (6000, 20000) > 0.02);
  5227. CHECK (rms (40000, 48000) < 0.01 * rms (6000, 20000));
  5228. CHECK (std::abs (l[0]) < 1e-6f); // the gains ramp up from 0 when the plugin is created
  5229. }
  5230. TEST (vocodex_draft_latency_and_pass_through)
  5231. {
  5232. // carrier pass-through at unit gain only (Wet 0): after a Flush the gains snap, so the output is the carrier,
  5233. // 16 samples late in Draft
  5234. VocodexSpec spec;
  5235. spec.params[0] = 0; // Wet
  5236. spec.params[4] = 12800; // CarVol = 1
  5237. for (const int draftField : { 1, 0 })
  5238. {
  5239. spec.block[4] = draftField;
  5240. const auto s = lynx::vocodex::parseState (spec.bytes());
  5241. CHECK (s.has_value());
  5242. lynx::vocodex::Engine engine;
  5243. engine.prepare (*s, 44100.0, 300, s->draft());
  5244. CHECK (engine.latencySamples() == (draftField == 0 ? 16 : 0));
  5245. engine.flush();
  5246. const auto saw = vocodexSaw (3000, 220.0, 44100.0);
  5247. std::vector<float> car (6000), mod (6000, 0.0f), out (6000);
  5248. for (int i = 0; i < 3000; ++i)
  5249. car[(std::size_t) (2 * i)] = car[(std::size_t) (2 * i + 1)] = saw[(std::size_t) i];
  5250. static constexpr int sizes[] { 300, 37, 128, 1, 255, 16, 299 }; // uneven blocks exercise the FIFOs
  5251. for (int done = 0, k = 0, n = 0; done < 3000; done += n, ++k)
  5252. {
  5253. n = std::min (sizes[k % 7], 3000 - done);
  5254. engine.process (mod.data() + 2 * done, mod.data() + 2 * done, car.data() + 2 * done, out.data() + 2 * done, n);
  5255. }
  5256. const int lag = engine.latencySamples();
  5257. auto maxError = 0.0f;
  5258. for (int i = lag; i < 3000; ++i)
  5259. maxError = std::max (maxError, std::abs (out[(std::size_t) (2 * i)] - saw[(std::size_t) (i - lag)]));
  5260. CHECK (maxError == 0.0f);
  5261. }
  5262. }
  5263. TEST (vocodex_soundgoodizer_stage_limits_the_output)
  5264. {
  5265. // SG > 0: the vocoder's output (loud here: Wet 2000) goes through the Soundgoodizer approximation, whose
  5266. // master limiter keeps the peaks under −0.2 dBFS; its look-ahead is reported as latency
  5267. VocodexSpec spec;
  5268. spec.params[0] = 2000;
  5269. spec.params[1] = 250;
  5270. lynx::EffectSlot slot = lynx::makeEffectSlot (lynx::EffectKind::vocodex);
  5271. slot.state = spec.bytes();
  5272. auto fx = lynx::makeEffect (slot);
  5273. fx->prepare (48000.0);
  5274. CHECK (fx->latencySamples() == 72); // 1.5 ms at 48 kHz
  5275. const auto car = vocodexSaw (48000, 110.0, 48000.0);
  5276. std::vector<float> mod (48000), l (48000, 0.0f), r (48000, 0.0f);
  5277. for (std::size_t i = 0; i < mod.size(); ++i)
  5278. mod[i] = 0.9f * (float) std::sin (0.07 * (double) i) * (float) std::sin (0.0003 * (double) i);
  5279. auto peak = 0.0f;
  5280. for (int done = 0; done < 48000; done += 512)
  5281. {
  5282. const int n = std::min (512, 48000 - done);
  5283. fx->setSidechain (mod.data() + done, mod.data() + done);
  5284. fx->setSidechain2 (car.data() + done, car.data() + done);
  5285. fx->process (l.data() + done, r.data() + done, n, slot.params, 120.0);
  5286. }
  5287. for (std::size_t i = 0; i < l.size(); ++i)
  5288. peak = std::max ({ peak, std::abs (l[i]), std::abs (r[i]) });
  5289. CHECK (peak > 0.5f && peak <= 0.9775f);
  5290. }
  5291. TEST (vocodex_tail_bypass_and_noise)
  5292. {
  5293. // both inputs silent for longer than 0.5 s + hold + release: the own input passes unchanged
  5294. VocodexSpec spec;
  5295. const auto s = lynx::vocodex::parseState (spec.bytes());
  5296. CHECK (s.has_value());
  5297. lynx::vocodex::Engine engine;
  5298. engine.prepare (*s, 44100.0, 512, false);
  5299. std::vector<float> zero (1024, 0.0f), own (1024), out (1024);
  5300. for (std::size_t i = 0; i < own.size(); ++i)
  5301. own[i] = 0.25f * (float) std::sin (0.01 * (double) i);
  5302. for (int b = 0; b < 80; ++b)
  5303. engine.process (own.data(), zero.data(), zero.data(), out.data(), 512);
  5304. CHECK (out == own);
  5305. // carrier noise: the IPP-compatible generator restarts from the same seed after a Flush
  5306. spec.params[6] = 9000;
  5307. const auto noisy = lynx::vocodex::parseState (spec.bytes());
  5308. lynx::vocodex::Engine a;
  5309. a.prepare (*noisy, 44100.0, 512, false);
  5310. std::vector<float> mod (1024), first (1024), second (1024);
  5311. for (std::size_t i = 0; i < mod.size(); ++i)
  5312. mod[i] = 0.3f * (float) std::sin (0.05 * (double) i);
  5313. a.flush();
  5314. a.process (own.data(), mod.data(), zero.data(), first.data(), 512);
  5315. a.flush();
  5316. a.process (own.data(), mod.data(), zero.data(), second.data(), 512);
  5317. CHECK (first == second);
  5318. auto energy = 0.0;
  5319. for (auto v : first)
  5320. energy += (double) v * v;
  5321. CHECK (energy > 1e-6 && std::isfinite (energy));
  5322. }
  5323. TEST (synth_spectral_oscillator)
  5324. {
  5325. // 1/n spectrum = saw: same harmonic proportions and same level as LYNX's saw
  5326. lynx::SynthSettings saw;
  5327. saw.osc[0] = { lynx::Waveform::saw, 0, 0.0f, 1.0f };
  5328. saw.cutoff = 20000.0f;
  5329. auto spectral = saw;
  5330. spectral.osc[0].wave = lynx::Waveform::spectral;
  5331. for (int n = 1; n <= lynx::SynthSettings::spectrumSize; ++n)
  5332. spectral.spectrum[(std::size_t) n - 1] = 1.0f / (float) n;
  5333. const auto a = renderSynthNote (saw, 57, 24000), b = renderSynthNote (spectral, 57, 24000); // 220 Hz
  5334. for (const auto h : { 1, 2, 3, 5 })
  5335. {
  5336. const auto ea = goertzel (a, 220.0 * h, 4800, 24000), eb = goertzel (b, 220.0 * h, 4800, 24000);
  5337. CHECK (std::abs (10.0 * std::log10 (eb / ea)) < 0.5); // within 0.5 dB
  5338. }
  5339. // odd only: no 2nd harmonic
  5340. auto odd = spectral;
  5341. for (int n = 2; n <= lynx::SynthSettings::spectrumSize; n += 2)
  5342. odd.spectrum[(std::size_t) n - 1] = 0.0f;
  5343. const auto c = renderSynthNote (odd, 57, 24000);
  5344. CHECK (goertzel (c, 440.0, 4800, 24000) < 1e-4 * goertzel (c, 220.0, 4800, 24000));
  5345. // high note: the band-limited tables don't pass Nyquist (no aliasing below the fundamental)
  5346. const auto d = renderSynthNote (spectral, 105, 24000); // 3520 Hz
  5347. CHECK (goertzel (d, 1000.0, 4800, 24000) < 1e-3 * goertzel (d, 3520.0, 4800, 24000));
  5348. }
  5349. TEST (compressor_sidechain_ducks_and_orders_mixer)
  5350. {
  5351. // the detector listens to the side input: quiet signal on the track, loud kick on the sidechain -> reduction
  5352. auto slot = lynx::makeEffectSlot (lynx::EffectKind::compressor);
  5353. slot.params[0] = 0.5f; // threshold
  5354. slot.params[1] = 1.0f; // high ratio
  5355. slot.params[4] = 0.0f;
  5356. auto run = [&] (bool withSidechain) {
  5357. auto fx = lynx::makeEffect (lynx::EffectKind::compressor);
  5358. fx->prepare (48000.0);
  5359. std::vector<float> l (4800, 0.1f), r (4800, 0.1f), kick (4800, 1.0f);
  5360. if (withSidechain)
  5361. fx->setSidechain (kick.data(), kick.data());
  5362. fx->process (l.data(), r.data(), 4800, slot.params, 120.0);
  5363. return l.back();
  5364. };
  5365. const auto alone = run (false), ducked = run (true);
  5366. CHECK (ducked < 0.5f * alone);
  5367. // order: track 5 listens to 7 via sidechain -> 7 comes before 5
  5368. auto song = lynx::Song::makeDefault();
  5369. while (song.mixer.size() < 8)
  5370. song.mixer.push_back ({});
  5371. auto comp = lynx::makeEffectSlot (lynx::EffectKind::compressor);
  5372. comp.sidechain = 7;
  5373. song.mixer[5].effects.push_back (comp);
  5374. const auto order = song.mixerOrder();
  5375. const auto at = [&] (int t) { return std::find (order.begin(), order.end(), t) - order.begin(); };
  5376. CHECK (at (7) < at (5));
  5377. }
  5378. TEST (pitch_correction_pulls_to_allowed_note)
  5379. {
  5380. auto run = [] (const lynx::EffectParams& p, double hz) {
  5381. auto fx = lynx::makeEffect (lynx::EffectKind::pitchCorrect);
  5382. fx->prepare (48000.0);
  5383. std::vector<float> l (48000 * 2), r;
  5384. for (std::size_t i = 0; i < l.size(); ++i)
  5385. l[i] = 0.5f * (float) std::sin (2.0 * 3.141592653589793 * hz * (double) i / 48000.0);
  5386. r = l;
  5387. fx->process (l.data(), r.data(), (int) l.size(), p, 120.0);
  5388. // frequency from zero crossings in the last second
  5389. int crossings = 0;
  5390. for (std::size_t i = 48000 + 1; i < l.size(); ++i)
  5391. crossings += (l[i - 1] < 0.0f) != (l[i] < 0.0f);
  5392. return crossings / 2.0;
  5393. };
  5394. auto slot = lynx::makeEffectSlot (lynx::EffectKind::pitchCorrect); // chromatic, instant, A 440
  5395. CHECK (std::abs (run (slot.params, 452.0) - 440.0) < 4.0);
  5396. for (int k = 0; k < 12; ++k)
  5397. slot.params[(std::size_t) (5 + k)] = k == 0 ? 1.0f : 0.0f; // only C
  5398. CHECK (std::abs (run (slot.params, 452.0) - 523.25) < 5.0); // C5 (523 Hz) is closer than C4 (262)
  5399. slot.params[2] = 1.0f; // turn everything off: passes unchanged
  5400. CHECK (std::abs (run (slot.params, 452.0) - 452.0) < 4.0);
  5401. }
  5402. TEST (pitch_correction_bypass_is_a_pure_delay)
  5403. {
  5404. // FL's Pitcher with Bypass All still runs its shifter: the plain path is an exact 9-sample delay, the formant
  5405. // path (256-Hann overlap-add) an exact 257-sample delay, and Gender changes nothing without a shift
  5406. // (REA_rodada30 §2.4/2.5); both are reported as latency
  5407. std::vector<float> in (48000);
  5408. for (std::size_t i = 0; i < in.size(); ++i)
  5409. in[i] = 0.5f * (float) std::sin (2.0 * 3.141592653589793 * 440.0 * (double) i / 48000.0)
  5410. + 0.2f * (float) std::sin (2.0 * 3.141592653589793 * 1234.5 * (double) i / 48000.0);
  5411. auto run = [&] (bool formant, float gender, int& latency) {
  5412. auto fx = lynx::makeEffect (lynx::EffectKind::pitchCorrect);
  5413. fx->prepare (48000.0);
  5414. auto slot = lynx::makeEffectSlot (lynx::EffectKind::pitchCorrect);
  5415. slot.params[2] = 1.0f;
  5416. slot.params[29] = formant ? 1.0f : 0.0f;
  5417. slot.params[30] = gender;
  5418. auto l = in, r = in;
  5419. for (std::size_t i = 0; i < l.size(); i += 480)
  5420. fx->process (l.data() + i, r.data() + i, 480, slot.params, 120.0);
  5421. latency = fx->latencySamples();
  5422. return l;
  5423. };
  5424. int latency = 0;
  5425. auto plain = run (false, 0.5f, latency);
  5426. CHECK (latency == 9);
  5427. auto worst = 0.0f;
  5428. for (std::size_t i = 4000; i < in.size(); ++i)
  5429. worst = std::max (worst, std::abs (plain[i] - in[i - 9]));
  5430. CHECK (worst < 1e-5f);
  5431. auto formant = run (true, 0.8f, latency);
  5432. CHECK (latency == 257);
  5433. worst = 0.0f;
  5434. for (std::size_t i = 4000; i < in.size(); ++i)
  5435. worst = std::max (worst, std::abs (formant[i] - in[i - 257]));
  5436. CHECK (worst < 1e-5f);
  5437. }
  5438. TEST (pitch_correction_formant_path)
  5439. {
  5440. // Formant on: PSOLA keeps the correction (output pitch = grain spacing) while Gender resamples the grains:
  5441. // the spectrum of a saw moves up with Gender > 0.5 and down with Gender < 0.5
  5442. auto run = [] (float gender) {
  5443. auto fx = lynx::makeEffect (lynx::EffectKind::pitchCorrect);
  5444. fx->prepare (48000.0);
  5445. auto slot = lynx::makeEffectSlot (lynx::EffectKind::pitchCorrect); // chromatic, instant, A 440
  5446. slot.params[29] = 1.0f;
  5447. slot.params[30] = gender;
  5448. std::vector<float> l (48000 * 2), r;
  5449. for (std::size_t i = 0; i < l.size(); ++i)
  5450. l[i] = 0.5f * (float) (2.0 * std::fmod (452.0 * (double) i / 48000.0, 1.0) - 1.0); // saw
  5451. r = l;
  5452. fx->process (l.data(), r.data(), (int) l.size(), slot.params, 120.0);
  5453. l.erase (l.begin(), l.begin() + 48000);
  5454. return l;
  5455. };
  5456. // period by autocorrelation (lags 60…160 = 300…800 Hz)
  5457. auto pitch = [] (const std::vector<float>& x) {
  5458. auto best = 0.0, bestLag = 0.0;
  5459. for (int lag = 60; lag <= 160; ++lag)
  5460. {
  5461. auto sum = 0.0;
  5462. for (std::size_t i = 0; i + (std::size_t) lag < x.size(); ++i)
  5463. sum += (double) x[i] * x[i + (std::size_t) lag];
  5464. if (sum > best)
  5465. {
  5466. best = sum;
  5467. bestLag = lag;
  5468. }
  5469. }
  5470. return 48000.0 / bestLag;
  5471. };
  5472. // brightness: energy of the first difference relative to the energy
  5473. auto brightness = [] (const std::vector<float>& x) {
  5474. auto e = 0.0, d = 0.0;
  5475. for (std::size_t i = 1; i < x.size(); ++i)
  5476. {
  5477. e += (double) x[i] * x[i];
  5478. d += (double) (x[i] - x[i - 1]) * (x[i] - x[i - 1]);
  5479. }
  5480. return d / e;
  5481. };
  5482. const auto neutral = run (0.5f), up = run (0.8f), down = run (0.3f);
  5483. CHECK (std::abs (pitch (neutral) - 440.0) < 5.0); // 452 Hz pulled to A
  5484. CHECK (std::abs (pitch (up) - 440.0) < 5.0); // Gender does not move the pitch
  5485. CHECK (brightness (up) > 1.5 * brightness (neutral));
  5486. CHECK (brightness (down) < 0.7 * brightness (neutral));
  5487. }
  5488. TEST (parallel_container_inner_links_modulate)
  5489. {
  5490. // one branch: utility (gain) + a control-only auto-pan LFO (1 beat); the link maps the LFO 0..1 onto the
  5491. // utility gain −24 dB..0 dB, so the level must swing; without the link it stays put
  5492. auto container = lynx::makeEffectSlot (lynx::EffectKind::parallel);
  5493. auto gain = lynx::makeEffectSlot (lynx::EffectKind::utility);
  5494. auto lfo = lynx::makeEffectSlot (lynx::EffectKind::autoPan);
  5495. lfo.params[0] = 1.0f / 64.0f;
  5496. lfo.params[4] = 1.0f; // control only: audio passes unchanged
  5497. container.branches.push_back ({ { gain, lfo }, 1.0f });
  5498. lynx::EffectLink link;
  5499. link.source = 1;
  5500. link.param = 0;
  5501. for (int i = 0; i <= 32; ++i)
  5502. link.curve.push_back (0.5f * (float) i / 32.0f);
  5503. auto levels = [&] (bool linked) {
  5504. auto slot = container;
  5505. if (linked)
  5506. slot.links.push_back (link);
  5507. auto fx = lynx::makeParallelEffect (slot);
  5508. fx->prepare (48000.0);
  5509. float lo = 1e9f, hi = 0.0f;
  5510. for (int block = 0; block < 94; ++block) // ~1 beat at 120 BPM in 256-sample blocks
  5511. {
  5512. std::vector<float> l (256, 1.0f), r (256, 1.0f);
  5513. fx->setSongPosition (block * 256.0 / 48000.0 * 2.0 * 960.0); // the engine positions every block
  5514. fx->process (l.data(), r.data(), 256, slot.params, 120.0);
  5515. lo = std::min (lo, std::abs (l[128]));
  5516. hi = std::max (hi, std::abs (l[128]));
  5517. }
  5518. return std::pair { lo, hi };
  5519. };
  5520. const auto [lo, hi] = levels (true);
  5521. CHECK (hi > 0.8f && lo < 0.12f);
  5522. const auto [lo0, hi0] = levels (false);
  5523. CHECK (std::abs (hi0 - lo0) < 1e-4f);
  5524. }
  5525. TEST (synth_spectrum_decays_per_harmonic)
  5526. {
  5527. // 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
  5528. lynx::SynthSettings s;
  5529. s.osc[0] = { lynx::Waveform::spectral, 0, 0.0f, 1.0f };
  5530. s.cutoff = 20000.0f;
  5531. s.decay = 0.0f;
  5532. s.sustain = 1.0f;
  5533. s.spectrum[0] = 1.0f;
  5534. s.spectrum[2] = 1.0f;
  5535. s.spectrumDecay[2] = 0.2f;
  5536. const auto x = renderSynthNote (s, 57, 48000); // 220 Hz, 48 kHz, 1 s
  5537. // equal 2400-sample windows (Goertzel power grows with the window): 10…60 ms and 500…550 ms
  5538. const auto early1 = goertzel (x, 220.0, 480, 2880), early3 = goertzel (x, 660.0, 480, 2880);
  5539. const auto late1 = goertzel (x, 220.0, 24000, 26400), late3 = goertzel (x, 660.0, 24000, 26400);
  5540. CHECK (early3 > 0.05 * early1); // ≈ −9 dB on average over 10…60 ms
  5541. CHECK (late3 < 1e-4 * late1);
  5542. CHECK (std::abs (10.0 * std::log10 (late1 / early1)) < 1.0); // the 1st holds
  5543. // without per-harmonic decay the spectrum stays as it is
  5544. s.spectrumDecay[2] = 0.0f;
  5545. const auto y = renderSynthNote (s, 57, 48000);
  5546. CHECK (std::abs (10.0 * std::log10 (goertzel (y, 660.0, 24000, 26400) / goertzel (y, 660.0, 480, 2880))) < 1.0);
  5547. }
  5548. TEST (worker_pool_runs_each_index_once_per_round)
  5549. {
  5550. // rounds of alternating sizes (a stalled worker must never run an index of a later round), each index
  5551. // exactly once, and nothing running after parallelFor returns
  5552. lynx::WorkerPool pool (3);
  5553. std::vector<std::atomic<int>> hits (64);
  5554. std::atomic<int> round { 0 }, outside { 0 }, wrongRound { 0 };
  5555. std::atomic<bool> open { false };
  5556. int failures = 0;
  5557. for (int r = 1; r <= 20000; ++r)
  5558. {
  5559. const auto n = (r % 3 == 0) ? 64 : (r % 3 == 1 ? 2 : 9);
  5560. for (int i = 0; i < n; ++i)
  5561. hits[(std::size_t) i].store (0);
  5562. round.store (r);
  5563. open.store (true);
  5564. auto fn = [&, r] (int i) {
  5565. if (! open.load())
  5566. outside.fetch_add (1);
  5567. if (round.load() != r)
  5568. wrongRound.fetch_add (1);
  5569. hits[(std::size_t) i].fetch_add (1);
  5570. };
  5571. pool.parallelFor (n, fn);
  5572. open.store (false);
  5573. for (int i = 0; i < n; ++i)
  5574. failures += hits[(std::size_t) i].load() != 1;
  5575. }
  5576. CHECK (failures == 0);
  5577. CHECK (outside.load() == 0);
  5578. CHECK (wrongRound.load() == 0);
  5579. }
  5580. TEST (ladder_filter_follows_toxic_law)
  5581. {
  5582. // the 4-pole ladder: −24 dB/oct far above the cutoff (vs −12 for the SVF), resonance raises the corner, and
  5583. // the input saturation keeps it bounded even at full resonance
  5584. auto level = [] (bool ladder, float res, double hz) {
  5585. lynx::SynthSettings s;
  5586. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  5587. s.cutoff = 500.0f;
  5588. s.resonance = res;
  5589. s.ladder = ladder;
  5590. const auto key = (int) std::lround (69.0 + 12.0 * std::log2 (hz / 440.0));
  5591. const auto x = renderSynthNote (s, key, 48000);
  5592. double e = 0.0, peak = 0.0;
  5593. for (std::size_t i = 24000; i < 48000; ++i)
  5594. e += (double) x[i] * x[i], peak = std::max (peak, (double) std::abs (x[i]));
  5595. return std::pair { std::sqrt (e / 24000.0), peak };
  5596. };
  5597. 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
  5598. const auto svfHigh = level (false, 0.0f, 3520.0).first / level (false, 0.0f, 110.0).first;
  5599. CHECK (20.0 * std::log10 (high / low) < -55.0); // ≈ 24 dB/oct over ~2.8 octaves
  5600. CHECK (20.0 * std::log10 (svfHigh) > -45.0); // the 2-pole SVF falls much less
  5601. const auto corner0 = level (true, 0.0f, 523.25).first, corner1 = level (true, 0.6f, 523.25).first;
  5602. CHECK (corner1 > 1.5 * corner0); // resonance boosts near the cutoff
  5603. const auto loud = level (true, 1.0f, 523.25);
  5604. CHECK (std::isfinite (loud.first) && loud.second < 20.0); // self-oscillation stays bounded
  5605. }
  5606. TEST (synth_spectrum_settles_on_target)
  5607. {
  5608. // ALT DECAY-like morph: harmonic 3 starts at 1 and settles on 0.25 (−12 dB) instead of fading out
  5609. lynx::SynthSettings s;
  5610. s.osc[0] = { lynx::Waveform::spectral, 0, 0.0f, 1.0f };
  5611. s.cutoff = 20000.0f;
  5612. s.decay = 0.0f;
  5613. s.sustain = 1.0f;
  5614. s.spectrum[0] = 1.0f;
  5615. s.spectrum[2] = 1.0f;
  5616. s.spectrumDecay[2] = 0.1f;
  5617. s.spectrumTarget[2] = 0.25f;
  5618. const auto x = renderSynthNote (s, 57, 48000);
  5619. const auto ratio = goertzel (x, 660.0, 24000, 26400) / goertzel (x, 220.0, 24000, 26400);
  5620. CHECK (std::abs (10.0 * std::log10 (ratio) - 20.0 * std::log10 (0.25)) < 1.0);
  5621. }
  5622. TEST (kepler_chorus_is_stereo_and_keeps_level)
  5623. {
  5624. // chorus I on a sine: L and R differ (opposite LFO phases), the level stays close to the dry one
  5625. lynx::SynthSettings s;
  5626. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  5627. s.cutoff = 20000.0f;
  5628. auto dry = s;
  5629. s.chorus = 1;
  5630. auto render = [] (const lynx::SynthSettings& set) {
  5631. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  5632. inst->prepare (48000.0);
  5633. lynx::ChannelDef c;
  5634. c.synth = set;
  5635. inst->configure (c, 120.0);
  5636. inst->noteOn (69, 1.0f);
  5637. std::vector<float> l (96000), r (96000);
  5638. inst->render (l.data(), r.data(), 96000, 1.0f, 1.0f);
  5639. return std::pair { l, r };
  5640. };
  5641. const auto [l, r] = render (s);
  5642. const auto [dl, dr] = render (dry);
  5643. double diff = 0.0, e = 0.0, ed = 0.0;
  5644. for (std::size_t i = 48000; i < 96000; ++i)
  5645. diff += std::abs (l[i] - r[i]), e += (double) l[i] * l[i], ed += (double) dl[i] * dl[i];
  5646. CHECK (diff / 48000.0 > 1e-3);
  5647. CHECK (std::abs (10.0 * std::log10 (e / ed)) < 3.0);
  5648. }
  5649. TEST (fl_pan_law_matches_love_philter_dll)
  5650. {
  5651. // values printed by the installation's Love Philter pan routine for vol 0.8 (REA_rodada27 §3.1, lppan.txt)
  5652. struct Row { double pan, ll, rr, rl, lr; };
  5653. const Row rows[] = { { -1.5, 0.239782482, -0.432956904, 0.805467963, 0.0 }, { -0.5, 0.805467963, 0.432956904, 0.239782482, 0.0 },
  5654. { 0.0, 0.8, 0.8, 0.0, 0.0 }, { 0.75, 0.220719516, 0.707889318, 0.0, 0.401742548 },
  5655. { 1.0, 0.0, 0.565685451, 0.0, 0.565685451 } };
  5656. for (const auto& row : rows)
  5657. {
  5658. float ll, rl, lr, rr;
  5659. lynx::flPanMatrix (row.pan, ll, rl, lr, rr);
  5660. CHECK (std::abs (0.8 * ll - row.ll) < 1e-6 && std::abs (0.8 * rr - row.rr) < 1e-6);
  5661. CHECK (std::abs (0.8 * rl - row.rl) < 1e-6 && std::abs (0.8 * lr - row.lr) < 1e-6);
  5662. }
  5663. }
  5664. TEST (effector_units_match_fl_dll_impulse_responses)
  5665. {
  5666. // impulse responses of the installation's Effector engine (REA_rodada27 §2, eu_<kind>_<X>_<Y>.txt; LFO off,
  5667. // wet 1, blocks of 256): samples 1, 10, 100 and 1000
  5668. struct Case { int kind; float x, y; double v[4]; };
  5669. const Case cases[] = { { 3, 0.5f, 0.5f, { -0.603055418, 0.159798339, -0.0055043716, -1.06241259e-06 } },
  5670. { 4, 0.2f, 0.5f, { 4.68885949e-26, 4.20032622e-19, 0.000487731799, 2.27715846e-09 } },
  5671. { 4, 0.8f, 0.3f, { -0.293783396, -0.0306414738, -0.00068128563, 1.358577e-15 } } };
  5672. for (const auto& c : cases)
  5673. {
  5674. auto fx = lynx::effector::make();
  5675. fx->prepare (44100.0);
  5676. lynx::EffectParams p {};
  5677. p[lynx::effector::type] = c.kind / 11.0f;
  5678. p[lynx::effector::wetMix] = 1.0f;
  5679. p[lynx::effector::paramX] = c.x;
  5680. p[lynx::effector::paramY] = c.y;
  5681. p[lynx::effector::modX] = p[lynx::effector::modY] = 0.5f;
  5682. p[lynx::effector::modRate] = 0.5f;
  5683. p[lynx::effector::inputLevel] = 1.0f;
  5684. p[lynx::effector::outputGain] = 0.5f;
  5685. std::vector<float> l (1024, 0.0f), r (1024, 0.0f);
  5686. l[0] = r[0] = 1.0f;
  5687. for (int d = 0; d < 1024; d += 256)
  5688. fx->process (l.data() + d, r.data() + d, 256, p, 120.0);
  5689. const int at[4] { 1, 10, 100, 1000 };
  5690. for (int k = 0; k < 4; ++k)
  5691. CHECK (std::abs (l[(std::size_t) at[k]] - c.v[k]) < 2e-7 + 1e-5 * std::abs (c.v[k]));
  5692. }
  5693. }
  5694. TEST (harmless_stereo_tremolo_and_vibrato)
  5695. {
  5696. // tremolo d = 1: each side swings between 0 and 1.25 at 5 Hz, L and R in anti-phase; vibrato modulates the pitch
  5697. lynx::SynthSettings s;
  5698. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  5699. s.cutoff = 20000.0f;
  5700. s.stereoTremolo = 1.0f;
  5701. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  5702. inst->prepare (48000.0);
  5703. lynx::ChannelDef c;
  5704. c.synth = s;
  5705. inst->configure (c, 120.0);
  5706. inst->noteOn (69, 1.0f);
  5707. std::vector<float> l (48000), r (48000);
  5708. inst->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  5709. 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; };
  5710. // θ = 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
  5711. CHECK (envelope (l, 19200) > 4.0f * envelope (r, 19200));
  5712. CHECK (envelope (r, 24000) > 4.0f * envelope (l, 24000));
  5713. // vibrato 100 cents: zero crossings vary in spacing; without it they are regular
  5714. auto crossingsSpread = [] (float cents) {
  5715. lynx::SynthSettings v;
  5716. v.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  5717. v.cutoff = 20000.0f;
  5718. v.vibratoCents = cents;
  5719. const auto x = renderSynthNote (v, 69, 48000);
  5720. std::vector<int> zc;
  5721. for (int i = 24000; i < 48000; ++i)
  5722. if (x[(std::size_t) i - 1] < 0.0f && x[(std::size_t) i] >= 0.0f)
  5723. zc.push_back (i);
  5724. int lo = 1 << 30, hi = 0;
  5725. for (std::size_t k = 1; k < zc.size(); ++k)
  5726. lo = std::min (lo, zc[k] - zc[k - 1]), hi = std::max (hi, zc[k] - zc[k - 1]);
  5727. return hi - lo;
  5728. };
  5729. CHECK (crossingsSpread (0.0f) <= 1);
  5730. CHECK (crossingsSpread (100.0f) >= 4);
  5731. }
  5732. TEST (physical_models_sound_and_end)
  5733. {
  5734. // Sakura: a plucked string with default-ish parameters rings and fades after the release; Drumpad: a hit decays
  5735. for (const auto kind : { lynx::InstrumentKind::sakura, lynx::InstrumentKind::drumpad })
  5736. {
  5737. lynx::ChannelDef c;
  5738. c.instrument = kind;
  5739. if (kind == lynx::InstrumentKind::sakura)
  5740. {
  5741. c.modelParams.assign (146, 0.5f);
  5742. c.modelParams[111] = 3.0f; // both strings at the note
  5743. c.modelParams[113] = 0.5f; // octave ×1
  5744. c.modelParams[6] = c.modelParams[11] = 0.99f; // long decay
  5745. c.modelParams[31] = 0.0f; // noise exciter
  5746. }
  5747. else
  5748. {
  5749. c.modelParams.assign (38, 0.5f);
  5750. c.modelParams[0] = 1.0f; // retrigger noise
  5751. c.modelParams[30] = c.modelParams[31] = c.modelParams[32] = c.modelParams[33] = 0.0f; // no velocity morph
  5752. }
  5753. auto inst = lynx::makeInstrument (kind);
  5754. inst->prepare (48000.0);
  5755. inst->configure (c, 120.0);
  5756. inst->noteOn (60, 0.8f);
  5757. std::vector<float> l (48000), r (48000);
  5758. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  5759. inst->noteOff (60);
  5760. inst->render (l.data() + 24000, r.data() + 24000, 24000, 1.0f, 1.0f);
  5761. double early = 0.0;
  5762. for (int i = 0; i < 12000; ++i)
  5763. early += (double) l[(std::size_t) i] * l[(std::size_t) i];
  5764. CHECK (early > 1e-6);
  5765. CHECK (std::all_of (l.begin(), l.end(), [] (float v) { return std::isfinite (v); }));
  5766. std::vector<float> tail (480000), tailR (480000);
  5767. inst->render (tail.data(), tailR.data(), 480000, 1.0f, 1.0f); // 10 s later the voice has ended
  5768. CHECK (inst->idle());
  5769. }
  5770. }
  5771. TEST (squeeze_matches_fl_model)
  5772. {
  5773. // Fruity Squeeze: Steps quantises, Mix 0 passes the input dry ×Volume/127; a silent block is left untouched
  5774. auto slot = lynx::makeEffectSlot (lynx::EffectKind::squeeze);
  5775. slot.params[1] = 0.0f; // mix 0: dry only
  5776. auto fx = lynx::makeEffect (lynx::EffectKind::squeeze);
  5777. fx->prepare (44100.0);
  5778. std::vector<float> l (512, 0.3f), r (512, -0.2f);
  5779. fx->process (l.data(), r.data(), 512, slot.params, 120.0);
  5780. CHECK (std::abs (l[100] - 0.3f) < 1e-6f && std::abs (r[100] + 0.2f) < 1e-6f); // Volume 127/127
  5781. slot.params[1] = 1.0f; // wet only
  5782. slot.params[2] = 32000.0f / 32768.0f; // 32768^(1 − 32000/32768) ≈ 1.27 levels per unit → heavy quantisation
  5783. std::vector<float> a (512), b (512);
  5784. for (int i = 0; i < 512; ++i)
  5785. a[(std::size_t) i] = b[(std::size_t) i] = 0.4f * (float) std::sin (i * 0.05);
  5786. fx->process (a.data(), b.data(), 512, slot.params, 120.0);
  5787. const auto levels = std::pow (32768.0f, 1.0f - 32000.0f / 32768.0f);
  5788. for (int i = 0; i < 512; i += 37)
  5789. CHECK (std::abs (a[(std::size_t) i] * levels - std::nearbyint (a[(std::size_t) i] * levels)) < 1e-3f);
  5790. std::vector<float> z (512, 0.0f), z2 (512, 0.0f);
  5791. fx->process (z.data(), z2.data(), 512, slot.params, 120.0);
  5792. CHECK (z[10] == 0.0f);
  5793. }
  5794. TEST (sakura_matrix_and_effects)
  5795. {
  5796. // REA_rodada29 §1: velocity → level follows 10^(2m)·0.05 (vel 1 vs 0.5 → ×10 in amplitude); the delay leaves
  5797. // an echo after the note has ended and keeps the instrument from going idle until its tail is silent
  5798. auto base = [] {
  5799. lynx::ChannelDef c;
  5800. c.instrument = lynx::InstrumentKind::sakura;
  5801. c.modelParams.assign (146, 0.0f);
  5802. const std::pair<int, float> values[] { { 0, 0.375f }, { 1, 0.5f }, { 3, 0.5f }, { 4, 1.0f }, { 6, 0.95f }, { 9, 0.3f },
  5803. { 11, 0.95f }, { 14, 0.3f }, { 18, 0.5f }, { 19, 0.5f }, { 27, 0.5f }, { 28, 1.0f },
  5804. { 29, 0.7f }, { 31, 1.0f }, { 32, 0.5f }, { 111, 3.0f }, { 113, 0.5f } };
  5805. for (const auto& [i, v] : values)
  5806. c.modelParams[(std::size_t) i] = v;
  5807. return c;
  5808. };
  5809. auto render = [] (const lynx::ChannelDef& c, float velocity, int held, int total) {
  5810. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sakura);
  5811. inst->prepare (48000.0);
  5812. inst->configure (c, 120.0);
  5813. inst->noteOn (60, velocity);
  5814. std::vector<float> l ((std::size_t) total), r ((std::size_t) total);
  5815. for (int s = 0; s < total; s += 256)
  5816. {
  5817. if (s == held)
  5818. inst->noteOff (60);
  5819. inst->render (l.data() + s, r.data() + s, std::min (256, total - s), 1.0f, 1.0f);
  5820. }
  5821. return std::make_pair (l, std::move (inst));
  5822. };
  5823. auto energy = [] (const std::vector<float>& x, int from, int to) {
  5824. double e = 0.0;
  5825. for (int i = from; i < to; ++i)
  5826. e += (double) x[(std::size_t) i] * x[(std::size_t) i];
  5827. return e;
  5828. };
  5829. auto c = base();
  5830. c.modelParams[79] = 6.0f; // slot 1: velocity → level, amount 1
  5831. c.modelParams[80] = 1.0f;
  5832. c.modelParams[82] = 1.0f;
  5833. const auto loud = energy (render (c, 1.0f, 24064, 24064).first, 0, 24064);
  5834. const auto soft = energy (render (c, 0.5f, 24064, 24064).first, 0, 24064);
  5835. CHECK (loud > 1e-6 && std::abs (loud / soft - 100.0) < 1.0);
  5836. auto d = base();
  5837. auto [dry, dryInst] = render (d, 0.8f, 4864, 72000);
  5838. d.modelParams[63] = 1.0f; // delay on: time 0.5 → ≈ 0.52 s, wet 1, no feedback: one echo
  5839. d.modelParams[64] = 0.5f;
  5840. d.modelParams[69] = 1.0f;
  5841. auto [wet, wetInst] = render (d, 0.8f, 4864, 72000);
  5842. CHECK (energy (wet, 26000, 40000) > 100.0 * energy (dry, 26000, 40000) + 1e-9); // the note ends near 0.2 s
  5843. CHECK (dryInst->idle() || energy (dry, 70000, 72000) < 1e-12);
  5844. CHECK (! wetInst->idle()); // the echo tail has not been silent for 3 s yet
  5845. }
  5846. TEST (drumsynth_live_engine)
  5847. {
  5848. // REA_rodada30 §1: key → patch slot, state parsing, the engine against our reference model (no DLL: synthesised
  5849. // sources only, noise from the fallback seed), voice modes, patch level/pan
  5850. CHECK (lynx::drumSynthKeyToSlot (48) == 0 && lynx::drumSynthKeyToSlot (71) == 23 && lynx::drumSynthKeyToSlot (0) == 24);
  5851. CHECK (lynx::drumSynthKeyToSlot (47) == 71 && lynx::drumSynthKeyToSlot (72) == 72 && lynx::drumSynthKeyToSlot (119) == 119);
  5852. CHECK (lynx::drumSynthKeyToSlot (120) == -1);
  5853. // a version 3 state: 120 names, 120 × 38 ints (send track −1 becomes 0 below version 4), flags
  5854. std::vector<std::uint8_t> blob;
  5855. auto put = [&] (std::uint32_t v) { for (int k = 0; k < 4; ++k) blob.push_back ((std::uint8_t) (v >> (8 * k))); };
  5856. put (3);
  5857. put (66);
  5858. for (int i = 0; i < 120; ++i)
  5859. blob.push_back (2), blob.push_back ('a'), blob.push_back ((std::uint8_t) ('0' + i % 10));
  5860. for (int i = 0; i < 120 * 38; ++i)
  5861. put ((std::uint32_t) (i % 38 == 36 ? -1 : i % 38 == 4 ? 300 : 0));
  5862. put (0);
  5863. const auto parsed = lynx::drumSynthLiveParams (blob);
  5864. CHECK (parsed && (int) parsed->size() == lynx::drumSynthParamCount);
  5865. CHECK (parsed && (*parsed)[36] == 0.0f && (*parsed)[38 * 7 + 4] == 300.0f && (*parsed)[(std::size_t) lynx::drumSynthEditorKeyIndex] == 66.0f);
  5866. blob.resize (500);
  5867. CHECK (! lynx::drumSynthLiveParams (blob));
  5868. // patch on key 60 (slot 12): tone-mode Osc1 with sweep and click, noise-band Osc2, ring, 2 retriggers
  5869. 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,
  5870. 0, 0, 0, 0, 0, 0, 30, -1, 0, 0, 64 };
  5871. lynx::ChannelDef c;
  5872. c.instrument = lynx::InstrumentKind::drumsynth;
  5873. c.modelParams.assign ((std::size_t) lynx::drumSynthParamCount, 0.0f);
  5874. for (int s = 0; s < 120; ++s)
  5875. c.modelParams[(std::size_t) (38 * s + 15)] = c.modelParams[(std::size_t) (38 * s + 34)] = -1.0f;
  5876. for (int i = 0; i < 38; ++i)
  5877. c.modelParams[(std::size_t) (38 * 12 + i)] = (float) patch[i];
  5878. auto render = [] (const lynx::ChannelDef& def, std::vector<int> keys, int total, float gl = 1.0f, float gr = 1.0f) {
  5879. auto inst = lynx::makeInstrument (lynx::InstrumentKind::drumsynth);
  5880. inst->configure (def, 120.0);
  5881. inst->prepare (48000.0);
  5882. std::vector<float> l ((std::size_t) total), r ((std::size_t) total);
  5883. for (int s = 0; s < total; s += 512)
  5884. {
  5885. for (std::size_t k = 0; k + 1 < keys.size(); k += 2)
  5886. if (keys[k + 1] == s)
  5887. inst->noteOn (keys[k], 100.0f / 128.0f);
  5888. inst->render (l.data() + s, r.data() + s, std::min (512, total - s), gl, gr);
  5889. }
  5890. return std::make_tuple (l, r, std::move (inst));
  5891. };
  5892. {
  5893. auto [l, r, inst] = render (c, { 60, 0 }, 9600);
  5894. // reference model (REA round 30 dsl_model.py, seed 0x56CE, FL velocity 100, V = 1, centre: × g(100)·cos(π/4))
  5895. const std::pair<int, float> golden[] { { 0, -0.0074092713f }, { 10, -0.13961405f }, { 100, -0.47290668f }, { 1000, -0.29188696f },
  5896. { 3000, -0.22130175f }, { 6000, -0.049537566f }, { 9599, 0.010392102f } };
  5897. for (const auto& [i, v] : golden)
  5898. CHECK (std::abs (l[(std::size_t) i] - v) < 2e-6f && std::abs (r[(std::size_t) i] - v) < 2e-6f);
  5899. std::vector<float> tail (48000 * 4), tailR (tail.size());
  5900. inst->render (tail.data(), tailR.data(), (int) tail.size(), 1.0f, 1.0f);
  5901. CHECK (inst->idle()); // the engine reported the voice finished
  5902. }
  5903. auto energy = [] (const std::vector<float>& x, int from, int to) {
  5904. double e = 0.0;
  5905. for (int i = from; i < to; ++i)
  5906. e += (double) x[(std::size_t) i] * x[(std::size_t) i];
  5907. return e;
  5908. };
  5909. // a key without a patch level (slot 0, level 0) and a key outside the 120 patches are silent
  5910. CHECK (energy (std::get<0> (render (c, { 48, 0, 125, 0 }, 4096)), 0, 4096) == 0.0);
  5911. // mono: a second hit on the same key cuts the first; poly: both ring together (Osc2 off: no noise, deterministic)
  5912. auto tone = c;
  5913. tone.modelParams[38 * 12 + 14] = 0.0f;
  5914. const auto single = std::get<0> (render (tone, { 60, 0 }, 8192));
  5915. const auto mono = std::get<0> (render (tone, { 60, 0, 60, 2048 }, 8192));
  5916. auto poly = tone;
  5917. poly.modelParams[38 * 12 + 24] = 1.0f;
  5918. const auto both = std::get<0> (render (poly, { 60, 0, 60, 2048 }, 8192));
  5919. double monoDiff = 0.0, polyDiff = 0.0;
  5920. for (int i = 2048 + 300; i < 8192; ++i) // after the cut fade: mono = only the second hit, a copy of the first
  5921. 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]);
  5922. CHECK (monoDiff < 1e-3 && polyDiff > 1.0);
  5923. // patch pan +64 → right only; channel volume counts twice (FL applies Final.Vol in the engine and at the host)
  5924. auto right = c;
  5925. right.modelParams[38 * 12 + 1] = 64.0f;
  5926. const auto [pl, pr, pi] = render (right, { 60, 0 }, 4096);
  5927. CHECK (energy (pl, 0, 4096) < 1e-12 * energy (pr, 0, 4096) && energy (pr, 0, 4096) > 1.0);
  5928. const auto full = std::get<0> (render (tone, { 60, 0 }, 4096));
  5929. const auto half = std::get<0> (render (tone, { 60, 0 }, 4096, 0.5f, 0.5f));
  5930. CHECK (std::abs (half[100] - 0.25f * full[100]) < 1e-6f && std::abs (full[100]) > 0.01f);
  5931. }
  5932. TEST (kepler_lfo_bpm_sync)
  5933. {
  5934. // 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)
  5935. std::vector<std::uint8_t> state (0x21 + 34 * 4, 0);
  5936. auto putU32 = [&] (std::size_t o, std::uint32_t v) { std::memcpy (state.data() + o, &v, 4); };
  5937. putU32 (12, 9);
  5938. std::memcpy (state.data() + 16, "Kepler-1", 9);
  5939. putU32 (0x19, 4);
  5940. putU32 (0x1D, 34);
  5941. float k[34] {};
  5942. k[5] = 0.602085769f; // "Pads - Kepler" demo: n = 286
  5943. k[6] = 1.0f;
  5944. k[10] = 1.0f; // vibrato on
  5945. k[33] = 1.0f;
  5946. std::memcpy (state.data() + 0x21, k, sizeof k);
  5947. lynx::SynthSettings s;
  5948. float gain = 0.0f;
  5949. CHECK (lynx::synthFromKepler (state, s, gain));
  5950. CHECK (s.lfo[lynx::lfoPitch].sync && s.lfo[lynx::lfoPitch].secondsTiming);
  5951. CHECK (std::abs (s.lfo[lynx::lfoPitch].period - 286.0f / 192.0f) < 1e-6f);
  5952. k[5] = 0.0f; // slowest: 32 beats
  5953. std::memcpy (state.data() + 0x21, k, sizeof k);
  5954. CHECK (lynx::synthFromKepler (state, s, gain) && std::abs (s.lfo[lynx::lfoPitch].period - 32.0f) < 1e-6f);
  5955. k[6] = 0.0f; // free rate in seconds
  5956. std::memcpy (state.data() + 0x21, k, sizeof k);
  5957. CHECK (lynx::synthFromKepler (state, s, gain) && ! s.lfo[lynx::lfoPitch].sync);
  5958. }
  5959. namespace
  5960. {
  5961. // A Harmor state written from scratch (REA_rodada11 §4.1 layout, version 18): part A only — a decaying-harmonics
  5962. // timbre, low-pass + resonance, filter envelope, 3-voice unison, vibrato, pluck, tremolo, volume envelope with a
  5963. // velocity map — and the global block. Every other curve is neutral.
  5964. std::vector<std::uint8_t> harmorTestState (bool panLfo = true)
  5965. {
  5966. std::vector<std::uint8_t> b;
  5967. 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))); };
  5968. 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))); };
  5969. struct Pt { double dx, y, tension; int mode; };
  5970. auto curve = [&] (const std::vector<Pt>& pts, std::array<std::int32_t, 5> hdr) {
  5971. i32 (3), i32 (3), i32 ((std::int32_t) pts.size());
  5972. for (const auto& p : pts)
  5973. {
  5974. f64 (p.dx), f64 (p.y);
  5975. const auto t = (float) p.tension;
  5976. std::uint32_t u;
  5977. std::memcpy (&u, &t, 4);
  5978. i32 ((std::int32_t) u);
  5979. b.push_back ((std::uint8_t) p.mode), b.push_back (0), b.push_back (0), b.push_back (0);
  5980. }
  5981. for (auto h : hdr)
  5982. i32 (h);
  5983. };
  5984. const std::array<std::int32_t, 5> off { 0, 0, -1, -1, -1 }, on { 0, 1, -1, -1, -1 };
  5985. 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); };
  5986. i32 (18);
  5987. i32 (1 | 4);
  5988. std::vector<std::uint8_t> part;
  5989. std::swap (b, part);
  5990. std::array<std::int32_t, 386> p {};
  5991. const std::pair<int, int> values[] = { { 0, 500 }, { 3, 1000 }, { 9, 1024 }, { 11, 1000 }, { 12, 1000 }, { 17, 300 }, { 18, 4000 },
  5992. { 19, 500 }, { 20, 1000 }, { 24, 500 }, { 25, 500 }, { 28, 500 }, { 29, 256 }, { 30, -1 }, { 31, -1 }, { 33, -1 }, { 34, 3 },
  5993. { 35, 1 }, { 37, 192 }, { 38, 128 }, { 39, 500 }, { 40, 10000 }, { 41, 1 }, { 42, 10000 }, { 43, 1 }, { 45, 200 }, { 46, 500 },
  5994. { 47, 1 }, { 49, -140 }, { 50, 1200 }, { 51, 0 }, { 52, 5000 }, { 54, 500 }, { 56, 600 }, { 57, 300 }, { 59, 500 }, { 60, 600 },
  5995. { 64, 8192 }, { 66, 500 }, { 72, 600 }, { 74, 1000 }, { 75, 600 }, { 78, 5000 }, { 79, 500 }, { 80, 3000 } };
  5996. for (const auto& [i, v] : values)
  5997. p[(std::size_t) i] = v;
  5998. for (auto v : p)
  5999. i32 (v);
  6000. for (int i = 0; i < 12; ++i)
  6001. i32 (i); // module order
  6002. std::array<std::uint8_t, 0x4b> misc {};
  6003. auto put = [&] (int o, std::int32_t v) { std::memcpy (misc.data() + o, &v, 4); };
  6004. const float one = 1.0f;
  6005. put (0x08, 107), put (0x1c, 1), put (0x28, 200), std::memcpy (misc.data() + 0x30, &one, 4);
  6006. put (0x34, 0), put (0x38, 4), put (0x3c, 100), put (0x40, 108);
  6007. misc[0x44] = 1;
  6008. b.insert (b.end(), misc.begin(), misc.end());
  6009. 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 };
  6010. for (int k = 0; k < 43; ++k)
  6011. {
  6012. static const int mode2[] = { 2, 14, 23, 28, 30, 38, 39, 41, 42 }; // ×2 around 0.5: 1.0 is neutral
  6013. const bool centred = std::find (std::begin (mode1), std::end (mode1), k) != std::end (mode1);
  6014. const bool doubled = std::find (std::begin (mode2), std::end (mode2), k) != std::end (mode2);
  6015. const double neutral = centred && ! doubled ? 0.5 : 1.0;
  6016. i32 (3);
  6017. i32 (1065353216), i32 (1065353216), i32 (1065353216);
  6018. if (k == 1) // volume envelope: attack, decay to the sustain point, release
  6019. 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 });
  6020. else if (k == 4) // filter-1 envelope
  6021. curve ({ { 0, 1, 0, 0 }, { 0.25, 0.2, -0.5, 0 } }, { 0, 1, -1, -1, -1 });
  6022. else
  6023. flat (neutral);
  6024. for (int a : { 128, 128, 0, 128 })
  6025. i32 (a);
  6026. if (k == 0 && panLfo) // pan LFO
  6027. flat (1.0, on);
  6028. else
  6029. flat (0.5);
  6030. for (int a : { k == 0 ? 40000 : 0, 0, 0, 0 })
  6031. i32 (a);
  6032. i32 (0);
  6033. for (int m = 2; m < 11; ++m)
  6034. if (k == 1 && m == 3)
  6035. curve ({ { 0, 0.2, 0, 0 }, { 1, 1, -0.3, 0 } }, off); // velocity → volume
  6036. else
  6037. flat (neutral);
  6038. }
  6039. for (int c = 0; c < 26; ++c)
  6040. if (c == 2 || c == 3)
  6041. curve ({ { 0, 0.25, 0, 0 }, { 0.006, 0.12, -0.46, 0 }, { 0.994, 0, 0, 0 } }, off); // timbres
  6042. else if (c == 14)
  6043. curve ({ { 0, 1, 0, 0 }, { 1, 0, 0, 0 } }, off); // pluck curve
  6044. else
  6045. 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)));
  6046. std::swap (b, part);
  6047. i32 ((std::int32_t) part.size());
  6048. b.insert (b.end(), part.begin(), part.end());
  6049. std::array<std::int32_t, 53> g {};
  6050. g[0] = g[1] = g[2] = 256, g[10] = 500, g[11] = 1000, g[12] = 1000, g[15] = 1000;
  6051. for (auto v : g)
  6052. i32 (v);
  6053. for (int i = 0; i < 6; ++i)
  6054. i32 (i);
  6055. std::array<std::uint8_t, 0x3d> gm {};
  6056. const std::int32_t cr = 200, vr = 1;
  6057. std::memcpy (gm.data() + 12, &vr, 4);
  6058. std::memcpy (gm.data() + 24, &cr, 4);
  6059. b.insert (b.end(), gm.begin(), gm.end());
  6060. return b;
  6061. }
  6062. } // namespace
  6063. TEST (harmor_engine)
  6064. {
  6065. // REA_rodada34: state parsing, the additive engine against our reference model (hmodel.py), host levels, voice end
  6066. const auto blob = harmorTestState();
  6067. if (const char* dump = std::getenv ("LYNX_DUMP_HARMOR"))
  6068. std::ofstream (dump, std::ios::binary).write ((const char*) blob.data(), (std::streamsize) blob.size());
  6069. CHECK (lynx::harmorStateUsable (blob));
  6070. CHECK (lynx::harmorFallbacks (blob).size() == 1); // (only the harmonic-randomness note)
  6071. const auto at = lynx::harmorParamOffset (blob, 0, 52);
  6072. std::int32_t cutoff = 0;
  6073. CHECK (at > 0 && (std::memcpy (&cutoff, blob.data() + at, 4), cutoff == 5000));
  6074. CHECK (lynx::harmorParamOffset (blob, 1, 52) < 0 && lynx::harmorParamOffset (blob, -1, 12) > at);
  6075. auto broken = blob;
  6076. broken.resize (broken.size() / 2);
  6077. CHECK (! lynx::harmorStateUsable (broken));
  6078. auto old = blob;
  6079. old[0] = 15; // articulators and curves are stored from version 16
  6080. CHECK (! lynx::harmorStateUsable (old));
  6081. lynx::ChannelDef c;
  6082. c.instrument = lynx::InstrumentKind::harmor;
  6083. c.pluginState = blob;
  6084. auto render = [] (const lynx::ChannelDef& def, int total, float gl, float gr, int offAt) {
  6085. auto inst = lynx::makeInstrument (lynx::InstrumentKind::harmor);
  6086. inst->configure (def, 120.0);
  6087. inst->prepare (44100.0);
  6088. std::vector<float> l ((std::size_t) total), r ((std::size_t) total);
  6089. inst->noteOn (60, 0.78125f);
  6090. for (int s = 0; s < total; s += 512)
  6091. {
  6092. if (s == offAt)
  6093. inst->noteOff (60);
  6094. inst->render (l.data() + s, r.data() + s, std::min (512, total - s), gl, gr);
  6095. }
  6096. return std::make_tuple (l, r, std::move (inst));
  6097. };
  6098. {
  6099. // reference model (REA round 34 hmodel.py; C5 at FL velocity 100, Final.Vol 1, centre, released at 6144, the
  6100. // Mersenne Twister seeded like LYNX's)
  6101. auto [l, r, inst] = render (c, 8192, 1.0f, 1.0f, 6144);
  6102. const std::tuple<int, float, float> golden[] {
  6103. { 0, 0.0f, 0.0f }, { 100, 0.00947693f, 0.04249846f }, { 1000, 0.08140575f, -0.03251422f }, { 3000, 0.05928446f, -0.00247572f },
  6104. { 6000, 0.02997839f, 0.14549091f }, { 7000, -0.01121871f, 0.04197952f }, { 8191, 0.00314545f, 0.03857505f } };
  6105. for (const auto& [i, gl, gr] : golden)
  6106. CHECK (std::abs (l[(std::size_t) i] - gl) < 2e-6f && std::abs (r[(std::size_t) i] - gr) < 2e-6f);
  6107. // after the release the volume envelope ends, the record declicks and the instrument goes idle
  6108. std::vector<float> tail (44100), tailR (tail.size());
  6109. inst->render (tail.data(), tailR.data(), (int) tail.size(), 1.0f, 1.0f);
  6110. CHECK (inst->idle());
  6111. CHECK (std::abs (tail.back()) == 0.0f);
  6112. }
  6113. // the reference renderer gives the same samples as the instrument
  6114. {
  6115. const auto ref = lynx::harmor::renderReference (blob, { { 0, 60, 0.78125, 1.0, 0.0, 6144 } }, 44100.0, 8192);
  6116. const auto [l, r, inst] = render (c, 8192, 1.0f, 1.0f, 6144);
  6117. double worst = 0.0;
  6118. for (int i = 0; i < 8192; ++i)
  6119. 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]) });
  6120. CHECK (worst == 0.0);
  6121. }
  6122. // FL's level law applied once: half the channel volume halves the output; full right pan silences the left side
  6123. const auto full = std::get<0> (render (c, 2048, 1.0f, 1.0f, -1));
  6124. const auto half = std::get<0> (render (c, 2048, 0.5f, 0.5f, -1));
  6125. CHECK (std::abs (half[1000] - 0.5f * full[1000]) < 1e-6f && std::abs (full[1000]) > 0.01f);
  6126. auto mono = c;
  6127. mono.pluginState = harmorTestState (false); // no pan LFO ...
  6128. const std::int32_t one = 1;
  6129. std::memcpy (mono.pluginState.data() + lynx::harmorParamOffset (mono.pluginState, 0, 34), &one, 4); // ... nor unison spread
  6130. const auto [pl, pr, pi] = render (mono, 2048, 0.0f, 1.41421356f, -1);
  6131. double el = 0.0, er = 0.0;
  6132. for (int i = 0; i < 2048; ++i)
  6133. el += (double) pl[(std::size_t) i] * pl[(std::size_t) i], er += (double) pr[(std::size_t) i] * pr[(std::size_t) i];
  6134. CHECK (el < 1e-10 * er && er > 1e-3);
  6135. }
  6136. namespace
  6137. {
  6138. // An Ogun state written from scratch (REA_rodada37 §1.3 layout, version 18; zlib with stored blocks): richness 4
  6139. // (255 partials), pre-decay, decay/release, fullness, Seed 1 + fixed Seed 2 with morph, 3-voice unison, a 2-stage
  6140. // low-pass with an LFO on its cutoff, a volume envelope with a sustain point and a velocity map, declick, normalisation,
  6141. // Impulse/Decay maps, and every plugin effect (EQ band, chorus, ping-pong delay, reverb). Everything else is neutral.
  6142. std::vector<std::uint8_t> ogunTestState()
  6143. {
  6144. std::vector<std::uint8_t> b;
  6145. 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))); };
  6146. auto f32v = [&] (float v) { std::uint32_t u; std::memcpy (&u, &v, 4); i32 ((std::int32_t) u); };
  6147. 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))); };
  6148. struct Pt { double dx, y, tension; int mode; };
  6149. auto curve = [&] (int type, const std::vector<Pt>& pts, std::array<std::int32_t, 5> hdr) {
  6150. i32 (type), i32 (3), i32 ((std::int32_t) pts.size());
  6151. for (const auto& p : pts)
  6152. {
  6153. f64 (p.dx), f64 (p.y), f32v ((float) p.tension);
  6154. b.push_back ((std::uint8_t) p.mode), b.push_back (0), b.push_back (0), b.push_back (0);
  6155. }
  6156. for (auto h : hdr)
  6157. i32 (h);
  6158. };
  6159. const std::array<std::int32_t, 5> off { 0, 0, -1, -1, -1 }, on { 0, 1, -1, -1, -1 };
  6160. auto flat = [&] (int type, double y) { curve (type, { { 0, y, 0, 0 }, { 1, y, 0, 0 } }, off); };
  6161. std::array<std::int32_t, 64> P {};
  6162. const std::pair<int, int> values[] = { { 0, 128 }, { 5, 300 }, { 6, 3000 }, { 7, 2000 }, { 8, 200 }, { 9, 500 }, { 10, 12 },
  6163. { 11, 34 }, { 12, 3 }, { 13, 64 }, { 14, 64 }, { 15, 40 }, { 16, 64 }, { 17, 180 }, { 18, 60 }, { 19, 2 }, { 20, 300 },
  6164. { 21, 400 }, { 22, 40 }, { 23, 30 }, { 24, 20 }, { 25, 64 }, { 26, 40 }, { 27, 96 }, { 28, 100 }, { 29, 64 }, { 30, 2 },
  6165. { 31, 19 }, { 32, 221 }, { 33, 0 }, { 34, 50 }, { 35, 100 }, { 36, 20 }, { 37, 60 }, { 38, 2 }, { 39, 64 }, { 40, 300 },
  6166. { 43, 30000 }, { 46, 20000 }, { 49, 0 }, { 50, 2 }, { 51, 0 }, { 52, 9 }, { 53, 1 }, { 54, 0 },
  6167. { 55, 0x01000000 }, // +0x20b: pitch follows the key
  6168. { 56, 0x00010000 }, // +0x20e: declick
  6169. { 62, 0x00000100 } }; // +0x225: normalise
  6170. for (const auto& [i, v] : values)
  6171. P[(std::size_t) i] = v;
  6172. for (auto v : P)
  6173. i32 (v);
  6174. b.push_back (0), b.push_back (1), b.push_back (0); // delay: not tempo-based, on
  6175. i32 (1), i32 (1), i32 (1); // EQ band types: peaking
  6176. b.push_back (0); // comment: 0 characters
  6177. for (int k = 0; k < 13; ++k)
  6178. {
  6179. static constexpr int sum[] = { 1, 2, 3, 9, 11, 12 };
  6180. const double neutral = std::find (std::begin (sum), std::end (sum), k) != std::end (sum) ? 0.5 : 1.0;
  6181. i32 (1);
  6182. f32v (0.0f), f32v (1.0f), f32v (k == 1 ? 0.3f : 0.0f);
  6183. if (k == 0) // volume envelope: attack, decay to the sustain point, release
  6184. 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 });
  6185. else
  6186. flat (1, neutral);
  6187. for (int a : { 128, 128, 128, 128 })
  6188. i32 (a);
  6189. if (k == 1) // cutoff LFO
  6190. curve (2, { { 0, 0.8, 0, 0 } }, on);
  6191. else
  6192. flat (2, 0.5);
  6193. for (int a : { k == 1 ? 40000 : 0, 0, 0, 0 })
  6194. i32 (a);
  6195. i32 (0);
  6196. for (int m = 0; m < 4; ++m)
  6197. if (k == 0 && m == 1)
  6198. curve (3, { { 0, 0.3, 0, 0 }, { 1, 1, -0.2, 0 } }, off); // velocity → volume
  6199. else
  6200. flat (3, neutral);
  6201. }
  6202. flat (3, 0.0); // Forced: none
  6203. curve (3, { { 0, 0.6, 0, 0 }, { 1, 0.4, 0.3, 0 } }, off); // Impulse EQ
  6204. curve (3, { { 0, 0.5, 0, 0 }, { 1, 0.3, 0, 0 } }, off); // Decay EQ
  6205. flat (3, 0.5); // Release EQ
  6206. // u32 version + zlib (stored blocks)
  6207. std::vector<std::uint8_t> s { 18, 0, 0, 0, 0x78, 0x01 };
  6208. for (std::size_t i = 0; i < b.size();)
  6209. {
  6210. const auto len = std::min<std::size_t> (65535, b.size() - i);
  6211. s.push_back (i + len >= b.size() ? 1 : 0);
  6212. s.push_back ((std::uint8_t) len), s.push_back ((std::uint8_t) (len >> 8));
  6213. s.push_back ((std::uint8_t) ~len), s.push_back ((std::uint8_t) (~len >> 8));
  6214. s.insert (s.end(), b.begin() + (std::ptrdiff_t) i, b.begin() + (std::ptrdiff_t) (i + len));
  6215. i += len;
  6216. }
  6217. std::uint32_t a1 = 1, a2 = 0;
  6218. for (auto c : b)
  6219. a1 = (a1 + c) % 65521u, a2 = (a2 + a1) % 65521u;
  6220. for (int sh = 24; sh >= 0; sh -= 8)
  6221. s.push_back ((std::uint8_t) (((a2 << 16) | a1) >> sh));
  6222. return s;
  6223. }
  6224. } // namespace
  6225. TEST (ogun_engine)
  6226. {
  6227. // REA_rodada37: state parsing, the engine against our reference model (ogmodel.py), host levels, export quality
  6228. const auto blob = ogunTestState();
  6229. if (const char* dump = std::getenv ("LYNX_DUMP_OGUN"))
  6230. std::ofstream (dump, std::ios::binary).write ((const char*) blob.data(), (std::streamsize) blob.size());
  6231. CHECK (lynx::ogunStateUsable (blob));
  6232. CHECK (lynx::ogunFallbacks (blob).empty());
  6233. CHECK (lynx::ogunParam (blob, 17) == 180 && lynx::ogunParam (blob, 52) == 9 && ! lynx::ogunParam (blob, 64));
  6234. auto broken = blob;
  6235. broken.resize (broken.size() - 300);
  6236. CHECK (! lynx::ogunStateUsable (broken));
  6237. auto old = blob;
  6238. old[0] = 13; // the articulator layout is from version 14
  6239. CHECK (! lynx::ogunStateUsable (old));
  6240. // reference model (REA round 37 ogmodel.Plugin(state).run: C5 velocity 0.75 released at 6144, G5 velocity 0.625 at 2048
  6241. // released at 8192; host block 512)
  6242. 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 } };
  6243. const auto ref = lynx::ogun::renderReference (blob, notes, 44100.0, 16384);
  6244. CHECK (ref.size() == 2 * 16384);
  6245. if (const char* dump = std::getenv ("LYNX_DUMP_OGUN_OUT"))
  6246. std::ofstream (dump, std::ios::binary).write ((const char*) ref.data(), (std::streamsize) (ref.size() * 4));
  6247. const std::tuple<int, float, float> golden[] {
  6248. { 100, -7.763202e-05f, -8.919523e-05f }, { 1000, 0.06195267f, 0.03858230f }, { 3000, 0.01363476f, -0.00378433f },
  6249. { 6000, -0.06601223f, -0.03084030f }, { 9000, 0.04204506f, 0.02452896f }, { 12000, 0.03420147f, -0.01837870f },
  6250. { 16383, -0.00465311f, -0.00119627f } };
  6251. for (const auto& [i, gl, gr] : golden)
  6252. CHECK (std::abs (ref[2 * (std::size_t) i] - gl) < 2e-6f && std::abs (ref[2 * (std::size_t) i + 1] - gr) < 2e-6f);
  6253. // the instrument plays like the reference renderer (Final.Vol 1, centre)
  6254. lynx::ChannelDef c;
  6255. c.instrument = lynx::InstrumentKind::ogun;
  6256. c.pluginState = blob;
  6257. auto render = [&] (const lynx::ChannelDef& def, int total, float gl, float gr, bool held = false) {
  6258. auto inst = lynx::makeInstrument (lynx::InstrumentKind::ogun);
  6259. inst->configure (def, 120.0);
  6260. inst->prepare (44100.0);
  6261. std::vector<float> l ((std::size_t) total), r ((std::size_t) total);
  6262. for (int s = 0; s < total; s += 512)
  6263. {
  6264. if (s == 0)
  6265. inst->noteOn (60, 0.75f);
  6266. if (s == 2048)
  6267. inst->noteOn (67, 0.625f);
  6268. if (s == 6144 && ! held)
  6269. inst->noteOff (60);
  6270. if (s == 8192 && ! held)
  6271. inst->noteOff (67);
  6272. inst->render (l.data() + s, r.data() + s, std::min (512, total - s), gl, gr);
  6273. }
  6274. return std::make_tuple (l, r, std::move (inst));
  6275. };
  6276. {
  6277. auto [l, r, inst] = render (c, 16384, 1.0f, 1.0f);
  6278. double worst = 0.0;
  6279. for (int i = 0; i < 16384; ++i)
  6280. 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]) });
  6281. CHECK (worst == 0.0);
  6282. // the voices end and the effect tails die out: the instrument goes idle
  6283. std::vector<float> tail (44100), tailR (tail.size());
  6284. for (int k = 0; k < 20 && ! inst->idle(); ++k)
  6285. inst->render (tail.data(), tailR.data(), (int) tail.size(), 1.0f, 1.0f);
  6286. CHECK (inst->idle());
  6287. }
  6288. // FL's level law applied once (effects off): half the channel volume halves the output once the gain ramps
  6289. // (limited to 0.001 per sample) have settled on the sustain level; full right pan silences the left side
  6290. {
  6291. auto dry = c;
  6292. for (int i : { 19, 29, 40, 53 })
  6293. CHECK (lynx::ogunSetParam (dry.pluginState, i, 0)); // chorus, delay wet, EQ band and reverb off
  6294. CHECK (lynx::ogunStateUsable (dry.pluginState) && lynx::ogunParam (dry.pluginState, 19) == 0);
  6295. const auto full = std::get<0> (render (dry, 32768, 1.0f, 1.0f, true));
  6296. const auto half = std::get<0> (render (dry, 32768, 0.5f, 0.5f, true));
  6297. double worst = 0.0, peak = 0.0;
  6298. for (int i = 30000; i < 32768; ++i)
  6299. worst = std::max (worst, (double) std::abs (half[(std::size_t) i] - 0.5f * full[(std::size_t) i])),
  6300. peak = std::max (peak, (double) std::abs (full[(std::size_t) i]));
  6301. CHECK (worst <= 1e-7 * peak && peak > 1e-3);
  6302. // FL's default channel volume (100/128): FL hands Ogun Final.Vol = (11^v − 1)/10 (REA_rodada28 §4.1); LYNX's
  6303. // centred channel gains (√2·V·cos(π/4) each) give the reference model's level at that Final.Vol
  6304. const auto V = lynx::channelGain (0.78125f);
  6305. const auto g = V * std::cos (0.25f * 3.14159265f) * 1.41421356f;
  6306. const auto atDefault = std::get<0> (render (dry, 32768, g, g, true));
  6307. const auto refDefault = lynx::ogun::renderReference (dry.pluginState, { { 0, 60, 0.75, V, 0.0, 0.0, 0.0, 0.0, 0.5, -1 },
  6308. { 2048, 67, 0.625, V, 0.0, 0.0, 0.0, 0.0, 0.5, -1 } }, 44100.0, 32768);
  6309. double ei = 0.0, er0 = 0.0;
  6310. for (int i = 30000; i < 32768; ++i)
  6311. 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];
  6312. CHECK (er0 > 0.0 && std::abs (10.0 * std::log10 (ei / er0)) < 0.001);
  6313. const auto [pl, pr, pi] = render (dry, 4096, 0.0f, 1.41421356f);
  6314. double el = 0.0, er = 0.0;
  6315. for (int i = 0; i < 4096; ++i)
  6316. el += (double) pl[(std::size_t) i] * pl[(std::size_t) i], er += (double) pr[(std::size_t) i] * pr[(std::size_t) i];
  6317. CHECK (el < 1e-10 * er && er > 1e-3);
  6318. }
  6319. // export: FL renders Ogun at quality 4 (×2 rate, 32-point reader), LYNX too while it renders offline
  6320. {
  6321. lynx::setOfflineRendering (true);
  6322. auto [l, r, inst] = render (c, 8192, 1.0f, 1.0f);
  6323. lynx::setOfflineRendering (false);
  6324. lynx::ogun::RefOptions q4;
  6325. q4.quality = 4;
  6326. const auto ref4 = lynx::ogun::renderReference (blob, notes, 44100.0, 8192, q4);
  6327. double worst = 0.0, diff = 0.0;
  6328. for (int i = 0; i < 8192; ++i)
  6329. worst = std::max (worst, (double) std::abs (ref4[2 * (std::size_t) i] - l[(std::size_t) i])),
  6330. diff = std::max (diff, (double) std::abs (ref[2 * (std::size_t) i] - l[(std::size_t) i]));
  6331. CHECK (worst == 0.0 && diff > 1e-3);
  6332. const std::tuple<int, float, float> golden4[] {
  6333. { 100, 0.00605961f, 0.00628969f }, { 1000, 0.03729841f, 0.01727954f }, { 3000, -0.09010383f, -0.02551294f },
  6334. { 6000, 0.02167798f, -0.01115632f }, { 8191, 0.00320288f, -0.00615792f } };
  6335. for (const auto& [i, gl, gr] : golden4)
  6336. CHECK (std::abs (ref4[2 * (std::size_t) i] - gl) < 2e-6f && std::abs (ref4[2 * (std::size_t) i + 1] - gr) < 2e-6f);
  6337. }
  6338. // feature variants of the same state against the reference model (energy per side over 8192 samples, three
  6339. // samples; C1 released at 6144): qualities, richness, unison, the filter types, ALT DECAY, 1/√h, Seed 2 Random,
  6340. // infinite decay, logarithmic axis, velocity → position, other rates. Goldens from ogmodel.py (REA round 37).
  6341. {
  6342. struct Sample { int at; float l, r; };
  6343. struct Variant { const char* name; std::vector<std::pair<int, int>> params; int rate; double el, er; Sample s[3]; };
  6344. const Variant variants[] {
  6345. { "q1", { { 54, 1 } }, 44100, 11.0970402, 6.87820714, { { 1500, 0.0240363069f, -0.0148524037f }, { 4000, 0.0873190612f, -0.000715861097f }, { 7000, -0.0378603041f, -0.00338819111f } } },
  6346. { "q2", { { 54, 2 } }, 44100, 11.2405446, 6.68045082, { { 1500, 0.0448660068f, -0.00560745923f }, { 4000, -0.0122657465f, 0.0104285963f }, { 7000, -0.0216034129f, -0.0134632047f } } },
  6347. { "q3", { { 54, 3 } }, 44100, 11.3200608, 6.86196449, { { 1500, -0.0031537537f, -0.0242648814f }, { 4000, 0.0426301025f, 0.0364697985f }, { 7000, 0.00843803957f, 0.0302239582f } } },
  6348. { "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 } } },
  6349. { "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 } } },
  6350. { "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 } } },
  6351. { "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 } } },
  6352. { "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 } } },
  6353. { "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 } } },
  6354. { "alt", { { 62, 257 } }, 44100, 17.2485711, 9.99223979, { { 1500, -0.0319156498f, -0.0186850764f }, { 4000, -0.0769012421f, -0.0375530645f }, { 7000, 0.0310976505f, 0.0445244014f } } },
  6355. { "isqrt", { { 62, 65792 } }, 44100, 45.7309307, 27.1224593, { { 1500, -0.04376591f, -0.00845711026f }, { 4000, 0.0351300463f, -0.129557073f }, { 7000, 0.0096148327f, 0.00123740174f } } },
  6356. { "seed2rnd", { { 11, 0 } }, 44100, 16.8228819, 11.5433061, { { 1500, -0.0117614279f, -0.026497297f }, { 4000, 0.00265733898f, -0.07069581f }, { 7000, 0.00576663949f, 0.0565217957f } } },
  6357. { "decinf", { { 6, 10000 } }, 44100, 19.1879226, 11.0487311, { { 1500, -0.0324105881f, -0.0190765262f }, { 4000, -0.0809780285f, -0.0395730771f }, { 7000, 0.034197174f, 0.048585102f } } },
  6358. { "logx", { { 57, 16777216 } }, 44100, 12.3064326, 7.31519289, { { 1500, -0.0438990779f, 0.0096983267f }, { 4000, -0.0175748877f, 0.0313935578f }, { 7000, 0.0639200211f, 0.024419222f } } },
  6359. { "velpos", { { 56, 66304 } }, 44100, 4.9966925, 3.16540662, { { 1500, 0.0083851777f, -0.0165472236f }, { 4000, 0.0630451962f, 0.0156494901f }, { 7000, -0.0293043777f, -0.00182877108f } } },
  6360. { "fs48", { }, 48000, 10.8813888, 6.53592373, { { 1500, -0.0485184453f, -0.0319588967f }, { 4000, 0.0230421089f, -0.0286604818f }, { 7000, -0.0117630213f, -0.017459048f } } },
  6361. { "fs96", { }, 96000, 11.0189683, 6.39821883, { { 1500, -0.0267860368f, -0.0227564126f }, { 4000, 0.0238709711f, -0.0100849615f }, { 7000, -0.0034619756f, 0.0451687202f } } },
  6362. };
  6363. for (const auto& v : variants)
  6364. {
  6365. auto st = blob;
  6366. for (const auto& [i, x] : v.params)
  6367. CHECK (lynx::ogunSetParam (st, i, x));
  6368. const auto y = lynx::ogun::renderReference (st, { { 0, 60, 0.75, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 6144 },
  6369. { 2048, 67, 0.625, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1 } }, (double) v.rate, 8192);
  6370. double el = 0.0, er = 0.0, peak = 0.0;
  6371. for (std::size_t i = 0; i + 1 < y.size(); i += 2)
  6372. 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]) });
  6373. bool ok = y.size() == 2 * 8192 && std::abs (el - v.el) <= 1e-5 * v.el && std::abs (er - v.er) <= 1e-5 * v.er;
  6374. for (const auto& smp : v.s)
  6375. 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;
  6376. if (! ok)
  6377. std::printf (" Ogun variant %s differs from the model: energy %.9g %.9g (model %.9g %.9g)\n", v.name, el, er, v.el, v.er);
  6378. CHECK (ok);
  6379. }
  6380. }
  6381. }
  6382. // our own Maximus v7 state (layout REA_rodada8 §1.1): 7 globals, 4 × 13 band parameters, 8 envelopes (dx, y, tension, type)
  6383. static std::vector<std::uint8_t> maximusTestState (const std::array<int, 7>& g, const std::array<std::array<int, 13>, 4>& bands,
  6384. const std::array<std::vector<std::array<double, 4>>, 8>& envs, int oversampling)
  6385. {
  6386. std::vector<std::uint8_t> d;
  6387. auto put = [&] (const void* v, std::size_t n) { d.insert (d.end(), (const std::uint8_t*) v, (const std::uint8_t*) v + n); };
  6388. auto i32 = [&] (std::int32_t v) { put (&v, 4); };
  6389. i32 (7);
  6390. for (int copy = 0; copy < 2; ++copy)
  6391. {
  6392. for (auto v : g)
  6393. i32 (v);
  6394. for (const auto& b : bands)
  6395. for (auto v : b)
  6396. i32 (v);
  6397. }
  6398. d.resize (0x1fe, 0);
  6399. std::memcpy (d.data() + 0x1f4, &oversampling, 4);
  6400. for (const auto& e : envs)
  6401. {
  6402. i32 (3), i32 (2), i32 ((std::int32_t) e.size());
  6403. for (const auto& pt : e)
  6404. {
  6405. const double dx = pt[0], y = pt[1];
  6406. const float t = (float) pt[2];
  6407. put (&dx, 8), put (&y, 8), put (&t, 4);
  6408. const std::uint8_t flags[4] { (std::uint8_t) pt[3], 0, 0, 0 };
  6409. put (flags, 4);
  6410. }
  6411. i32 (0), i32 (-1), i32 (-1), i32 (-1), i32 (-1);
  6412. }
  6413. return d;
  6414. }
  6415. TEST (ogun_demo_channels)
  6416. {
  6417. // every Ogun channel of FL's demo projects (with its plugin effects) against the round-37 reference model, which is
  6418. // 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),
  6419. // 39 690 samples at 44.1 kHz, at the state's quality and at the export quality 4. Fingerprint: energy per side and
  6420. // four samples (the engine matches the model within float rounding, −125 dB or better on the whole signal).
  6421. if (realFlpDir.empty())
  6422. return;
  6423. struct Sample { int at; float l, r; };
  6424. struct Golden { const char* file; int ordinal; std::size_t stateSize; bool export4; double el, er; Sample s[4]; };
  6425. const Golden goldens[] {
  6426. { "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
  6427. { "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
  6428. { "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
  6429. { "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
  6430. { "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
  6431. { "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
  6432. { "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
  6433. { "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
  6434. { "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
  6435. { "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
  6436. { "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
  6437. { "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
  6438. { "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
  6439. { "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
  6440. { "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
  6441. { "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
  6442. { "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
  6443. { "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
  6444. { "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
  6445. { "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
  6446. { "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
  6447. { "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
  6448. { "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
  6449. { "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
  6450. { "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
  6451. { "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
  6452. { "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
  6453. { "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
  6454. { "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
  6455. { "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
  6456. { "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
  6457. { "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
  6458. { "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
  6459. { "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
  6460. { "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
  6461. { "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
  6462. { "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
  6463. { "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
  6464. { "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
  6465. { "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
  6466. };
  6467. std::map<std::string, std::vector<std::vector<std::uint8_t>>> states;
  6468. int checked = 0;
  6469. for (const auto& g : goldens)
  6470. {
  6471. if (! states.contains (g.file))
  6472. {
  6473. std::ifstream in (std::filesystem::path (realFlpDir) / "Demo projects" / g.file, std::ios::binary);
  6474. const std::vector<std::uint8_t> bytes ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  6475. auto& list = states[g.file];
  6476. if (! bytes.empty())
  6477. for (const auto& c : flp::parseProject (bytes).channels)
  6478. if (c.pluginName == "Ogun")
  6479. list.push_back (c.pluginState);
  6480. }
  6481. const auto& list = states[g.file];
  6482. if (list.empty())
  6483. continue; // not this installation
  6484. CHECK ((int) list.size() > g.ordinal);
  6485. if ((int) list.size() <= g.ordinal)
  6486. continue;
  6487. const auto& st = list[(std::size_t) g.ordinal];
  6488. CHECK (st.size() == g.stateSize);
  6489. lynx::ogun::RefOptions opt;
  6490. opt.quality = g.export4 ? 4 : -1;
  6491. const auto y = lynx::ogun::renderReference (st, { { 0, 60, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 20000 },
  6492. { 8000, 67, 0.6, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 26000 },
  6493. { 16000, 55, 0.95, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 30000 } }, 44100.0, 39690, opt);
  6494. double el = 0.0, er = 0.0, peak = 0.0;
  6495. for (std::size_t i = 0; i + 1 < y.size(); i += 2)
  6496. 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]) });
  6497. bool ok = y.size() == 2 * 39690 && std::abs (el - g.el) <= 1e-5 * g.el && std::abs (er - g.er) <= 1e-5 * g.er;
  6498. for (const auto& smp : g.s)
  6499. 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;
  6500. if (! ok)
  6501. std::printf (" Ogun %s #%d (q%s) differs from the model: energy %.9g %.9g (model %.9g %.9g)\n", g.file, g.ordinal,
  6502. g.export4 ? "4" : "-state", el, er, g.el, g.er);
  6503. CHECK (ok);
  6504. ++checked;
  6505. }
  6506. std::printf (" Ogun: %d demo renders checked against the reference model\n", checked);
  6507. CHECK (checked == (int) std::size (goldens));
  6508. }
  6509. TEST (harmless_rack)
  6510. {
  6511. // REA_rodada36: Harmless's effects rack against our reference model (rack.py / maxmodel.py, which match the
  6512. // installation's Harmless_x64.dll and SG_x64.dll), 44.1 kHz, host blocks of 512
  6513. std::vector<float> inL (8192), inR (8192);
  6514. for (int i = 0; i < 4096; ++i)
  6515. {
  6516. 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));
  6517. inR[(std::size_t) i] = (float) (1.2 * std::sin (2.0 * 3.141592653589793 * 660.0 * i / 44100.0));
  6518. }
  6519. auto run = [&] (const std::array<int, 100>& p, int compType, std::shared_ptr<const lynx::hlfx::MaximusPreset> comp, int total, int voicesUntil) {
  6520. lynx::hlfx::Rack rack;
  6521. std::array<int, 7> t {};
  6522. t[3] = compType;
  6523. rack.prepare (p, t, 44100.0, 120.0, std::move (comp));
  6524. std::vector<float> l (inL.begin(), inL.begin() + total), r (inR.begin(), inR.begin() + total);
  6525. for (int s = 0; s < total; s += 512)
  6526. rack.process (l.data() + s, r.data() + s, std::min (512, total - s), s < voicesUntil);
  6527. return std::make_pair (l, r);
  6528. };
  6529. {
  6530. // chorus type 3 (mix 400), ping-pong delay type 2 (vol 600, feedback 500, 1/4 beat), reverb type 4 (vol 700)
  6531. std::array<int, 100> p {};
  6532. p[90] = 3, p[91] = 400, p[92] = 2, p[93] = 600, p[94] = 500, p[95] = 48, p[96] = 4, p[97] = 700;
  6533. const auto [l, r] = run (p, 0, nullptr, 8192, 4096);
  6534. const std::tuple<int, float, float> golden[] { { 0, 0.0f, 0.0f }, { 500, -0.25248247f, 0.15141529f }, { 3000, -0.65128994f, -0.64854866f },
  6535. { 5000, -0.54308629f, -0.36827448f }, { 6000, -0.98378551f, -0.72790027f },
  6536. { 8191, 0.50599128f, -0.43637198f } };
  6537. for (const auto& [i, gl, gr] : golden)
  6538. CHECK (std::abs (l[(std::size_t) i] - gl) < 2e-6f && std::abs (r[(std::size_t) i] - gr) < 2e-6f);
  6539. }
  6540. {
  6541. // the delay alone: an impulse comes back after round(time·fs·0.3125/bpm) samples × (11^0.6 − 1)/10, then × feedback
  6542. std::array<int, 100> p {};
  6543. p[92] = 1, p[93] = 600, p[94] = 500, p[95] = 48;
  6544. lynx::hlfx::Rack rack;
  6545. rack.prepare (p, {}, 44100.0, 120.0, nullptr);
  6546. std::vector<float> l (16384), r (16384);
  6547. l[0] = 1.0f;
  6548. for (int s = 0; s < 16384; s += 512)
  6549. rack.process (l.data() + s, r.data() + s, 512, s == 0);
  6550. const auto D = 5512; // 48·44100·0.3125/120 = 5512.5 → 5512 (round half to even)
  6551. const auto vol = (float) ((std::exp ((double) (600 * 0.001f) * (double) (float) std::log (11.0)) - 1.0) * (double) 0.1f);
  6552. CHECK (std::abs (l[(std::size_t) D] - vol) < 1e-7f && std::abs (l[(std::size_t) D - 1]) < 1e-12f);
  6553. // the feedback ramps from 0.5 toward 0.5: the second echo is vol·0.5
  6554. CHECK (std::abs (l[(std::size_t) (2 * D)] - vol * 0.5f) < 1e-7f && std::abs (r[(std::size_t) D]) < 1e-12f);
  6555. }
  6556. // the compressor: Maximus states of our own (no preset data), checked against SG_x64.dll by REA round 36
  6557. using Env = std::vector<std::array<double, 4>>;
  6558. const Env def { { 0.0, 0.0, 0.0, 0 }, { 0.5, 0.5, 0.0, 0 }, { 0.5, 0.5, 0.0, 0 } };
  6559. 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,
  6560. int sus = 2882) { return std::array<int, 13> { mode, pre, post, sep, sat, ceil, att, rel2, 2, 5000, 3, sus, 0 }; };
  6561. {
  6562. // master brickwall at −0.22 dB only (bands off / compression off)
  6563. const auto st = maximusTestState ({ 19800, 1, 48065, 1, 1115, 1000, -1 }, { band (3), band (1), band (3), band (0) },
  6564. { def, def, def, def, def, def, def, def }, 0);
  6565. const auto preset = lynx::hlfx::makeMaximusPreset (st);
  6566. CHECK (preset != nullptr);
  6567. std::array<int, 100> p {};
  6568. p[98] = 1000;
  6569. const auto [l, r] = run (p, 1, preset, 4096, 4096);
  6570. // SG_x64.dll's own output (EXEC, REA_rodada40: bit-identical to the port)
  6571. const std::tuple<int, float, float> golden[] { { 100, 0.024997942f, 0.88166064f }, { 1000, 0.56971401f, -0.62808102f },
  6572. { 2047, -0.27541628f, 0.709135f }, { 3000, 0.32431623f, -0.37985197f },
  6573. { 4095, -0.12743522f, -0.15237485f } };
  6574. for (const auto& [i, gl, gr] : golden)
  6575. CHECK (std::abs (l[(std::size_t) i] - gl) < 2e-6f && std::abs (r[(std::size_t) i] - gr) < 2e-6f);
  6576. float peak = 0.0f;
  6577. for (int i = 2048; i < 4096; ++i)
  6578. peak = std::max ({ peak, std::abs (l[(std::size_t) i]), std::abs (r[(std::size_t) i]) });
  6579. CHECK (peak < 0.9751f);
  6580. }
  6581. {
  6582. // 24 dB crossovers, ×2 oversampling, low cut, stereo separation, saturation A, a knee with tension (type 7) and
  6583. // exponential tensions (type 0), release 2 on the master, band mix 600
  6584. const Env knee { { 0.0, 0.0, 0.0, 0 }, { 0.35, 0.35, 0.0, 0 }, { 0.65, 0.6, 0.36, 7 } };
  6585. const Env t0 { { 0.0, 0.0, 0.0, 0 }, { 0.5, 0.5, 0.14, 0 }, { 0.5, 0.5, 0.0, 0 } };
  6586. const Env m0 { { 0.0, 0.0, 0.0, 0 }, { 0.5, 0.5, 0.0, 0 }, { 0.5, 0.6, 0.085, 0 } };
  6587. const auto st = maximusTestState ({ 19800, 1, 48065, 1, 891, 600, 32768 },
  6588. { band (1, 1264, 1296, 500, -500, 1200), band (0, 1340, 1000, -348, 0, 1000, 1115, 0, 1570),
  6589. band (0, 1364, 1152, 0, 0, 1000, 1115, 0, 1186), band (0, 1000, 1000, 0, -196, 1000, 1115, 4464, 1538) },
  6590. { def, def, knee, def, t0, def, m0, def }, 1);
  6591. const auto preset = lynx::hlfx::makeMaximusPreset (st);
  6592. CHECK (preset != nullptr);
  6593. std::array<int, 100> p {};
  6594. p[98] = 600;
  6595. const auto [l, r] = run (p, 2, preset, 4096, 4096);
  6596. // SG_x64.dll's own output (EXEC, REA_rodada40; the port is within −142 dB of it)
  6597. const std::tuple<int, float, float> golden[] { { 100, 0.0f, 0.0f }, { 1000, -0.46856543f, -0.63262129f },
  6598. { 2047, 0.20268451f, 0.54145539f }, { 3000, -0.25613472f, -0.49985155f },
  6599. { 4095, 0.10172445f, 0.050564945f } };
  6600. for (const auto& [i, gl, gr] : golden)
  6601. CHECK (std::abs (l[(std::size_t) i] - gl) < 2e-6f && std::abs (r[(std::size_t) i] - gr) < 2e-6f);
  6602. }
  6603. {
  6604. // an .fst wrapper around a state is found; unsupported states are rejected
  6605. const auto st = maximusTestState ({ 19800, 1, 48065, 1, 1115, 1000, -1 }, { band (3), band (1), band (3), band (0) },
  6606. { def, def, def, def, def, def, def, def }, 0);
  6607. std::vector<std::uint8_t> fst { 'F', 'L', 'h', 'd', 6, 0, 0, 0, 0, 0, 1, 0, 0x60, 0, 'F', 'L', 'd', 't' };
  6608. std::vector<std::uint8_t> body { 0xC9, 8, 'M', 'a', 'x', 'i', 'm', 'u', 's', 0, 0xD5 };
  6609. for (auto n = st.size(); ; n >>= 7)
  6610. {
  6611. body.push_back ((std::uint8_t) ((n & 0x7f) | (n >= 0x80 ? 0x80 : 0)));
  6612. if (n < 0x80)
  6613. break;
  6614. }
  6615. body.insert (body.end(), st.begin(), st.end());
  6616. const auto len = (std::uint32_t) body.size();
  6617. for (int k = 0; k < 4; ++k)
  6618. fst.push_back ((std::uint8_t) (len >> (8 * k)));
  6619. fst.insert (fst.end(), body.begin(), body.end());
  6620. const auto found = lynx::hlfx::maximusStateFromFst (fst);
  6621. CHECK (found && *found == st);
  6622. auto rms = st;
  6623. rms[4 + 4 * (7 + 13 * 3 + 12)] = 1; // RMS detector on the master (decoded in REA_rodada40)
  6624. CHECK (lynx::hlfx::makeMaximusPreset (rms) != nullptr);
  6625. auto masterMid = st;
  6626. masterMid[0x1fc] = 1; // "Master Mid mode": not decoded
  6627. CHECK (lynx::hlfx::makeMaximusPreset (masterMid) == nullptr);
  6628. }
  6629. }
  6630. TEST (maximus_engine)
  6631. {
  6632. // REA_rodada40: the engine on its own (MaximusProcessor), states of our own against the installation's DLLs
  6633. // (goldens = the DLL's output for the same input, EXEC), and the containers of the mixer effect and Vocodex
  6634. std::vector<float> inL (4096), inR (4096);
  6635. for (int i = 0; i < 4096; ++i)
  6636. {
  6637. 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));
  6638. inR[(std::size_t) i] = (float) (1.2 * std::sin (2.0 * 3.141592653589793 * 660.0 * i / 44100.0));
  6639. }
  6640. auto run = [&] (std::shared_ptr<const lynx::hlfx::MaximusPreset> preset, int mix) {
  6641. lynx::hlfx::MaximusProcessor m;
  6642. m.prepare (std::move (preset), 44100.0, mix);
  6643. std::vector<float> l (inL), r (inR);
  6644. for (int s = 0; s < 4096; s += 512)
  6645. m.process (l.data() + s, r.data() + s, 512);
  6646. return std::make_pair (l, r);
  6647. };
  6648. using Env = std::vector<std::array<double, 4>>;
  6649. const Env def { { 0.0, 0.0, 0.0, 0 }, { 0.5, 0.5, 0.0, 0 }, { 0.5, 0.5, 0.0, 0 } };
  6650. const Env knee { { 0.0, 0.0, 0.0, 0 }, { 0.35, 0.35, 0.0, 0 }, { 0.65, 0.6, 0.36, 7 } };
  6651. const Env t0 { { 0.0, 0.0, 0.0, 0 }, { 0.5, 0.5, 0.14, 0 }, { 0.5, 0.5, 0.0, 0 } };
  6652. const Env m0 { { 0.0, 0.0, 0.0, 0 }, { 0.5, 0.5, 0.0, 0 }, { 0.5, 0.6, 0.085, 0 } };
  6653. 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,
  6654. int sus = 2882, int rms = 0) { return std::array<int, 13> { mode, pre, post, sep, sat, ceil, att, rel2, 2, 5000, 3, sus, rms }; };
  6655. auto check = [] (const std::pair<std::vector<float>, std::vector<float>>& out, const std::vector<std::tuple<int, float, float>>& golden) {
  6656. for (const auto& [i, gl, gr] : golden)
  6657. CHECK (std::abs (out.first[(std::size_t) i] - gl) < 2e-6f && std::abs (out.second[(std::size_t) i] - gr) < 2e-6f);
  6658. };
  6659. // RMS detectors, saturation mode B, a 5 Hz low cut, 12 dB high split (SG_x64.dll: port within −152 dB)
  6660. auto st3 = maximusTestState ({ 19800, 1, 48065, 0, 1115, 1000, 0 },
  6661. { band (0, 1500, 1000, 0, 400, 900, 1115, 0, 2882, 1), band (0, 1340, 1000, 0, 0, 1000, 1115, 0, 1570, 1),
  6662. band (1, 1000, 1200, 0, 1000, 1000), band (0, 1000, 1000, 0, 250, 1000, 1115, 4464, 2882, 1) },
  6663. { def, def, knee, def, t0, def, m0, def }, 0);
  6664. const auto p3 = lynx::hlfx::makeMaximusPreset (st3);
  6665. CHECK (p3 != nullptr);
  6666. check (run (p3, 1000), { { 100, 0.0f, 0.0f }, { 1000, 0.87061065f, 0.64004499f }, { 2047, -0.97266865f, 0.60940075f },
  6667. { 3000, 0.96658099f, 0.9250561f }, { 4095, 0.99094611f, -0.964059f } });
  6668. // the same with solo on (UI byte 0x1EF) and the low band selected (0x1E0): bit-identical to SG_x64.dll
  6669. auto solo = st3;
  6670. solo[0x1ef] = 1;
  6671. std::memset (solo.data() + 0x1e0, 0, 4);
  6672. check (run (lynx::hlfx::makeMaximusPreset (solo), 1000),
  6673. { { 100, 3.2922967e-06f, 0.00036916698f }, { 1000, 0.15653539f, -0.047913823f }, { 2047, -0.17336531f, 0.019099623f },
  6674. { 3000, 0.17185682f, -0.017173048f }, { 4095, 0.16714551f, 0.019473195f } });
  6675. // the legacy linear-phase FIR band split (UI byte 0x1FD; SG_x64.dll: port within −148 dB)
  6676. auto fir = st3;
  6677. fir[0x1fd] = 1;
  6678. check (run (lynx::hlfx::makeMaximusPreset (fir), 1000),
  6679. { { 100, 0.0f, 0.0f }, { 1000, 0.97986746f, 0.18555209f }, { 2047, -0.98930448f, -0.95970845f },
  6680. { 3000, 0.98856646f, -0.44592777f }, { 4095, 0.99069679f, 0.94382554f } });
  6681. // Soundgoodizer_x64.dll's own build with a v4 file (its presets' layout): a copy of the round-36 state without
  6682. // oversampling, through a byte-identical copy of the installation's DLL with this file as its preset (EXEC)
  6683. const auto st2 = maximusTestState ({ 19800, 1, 48065, 1, 891, 600, 32768 },
  6684. { band (1, 1264, 1296, 500, -500, 1200), band (0, 1340, 1000, -348, 0, 1000, 1115, 0, 1570),
  6685. band (0, 1364, 1152, 0, 0, 1000, 1115, 0, 1186), band (0, 1000, 1000, 0, -196, 1000, 1115, 4464, 1538) },
  6686. { def, def, knee, def, t0, def, m0, def }, 0);
  6687. std::vector<std::uint8_t> v4 { 4, 0, 0, 0 };
  6688. v4.insert (v4.end(), st2.begin() + 4, st2.begin() + 0x1f5);
  6689. v4.insert (v4.end(), st2.begin() + 0x1fe, st2.end());
  6690. const auto p4 = lynx::hlfx::makeMaximusPreset (v4, lynx::hlfx::MaximusBuild::soundgoodizer);
  6691. CHECK (p4 != nullptr);
  6692. check (run (p4, 600), { { 100, 0.0f, 0.0f }, { 1000, -0.60926896f, -0.6652832f }, { 2047, 0.40872875f, 0.36375371f },
  6693. { 3000, -0.41941205f, -0.61312866f }, { 4095, -0.12878418f, 0.27944946f } });
  6694. CHECK (lynx::hlfx::makeMaximusPreset (st2, lynx::hlfx::MaximusBuild::soundgoodizer) != nullptr); // v7: also read by that build
  6695. // the mixer effect's container and the effect itself
  6696. lynx::maximusfx::Blob blob;
  6697. blob.build = lynx::hlfx::MaximusBuild::soundgoodizer;
  6698. blob.mix = 600;
  6699. blob.state = v4;
  6700. const auto packed = lynx::maximusfx::pack (blob);
  6701. const auto back = lynx::maximusfx::unpack (packed);
  6702. CHECK (back && back->build == blob.build && back->mix == 600 && back->state == v4);
  6703. auto slot = lynx::makeEffectSlot (lynx::EffectKind::maximus);
  6704. slot.state = packed;
  6705. auto fx = lynx::makeEffect (slot);
  6706. fx->prepare (44100.0);
  6707. {
  6708. std::vector<float> l (inL), r (inR);
  6709. for (int s = 0; s < 4096; s += 1024) // longer host blocks are split into the engine's 512-frame calls
  6710. fx->process (l.data() + s, r.data() + s, 1024, slot.params, 120.0);
  6711. const auto ref = run (p4, 600);
  6712. CHECK (l == ref.first && r == ref.second);
  6713. }
  6714. const std::vector<std::uint8_t> sgState { 3, 0, 0, 0, 2, 0, 0, 0, 0x78, 2, 0, 0 };
  6715. const auto sg = lynx::maximusfx::parseSoundgoodizer (sgState);
  6716. CHECK (sg && sg->preset == 2 && sg->amount == 632 && std::string (lynx::maximusfx::soundgoodizerPresetFile (2)) == "c.dat");
  6717. CHECK (lynx::soundgoodizerPresetPath (sgState) == "Plugins\\Fruity\\Effects\\Soundgoodizer\\Data\\Presets\\c.dat");
  6718. CHECK (lynx::soundgoodizerExact (sgState, v4).has_value() && ! lynx::soundgoodizerExact (sgState, {}).has_value());
  6719. // Vocodex's appended installation data survives a round trip and leaves FL's state untouched
  6720. const std::vector<std::uint8_t> flState { 8, 0, 0, 0, 1, 2, 3 };
  6721. lynx::vocodex::InstallData data;
  6722. data.sgDat = st2;
  6723. data.carrierState = { 9, 9, 9 };
  6724. const auto joined = lynx::vocodex::appendInstallData (flState, data);
  6725. const auto [raw, files] = lynx::vocodex::splitInstallData (joined);
  6726. CHECK (raw == flState && files.sgDat == st2 && files.carrierState == data.carrierState);
  6727. CHECK (lynx::vocodex::splitInstallData (flState).first == flState);
  6728. }
  6729. // ---- Sytrus (REA_rodada31) -------------------------------------------------------------------------------------------
  6730. // A Sytrus state built from scratch (version 25 layout, our own values — no FL preset data), zlib "stored" blocks.
  6731. namespace
  6732. {
  6733. struct SytrusTestPatch
  6734. {
  6735. std::vector<std::int32_t> main = std::vector<std::int32_t> (240, 0); // 962-byte main block as ints (+ mute bytes)
  6736. struct Op
  6737. {
  6738. int p[10] { 0, 256, 0, 0, 0, 0, 0, 0, 0, 0 };
  6739. int ratio = 20000, offset = 0, noise = 0;
  6740. std::vector<float> amps { 1.0f };
  6741. std::uint8_t flags[8] {};
  6742. int env1[3] { -1, -1, -1 }; // volume envelope: on (≠ −1 → on), decay point, sustain point
  6743. std::vector<std::pair<double, double>> env1pts;
  6744. } ops[6];
  6745. struct Filt
  6746. {
  6747. int p[10] { 0, 0, 128, 0, 128, 0, 0, 128, 128, 0 };
  6748. int type = 3;
  6749. } filts[3];
  6750. std::array<std::array<std::uint8_t, 23>, 3> delays {};
  6751. std::array<std::int32_t, 9> reverb { 19, 221, 0, 50, 80, 30, 221, 2, 0 };
  6752. bool reverbOn = false;
  6753. int eqmode = 0;
  6754. SytrusTestPatch()
  6755. {
  6756. main[0] = 128, main[1] = 128;
  6757. for (int i = 0; i < 8; ++i)
  6758. main[(std::size_t) (165 + i)] = (i % 4 == 2) ? 0 : 128;
  6759. main[173] = 1, main[175] = 128, main[188] = 128, main[189] = -1, main[190] = main[191] = 256;
  6760. }
  6761. void cell (int layer, int row, int col, int v) { main[(std::size_t) (3 + layer * 81 + row * 9 + col)] = v; }
  6762. std::vector<std::uint8_t> blob() const
  6763. {
  6764. std::vector<std::uint8_t> b;
  6765. 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))); };
  6766. auto f32 = [&] (float v) { std::int32_t x; std::memcpy (&x, &v, 4); i32 (x); };
  6767. 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))); };
  6768. // point lists: kind 1 envelope, 2 LFO, 3 map / shaper curve; format version 3
  6769. auto env = [&] (int kind, const std::vector<std::pair<double, double>>& pts, int on, int decay, int sus) {
  6770. i32 (kind), i32 (3), i32 ((std::int32_t) pts.size());
  6771. for (const auto& [dt, y] : pts)
  6772. f64 (dt), f64 (y), f32 (0.0f), i32 (0);
  6773. i32 (0), i32 (on), i32 (decay), i32 (-1), i32 (sus);
  6774. };
  6775. for (int i = 0; i < 240; ++i)
  6776. if (4 * i + 4 <= 0x320)
  6777. i32 (main[(std::size_t) i]);
  6778. b.resize (962, 0); // mute bytes: none muted
  6779. i32 (0); // global declick amount
  6780. b.push_back (0), b.push_back (0), b.push_back (0); // OSC grouping, DC stage, GIBBS OFF
  6781. for (int k = 0; k < 9; ++k)
  6782. b.push_back (k == 7 ? 1 : 0); // flag group (release multiplier on, as Default.fst)
  6783. for (const auto& d : delays)
  6784. b.insert (b.end(), d.begin(), d.end());
  6785. for (auto v : reverb)
  6786. i32 (v);
  6787. b.push_back (reverbOn ? 1 : 0), b.push_back (0);
  6788. i32 (eqmode);
  6789. for (int k = 0; k < 3; ++k)
  6790. i32 (0), i32 (30000), i32 (20000), i32 (k);
  6791. b.push_back (0); // no info text
  6792. for (int u = 0; u < 10; ++u)
  6793. {
  6794. const int narts = u < 6 ? 6 : (u < 9 ? 8 : 2);
  6795. for (int j = 0; j < 10; ++j)
  6796. i32 (u < 6 ? ops[u].p[j] : (u < 9 ? filts[u - 6].p[j] : 0));
  6797. if (u < 6)
  6798. {
  6799. const auto& o = ops[u];
  6800. const auto at = b.size();
  6801. b.resize (at + 0x828, 0);
  6802. auto put = [&] (std::size_t off, const void* src, std::size_t n) { std::memcpy (b.data() + at + off, src, n); };
  6803. put (0, &o.ratio, 4), put (4, &o.offset, 4), put (8, &o.noise, 4);
  6804. put (0xc, o.amps.data(), 4 * o.amps.size());
  6805. const std::int32_t shape[5] { 0, 0, 0, 0, 128 };
  6806. put (0x80c, shape, sizeof shape);
  6807. put (0x820, o.flags, 8);
  6808. }
  6809. else if (u < 9)
  6810. {
  6811. const auto at = b.size();
  6812. b.resize (at + 0x30, 0);
  6813. std::memcpy (b.data() + at + 0x2c, &filts[u - 6].type, 4);
  6814. env (3, { { 0.0, 0.0 }, { 1.0, 1.0 } }, 0, -1, -1);
  6815. b.push_back (0);
  6816. }
  6817. for (int k = 0; k < narts; ++k)
  6818. {
  6819. const bool add = k == 0 || k == 3 || (u >= 6 && u <= 8 && (k == 2 || k == 3)) || (u < 6 && k == 4);
  6820. const double neutral = add ? 0.5 : 1.0;
  6821. i32 (3), i32 (0), f32 (1.0f), f32 (1.0f);
  6822. if (u < 6 && k == 1 && ops[u].env1[0] != -1)
  6823. env (1, ops[u].env1pts, -1, ops[u].env1[1], ops[u].env1[2]);
  6824. else
  6825. env (1, { { 0.0, 0.0 }, { 1.0, 1.0 } }, 0, -1, -1);
  6826. i32 (128), i32 (128), i32 (0), i32 (128);
  6827. env (2, { { 0.0, 1.0 }, { 1.0, 1.0 } }, 0, -1, -1);
  6828. i32 (40000), i32 (0), i32 (0), i32 (0), i32 (0);
  6829. for (int m = 0; m < 6; ++m)
  6830. env (3, { { 0.0, neutral }, { 1.0, neutral } }, 0, -1, -1);
  6831. }
  6832. }
  6833. b.push_back (0), b.push_back (0);
  6834. // zlib with stored blocks
  6835. std::vector<std::uint8_t> z { 0x78, 0x01 };
  6836. for (std::size_t at = 0; at < b.size(); at += 65535)
  6837. {
  6838. const auto n = std::min<std::size_t> (65535, b.size() - at);
  6839. z.push_back (at + n >= b.size() ? 1 : 0);
  6840. z.push_back ((std::uint8_t) n), z.push_back ((std::uint8_t) (n >> 8));
  6841. z.push_back ((std::uint8_t) ~n), z.push_back ((std::uint8_t) (~n >> 8));
  6842. z.insert (z.end(), b.begin() + (std::ptrdiff_t) at, b.begin() + (std::ptrdiff_t) (at + n));
  6843. }
  6844. std::uint32_t a = 1, c = 0;
  6845. for (auto x : b)
  6846. a = (a + x) % 65521, c = (c + a) % 65521;
  6847. for (int k = 3; k >= 0; --k)
  6848. z.push_back ((std::uint8_t) (((c << 16) | a) >> (8 * k)));
  6849. std::vector<std::uint8_t> out { 25, 0, 0, 0 };
  6850. out.insert (out.end(), z.begin(), z.end());
  6851. return out;
  6852. }
  6853. };
  6854. // renders like FL's Gen_Render calls: notes start/release at the block that contains them
  6855. std::pair<std::vector<float>, std::vector<float>> sytrusRender (const std::vector<std::uint8_t>& blob, bool renderMode, int n,
  6856. std::vector<std::array<int, 3>> notes, double fs = 44100.0)
  6857. {
  6858. lynx::sytrus::Engine e;
  6859. e.setTempo (120.0);
  6860. e.prepare (fs, renderMode, 512);
  6861. e.setPatch (lynx::sytrus::parsePatch (blob));
  6862. std::vector<float> l ((std::size_t) n), r ((std::size_t) n);
  6863. for (int n0 = 0; n0 < n; n0 += 512)
  6864. {
  6865. for (std::size_t k = 0; k < notes.size(); ++k)
  6866. {
  6867. if (notes[k][1] >= n0 && notes[k][1] < n0 + 512)
  6868. {
  6869. lynx::sytrus::NoteParams p;
  6870. p.key = (float) notes[k][0];
  6871. p.id = (std::int64_t) k + 1;
  6872. e.noteOn (p);
  6873. }
  6874. if (notes[k][2] >= n0 && notes[k][2] < n0 + 512)
  6875. e.release ((std::int64_t) k + 1);
  6876. }
  6877. e.render (l.data() + n0, r.data() + n0, std::min (512, n - n0), 1.0f, 0.0f);
  6878. }
  6879. return { l, r };
  6880. }
  6881. } // namespace
  6882. TEST (sytrus_engine_sine)
  6883. {
  6884. // one sine operator, ratio 1, OUT 256, no envelopes: C5 = 523.2511 Hz at 0.7071 (centre of the pan law, §6.1)
  6885. SytrusTestPatch t;
  6886. t.cell (0, 0, 8, 256);
  6887. const auto blob = t.blob();
  6888. CHECK (lynx::sytrus::stateUsable (blob));
  6889. CHECK (lynx::sytrus::parsePatch (blob) != nullptr);
  6890. auto broken = blob;
  6891. broken.resize (broken.size() / 2);
  6892. CHECK (! lynx::sytrus::stateUsable (broken));
  6893. const auto [l, r] = sytrusRender (blob, false, 8192, { { 60, 0, 4096 } });
  6894. double worst = 0.0;
  6895. for (int k = 0; k < 4000; ++k)
  6896. 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)));
  6897. CHECK (worst < 2e-5);
  6898. CHECK (l == r);
  6899. // 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
  6900. // 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)
  6901. int last = 0;
  6902. for (int k = 0; k < 8192; ++k)
  6903. if (l[(std::size_t) k] != 0.0f)
  6904. last = k;
  6905. CHECK (last == 4895);
  6906. // key 69 = 880 Hz; 48 kHz
  6907. const auto [l2, r2] = sytrusRender (blob, false, 4096, { { 69, 0, -1 } }, 48000.0);
  6908. worst = 0.0;
  6909. for (int k = 0; k < 4000; ++k)
  6910. 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)));
  6911. CHECK (worst < 5e-5);
  6912. (void) r2;
  6913. }
  6914. TEST (sytrus_engine_reference)
  6915. {
  6916. // FM 2→1, Vanilla LP filter, volume envelope, unison 3, delay and reverb, 2× oversampling with the 8-sample
  6917. // envelope tick (render settings): against our Python reference model of REA_rodada31 (sytmodel.render)
  6918. SytrusTestPatch t;
  6919. t.main[195] = 0, t.main[196] = 1, t.main[193] = 0, t.main[194] = 1;
  6920. t.main[173] = 3, t.main[174] = 64, t.main[176] = 100;
  6921. t.ops[1].ratio = 40000;
  6922. t.cell (0, 0, 1, 128); // op 2 → op 1 FM
  6923. t.cell (0, 0, 8, 128);
  6924. t.cell (0, 6, 0, 256); // op 1 → filter 1
  6925. t.cell (0, 6, 8, 256);
  6926. t.cell (0, 0, 7, 200); // FX send
  6927. t.filts[0].p[0] = 1, t.filts[0].p[2] = 180, t.filts[0].p[3] = 60;
  6928. t.ops[0].env1[0] = 0, t.ops[0].env1[1] = 1, t.ops[0].env1[2] = 2;
  6929. t.ops[0].env1pts = { { 0.0, 0.0 }, { 0.05, 1.0 }, { 0.1, 0.6 }, { 0.2, 0.0 } };
  6930. const std::int32_t d0[5] { 40, 100, 50, 100, 0 };
  6931. std::memcpy (t.delays[0].data(), d0, 20);
  6932. t.delays[0][22] = 1;
  6933. t.reverb = { 19, 221, 10, 50, 80, 30, 100, 2, 100 };
  6934. t.reverbOn = true;
  6935. const auto blob = t.blob();
  6936. const auto [l, r] = sytrusRender (blob, true, 12000, { { 60, 0, 6000 } });
  6937. // reference values (model render_mode=True, 44.1 kHz, block 512, key 60, velocity 0.78125, release at 6000); the same
  6938. // state rendered by FL's own Sytrus DLL in render mode differs from this by −136 dB (EXEC, REA round 31 harness)
  6939. const std::array<std::pair<int, float>, 8> golden { { { 100, -0.00235529384f }, { 777, -0.175126165f }, { 2000, 0.30976975f }, { 4321, -0.0213534199f },
  6940. { 6100, 0.202372357f }, { 7000, 0.249530748f }, { 9000, 0.0307101421f }, { 11999, 0.176390275f } } };
  6941. for (const auto& [i, v] : golden)
  6942. CHECK (std::abs (l[(std::size_t) i] - v) < 1e-6f);
  6943. const std::array<std::pair<int, float>, 3> goldenR { { { 777, -0.166890964f }, { 4321, -0.212358952f }, { 9000, -0.0251909085f } } };
  6944. for (const auto& [i, v] : goldenR)
  6945. CHECK (std::abs (r[(std::size_t) i] - v) < 1e-6f);
  6946. }
  6947. TEST (sytrus_instrument)
  6948. {
  6949. // the LYNX instrument: state in ChannelDef::pluginState, channel volume/pan recovered from the rack gains
  6950. SytrusTestPatch t;
  6951. t.cell (0, 0, 8, 256);
  6952. lynx::ChannelDef c;
  6953. c.instrument = lynx::InstrumentKind::sytrus;
  6954. c.pluginState = t.blob();
  6955. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sytrus);
  6956. inst->prepare (44100.0);
  6957. inst->configure (c, 120.0);
  6958. CHECK (inst->idle());
  6959. std::vector<float> l (4096), r (4096);
  6960. inst->noteOn (60, 100.0f / 128.0f);
  6961. // 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
  6962. inst->render (l.data(), r.data(), 4096, 0.5f, 0.5f);
  6963. double peak = 0.0;
  6964. for (int k = 1000; k < 4096; ++k)
  6965. peak = std::max (peak, (double) std::abs (l[(std::size_t) k]));
  6966. CHECK (std::abs (peak - 0.5 * 0.70710678) < 1e-3); // Final.Vol 0.5 × the plugin's centre pan law
  6967. CHECK (! inst->idle());
  6968. inst->noteOff (60);
  6969. std::vector<float> tail (44100 * 3), tailR (tail.size());
  6970. inst->render (tail.data(), tailR.data(), (int) tail.size(), 0.5f, 0.5f);
  6971. CHECK (inst->idle());
  6972. CHECK (tail.back() == 0.0f);
  6973. }
  6974. TEST (harmor_effects_rack)
  6975. {
  6976. // REA_rodada38: the rack runs in the state's unit order and the records' FX send joins it at unit 4 — with the FX
  6977. // amount at 1000 every record output bypasses a reverb placed before unit 4 (EXEC: −600 dB vs the rack off)
  6978. auto blob = harmorTestState (false);
  6979. auto set = [&] (std::vector<std::uint8_t>& st, int part, int index, std::int32_t v) {
  6980. std::memcpy (st.data() + lynx::harmorParamOffset (st, part, index), &v, 4);
  6981. };
  6982. set (blob, 0, 10, 1000); // all to the FX send
  6983. auto render = [] (const std::vector<std::uint8_t>& st) {
  6984. return lynx::harmor::renderReference (st, { { 0, 60, 0.8, 1.0, 0.0, 6000 } }, 44100.0, 12000);
  6985. };
  6986. const auto dry = render (blob);
  6987. auto rev = blob;
  6988. set (rev, -1, 22, 1); // reverb on: room 50, diffusion 100, decay 2^3·0.1 s, high cut / damping off, wet 0.8
  6989. 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);
  6990. set (rev, -1, 30, 2), set (rev, -1, 31, 800);
  6991. const auto bypassed = render (rev);
  6992. double eb = 0.0, db = 0.0;
  6993. for (std::size_t i = 0; i < dry.size(); ++i)
  6994. eb += (double) (bypassed[i] - dry[i]) * (bypassed[i] - dry[i]), db += (double) dry[i] * dry[i];
  6995. CHECK (eb < 1e-12 * db && db > 1e-3); // (float rounding of the rack's buffers only)
  6996. auto after = rev;
  6997. const std::int32_t order[6] { 0, 1, 2, 4, 3, 5 }; // the join before the reverb
  6998. for (int k = 0; k < 6; ++k)
  6999. set (after, -1, 53 + k, order[k]);
  7000. const auto wet = render (after);
  7001. double e = 0.0, d = 0.0;
  7002. bool finite = true;
  7003. for (std::size_t i = 0; i < wet.size(); ++i)
  7004. e += (double) (wet[i] - dry[i]) * (wet[i] - dry[i]), d += (double) dry[i] * dry[i], finite = finite && std::isfinite (wet[i]);
  7005. CHECK (finite && e > 1e-4 * d && d > 1e-3);
  7006. // a distortion (type 6) and a delay on the dry path change the sound, stay finite, and the instrument ends quiet
  7007. auto dist = harmorTestState (false);
  7008. {
  7009. const auto at = lynx::harmorParamOffset (dist, -1, 0) + 0xd4 + 0x18 + 48; // global misc +48: distortion type
  7010. const std::int32_t six = 6;
  7011. std::memcpy (dist.data() + at, &six, 4);
  7012. }
  7013. set (dist, -1, 17, 600), set (dist, -1, 19, 1000), set (dist, -1, 21, 1100);
  7014. 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);
  7015. set (dist, -1, 47, 1050);
  7016. lynx::ChannelDef c;
  7017. c.instrument = lynx::InstrumentKind::harmor;
  7018. c.pluginState = dist;
  7019. auto inst = lynx::makeInstrument (lynx::InstrumentKind::harmor);
  7020. inst->configure (c, 120.0);
  7021. inst->prepare (44100.0);
  7022. std::vector<float> l (44100 * 4), r (l.size());
  7023. inst->noteOn (60, 0.8f);
  7024. double energy = 0.0;
  7025. for (int s = 0; s < (int) l.size(); s += 512)
  7026. {
  7027. if (s == 8192)
  7028. inst->noteOff (60);
  7029. inst->render (l.data() + s, r.data() + s, 512, 1.0f, 1.0f);
  7030. }
  7031. for (std::size_t i = 0; i < l.size(); ++i)
  7032. finite = finite && std::isfinite (l[i]) && std::isfinite (r[i]), energy += (double) l[i] * l[i];
  7033. CHECK (finite && energy > 1.0);
  7034. std::vector<float> tail (44100 * 6), tailR (tail.size());
  7035. for (int s = 0; s < (int) tail.size(); s += 512)
  7036. inst->render (tail.data() + s, tailR.data() + s, 512, 1.0f, 1.0f);
  7037. CHECK (inst->idle());
  7038. }
  7039. TEST (harmless_engine)
  7040. {
  7041. // REA_rodada32: state parsing, the additive engine against our reference model (hlmodel.py), host levels, voice end
  7042. std::vector<std::uint8_t> blob;
  7043. 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))); };
  7044. std::array<std::int32_t, 100> p {}; // the reference's clean patch: Saw, open filter, no modulation
  7045. for (int i = 11; i < 23; ++i)
  7046. p[(std::size_t) i] = 1000;
  7047. 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;
  7048. 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;
  7049. // + resonance, pluck, 3-voice unison, tremolo, LFO on pitch
  7050. 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;
  7051. put (12);
  7052. for (auto v : p)
  7053. put (v);
  7054. for (int i = 0; i < 7; ++i)
  7055. put (0);
  7056. put (524); // Custom colour table: 524 × (amplitude, phase)
  7057. for (int i = 0; i < 1048; ++i)
  7058. {
  7059. const auto f = i < 524 ? 1.0f / (float) (i + 1) : 0.25f;
  7060. std::uint32_t bits = 0;
  7061. std::memcpy (&bits, &f, 4);
  7062. put ((std::int32_t) bits);
  7063. }
  7064. const auto parsed = lynx::harmlessParams (blob);
  7065. CHECK (parsed && (int) parsed->size() == lynx::harmlessParamCount);
  7066. CHECK (parsed && (*parsed)[54] == 3500.0f && (*parsed)[99] == 0.0f && (*parsed)[lynx::harmlessCustomFlagIndex] == 1.0f);
  7067. CHECK (parsed && (*parsed)[lynx::harmlessCustomIndex + 1] == 0.5f && (*parsed)[lynx::harmlessCustomIndex + 524] == 0.25f);
  7068. auto old = blob;
  7069. old[0] = 3; // versions below 4 are not Harmless states we know
  7070. CHECK (! lynx::harmlessParams (old));
  7071. old = blob;
  7072. old.resize (300);
  7073. CHECK (! lynx::harmlessParams (old));
  7074. lynx::ChannelDef c;
  7075. c.instrument = lynx::InstrumentKind::harmless;
  7076. c.modelParams = *parsed;
  7077. c.modelParams[lynx::harmlessCustomFlagIndex] = 0.0f; // colour 0 (Saw): the custom table is not read
  7078. auto render = [] (const lynx::ChannelDef& def, int total, float gl, float gr, int offAt) {
  7079. auto inst = lynx::makeInstrument (lynx::InstrumentKind::harmless);
  7080. inst->configure (def, 120.0);
  7081. inst->prepare (44100.0);
  7082. std::vector<float> l ((std::size_t) total), r ((std::size_t) total);
  7083. inst->noteOn (60, 0.78125f);
  7084. for (int s = 0; s < total; s += 512)
  7085. {
  7086. if (s == offAt)
  7087. inst->noteOff (60);
  7088. inst->render (l.data() + s, r.data() + s, std::min (512, total - s), gl, gr);
  7089. }
  7090. return std::make_tuple (l, r, std::move (inst));
  7091. };
  7092. {
  7093. // reference model (REA round 32 hlmodel.py, C5 at FL velocity 100, channel volume 1, centre, released at 6144)
  7094. auto [l, r, inst] = render (c, 8192, 1.0f, 1.0f, 6144);
  7095. const std::tuple<int, float, float> golden[] {
  7096. { 0, 0.0f, 0.0f }, { 10, -0.02220994f, -0.06232700f }, { 100, 0.40623373f, 0.17308202f }, { 1000, -0.04091963f, -0.26821208f },
  7097. { 3000, 0.14519004f, 0.11027778f }, { 6000, 0.50411958f, 0.27901855f }, { 8191, 0.02117692f, -0.01466602f } };
  7098. for (const auto& [i, gl, gr] : golden)
  7099. CHECK (std::abs (l[(std::size_t) i] - gl) < 2e-6f && std::abs (r[(std::size_t) i] - gr) < 2e-6f);
  7100. // after the release the record fades out (below 1e-4, then 30 ms) and the instrument goes idle
  7101. std::vector<float> tail (44100), tailR (tail.size());
  7102. inst->render (tail.data(), tailR.data(), (int) tail.size(), 1.0f, 1.0f);
  7103. CHECK (inst->idle());
  7104. }
  7105. // FL's level law applied once: half the channel volume halves the output; full right pan silences the left side
  7106. const auto full = std::get<0> (render (c, 2048, 1.0f, 1.0f, -1));
  7107. const auto half = std::get<0> (render (c, 2048, 0.5f, 0.5f, -1));
  7108. CHECK (std::abs (half[100] - 0.5f * full[100]) < 1e-6f && std::abs (full[100]) > 0.1f);
  7109. auto mono = c;
  7110. mono.modelParams[25] = 0.0f; // no tremolo, no unison pan spread
  7111. mono.modelParams[65] = 1.0f;
  7112. const auto [pl, pr, pi] = render (mono, 2048, 0.0f, 1.41421356f, -1);
  7113. double el = 0.0, er = 0.0;
  7114. for (int i = 0; i < 2048; ++i)
  7115. el += (double) pl[(std::size_t) i] * pl[(std::size_t) i], er += (double) pr[(std::size_t) i] * pr[(std::size_t) i];
  7116. CHECK (el < 1e-10 * er && er > 1.0);
  7117. }
  7118. TEST (startup_sound)
  7119. {
  7120. // the splash's sound: the right length, finite, at its peak level, quiet before the whoosh swells,
  7121. // a landing "pop" at impactTime and a chime ringing after it
  7122. using namespace lynx::startup;
  7123. const auto sound = makeSound (48000.0);
  7124. CHECK (sound.left.size() == (std::size_t) (soundLength * 48000.0) && sound.right.size() == sound.left.size());
  7125. float peak = 0.0f;
  7126. bool finite = true;
  7127. for (std::size_t i = 0; i < sound.left.size(); ++i)
  7128. {
  7129. finite = finite && std::isfinite (sound.left[i]) && std::isfinite (sound.right[i]);
  7130. peak = std::max ({ peak, std::abs (sound.left[i]), std::abs (sound.right[i]) });
  7131. }
  7132. CHECK (finite && std::abs (peak - peakLevel) < 1.0e-4f);
  7133. auto rms = [&sound] (double from, double to) {
  7134. double e = 0.0;
  7135. const auto a = (std::size_t) (from * 48000.0), b = (std::size_t) (to * 48000.0);
  7136. for (auto i = a; i < b; ++i)
  7137. e += (double) sound.left[i] * sound.left[i];
  7138. return std::sqrt (e / (double) (b - a));
  7139. };
  7140. CHECK (rms (0.0, 0.05) < 0.2 * rms (impactTime - 0.05, impactTime)); // the whoosh swells
  7141. CHECK (rms (impactTime, impactTime + 0.05) > rms (impactTime - 0.05, impactTime)); // the landing
  7142. CHECK (rms (0.8, 1.0) > 0.005 && rms (soundLength - 0.02, soundLength) < rms (0.8, 1.0)); // chime rings, tail fades
  7143. CHECK (makeSound (48000.0).left == sound.left); // the same sound on every start
  7144. }
  7145. namespace
  7146. {
  7147. // little-endian byte writer for the state builders below
  7148. struct Bytes
  7149. {
  7150. std::vector<std::uint8_t> b;
  7151. void raw (const char* s, std::size_t n) { b.insert (b.end(), s, s + n); }
  7152. 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); }
  7153. void f32 (float v) { b.insert (b.end(), reinterpret_cast<const std::uint8_t*> (&v), reinterpret_cast<const std::uint8_t*> (&v) + 4); }
  7154. void zeros (std::size_t n) { b.insert (b.end(), n, 0); }
  7155. void bytes (const std::vector<std::uint8_t>& o) { b.insert (b.end(), o.begin(), o.end()); }
  7156. };
  7157. // A GMS state written from scratch (REA_rodada12 §1.1 layout, "Syn4"): oscillator waves that don't exist (silent
  7158. // tables, so the result does not depend on an FL installation), noise through the ladder with envelope and LFO,
  7159. // unison, slide, distortion, delay, reverb and the output EQ.
  7160. std::vector<std::uint8_t> gmsTestState()
  7161. {
  7162. std::array<float, 212> P {};
  7163. for (int i : { 1, 2, 44, 55, 56, 57, 58, 59, 60, 207, 208, 209, 210, 211 })
  7164. P[(std::size_t) i] = 0.5f;
  7165. P[0] = 0.75f, P[4] = 0.1f, P[5] = 0.4f, P[6] = 0.6f, P[7] = 0.3f, P[8] = 0.8f;
  7166. 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;
  7167. 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;
  7168. P[147] = 1.0f, P[117] = 0.3f, P[127] = 0.6f; // distortion
  7169. P[153] = 1.0f, P[123] = 0.5f, P[133] = 0.4f, P[143] = 0.4f; // delay (1/2 beat)
  7170. P[154] = 1.0f, P[124] = 0.6f, P[134] = 0.5f; // reverb
  7171. P[206] = 1.0f, P[207] = 0.7f, P[211] = 0.3f; // output EQ
  7172. Bytes preset;
  7173. preset.raw ("4nyS", 4);
  7174. for (const char* path : { "NoSuchDir\\NoWave A.wav", "NoSuchDir\\NoWave B.wav", "NoSuchDir\\NoWave C.wav", "", "", "", "" })
  7175. {
  7176. const auto n = std::strlen (path);
  7177. preset.raw (path, n);
  7178. preset.zeros (512 - n);
  7179. }
  7180. preset.i32 (0), preset.i32 (0), preset.i32 (0);
  7181. for (auto v : P)
  7182. preset.f32 (v);
  7183. preset.raw ("LYNX test", 9);
  7184. preset.zeros (512 - 9);
  7185. Bytes s;
  7186. s.raw ("SSLF", 4);
  7187. s.i32 ((std::int32_t) preset.b.size());
  7188. s.bytes (preset.b);
  7189. return s.b;
  7190. }
  7191. // A Morphine state written from scratch (REA_rodada16 §3 / REA_rodada39 §2.2 layout): generators A and B with a few
  7192. // frames each (A loops, PWM on A), C and D silent, a morph line A→B, four envelopes (Eg1 → pitch and velocity →
  7193. // amplitude through the matrix), the master ADSR and every plugin effect on.
  7194. std::vector<std::uint8_t> morphineTestState()
  7195. {
  7196. auto mbp = [] (int seed) {
  7197. Bytes b;
  7198. b.raw ("0PBM", 4);
  7199. for (int a = 0; a < 3; ++a)
  7200. for (int byte = 0; byte < 16; ++byte)
  7201. {
  7202. b.b.push_back (0xff);
  7203. for (int bit = 0; bit < 8; ++bit)
  7204. {
  7205. const auto k = byte * 8 + bit;
  7206. const float v = a == 0 ? std::cbrt (1.0f / (float) (k + 1 + seed * (k % 3))) * (k < 40 ? 1.0f : 0.2f)
  7207. : a == 1 ? 0.1f * (float) ((k * 7 + seed) % 11 - 5) / 5.0f
  7208. : 0.02f * (float) ((k * 5 + seed) % 7 - 3);
  7209. b.f32 (v);
  7210. }
  7211. }
  7212. return b.b;
  7213. };
  7214. auto msp = [&] (int frames, int seed, int loopMode) {
  7215. Bytes b;
  7216. b.raw ("0PSM", 4);
  7217. b.i32 (frames);
  7218. for (int f = 0; f < frames; ++f)
  7219. {
  7220. const auto m = mbp (seed + f);
  7221. b.i32 (20 + 7 * f), b.f32 (1.0f - 0.2f * (float) f), b.i32 ((std::int32_t) m.size());
  7222. b.bytes (m);
  7223. }
  7224. b.i32 (0x424);
  7225. b.i32 (10), b.i32 (40), b.i32 (0), b.i32 (loopMode);
  7226. b.f32 (0.45f), b.f32 (0.6f), b.f32 (0.5f), b.i32 (0);
  7227. for (int k = 0; k < 128; ++k)
  7228. b.f32 (0.3f);
  7229. for (int k = 0; k < 128; ++k)
  7230. b.f32 (1.0f);
  7231. return b.b;
  7232. };
  7233. auto mvc = [&] (int frames, int seed, int pwmMode) {
  7234. Bytes z;
  7235. z.raw ("0HZM", 4);
  7236. z.i32 (1);
  7237. const auto s = msp (frames, seed, 1);
  7238. z.i32 (128), z.f32 (frames > 1 ? 0.9f : 0.0f), z.i32 ((std::int32_t) s.size());
  7239. z.bytes (s);
  7240. Bytes b;
  7241. b.raw ("0CVM", 4);
  7242. b.i32 ((std::int32_t) z.b.size());
  7243. b.bytes (z.b);
  7244. 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);
  7245. return b.b;
  7246. };
  7247. Bytes p;
  7248. p.raw ("0roM", 4);
  7249. p.raw ("0RPM", 4);
  7250. for (const auto& g : { mvc (3, 1, 2), mvc (2, 7, 0), mvc (1, 3, 0), mvc (1, 5, 0) })
  7251. {
  7252. p.i32 ((std::int32_t) g.size());
  7253. p.bytes (g);
  7254. }
  7255. {
  7256. Bytes m;
  7257. m.raw ("0LMM", 4);
  7258. m.i32 (2), m.i32 (12);
  7259. m.f32 (0.0f), m.f32 (1.0f), m.i32 (60);
  7260. m.f32 (1.0f), m.f32 (1.0f), m.i32 (60);
  7261. m.i32 (0x54), m.i32 (0), m.i32 (0), m.i32 (0), m.i32 (0);
  7262. for (float v : { 1.0f, 0.8f, 0.0f, 0.0f, 0.5f, 0.4f, 0.5f, 0.5f })
  7263. m.f32 (v);
  7264. for (int k = 0; k < 4; ++k)
  7265. m.i32 (0);
  7266. m.f32 (0.5f), m.f32 (0.5f), m.f32 (0.5f), m.i32 (0);
  7267. p.i32 ((std::int32_t) m.b.size());
  7268. p.bytes (m.b);
  7269. }
  7270. {
  7271. Bytes d;
  7272. d.raw ("0DMM", 4);
  7273. d.i32 (4);
  7274. for (int e = 0; e < 4; ++e)
  7275. {
  7276. Bytes g;
  7277. g.raw ("0GEM", 4);
  7278. g.i32 (3), g.i32 (8);
  7279. g.f32 (0.0f), g.i32 (10), g.f32 (1.0f), g.i32 (40 + 10 * e), g.f32 (0.3f), g.i32 (50);
  7280. 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),
  7281. g.i32 (e == 0 ? 1 : 0);
  7282. d.i32 ((std::int32_t) g.b.size());
  7283. d.bytes (g.b);
  7284. }
  7285. d.i32 (0x94);
  7286. const int src[12] = { 5, 2 }, dst[12] = { 3, 1 };
  7287. const float amt[12] = { 0.56f, 0.7f };
  7288. for (int k = 0; k < 12; ++k)
  7289. d.i32 (src[k]);
  7290. for (int k = 0; k < 12; ++k)
  7291. d.i32 (dst[k]);
  7292. for (int k = 0; k < 12; ++k)
  7293. d.f32 (amt[k]);
  7294. p.i32 ((std::int32_t) d.b.size());
  7295. p.bytes (d.b);
  7296. }
  7297. {
  7298. 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
  7299. 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 …
  7300. 0.4f, 0.3f, 1.0f, 0.5f, 0.5f, 0.4f, 1.0f, 0.6f, 0.4f, 0.5f, // … delay, reverb, EQ …
  7301. 0.5f, 0.5f, 0.55f, 0.5f, 0.45f, 1.0f, 0.0f, 0.5f, 1.0f, 0.0f }; // EQ on, noise (muted)
  7302. Bytes g;
  7303. g.i32 (0x5c4);
  7304. for (auto v : A)
  7305. g.f32 (v);
  7306. g.zeros (0x5c4 - g.b.size());
  7307. p.bytes (g.b);
  7308. }
  7309. Bytes s;
  7310. s.raw ("SSLF", 4);
  7311. s.i32 ((std::int32_t) p.b.size());
  7312. s.bytes (p.b);
  7313. return s.b;
  7314. }
  7315. void dumpIfAsked (const char* var, const std::vector<std::uint8_t>& blob)
  7316. {
  7317. if (const char* path = std::getenv (var))
  7318. {
  7319. std::ofstream out (path, std::ios::binary);
  7320. out.write (reinterpret_cast<const char*> (blob.data()), (std::streamsize) blob.size());
  7321. }
  7322. }
  7323. } // namespace
  7324. TEST (gms_engine)
  7325. {
  7326. const auto blob = gmsTestState();
  7327. dumpIfAsked ("LYNX_DUMP_GMS", blob);
  7328. CHECK (lynx::gmsStateUsable (blob));
  7329. CHECK (lynx::gmsWaveNames (blob) == std::vector<std::string> ({ "NoWave A", "NoWave B", "NoWave C" }));
  7330. CHECK (lynx::gmsParamOffset (blob, 12) == 8 + 4 + 7 * 512 + 12 + 4 * 12 && lynx::gmsParamOffset (blob, 212) < 0);
  7331. auto broken = blob;
  7332. broken[8] = 'X';
  7333. CHECK (! lynx::gmsStateUsable (broken));
  7334. CHECK (! lynx::gmsStateUsable (std::vector<std::uint8_t> (blob.begin(), blob.begin() + 2000)));
  7335. // golden samples of our round-39 model (gmsmodel.GmsPlugin, waves missing → silent tables, tempo 140, 44.1 kHz,
  7336. // host blocks of 512): C5 vel 100 0–30000, E5 vel 80 11025–40000, G5 vel 110 22050–52000 (Init.Vol law A)
  7337. auto iv = [] (double vel) { return (std::pow (11.0, vel / 100.0) - 1.0) / 10.0; };
  7338. const std::vector<lynx::gms::RefNote> notes = { { 0, 60, (float) iv (100), 1.0, 0.0, 0.0, 30000 },
  7339. { 11025, 64, (float) iv (80), 1.0, 0.0, 0.0, 40000 },
  7340. { 22050, 67, (float) iv (110), 1.0, 0.0, 0.0, 52000 } };
  7341. const auto y = lynx::gms::renderReference (blob, notes, 44100.0, 66150, "");
  7342. CHECK (y.size() == 2 * 66150u);
  7343. 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 } };
  7344. for (const auto& g : golden)
  7345. 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);
  7346. double e = 0.0;
  7347. for (auto v : y)
  7348. e += (double) v * v;
  7349. CHECK (std::abs (std::sqrt (e / (double) y.size()) - 0.0790270452795) < 1e-6);
  7350. // the instrument: same engine behind LYNX's channel gains (V = 1, centre → law A), velocity → Init.Vol
  7351. lynx::ChannelDef c;
  7352. c.instrument = lynx::InstrumentKind::gms;
  7353. c.pluginState = blob;
  7354. auto inst = lynx::makeInstrument (lynx::InstrumentKind::gms);
  7355. inst->configure (c, 140.0);
  7356. inst->prepare (44100.0);
  7357. std::vector<float> l (8192, 0.0f), r (8192, 0.0f);
  7358. for (int b = 0; b < 16; ++b)
  7359. {
  7360. if (b == 0)
  7361. inst->noteOn (60, 0.78125f);
  7362. if (b == 10)
  7363. inst->noteOff (60);
  7364. inst->render (l.data() + 512 * b, r.data() + 512 * b, 512, 1.0f, 1.0f);
  7365. }
  7366. 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, "");
  7367. double diff = 0.0, energy = 0.0;
  7368. for (int i = 0; i < 8192; ++i)
  7369. {
  7370. 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]) });
  7371. energy += (double) l[(std::size_t) i] * l[(std::size_t) i];
  7372. }
  7373. CHECK (diff == 0.0 && energy > 1e-3);
  7374. }
  7375. TEST (morphine_engine)
  7376. {
  7377. const auto blob = morphineTestState();
  7378. dumpIfAsked ("LYNX_DUMP_MORPHINE", blob);
  7379. CHECK (lynx::morphineStateUsable (blob));
  7380. CHECK (lynx::morphineNoiseName (blob).empty());
  7381. const auto at = lynx::morphineParamOffset (blob, 9);
  7382. CHECK (at > 0);
  7383. float a9 = 0.0f;
  7384. std::memcpy (&a9, blob.data() + at, 4);
  7385. CHECK (a9 == 0.2f && lynx::morphineParamOffset (blob, 40) < 0);
  7386. auto broken = blob;
  7387. broken[12] = 'X'; // the MPR0 tag
  7388. CHECK (! lynx::morphineStateUsable (broken));
  7389. CHECK (! lynx::morphineStateUsable (std::vector<std::uint8_t> (blob.begin(), blob.end() - 10)));
  7390. // golden samples of our round-39 model (mormodel.Synth, tempo 120, 44.1 kHz, host blocks of 512): keys 60/64/67,
  7391. // Init.Vol 1.0/0.5/2.0, note-offs at 30000/50000/70000
  7392. const std::vector<lynx::morphine::RefNote> notes = { { 0, 60, 1.0, 1.0, 0.0, 0.0, 30000 },
  7393. { 11025, 64, 0.5, 1.0, 0.0, 0.0, 50000 },
  7394. { 22050, 67, 2.0, 1.0, 0.0, 0.0, 70000 } };
  7395. const auto y = lynx::morphine::renderReference (blob, notes, 44100.0, 80000, "");
  7396. CHECK (y.size() == 2 * 80000u);
  7397. 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 } };
  7398. for (const auto& g : golden)
  7399. 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);
  7400. double e = 0.0;
  7401. for (auto v : y)
  7402. e += (double) v * v;
  7403. CHECK (std::abs (std::sqrt (e / (double) y.size()) - 0.18467099041) < 1e-6);
  7404. // the instrument: same engine behind LYNX's channel gains
  7405. lynx::ChannelDef c;
  7406. c.instrument = lynx::InstrumentKind::morphine;
  7407. c.pluginState = blob;
  7408. auto inst = lynx::makeInstrument (lynx::InstrumentKind::morphine);
  7409. inst->configure (c, 120.0);
  7410. inst->prepare (44100.0);
  7411. std::vector<float> l (8192, 0.0f), r (8192, 0.0f);
  7412. for (int b = 0; b < 16; ++b)
  7413. {
  7414. if (b == 0)
  7415. inst->noteOn (60, 0.78125f);
  7416. if (b == 10)
  7417. inst->noteOff (60);
  7418. inst->render (l.data() + 512 * b, r.data() + 512 * b, 512, 1.0f, 1.0f);
  7419. }
  7420. 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, "");
  7421. double diff = 0.0, energy = 0.0;
  7422. for (int i = 0; i < 8192; ++i)
  7423. {
  7424. 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]) });
  7425. energy += (double) l[(std::size_t) i] * l[(std::size_t) i];
  7426. }
  7427. CHECK (diff == 0.0 && energy > 1e-3);
  7428. }
  7429. // Workflow P2 (docs/WORKFLOW_FL.md)
  7430. #include "WorkflowP2Tests.inc"