tests.cpp 233 KB

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