tests.cpp 257 KB

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