tests.cpp 189 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580
  1. // Testes do núcleo (sem JUCE). Uso: lynx_tests [pasta-com-arquivos-flp]
  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 <vector>
  12. #include "core/Dither.h"
  13. #include "core/Effects.h"
  14. #include "core/Effector.h"
  15. #include "core/FlpImport.h"
  16. #include "core/FlEffects.h"
  17. #include "core/FlPatcher.h"
  18. #include "core/FlSamplers.h"
  19. #include "core/FlSynths.h"
  20. #include "core/Inflate.h"
  21. #include "core/WavPack.h"
  22. #include "core/FlWrapper.h"
  23. #include "core/LiveEventQueue.h"
  24. #include "core/RackRenderer.h"
  25. #include "core/Scheduler.h"
  26. #include "core/SnapshotExchange.h"
  27. #include "core/SoftClip.h"
  28. #include "core/Slicer.h"
  29. #include "core/Templates.h"
  30. #include "core/TimeStretch.h"
  31. #include "core/WorkerPool.h"
  32. #include "core/Song.h"
  33. #include "core/NoteEdit.h"
  34. #include "core/Recorder.h"
  35. #include "flp/Flp.h"
  36. namespace
  37. {
  38. int failures = 0;
  39. int checks = 0;
  40. std::vector<std::pair<const char*, std::function<void()>>>& registry()
  41. {
  42. static std::vector<std::pair<const char*, std::function<void()>>> r;
  43. return r;
  44. }
  45. struct Register
  46. {
  47. Register (const char* name, std::function<void()> fn) { registry().emplace_back (name, std::move (fn)); }
  48. };
  49. #define TEST(name) \
  50. static void name(); \
  51. static Register reg_##name (#name, name); \
  52. static void name()
  53. #define CHECK(cond) \
  54. do \
  55. { \
  56. ++checks; \
  57. if (! (cond)) \
  58. { \
  59. ++failures; \
  60. std::printf (" FALHOU %s:%d: %s\n", __FILE__, __LINE__, #cond); \
  61. } \
  62. } while (false)
  63. std::string realFlpDir;
  64. // --- utilitários para montar .flp sintéticos -------------------------------
  65. struct FlpBuilder
  66. {
  67. std::vector<std::uint8_t> bytes;
  68. FlpBuilder (std::uint16_t ppq = 96)
  69. {
  70. put ("FLhd");
  71. u32 (6);
  72. u16 (0);
  73. u16 (1);
  74. u16 (ppq);
  75. put ("FLdt");
  76. u32 (0); // tamanho não é usado pelo leitor
  77. }
  78. void put (const char* s) { bytes.insert (bytes.end(), s, s + std::strlen (s)); }
  79. void u8 (std::uint8_t v) { bytes.push_back (v); }
  80. void u16 (std::uint16_t v) { u8 ((std::uint8_t) v); u8 ((std::uint8_t) (v >> 8)); }
  81. void u32 (std::uint32_t v) { u16 ((std::uint16_t) v); u16 ((std::uint16_t) (v >> 16)); }
  82. void varint (std::size_t n)
  83. {
  84. do
  85. {
  86. auto b = (std::uint8_t) (n & 0x7F);
  87. n >>= 7;
  88. u8 (n ? (std::uint8_t) (b | 0x80) : b);
  89. } while (n);
  90. }
  91. void data (std::uint8_t id, const std::vector<std::uint8_t>& payload)
  92. {
  93. u8 (id);
  94. varint (payload.size());
  95. bytes.insert (bytes.end(), payload.begin(), payload.end());
  96. }
  97. void ascii (std::uint8_t id, const std::string& s)
  98. {
  99. std::vector<std::uint8_t> p (s.begin(), s.end());
  100. p.push_back (0);
  101. data (id, p);
  102. }
  103. void utf16 (std::uint8_t id, const std::u16string& s)
  104. {
  105. std::vector<std::uint8_t> p;
  106. for (auto c : s)
  107. {
  108. p.push_back ((std::uint8_t) c);
  109. p.push_back ((std::uint8_t) (c >> 8));
  110. }
  111. p.push_back (0);
  112. p.push_back (0);
  113. data (id, p);
  114. }
  115. };
  116. std::vector<std::uint8_t> noteRecord (std::uint32_t pos, std::uint16_t channel, std::uint32_t len, std::uint16_t key,
  117. std::uint8_t velocity)
  118. {
  119. std::vector<std::uint8_t> r (24, 0);
  120. std::memcpy (&r[0], &pos, 4);
  121. std::memcpy (&r[6], &channel, 2);
  122. std::memcpy (&r[8], &len, 4);
  123. std::memcpy (&r[12], &key, 2);
  124. r[16] = 120;
  125. r[20] = 64;
  126. r[21] = velocity;
  127. return r;
  128. }
  129. } // namespace
  130. // ---------------------------------------------------------------------------
  131. // FLP
  132. TEST (flp_rejects_garbage)
  133. {
  134. std::vector<std::uint8_t> junk (64, 0x41);
  135. bool threw = false;
  136. try { flp::EventReader r (junk); } catch (const flp::Error&) { threw = true; }
  137. CHECK (threw);
  138. }
  139. TEST (flp_reads_size_classes_varint_and_extended_ids)
  140. {
  141. FlpBuilder b;
  142. b.u8 (0x15); b.u8 (2); // u8
  143. b.u8 (0x40); b.u16 (513); // u16
  144. b.u8 (0x9C); b.u32 (128500); // u32
  145. b.data (0xD5, std::vector<std::uint8_t> (300, 7)); // varint de 2 bytes
  146. b.u8 (0xAC); b.u32 (0xC0000100); b.varint (3); b.u8 (1); b.u8 (2); b.u8 (3); // ID estendido
  147. flp::EventReader r (b.bytes);
  148. flp::Event e;
  149. CHECK (r.header().ppq == 96);
  150. CHECK (r.next (e) && e.id == 0x15 && e.value == 2);
  151. CHECK (r.next (e) && e.id == 0x40 && e.value == 513);
  152. CHECK (r.next (e) && e.id == 0x9C && e.value == 128500);
  153. CHECK (r.next (e) && e.id == 0xD5 && e.data.size() == 300 && e.data[299] == 7);
  154. CHECK (r.next (e) && e.id == 0xC0000100 && e.isData() && e.data.size() == 3 && e.data[2] == 3);
  155. CHECK (! r.next (e));
  156. }
  157. TEST (flp_truncated_file_throws)
  158. {
  159. FlpBuilder b;
  160. b.u8 (0x9C); b.u8 (1); // u32 com só 1 byte
  161. flp::EventReader r (b.bytes);
  162. flp::Event e;
  163. bool threw = false;
  164. try { r.next (e); } catch (const flp::Error&) { threw = true; }
  165. CHECK (threw);
  166. }
  167. TEST (flp_version_numbers)
  168. {
  169. CHECK (flp::parseVersionNumber ("25.2.5.5319") == 25002005u);
  170. CHECK (flp::parseVersionNumber ("20.99.3000.3031") == 20102000u);
  171. CHECK (flp::parseVersionNumber ("11.0.3") == 11000003u);
  172. }
  173. TEST (flp_playlist_record_size_by_version)
  174. {
  175. CHECK (flp::playlistRecordSize (12009003, 64) == 32);
  176. CHECK (flp::playlistRecordSize (21000000, 120) == 60);
  177. CHECK (flp::playlistRecordSize (25002005, 160) == 80);
  178. CHECK (flp::playlistRecordSize (25002005, 60) == 60); // tamanho não bate com a versão → tenta os outros
  179. CHECK (flp::playlistRecordSize (25002005, 7) == 0);
  180. }
  181. TEST (flp_parses_project_model)
  182. {
  183. FlpBuilder b (96);
  184. b.ascii (0xC7, "25.2.5.5319");
  185. b.u8 (0x9C); b.u32 (174500);
  186. b.utf16 (0xC2, u"Título");
  187. b.u8 (0x41); b.u16 (3);
  188. b.u8 (0x96); b.u32 (0x00A14547); // BGR no arquivo
  189. auto notes = noteRecord (96, 1, 48, 64, 100);
  190. auto n2 = noteRecord (0, 0, 0, 60, 128);
  191. notes.insert (notes.end(), n2.begin(), n2.end());
  192. b.data (0xE0, notes);
  193. b.u8 (0x40); b.u16 (0);
  194. b.u8 (0x15); b.u8 (0);
  195. b.utf16 (0xCB, u"Kick");
  196. {
  197. std::vector<std::uint8_t> levels (24, 0);
  198. const std::int32_t lv[] = { 3200, 12800, -150 };
  199. std::memcpy (levels.data(), lv, sizeof (lv));
  200. b.data (0xDB, levels);
  201. }
  202. b.u8 (0x68); b.u16 (5);
  203. b.u8 (0x40); b.u16 (1);
  204. b.u8 (0x15); b.u8 (2);
  205. b.utf16 (0xC9, u"FLEX");
  206. b.utf16 (0xCB, u"Lead");
  207. b.u8 (0x63); b.u16 (0);
  208. std::vector<std::uint8_t> item (80, 0);
  209. std::uint32_t pos = 384, len = 768;
  210. std::uint16_t base = 20480, idx = 20480 + 3, rv = 499 - 2;
  211. std::memcpy (&item[0], &pos, 4);
  212. std::memcpy (&item[4], &base, 2);
  213. std::memcpy (&item[6], &idx, 2);
  214. std::memcpy (&item[8], &len, 4);
  215. std::memcpy (&item[12], &rv, 2);
  216. b.data (0xE9, item);
  217. b.utf16 (0xCC, u"Drums");
  218. b.data (0xEC, std::vector<std::uint8_t> (12, 0));
  219. b.data (0xEC, std::vector<std::uint8_t> (12, 0));
  220. const auto p = flp::parseProject (b.bytes);
  221. CHECK (p.version == "25.2.5.5319");
  222. CHECK (std::abs (p.tempo - 174.5) < 1e-9);
  223. CHECK (p.title == "Título");
  224. CHECK (p.channels.size() == 2);
  225. CHECK (p.channels[0].name == "Kick" && p.channels[0].mixerTrack == 5);
  226. CHECK (p.channels[0].hasLevels && p.channels[0].pan == 3200 && p.channels[0].volume == 12800 && p.channels[0].pitchCents == -150);
  227. CHECK (p.channels[1].type == flp::ChannelType::instrument && p.channels[1].pluginName == "FLEX");
  228. CHECK (p.patterns.size() == 1 && p.patterns[0].index == 3);
  229. CHECK (p.patterns[0].colour && *p.patterns[0].colour == 0x4745A1);
  230. CHECK (p.patterns[0].notes.size() == 2 && p.patterns[0].notes[0].position == 0); // ordenadas
  231. CHECK (p.patterns[0].notes[1].key == 64 && p.patterns[0].notes[1].length == 48);
  232. CHECK (p.arrangements.size() == 1 && p.arrangements[0].items.size() == 1);
  233. const auto& it = p.arrangements[0].items[0];
  234. CHECK (it.kind == flp::PlaylistItem::Kind::pattern && it.index == 3 && it.track == 2 && it.position == 384);
  235. CHECK (p.mixer.size() == 2 && p.mixer[0].name == "Drums" && p.mixer[1].name.empty());
  236. CHECK (p.warnings.empty());
  237. }
  238. TEST (flp_fuzz_corrupted_files_do_not_crash)
  239. {
  240. if (realFlpDir.empty())
  241. return;
  242. // alguns .flp reais, corrompidos de várias formas: o parser pode recusar (flp::Error), mas
  243. // nunca travar, ler fora do buffer ou produzir um Song com índices inválidos
  244. std::vector<std::vector<std::uint8_t>> sources;
  245. for (auto& entry : std::filesystem::recursive_directory_iterator (realFlpDir))
  246. if (entry.path().extension() == ".flp" && sources.size() < 6 && std::filesystem::file_size (entry.path()) < 3'000'000)
  247. {
  248. std::ifstream in (entry.path(), std::ios::binary);
  249. sources.emplace_back ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  250. }
  251. std::uint32_t seed = 2024;
  252. auto rnd = [&] (std::uint32_t n) { seed = seed * 1664525u + 1013904223u; return n == 0 ? 0u : (seed >> 8) % n; };
  253. int parsed = 0, rejected = 0;
  254. for (int round = 0; round < 240 && ! sources.empty(); ++round)
  255. {
  256. auto bytes = sources[(std::size_t) rnd ((std::uint32_t) sources.size())];
  257. switch (round % 4)
  258. {
  259. case 0: bytes.resize (rnd ((std::uint32_t) bytes.size())); break; // truncado
  260. 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;
  261. case 2: // tamanho de evento absurdo
  262. for (int k = 0; k < 5; ++k)
  263. bytes[(std::size_t) rnd ((std::uint32_t) bytes.size())] = 0xFF;
  264. break;
  265. default: // bloco embaralhado
  266. {
  267. const auto a = rnd ((std::uint32_t) bytes.size()), b = rnd ((std::uint32_t) bytes.size());
  268. std::reverse (bytes.begin() + std::min (a, b), bytes.begin() + std::max (a, b));
  269. break;
  270. }
  271. }
  272. try
  273. {
  274. const auto project = flp::parseProject (bytes);
  275. const auto song = lynx::importFlp (project);
  276. ++parsed;
  277. for (const auto& p : song.patterns)
  278. for (const auto& n : p.notes)
  279. CHECK (n.channel >= 0 && n.channel < (int) song.channels.size());
  280. for (const auto& c : song.playlist)
  281. CHECK (c.kind != lynx::ClipKind::pattern || (c.pattern >= 0 && c.pattern < (int) song.patterns.size()));
  282. }
  283. catch (const flp::Error&)
  284. {
  285. ++rejected;
  286. }
  287. }
  288. std::printf (" fuzz: %d importados, %d recusados\n", parsed, rejected);
  289. CHECK (parsed + rejected == 240);
  290. }
  291. TEST (plugin_state_decoders_survive_garbage)
  292. {
  293. // blobs aleatórios (tamanhos variados, incluindo cabeçalhos válidos com o resto lixo)
  294. std::uint32_t seed = 77;
  295. auto rnd = [&] { seed = seed * 1664525u + 1013904223u; return seed >> 8; };
  296. const char* plugins[] = { "Fruity Parametric EQ 2", "Fruity Limiter", "Fruity Reeverb 2", "Fruity Delay 2", "Fruity Delay 3",
  297. "Fruity Compressor", "Fruity Balance", "Fruity PanOMatic", "Fruity Stereo Shaper", "Fruity Phase Inverter" };
  298. int decoded = 0;
  299. for (int round = 0; round < 3000; ++round)
  300. {
  301. std::vector<std::uint8_t> blob ((std::size_t) (rnd() % 600));
  302. for (auto& b : blob)
  303. b = (std::uint8_t) rnd();
  304. if (blob.size() >= 4 && round % 3 == 0) // versões que os leitores aceitam
  305. {
  306. const std::uint32_t versions[] = { 8, 10001, 10000, 12, 14, 6, 1 };
  307. const auto v = versions[rnd() % 7];
  308. std::memcpy (blob.data(), &v, 4);
  309. }
  310. if (auto fx = lynx::effectFromFl (plugins[rnd() % 10], blob))
  311. {
  312. ++decoded;
  313. for (auto v : fx->params)
  314. CHECK (std::isfinite (v) && v >= 0.0f && v <= 1.0f);
  315. }
  316. lynx::SynthSettings synth;
  317. if (lynx::synthFrom3xOsc (blob, synth))
  318. for (const auto& o : synth.osc)
  319. CHECK (std::isfinite (o.level) && o.level >= 0.0f && o.level <= 1.0f);
  320. float harmlessGain = 1.0f;
  321. if (lynx::synthFromHarmless (blob, 120.0, synth, harmlessGain))
  322. CHECK (std::isfinite (harmlessGain) && std::isfinite (synth.cutoff) && std::isfinite (synth.attack));
  323. if (lynx::synthFromFruitKick (blob, synth))
  324. CHECK (std::isfinite (synth.decay) && std::isfinite (synth.pitchEnv.amount));
  325. if (lynx::synthFromGms (blob, 120.0, synth, harmlessGain) || lynx::synthFromHarmor (blob, synth, harmlessGain) || lynx::synthFromOgun (blob, synth, harmlessGain)
  326. || lynx::synthFromSakura (blob, synth) || lynx::synthFromKepler (blob, synth, harmlessGain))
  327. CHECK (std::isfinite (synth.cutoff) && std::isfinite (synth.attack) && std::isfinite (harmlessGain));
  328. if (auto sound = lynx::drumSynthLiveSound (blob))
  329. CHECK (sound->size() < 256);
  330. if (auto wave = lynx::waveTravellerSample (blob))
  331. CHECK (! wave->first.empty() && wave->second >= 0 && wave->second <= 127);
  332. lynx::synthFromBooBass (blob, synth);
  333. if (lynx::synthFromPoiZone (blob, synth, harmlessGain) || lynx::synthFromBassDrum (blob, synth, harmlessGain) || lynx::synthFromToxic (blob, synth, harmlessGain)
  334. || lynx::synthFromMorphine (blob, synth, harmlessGain))
  335. CHECK (std::isfinite (synth.cutoff) && std::isfinite (harmlessGain));
  336. if (auto patch = lynx::drumpadPatchName (blob))
  337. CHECK (patch->size() <= 0x30 && std::isfinite (lynx::drumToneForName (*patch).decay));
  338. if (auto flex = lynx::flexPresetName (blob))
  339. CHECK ((! flex->first.empty() || ! flex->second.empty()) && flex->second.size() <= 1024);
  340. if (lynx::synthFromSytrus (blob, 120.0, synth, harmlessGain))
  341. CHECK (std::isfinite (synth.cutoff) && std::isfinite (synth.attack));
  342. if (lynx::synthFromDX10 (blob, synth))
  343. CHECK (std::isfinite (synth.decay) && std::isfinite (synth.release) && std::isfinite (synth.osc[1].level));
  344. if (blob.size() >= 4 && round % 5 == 0) // cabeçalho do MiniSynth com o resto lixo
  345. {
  346. std::memcpy (blob.data(), "SSLF", 4);
  347. if (blob.size() > 220)
  348. {
  349. std::memcpy (blob.data() + 40, "DATA", 4);
  350. std::memcpy (blob.data() + 48, "0rev", 4);
  351. }
  352. }
  353. if (lynx::synthFromMiniSynth (blob, 120.0, synth))
  354. CHECK (std::isfinite (synth.cutoff) && std::isfinite (synth.decay) && std::isfinite (synth.attack));
  355. lynx::ForeignPlugin foreign;
  356. lynx::parseFlWrapper (blob, foreign);
  357. std::vector<std::uint8_t> component, controller;
  358. lynx::splitFlVst3State (blob, component, controller);
  359. }
  360. CHECK (decoded == 3000); // todo nome conhecido dá um efeito (padrão quando o blob não serve)
  361. }
  362. TEST (inflate_zlib)
  363. {
  364. // Huffman fixo com cópias para trás
  365. const std::uint8_t fixed[] = { 0x78, 0xda, 0x4b, 0x4c, 0x4a, 0x4e, 0xc4, 0x86, 0x22, 0x00, 0x7c, 0x69, 0x09, 0x89 };
  366. const auto a = lynx::inflateZlib (fixed, sizeof (fixed));
  367. CHECK (a && std::string (a->begin(), a->end()) == "abcabcabcabcabcabcabcabcX");
  368. // bloco sem compressão
  369. const std::uint8_t stored[] = { 0x78, 0x01, 0x01, 0x03, 0x00, 0xfc, 0xff, 'L', 'Y', 'N', 0x00, 0x00, 0x00, 0x00 };
  370. const auto b = lynx::inflateZlib (stored, sizeof (stored));
  371. CHECK (b && std::string (b->begin(), b->end()) == "LYN");
  372. // truncado, cabeçalho errado e limite de tamanho
  373. CHECK (! lynx::inflateZlib (fixed, 6));
  374. const std::uint8_t bad[] = { 0x12, 0x34, 0x00 };
  375. CHECK (! lynx::inflateZlib (bad, sizeof (bad)));
  376. CHECK (! lynx::inflateZlib (fixed, sizeof (fixed), false, 10));
  377. }
  378. TEST (fl_round15_effects_convert_known_values)
  379. {
  380. auto blob = [] (std::vector<std::int32_t> words) {
  381. std::vector<std::uint8_t> b (words.size() * 4);
  382. std::memcpy (b.data(), words.data(), b.size());
  383. return b;
  384. };
  385. // Frequency Shifter "+800 Hz": frequência 51542 na faixa de 20 kHz, 100% úmido
  386. const auto fs = lynx::effectFromFl ("Frequency Shifter", blob ({ 4, 10000, 0, 51542, 0, 10000, 10000, 5000, 10000, 0, 5000, 0, 0 }));
  387. CHECK (fs && fs->kind == lynx::EffectKind::freqShift);
  388. if (fs)
  389. {
  390. const auto x = (fs->params[0] - 0.5) * 2.0;
  391. CHECK (std::abs (2000.0 * x * std::abs (x) - 800.0) < 10.0);
  392. CHECK (std::abs (fs->params[1] - 1.0f) < 1e-4f);
  393. }
  394. // Emphasis: entrada 0,0625 (= +1,5 dB) e teto 0,9308 (≈ −1,6 dB) -> limiter
  395. const auto em = lynx::effectFromFl ("Emphasis", blob ({ 8, 0, 0, 2, 1, 0, 0, 625, 10000, 10000, 9308, 0, 2, 7, 0 }));
  396. CHECK (em && em->kind == lynx::EffectKind::limiter && em->enabled);
  397. if (em)
  398. {
  399. CHECK (std::abs (em->params[1] * 24.0f - 1.5f) < 0.05f);
  400. CHECK (std::abs (em->params[0] * 12.0f - 12.0f + 1.6f) < 0.1f);
  401. }
  402. // Pitch Shifter +12 st, mix 100%
  403. 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 }));
  404. CHECK (ps && ps->kind == lynx::EffectKind::pitchShift && std::abs (ps->params[0] - (0.5f + 12.0f / 48.0f)) < 1e-4f);
  405. }
  406. TEST (frequency_shifter_moves_spectrum_by_hz)
  407. {
  408. auto fx = lynx::makeEffect (lynx::EffectKind::freqShift);
  409. fx->prepare (48000.0);
  410. auto slot = lynx::makeEffectSlot (lynx::EffectKind::freqShift);
  411. // +200 Hz: x·|x|·2000 = 200 -> x = sqrt(0,1)
  412. slot.params[0] = (float) (0.5 + std::sqrt (0.1) / 2.0);
  413. std::vector<float> l (48000), r (48000);
  414. for (int i = 0; i < 48000; ++i)
  415. l[(std::size_t) i] = r[(std::size_t) i] = (float) std::sin (2.0 * 3.141592653589793 * 1000.0 * i / 48000.0);
  416. for (int done = 0; done < 48000; done += 480)
  417. fx->process (l.data() + done, r.data() + done, 480, slot.params, 120.0);
  418. auto energy = [&] (double f) {
  419. const auto w = 2.0 * 3.141592653589793 * f / 48000.0, k = 2.0 * std::cos (w);
  420. double s1 = 0.0, s2 = 0.0;
  421. for (int i = 9600; i < 48000; ++i)
  422. {
  423. const auto s0 = l[(std::size_t) i] + k * s1 - s2;
  424. s2 = s1;
  425. s1 = s0;
  426. }
  427. return s1 * s1 + s2 * s2 - k * s1 * s2;
  428. };
  429. // a energia vai para 1200 Hz; sobra pouco em 1000 e quase nada na imagem (800)
  430. CHECK (energy (1200.0) > 50.0 * energy (1000.0));
  431. CHECK (energy (1200.0) > 50.0 * energy (800.0));
  432. }
  433. TEST (pitch_shift_moves_frequency_keeps_length)
  434. {
  435. auto fx = lynx::makeEffect (lynx::EffectKind::pitchShift);
  436. fx->prepare (48000.0);
  437. auto slot = lynx::makeEffectSlot (lynx::EffectKind::pitchShift);
  438. auto crossingsAfter = [&] (float semitoneParam) {
  439. fx->reset();
  440. slot.params[0] = semitoneParam;
  441. std::vector<float> l (48000), r (48000);
  442. for (int i = 0; i < 48000; ++i)
  443. l[(std::size_t) i] = r[(std::size_t) i] = (float) std::sin (2.0 * 3.141592653589793 * 220.0 * i / 48000.0);
  444. for (int done = 0; done < 48000; done += 512)
  445. fx->process (l.data() + done, r.data() + done, std::min (512, 48000 - done), slot.params, 120.0);
  446. int crossings = 0;
  447. for (int i = 9600; i < 48000; ++i)
  448. crossings += (l[(std::size_t) i - 1] < 0.0f) != (l[(std::size_t) i] < 0.0f);
  449. for (auto v : l)
  450. CHECK (std::isfinite (v) && std::abs (v) < 1.6f);
  451. return crossings / 0.8 / 2.0; // ciclos por segundo
  452. };
  453. CHECK (std::abs (crossingsAfter (0.5f) - 220.0) < 8.0); // 0 st
  454. CHECK (std::abs (crossingsAfter (0.5f + 12.0f / 48.0f) - 440.0) < 25.0); // +12 st
  455. CHECK (std::abs (crossingsAfter (0.5f - 12.0f / 48.0f) - 110.0) < 12.0); // −12 st
  456. }
  457. TEST (volume_gate_follows_bar_position)
  458. {
  459. auto fx = lynx::makeEffect (lynx::EffectKind::volumeGate);
  460. fx->prepare (48000.0);
  461. auto slot = lynx::makeEffectSlot (lynx::EffectKind::volumeGate);
  462. for (int i = 0; i < 32; ++i)
  463. slot.params[(std::size_t) i] = i < 16 ? 1.0f : 0.0f; // dois primeiros tempos abertos, dois fechados
  464. slot.params[33] = slot.params[34] = 0.0f; // sem suavização
  465. // 120 BPM: um tempo = 0,5 s = 24000 amostras; o compasso de 4 tempos começa no tick 0
  466. std::vector<float> l (96000, 1.0f), r (96000, 1.0f);
  467. fx->setSongPosition (0.0);
  468. for (int done = 0; done < 96000; done += 512)
  469. fx->process (l.data() + done, r.data() + done, std::min (512, 96000 - done), slot.params, 120.0);
  470. CHECK (l[10000] > 0.99f && l[40000] > 0.99f); // tempos 1 e 2
  471. CHECK (l[60000] < 0.01f && l[90000] < 0.01f); // tempos 3 e 4
  472. // começando no meio do compasso (tempo 3): já fechado
  473. std::vector<float> l2 (4800, 1.0f), r2 (4800, 1.0f);
  474. fx->reset();
  475. fx->setSongPosition (2.0 * lynx::ppq);
  476. fx->process (l2.data(), r2.data(), 4800, slot.params, 120.0);
  477. CHECK (l2[4000] < 0.01f);
  478. // mix 0: transparente
  479. slot.params[32] = 0.0f;
  480. std::vector<float> l3 (4800, 1.0f), r3 (4800, 1.0f);
  481. fx->setSongPosition (2.0 * lynx::ppq);
  482. fx->process (l3.data(), r3.data(), 4800, slot.params, 120.0);
  483. CHECK (l3[4000] > 0.99f);
  484. }
  485. TEST (patcher_branch_heads_follow_rea)
  486. {
  487. auto words = [] (std::vector<std::int32_t> v) {
  488. std::vector<std::uint8_t> b (v.size() * 4);
  489. std::memcpy (b.data(), v.data(), b.size());
  490. return b;
  491. };
  492. // Frequency Splitter, 2 bandas, destinos 1/2/3, inclinação combo 3 (24 dB/oit), envio do agudo −6 dB
  493. std::vector<std::int32_t> fs (18, 0);
  494. fs[0] = 4;
  495. fs[1] = 32768;
  496. fs[3] = 3;
  497. fs[6] = 0;
  498. fs[11] = -600;
  499. fs[15] = 1;
  500. fs[16] = 2;
  501. fs[17] = 3;
  502. const auto split = words (fs);
  503. const auto low = lynx::patcherBranchHead ("Frequency Splitter", split, 1);
  504. CHECK (low.valid && low.slot && low.note.empty());
  505. if (low.slot)
  506. {
  507. CHECK (lynx::peq::type (low.slot->params[(std::size_t) lynx::peq::param (0, 0)]) == lynx::peq::BandType::highCut);
  508. CHECK (lynx::peq::slopeStages (low.slot->params[(std::size_t) lynx::peq::slopeParam]) == 2);
  509. }
  510. const auto mid = lynx::patcherBranchHead ("Frequency Splitter", split, 2);
  511. CHECK (mid.valid && mid.gain == 0.0f); // em 2 bandas a média é muda
  512. const auto high = lynx::patcherBranchHead ("Frequency Splitter", split, 3);
  513. CHECK (high.valid && std::abs (high.gain - std::pow (10.0f, -6.0f / 20.0f)) < 1e-4f);
  514. CHECK (! lynx::patcherBranchHead ("Frequency Splitter", split, 7).valid);
  515. // Stereo Shaper com matriz identidade: a diferença (destino 4) é zero
  516. const auto shaper = words ({ 3, 0, 12800, 12800, 0, 0, 0, 4, 0 });
  517. const auto diff = lynx::patcherBranchHead ("Fruity Stereo Shaper", shaper, 4);
  518. 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);
  519. CHECK (! lynx::patcherBranchHead ("Fruity Stereo Shaper", shaper, 2).valid);
  520. }
  521. TEST (parallel_container_sums_branches)
  522. {
  523. // dois ramos: seco com ganho 0,5 e um utilitário que inverte a fase (matriz −1) com ganho 0,5 -> silêncio
  524. auto slot = lynx::makeEffectSlot (lynx::EffectKind::parallel);
  525. lynx::EffectBranch dry;
  526. dry.gain = 0.5f;
  527. lynx::EffectBranch inverted;
  528. inverted.gain = 0.5f;
  529. auto flip = lynx::makeEffectSlot (lynx::EffectKind::utility);
  530. flip.params[2] = flip.params[5] = 0.25f; // (−1 + 2)/4
  531. inverted.chain.push_back (flip);
  532. slot.branches = { dry, inverted };
  533. auto fx = lynx::makeParallelEffect (slot);
  534. fx->prepare (48000.0);
  535. std::vector<float> l (9000, 0.8f), r (9000, -0.4f);
  536. fx->process (l.data(), r.data(), 9000, slot.params, 120.0);
  537. CHECK (std::abs (l[100]) < 1e-5f && std::abs (r[8999]) < 1e-5f);
  538. // só o ramo seco com ganho 2: dobra
  539. slot.branches = { lynx::EffectBranch { {}, 2.0f } };
  540. auto doubler = lynx::makeParallelEffect (slot);
  541. doubler->prepare (48000.0);
  542. std::fill (l.begin(), l.end(), 0.25f);
  543. doubler->process (l.data(), r.data(), 9000, slot.params, 120.0);
  544. CHECK (std::abs (l[5000] - 0.5f) < 1e-6f);
  545. }
  546. TEST (fl_controller_constant_outputs)
  547. {
  548. std::vector<std::int32_t> xy { 2, 32768, 0, 65536, 0, 16384, 0, 65536, 0, 1024, 256 };
  549. std::vector<std::uint8_t> blob (xy.size() * 4 + 8, 0);
  550. std::memcpy (blob.data(), xy.data(), xy.size() * 4);
  551. CHECK (std::abs (lynx::controllerConstantOutput ("Fruity X-Y Controller", blob, 0).value_or (-1.0f) - 0.5f) < 1e-4f);
  552. CHECK (std::abs (lynx::controllerConstantOutput ("Fruity X-Y Controller", blob, 1).value_or (-1.0f) - 0.25f) < 1e-4f);
  553. // Control Surface: versão + grupo { 0x836: valor 0,75, -, saída 2 }
  554. std::vector<std::uint8_t> cs (4, 0);
  555. cs[0] = 1;
  556. auto chunk = [] (std::vector<std::uint8_t>& out, std::uint32_t id, const std::vector<std::uint8_t>& body) {
  557. const auto size = (std::uint64_t) body.size();
  558. out.insert (out.end(), reinterpret_cast<const std::uint8_t*> (&id), reinterpret_cast<const std::uint8_t*> (&id) + 4);
  559. out.insert (out.end(), reinterpret_cast<const std::uint8_t*> (&size), reinterpret_cast<const std::uint8_t*> (&size) + 8);
  560. out.insert (out.end(), body.begin(), body.end());
  561. };
  562. std::vector<std::uint8_t> value (12, 0);
  563. const float v = 0.75f;
  564. const std::int32_t out = 2;
  565. std::memcpy (value.data(), &v, 4);
  566. std::memcpy (value.data() + 8, &out, 4);
  567. std::vector<std::uint8_t> group;
  568. chunk (group, 0x836, value);
  569. chunk (cs, 0, group);
  570. CHECK (std::abs (lynx::controllerConstantOutput ("Control Surface", cs, 2).value_or (-1.0f) - 0.75f) < 1e-6f);
  571. CHECK (! lynx::controllerConstantOutput ("Control Surface", cs, 0).has_value());
  572. }
  573. TEST (flp_midi_out_notes_reach_wrapper_on_same_port)
  574. {
  575. auto record = [] (std::vector<std::uint8_t>& out, std::uint32_t id, std::vector<std::uint8_t> body) {
  576. const auto size = (std::uint64_t) body.size();
  577. out.insert (out.end(), reinterpret_cast<const std::uint8_t*> (&id), reinterpret_cast<const std::uint8_t*> (&id) + 4);
  578. out.insert (out.end(), reinterpret_cast<const std::uint8_t*> (&size), reinterpret_cast<const std::uint8_t*> (&size) + 8);
  579. out.insert (out.end(), body.begin(), body.end());
  580. };
  581. auto i32s = [] (std::vector<std::int32_t> v) {
  582. std::vector<std::uint8_t> b (v.size() * 4);
  583. std::memcpy (b.data(), v.data(), b.size());
  584. return b;
  585. };
  586. flp::Project p;
  587. flp::Channel midiOut;
  588. midiOut.index = 0;
  589. midiOut.type = flp::ChannelType::native;
  590. midiOut.pluginName = "MIDI Out";
  591. midiOut.pluginState = i32s ({ 7, 0, -1, -1, -1, 0, 3, 0 }); // canal 1, porta 3 (@24)
  592. flp::Channel wrapper;
  593. wrapper.index = 1;
  594. wrapper.type = flp::ChannelType::native;
  595. wrapper.pluginName = "Fruity Wrapper";
  596. wrapper.pluginState = i32s ({ 9 });
  597. record (wrapper.pluginState, 0x32, i32s ({ 7 })); // VST3
  598. record (wrapper.pluginState, 0x01, i32s ({ 3, -1, 0, 0, 0 })); // porta de entrada 3
  599. p.channels = { midiOut, wrapper };
  600. flp::Pattern pattern;
  601. pattern.index = 1;
  602. flp::Note note;
  603. note.channel = 0;
  604. note.key = 64;
  605. note.length = 96;
  606. pattern.notes.push_back (note);
  607. p.patterns.push_back (pattern);
  608. const auto song = lynx::importFlp (p);
  609. CHECK (song.channels.size() == 2 && song.channels[0].muted);
  610. CHECK (song.channels[1].plugin.foreign.midiInPort == 3);
  611. int toWrapper = 0;
  612. for (const auto& pat : song.patterns)
  613. for (const auto& n : pat.notes)
  614. toWrapper += n.channel == 1 && n.key == 64;
  615. CHECK (toWrapper == 1);
  616. }
  617. TEST (flp_effect_automation_follows_slots_and_params)
  618. {
  619. // trilha 1: slot 0 com um efeito sem equivalente (sai), slot 2 com o Parametric EQ 2
  620. flp::Project p;
  621. flp::MixerInsert insert;
  622. insert.index = 1;
  623. insert.slots.push_back ({ 0, "Some Unknown FX", {} });
  624. insert.slots.push_back ({ 2, "Fruity Parametric EQ 2", {} });
  625. p.mixer.push_back (insert);
  626. auto clip = [&] (int index, std::uint32_t target) {
  627. flp::Channel c;
  628. c.index = index;
  629. c.type = flp::ChannelType::automationClip;
  630. c.automation = { { 0.0, 0.0 }, { 96.0, 1.0 } };
  631. p.channels.push_back (c);
  632. p.automationLinks.push_back ({ index, { target } });
  633. };
  634. 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; };
  635. clip (0, mixer (1, 2, 0x8000 + 7)); // frequência da banda 1 do EQ
  636. clip (1, mixer (1, 2, 0x1F01)); // mix do slot do EQ
  637. clip (2, mixer (1, 0, 0x8000)); // parâmetro do efeito que saiu
  638. clip (3, mixer (1, 2, 0x8000 + 21)); // tipo da banda: sem equivalente
  639. const auto song = lynx::importFlp (p);
  640. CHECK (song.automations.size() == 4);
  641. CHECK (song.mixer[1].effects.size() == 1 && song.mixer[1].effects[0].kind == lynx::EffectKind::parametricEq);
  642. const auto& freq = song.automations[0];
  643. CHECK (freq.target.kind == lynx::AutomationTargetKind::effectParam && freq.target.index == 1 && freq.target.slot == 0);
  644. CHECK (freq.target.param == lynx::peq::param (0, 1));
  645. // 0..1 do FL (20 Hz..20 kHz) vira a nossa escala de frequência
  646. CHECK (std::abs (freq.points.front().value - lynx::peq::hzValue (20.0)) < 1e-4f);
  647. CHECK (std::abs (freq.points.back().value - lynx::peq::hzValue (20000.0)) < 1e-4f);
  648. CHECK (song.automations[1].target.kind == lynx::AutomationTargetKind::effectMix && song.automations[1].target.slot == 0);
  649. CHECK (song.automations[2].target.kind == lynx::AutomationTargetKind::none);
  650. CHECK (song.automations[3].target.kind == lynx::AutomationTargetKind::none);
  651. // o mix automatizado é lido/escrito pelo alvo
  652. auto copy = song;
  653. CHECK (copy.setTargetValue (song.automations[1].target, 0.25f) && std::abs (copy.mixer[1].effects[0].mix - 0.25f) < 1e-6f);
  654. CHECK (std::abs (copy.targetValue (song.automations[1].target) - 0.25f) < 1e-6f);
  655. }
  656. TEST (flp_real_files)
  657. {
  658. if (realFlpDir.empty())
  659. {
  660. std::printf (" (pulado: passe uma pasta com .flp como argumento)\n");
  661. return;
  662. }
  663. int files = 0, withNotes = 0, withPlaylist = 0, automations = 0, automationsWithTarget = 0, sends = 0;
  664. int threeOsc = 0, threeOscDecoded = 0, wrapped = 0, wrappedParsed = 0, markers = 0, signatures = 0, trackEqs = 0;
  665. int harmless = 0, harmlessDecoded = 0, sytrus = 0, sytrusDecoded = 0;
  666. std::map<std::string, std::pair<int, int>> generators; // GMS/Ogun/Autogun/Sakura/DrumSynth: canais, decodificados
  667. int peqSlots = 0, peqShaped = 0, reverbs = 0, reverbsDryless = 0, reverbsLowCut = 0;
  668. int dwChannels = 0, dwZones = 0, fpcKits = 0, padChannels = 0, padNotes = 0;
  669. // import com os samples da instalação (o realFlpDir é ...\Data): para DirectWave/FPC
  670. lynx::FlpImportOptions withFiles;
  671. const auto flRoot = std::filesystem::path (realFlpDir).parent_path().string();
  672. withFiles.roots = { flRoot, realFlpDir, "" };
  673. withFiles.fileExists = [] (const std::string& path) {
  674. auto local = path;
  675. std::replace (local.begin(), local.end(), '\\', '/');
  676. return std::filesystem::exists (local);
  677. };
  678. withFiles.readFile = [] (const std::string& path) {
  679. auto local = path;
  680. std::replace (local.begin(), local.end(), '\\', '/');
  681. std::ifstream in (local, std::ios::binary);
  682. return std::vector<std::uint8_t> ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  683. };
  684. int embeddedSaved = 0;
  685. withFiles.saveEmbedded = [&embeddedSaved] (const std::vector<std::uint8_t>& wav, const std::string&) {
  686. ++embeddedSaved;
  687. return wav.size() > 44 ? std::string ("embutido.wav") : std::string();
  688. };
  689. int slicedChannels = 0, flKeysChannels = 0;
  690. for (auto& entry : std::filesystem::recursive_directory_iterator (realFlpDir))
  691. {
  692. if (entry.path().extension() != ".flp")
  693. continue;
  694. std::ifstream in (entry.path(), std::ios::binary);
  695. std::vector<std::uint8_t> bytes ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  696. ++files;
  697. try
  698. {
  699. const auto p = flp::parseProject (bytes);
  700. CHECK (! p.version.empty());
  701. CHECK (p.tempo > 10.0 && p.tempo < 1000.0);
  702. const auto song = lynx::importFlp (p);
  703. CHECK (! song.patterns.empty());
  704. {
  705. const auto full = lynx::importFlp (p, withFiles);
  706. bool hasFpc = false;
  707. for (const auto& c : p.channels)
  708. hasFpc = hasFpc || c.pluginName == "FPC";
  709. for (const auto& c : full.channels)
  710. {
  711. flKeysChannels += c.zones.size() == 30 && c.zones.front().path.find ("CHANGPIANO") != std::string::npos ? 1 : 0;
  712. if (c.sampler.slices.size() >= 4)
  713. {
  714. ++slicedChannels;
  715. CHECK (std::is_sorted (c.sampler.slices.begin(), c.sampler.slices.end()));
  716. CHECK (c.sampler.slices.back() < 1.0f);
  717. }
  718. if (! c.zones.empty() && c.name.find (" - ") == std::string::npos)
  719. {
  720. ++dwChannels;
  721. dwZones += (int) c.zones.size();
  722. }
  723. padChannels += c.name.find (" - ") != std::string::npos && c.instrument == lynx::InstrumentKind::sampler ? 1 : 0;
  724. }
  725. fpcKits += hasFpc;
  726. for (const auto& pat : full.patterns)
  727. for (const auto& n : pat.notes)
  728. {
  729. CHECK (n.channel >= 0 && n.channel < (int) full.channels.size());
  730. padNotes += full.channels[(std::size_t) n.channel].name.find (" - ") != std::string::npos ? 1 : 0;
  731. }
  732. }
  733. const auto peqDefaults = lynx::makeEffectSlot (lynx::EffectKind::parametricEq).params;
  734. for (const auto& t : song.mixer)
  735. for (const auto& fx : t.effects)
  736. {
  737. if (fx.kind == lynx::EffectKind::parametricEq)
  738. {
  739. ++peqSlots;
  740. peqShaped += fx.params != peqDefaults;
  741. for (double hz : { 50.0, 1000.0, 10000.0 })
  742. CHECK (std::isfinite (lynx::peq::responseDb (fx.params, 48000.0, hz)));
  743. }
  744. if (fx.kind == lynx::EffectKind::reverb)
  745. {
  746. ++reverbs;
  747. reverbsDryless += fx.params[4] < 0.01f;
  748. reverbsLowCut += fx.params[5] > 0.0f;
  749. }
  750. }
  751. for (const auto& t : song.mixer)
  752. if (t.eq.active())
  753. {
  754. ++trackEqs;
  755. for (std::size_t b = 0; b < 3; ++b)
  756. CHECK (t.eq.hz[b] >= 10.0f && t.eq.hz[b] <= 16000.0f && std::abs (t.eq.gainDb[b]) <= 18.0f);
  757. }
  758. for (const auto& a : song.arrangements)
  759. for (const auto& m : a.markers)
  760. {
  761. ++markers;
  762. signatures += m.isSignature();
  763. CHECK (m.tick >= 0);
  764. }
  765. // Fruity Wrapper (canais e slots do mixer): todo blob dos demos é lido
  766. auto countWrapper = [&] (const std::string& plugin, const std::vector<std::uint8_t>& state) {
  767. if (plugin != "Fruity Wrapper")
  768. return;
  769. ++wrapped;
  770. lynx::ForeignPlugin f;
  771. wrappedParsed += lynx::parseFlWrapper (state, f) && f.format != lynx::ForeignPlugin::Format::none && ! f.name.empty();
  772. };
  773. for (const auto& c : p.channels)
  774. countWrapper (c.pluginName, c.pluginState);
  775. for (const auto& insert : p.mixer)
  776. for (const auto& slot : insert.slots)
  777. countWrapper (slot.plugin, slot.state);
  778. // Harmless: todo estado dos demos vira synth, com valores finitos
  779. for (const auto& c : p.channels)
  780. if (c.pluginName == "Harmless")
  781. {
  782. ++harmless;
  783. lynx::SynthSettings hs;
  784. float g = 1.0f;
  785. if (lynx::synthFromHarmless (c.pluginState, 128.0, hs, g))
  786. {
  787. ++harmlessDecoded;
  788. CHECK (std::isfinite (g) && hs.cutoff >= 20.0f && hs.cutoff <= 20000.0f && std::isfinite (hs.decay) && std::isfinite (hs.release));
  789. }
  790. }
  791. // Sytrus: todo estado dos demos (zlib + 10 unidades) decodifica, com valores finitos
  792. for (const auto& c : p.channels)
  793. if (c.pluginName == "Sytrus")
  794. {
  795. ++sytrus;
  796. lynx::SynthSettings ss;
  797. float g = 1.0f;
  798. if (lynx::synthFromSytrus (c.pluginState, 128.0, ss, g))
  799. {
  800. ++sytrusDecoded;
  801. CHECK (std::isfinite (g) && ss.cutoff >= 20.0f && ss.cutoff <= 20000.0f && std::isfinite (ss.attack) && std::isfinite (ss.decay)
  802. && std::isfinite (ss.release) && ss.sustain >= 0.0f && ss.sustain <= 1.0f && std::isfinite (ss.filterEnv.amount));
  803. for (const auto& o : ss.osc)
  804. CHECK (o.level >= 0.0f && o.level <= 1.0f && o.octave >= -3 && o.octave <= 3);
  805. }
  806. }
  807. // geradores da rodada 12
  808. for (const auto& c : p.channels)
  809. {
  810. lynx::SynthSettings gs;
  811. float g = 1.0f;
  812. int decoded = -1;
  813. if (c.pluginName == "Harmor")
  814. decoded = lynx::synthFromHarmor (c.pluginState, gs, g);
  815. else if (c.pluginName == "GMS")
  816. decoded = lynx::synthFromGms (c.pluginState, 128.0, gs, g);
  817. else if (c.pluginName == "Ogun" || c.pluginName == "Autogun")
  818. decoded = lynx::synthFromOgun (c.pluginState, gs, g);
  819. else if (c.pluginName == "Sakura")
  820. decoded = lynx::synthFromSakura (c.pluginState, gs);
  821. else if (c.pluginName == "Kepler")
  822. decoded = lynx::synthFromKepler (c.pluginState, gs, g);
  823. else if (c.pluginName == "Wave Traveller")
  824. decoded = lynx::waveTravellerSample (c.pluginState).has_value() ? 2 : 0;
  825. else if (c.pluginName == "PoiZone")
  826. decoded = lynx::synthFromPoiZone (c.pluginState, gs, g);
  827. else if (c.pluginName == "BassDrum")
  828. decoded = lynx::synthFromBassDrum (c.pluginState, gs, g);
  829. else if (c.pluginName == "Toxic Biohazard")
  830. decoded = lynx::synthFromToxic (c.pluginState, gs, g);
  831. else if (c.pluginName == "Morphine")
  832. decoded = lynx::synthFromMorphine (c.pluginState, gs, g);
  833. else if (c.pluginName == "BooBass")
  834. decoded = lynx::synthFromBooBass (c.pluginState, gs);
  835. else if (c.pluginName == "Drumpad" || c.pluginName == "DrumPad")
  836. decoded = lynx::drumpadPatchName (c.pluginState).has_value() ? 2 : 0;
  837. else if (c.pluginName == "Fruity Envelope Controller" && c.pluginState.size() >= 4 && c.pluginState[2] >= 6) // v >= 6
  838. decoded = lynx::parseEnvelopeController (c.pluginState).has_value() ? 2 : 0;
  839. else if (c.pluginName == "FLEX")
  840. decoded = lynx::flexPresetName (c.pluginState).has_value() ? 2 : 0;
  841. else if (c.pluginName == "Fruity DrumSynth Live")
  842. {
  843. const auto sound = lynx::drumSynthLiveSound (c.pluginState);
  844. decoded = sound && ! lynx::drumSampleCandidates (*sound).empty();
  845. }
  846. if (decoded < 0)
  847. continue;
  848. auto& counter = generators[c.pluginName];
  849. ++counter.first;
  850. counter.second += decoded != 0;
  851. if (decoded == 1 && c.pluginName != "Fruity DrumSynth Live")
  852. {
  853. CHECK (std::isfinite (g) && g >= 0.0f && gs.cutoff >= 20.0f && gs.cutoff <= 20000.0f && gs.sustain >= 0.0f && gs.sustain <= 1.0f);
  854. 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));
  855. for (const auto& o : gs.osc)
  856. CHECK (o.level >= 0.0f && o.level <= 4.0f && std::isfinite (o.detune) && std::isfinite (o.pan));
  857. }
  858. }
  859. // 3x Osc: todo estado dos demos decodifica, com níveis que somam no máximo 1
  860. for (const auto& c : p.channels)
  861. if (c.pluginName == "3x Osc")
  862. {
  863. ++threeOsc;
  864. lynx::SynthSettings s;
  865. if (lynx::synthFrom3xOsc (c.pluginState, s))
  866. {
  867. ++threeOscDecoded;
  868. // com AM o osc 3 é a profundidade da modulação e fica fora da soma
  869. const auto sum = s.osc[0].level + s.osc[1].level + (s.am ? 0.0f : s.osc[2].level);
  870. CHECK (sum <= 1.001f && s.osc[2].level <= 1.0f);
  871. for (const auto& o : s.osc)
  872. CHECK (o.octave >= -2 && o.octave <= 2 && std::abs (o.semitones) <= 11 && std::abs (o.pan) <= 1.0f);
  873. }
  874. }
  875. for (auto& pat : p.patterns)
  876. if (! pat.notes.empty())
  877. {
  878. ++withNotes;
  879. break;
  880. }
  881. for (auto& a : p.arrangements)
  882. for (auto& item : a.items)
  883. CHECK (item.track >= 0 && item.track < 500);
  884. for (auto& clip : song.playlist)
  885. {
  886. CHECK (clip.pattern >= 0 && clip.pattern < (int) song.patterns.size());
  887. CHECK (clip.length > 0 && clip.offset >= 0);
  888. if (clip.kind == lynx::ClipKind::automation)
  889. CHECK (clip.automation >= 0 && clip.automation < (int) song.automations.size());
  890. }
  891. for (auto& a : song.automations)
  892. {
  893. ++automations;
  894. automationsWithTarget += a.target.kind != lynx::AutomationTargetKind::none;
  895. CHECK (a.isLive() || ! a.points.empty());
  896. for (std::size_t i = 1; i < a.points.size(); ++i)
  897. CHECK (a.points[i].tick >= a.points[i - 1].tick);
  898. }
  899. // roteamento importado sem ciclos e com destinos válidos
  900. CHECK (song.mixerOrder().size() + 1 == song.mixer.size());
  901. for (auto& t : song.mixer)
  902. for (auto& s : t.sends)
  903. {
  904. ++sends;
  905. CHECK (s.target > 0 && s.target < (int) song.mixer.size());
  906. }
  907. if (! song.playlist.empty())
  908. ++withPlaylist;
  909. }
  910. catch (const flp::Error& e)
  911. {
  912. ++failures;
  913. std::printf (" FALHOU %s: %s\n", entry.path().string().c_str(), e.what());
  914. }
  915. }
  916. CHECK (threeOscDecoded == threeOsc);
  917. std::printf (" Harmless: %d canais, %d decodificados\n", harmless, harmlessDecoded);
  918. std::printf (" Sytrus: %d canais, %d decodificados\n", sytrus, sytrusDecoded);
  919. for (const auto& [name, counter] : generators)
  920. {
  921. std::printf (" %s: %d canais, %d decodificados\n", name.c_str(), counter.first, counter.second);
  922. CHECK (counter.second == counter.first);
  923. }
  924. // Gross Beat dos demos: o slot de volume vira o gate (os que usam um slot com envelope ficam com passos < 1)
  925. {
  926. int embeddedZones = 0, lovePhilters = 0, lovePhiltersRead = 0, lovePhiltersConverted = 0, gates = 0, shaped = 0, effectors = 0, patchers = 0, serial = 0, parallel = 0, generatorPatchers = 0;
  927. for (const auto& entry : std::filesystem::recursive_directory_iterator (std::filesystem::path (realFlpDir) / "Demo projects"))
  928. if (entry.path().extension() == ".flp")
  929. {
  930. std::ifstream in (entry.path(), std::ios::binary);
  931. const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  932. try
  933. {
  934. const auto project = flp::parseProject (file);
  935. for (const auto& insert : project.mixer)
  936. for (const auto& slot : insert.slots)
  937. if (slot.plugin == "Gross Beat")
  938. {
  939. const auto fx = lynx::effectFromFl (slot.plugin, slot.state);
  940. CHECK (fx && fx->kind == lynx::EffectKind::volumeGate);
  941. ++gates;
  942. if (fx && std::any_of (fx->params.begin(), fx->params.begin() + 32, [] (float v) { return v < 0.99f; }))
  943. ++shaped;
  944. }
  945. else if (slot.plugin == "Fruity Love Philter")
  946. {
  947. ++lovePhilters;
  948. lovePhiltersRead += lynx::parseLovePhilter (slot.state).has_value();
  949. if (const auto conv = lynx::lovePhilterEffects (slot.state))
  950. {
  951. ++lovePhiltersConverted;
  952. CHECK (! conv->slots.empty());
  953. for (const auto& fx : conv->slots)
  954. for (auto v : fx.params)
  955. CHECK (std::isfinite (v) && v >= 0.0f && v <= 1.0f);
  956. }
  957. }
  958. else if (slot.plugin == "Effector")
  959. effectors += lynx::effectFromFl (slot.plugin, slot.state).has_value();
  960. else if (slot.plugin == "Patcher")
  961. {
  962. const auto graph = lynx::parsePatcher (slot.state);
  963. CHECK (graph.has_value());
  964. ++patchers;
  965. if (graph && ! graph->serialChain.empty())
  966. ++serial;
  967. if (graph && ! graph->branches.empty())
  968. ++parallel;
  969. }
  970. for (const auto& c : project.channels)
  971. if (c.pluginName == "DirectWave")
  972. if (const auto program = lynx::directWaveProgram (c.pluginState))
  973. for (const auto& wav : program->embeddedWav)
  974. if (! wav.empty())
  975. {
  976. ++embeddedZones;
  977. CHECK (wav.size() > 44 && std::memcmp (wav.data(), "RIFF", 4) == 0);
  978. }
  979. for (const auto& c : project.channels)
  980. if (c.pluginName == "Patcher")
  981. {
  982. const auto graph = lynx::parsePatcher (c.pluginState);
  983. CHECK (graph.has_value());
  984. generatorPatchers += graph && graph->mainGenerator >= 0;
  985. }
  986. }
  987. catch (const flp::Error&) {}
  988. }
  989. std::printf (" Gross Beat: %d slots, %d com gate; Effector: %d convertidos; Love Philter: %d, %d lidos\n", gates, shaped, effectors,
  990. lovePhilters, lovePhiltersRead);
  991. CHECK (lovePhiltersRead == lovePhilters && lovePhiltersConverted == lovePhilters);
  992. std::printf (" DirectWave: %d zonas com áudio embutido\n", embeddedZones);
  993. CHECK (embeddedZones == 12);
  994. std::printf (" Patcher: %d no mixer (%d em série, %d em ramos paralelos simples), %d como instrumento com gerador\n", patchers, serial,
  995. parallel, generatorPatchers);
  996. CHECK (gates == 0 || shaped > 0);
  997. }
  998. // Envelope Controller "Basic Sidechain" (Future House): cai na nota e volta a ~1 em ~1/3 s
  999. {
  1000. const auto path = std::filesystem::path (realFlpDir) / "Demo projects" / "Demo songs" / "Asher Postman - Future House.flp";
  1001. if (std::filesystem::exists (path))
  1002. {
  1003. std::ifstream in (path, std::ios::binary);
  1004. const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1005. const auto song = lynx::importFlp (flp::parseProject (file));
  1006. const lynx::ChannelDef* controller = nullptr;
  1007. for (const auto& c : song.channels)
  1008. if (c.instrument == lynx::InstrumentKind::controller)
  1009. controller = &c;
  1010. CHECK (controller != nullptr);
  1011. if (controller != nullptr)
  1012. {
  1013. auto inst = lynx::makeInstrument (lynx::InstrumentKind::controller);
  1014. inst->prepare (48000.0);
  1015. inst->configure (*controller, song.bpm);
  1016. std::vector<float> l (480), r (480);
  1017. inst->render (l.data(), r.data(), 480, 1.0f, 1.0f);
  1018. inst->noteOn (60, 1.0f);
  1019. inst->render (l.data(), r.data(), 480, 1.0f, 1.0f); // 10 ms
  1020. const auto ducked = inst->controlOutput (0);
  1021. for (int i = 0; i < 100; ++i) // +1 s
  1022. inst->render (l.data(), r.data(), 480, 1.0f, 1.0f);
  1023. const auto recovered = inst->controlOutput (0);
  1024. std::printf (" Envelope Controller (Basic Sidechain): %.2f na nota, %.2f depois de 1 s\n", ducked, recovered);
  1025. CHECK (ducked < 0.3f && recovered > 0.9f);
  1026. }
  1027. }
  1028. }
  1029. // fuzz por mutação: estados reais com bytes trocados e cortados não podem derrubar os leitores
  1030. {
  1031. std::map<std::string, std::vector<std::uint8_t>> samples; // um blob real por plugin
  1032. for (const auto& entry : std::filesystem::recursive_directory_iterator (std::filesystem::path (realFlpDir) / "Demo projects"))
  1033. {
  1034. if (entry.path().extension() != ".flp")
  1035. continue;
  1036. std::ifstream in (entry.path(), std::ios::binary);
  1037. const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1038. try
  1039. {
  1040. const auto project = flp::parseProject (file);
  1041. for (const auto& c : project.channels)
  1042. if (! c.pluginState.empty())
  1043. samples.emplace (c.pluginName, c.pluginState);
  1044. for (const auto& insert : project.mixer)
  1045. for (const auto& slot : insert.slots)
  1046. if (! slot.state.empty())
  1047. samples.emplace (slot.plugin, slot.state);
  1048. }
  1049. catch (const flp::Error&) {}
  1050. }
  1051. std::uint32_t seed = 12345;
  1052. auto rnd = [&seed] { seed = seed * 1664525u + 1013904223u; return seed >> 8; };
  1053. int mutations = 0;
  1054. for (const auto& [name, original] : samples)
  1055. for (int round = 0; round < 40; ++round)
  1056. {
  1057. auto blob = original;
  1058. if (round % 4 == 3 && ! blob.empty())
  1059. blob.resize (rnd() % blob.size()); // cortado
  1060. else
  1061. for (int k = 0; k < 1 + (int) (rnd() % 8) && ! blob.empty(); ++k)
  1062. blob[rnd() % blob.size()] = (std::uint8_t) rnd();
  1063. ++mutations;
  1064. lynx::SynthSettings synth;
  1065. float gain = 1.0f;
  1066. lynx::synthFromSytrus (blob, 120.0, synth, gain);
  1067. lynx::synthFromHarmor (blob, synth, gain);
  1068. lynx::synthFromGms (blob, 120.0, synth, gain);
  1069. lynx::synthFromOgun (blob, synth, gain);
  1070. lynx::synthFromMorphine (blob, synth, gain);
  1071. lynx::synthFromKepler (blob, synth, gain);
  1072. lynx::synthFromPoiZone (blob, synth, gain);
  1073. lynx::synthFromToxic (blob, synth, gain);
  1074. lynx::synthFromBassDrum (blob, synth, gain);
  1075. lynx::synthFromHarmless (blob, 120.0, synth, gain);
  1076. lynx::parseEnvelopeController (blob);
  1077. lynx::parseKeyboardController (blob);
  1078. lynx::parseLovePhilter (blob);
  1079. lynx::parsePatcher (blob);
  1080. lynx::effectFromFl (name, blob);
  1081. lynx::fpcPads (blob);
  1082. lynx::directWaveProgram (blob);
  1083. CHECK (std::isfinite (gain) && std::isfinite (synth.cutoff));
  1084. }
  1085. std::printf (" fuzz por mutação: %d blobs de %d plugins\n", mutations, (int) samples.size());
  1086. }
  1087. // samples WavPack (.wv) dos pacotes do FL: todos decodificam, com áudio finito e não mudo
  1088. {
  1089. int files = 0, decoded = 0, audible = 0;
  1090. double seconds = 0.0;
  1091. for (const auto& entry : std::filesystem::recursive_directory_iterator (std::filesystem::path (realFlpDir) / "Patches" / "Packs"))
  1092. if (entry.path().extension() == ".wv")
  1093. {
  1094. std::ifstream in (entry.path(), std::ios::binary);
  1095. const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1096. ++files;
  1097. lynx::DecodedAudio audio;
  1098. if (! lynx::decodeWavPack (file.data(), file.size(), audio))
  1099. continue;
  1100. ++decoded;
  1101. float peak = 0.0f;
  1102. bool finite = true;
  1103. for (const auto& ch : audio.channels)
  1104. for (auto v : ch)
  1105. {
  1106. finite = finite && std::isfinite (v);
  1107. peak = std::max (peak, std::abs (v));
  1108. }
  1109. CHECK (finite && peak <= 4.0f);
  1110. audible += peak > 1e-4f;
  1111. seconds += (double) audio.channels[0].size() / audio.sampleRate;
  1112. }
  1113. std::printf (" WavPack: %d arquivos .wv, %d decodificados, %d com som, %.0f s de áudio\n", files, decoded, audible, seconds);
  1114. CHECK (decoded == files);
  1115. }
  1116. // presets nativos do GMS (.gmsynth = o conteúdo do 0xD5 sem o "SSLF")
  1117. int gmsPresets = 0, gmsDecoded = 0;
  1118. const auto gmsFolder = std::filesystem::path (realFlpDir) / "Patches" / "Plugin presets" / "Generators" / "GMS";
  1119. if (std::filesystem::exists (gmsFolder))
  1120. for (const auto& entry : std::filesystem::recursive_directory_iterator (gmsFolder))
  1121. if (entry.path().extension() == ".gmsynth")
  1122. {
  1123. std::ifstream in (entry.path(), std::ios::binary);
  1124. std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1125. std::vector<std::uint8_t> blob { 'S', 'S', 'L', 'F' };
  1126. const auto n = (std::uint32_t) file.size();
  1127. blob.insert (blob.end(), reinterpret_cast<const std::uint8_t*> (&n), reinterpret_cast<const std::uint8_t*> (&n) + 4);
  1128. blob.insert (blob.end(), file.begin(), file.end());
  1129. lynx::SynthSettings gs;
  1130. float g = 1.0f;
  1131. ++gmsPresets;
  1132. if (lynx::synthFromGms (blob, 120.0, gs, g))
  1133. {
  1134. ++gmsDecoded;
  1135. CHECK (std::isfinite (g) && gs.cutoff >= 20.0f && std::isfinite (gs.pitchEnv.amount) && std::isfinite (gs.lfo[lynx::lfoPitch].period));
  1136. }
  1137. }
  1138. std::printf (" presets GMS: %d, %d decodificados\n", gmsPresets, gmsDecoded);
  1139. // o botão "Presets do FL" do synth: .fst de Sytrus/Harmor e .gmsynth viram ajustes do synth
  1140. int presetFiles = 0, presetsRead = 0;
  1141. for (const auto* name : { "Sytrus", "Harmor", "GMS", "Harmless", "Ogun", "Sakura", "Fruit Kick", "Fruity DX10", "MiniSynth", "Kepler",
  1142. "PoiZone", "Toxic Biohazard", "BassDrum" })
  1143. {
  1144. const auto folder = std::filesystem::path (realFlpDir) / "Patches" / "Plugin presets" / "Generators" / name;
  1145. if (! std::filesystem::exists (folder))
  1146. continue;
  1147. for (const auto& entry : std::filesystem::recursive_directory_iterator (folder))
  1148. if (entry.path().extension() == ".fst" || entry.path().extension() == ".gmsynth")
  1149. {
  1150. std::ifstream in (entry.path(), std::ios::binary);
  1151. const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
  1152. ++presetFiles;
  1153. presetsRead += lynx::synthFromFlPreset (file).has_value();
  1154. }
  1155. }
  1156. std::printf (" presets de synth do FL: %d arquivos, %d lidos\n", presetFiles, presetsRead);
  1157. CHECK (presetsRead >= presetFiles * 95 / 100);
  1158. CHECK (gmsDecoded == gmsPresets);
  1159. CHECK (sytrusDecoded == sytrus);
  1160. CHECK (harmlessDecoded == harmless && harmless > 100);
  1161. // presets de canal do 3x Osc que vêm com o FL (.fst): todos viram ajustes do synth
  1162. int presets = 0, presetsDecoded = 0;
  1163. const auto presetDir = std::filesystem::path (realFlpDir) / "Patches" / "Channel presets" / "3x Osc";
  1164. if (std::filesystem::is_directory (presetDir))
  1165. for (auto& entry : std::filesystem::directory_iterator (presetDir))
  1166. if (entry.path().extension() == ".fst")
  1167. {
  1168. ++presets;
  1169. std::ifstream in (entry.path(), std::ios::binary);
  1170. std::vector<std::uint8_t> bytes ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  1171. if (auto synth = lynx::synthFromFlPreset (bytes))
  1172. {
  1173. ++presetsDecoded;
  1174. CHECK (synth->osc[0].level + synth->osc[1].level + (synth->am ? 0.0f : synth->osc[2].level) <= 1.001f);
  1175. }
  1176. }
  1177. std::printf (" %d presets de 3x Osc, %d lidos\n", presets, presetsDecoded);
  1178. CHECK (presetsDecoded == presets);
  1179. // presets de efeito do FL que viram efeitos internos
  1180. int fxPresets = 0, fxDecoded = 0;
  1181. for (auto kind : { lynx::EffectKind::parametricEq, lynx::EffectKind::limiter, lynx::EffectKind::reverb, lynx::EffectKind::delay,
  1182. lynx::EffectKind::utility })
  1183. for (const auto& plugin : lynx::flPluginsForEffect (kind))
  1184. {
  1185. const auto dir = std::filesystem::path (realFlpDir) / "Patches" / "Plugin presets" / "Effects" / plugin;
  1186. if (! std::filesystem::is_directory (dir))
  1187. continue;
  1188. for (auto& entry : std::filesystem::recursive_directory_iterator (dir))
  1189. if (entry.path().extension() == ".fst")
  1190. {
  1191. ++fxPresets;
  1192. std::ifstream in (entry.path(), std::ios::binary);
  1193. std::vector<std::uint8_t> bytes ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  1194. fxDecoded += lynx::effectFromFlPreset (bytes).has_value();
  1195. }
  1196. }
  1197. std::printf (" %d presets de efeito do FL, %d lidos\n", fxPresets, fxDecoded);
  1198. CHECK (fxDecoded == fxPresets);
  1199. CHECK (wrappedParsed == wrapped);
  1200. std::printf (" %d plugins no Fruity Wrapper, %d lidos\n", wrapped, wrappedParsed);
  1201. std::printf (" %d marcadores, %d mudanças de compasso, %d trilhas com EQ\n", markers, signatures, trackEqs);
  1202. std::printf (" %d EQs paramétricos (%d com ajustes do FL), %d reverbs (%d sem seco)\n", peqSlots, peqShaped, reverbs, reverbsDryless);
  1203. std::printf (" DirectWave: %d canais, %d zonas; FPC: %d projetos, %d canais de pad, %d notas nos pads\n", dwChannels, dwZones, fpcKits,
  1204. padChannels, padNotes);
  1205. CHECK (dwZones > 1000 && padChannels > 250 && padNotes > 500);
  1206. std::printf (" canais fatiados (Slicer/Slicex): %d; WAVs embutidos gravados: %d\n", slicedChannels, embeddedSaved);
  1207. CHECK (slicedChannels >= 25 && embeddedSaved >= 10); // sem decodificar Ogg aqui, parte dos loops fica sem duração
  1208. std::printf (" FL Keys (Grand Piano, 30 zonas): %d canais\n", flKeysChannels);
  1209. CHECK (flKeysChannels >= 8);
  1210. CHECK (peqSlots > 1000 && peqShaped > 900 && reverbsDryless > 20 && reverbsLowCut > 250);
  1211. CHECK (markers > 300 && signatures > 60);
  1212. std::printf (" %d canais 3x Osc, %d decodificados\n", threeOsc, threeOscDecoded);
  1213. std::printf (" %d arquivos .flp lidos, %d com notas, %d com playlist, %d automações (%d com alvo), %d envios\n",
  1214. files, withNotes, withPlaylist, automations, automationsWithTarget, sends);
  1215. CHECK (files > 0);
  1216. CHECK (automations > 0 && sends > 0);
  1217. }
  1218. // ---------------------------------------------------------------------------
  1219. // Sequenciador
  1220. TEST (pattern_toggle_step_and_length)
  1221. {
  1222. lynx::Pattern p;
  1223. CHECK (! p.hasStep (0, 4));
  1224. p.toggleStep (0, 4);
  1225. CHECK (p.hasStep (0, 4));
  1226. CHECK (p.notes.size() == 1 && p.notes[0].start == 4 * lynx::ticksPerStep);
  1227. CHECK (p.effectiveLength (4) == 4 * lynx::ppq); // um compasso
  1228. p.toggleStep (1, 20); // segundo compasso
  1229. CHECK (p.effectiveLength (4) == 8 * lynx::ppq);
  1230. p.toggleStep (0, 4);
  1231. CHECK (! p.hasStep (0, 4) && p.notes.size() == 1);
  1232. }
  1233. TEST (scheduler_places_events_at_exact_samples)
  1234. {
  1235. lynx::Pattern p;
  1236. p.toggleStep (0, 0);
  1237. p.toggleStep (0, 4); // tick 960 = 1 tempo
  1238. const double sr = 48000.0, bpm = 120.0; // 1 tempo = 0,5 s = 24000 samples
  1239. const auto tps = lynx::ticksPerSample (bpm, sr);
  1240. lynx::EventBuffer ev;
  1241. lynx::schedulePatternLoop (p, p.effectiveLength (4), 23900.0 * tps, 512, tps, ev);
  1242. // a nota do tempo 2 começa no sample 24000 → offset 100 neste bloco
  1243. int ons = 0;
  1244. for (auto& e : ev)
  1245. if (e.type == lynx::NoteEvent::Type::on)
  1246. {
  1247. ++ons;
  1248. CHECK (e.sampleOffset == 100);
  1249. }
  1250. CHECK (ons == 1);
  1251. }
  1252. TEST (scheduler_wraps_the_loop)
  1253. {
  1254. lynx::Pattern p;
  1255. p.toggleStep (2, 0);
  1256. const auto len = p.effectiveLength (4); // 3840 ticks
  1257. const double sr = 48000.0;
  1258. const auto tps = lynx::ticksPerSample (120.0, sr);
  1259. lynx::EventBuffer ev;
  1260. // bloco que atravessa o fim do loop: começa 10 samples antes
  1261. const auto start = (double) len - 10.0 * tps;
  1262. lynx::schedulePatternLoop (p, len, start, 64, tps, ev);
  1263. bool found = false;
  1264. for (auto& e : ev)
  1265. if (e.type == lynx::NoteEvent::Type::on && e.channel == 2)
  1266. {
  1267. found = true;
  1268. CHECK (e.sampleOffset == 10);
  1269. }
  1270. CHECK (found);
  1271. }
  1272. TEST (scheduler_off_before_on_at_same_sample)
  1273. {
  1274. lynx::Pattern p;
  1275. lynx::Note a;
  1276. a.start = 0; a.length = 240; a.channel = 0;
  1277. lynx::Note b = a;
  1278. b.start = 240;
  1279. p.notes = { a, b };
  1280. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  1281. lynx::EventBuffer ev;
  1282. lynx::schedulePatternLoop (p, p.effectiveLength (4), 200.0, 4000, tps, ev);
  1283. CHECK (ev.size() >= 2);
  1284. CHECK (ev[0].type == lynx::NoteEvent::Type::off);
  1285. CHECK (ev[1].type == lynx::NoteEvent::Type::on);
  1286. CHECK (ev[0].sampleOffset == ev[1].sampleOffset);
  1287. }
  1288. TEST (snapshot_exchange_hands_over_and_recycles)
  1289. {
  1290. struct Counted
  1291. {
  1292. int value;
  1293. int* alive;
  1294. Counted (int v, int* a) : value (v), alive (a) { ++*alive; }
  1295. ~Counted() { --*alive; }
  1296. };
  1297. int alive = 0;
  1298. {
  1299. lynx::SnapshotExchange<Counted> x;
  1300. CHECK (x.acquire() == nullptr);
  1301. x.publish (std::make_unique<Counted> (1, &alive));
  1302. CHECK (x.acquire()->value == 1);
  1303. x.publish (std::make_unique<Counted> (2, &alive));
  1304. x.publish (std::make_unique<Counted> (3, &alive)); // 2 nunca foi lido: liberado na hora
  1305. CHECK (alive == 2);
  1306. CHECK (x.acquire()->value == 3);
  1307. CHECK (alive == 2); // o 1 foi devolvido, mas só a UI libera
  1308. x.collectGarbage();
  1309. CHECK (alive == 1);
  1310. // sem coleta, as vagas de devolução enchem e o áudio segura o atual
  1311. for (int i = 0; i < 20; ++i)
  1312. {
  1313. x.publish (std::make_unique<Counted> (10 + i, &alive));
  1314. CHECK (x.acquire() != nullptr);
  1315. }
  1316. }
  1317. CHECK (alive == 0);
  1318. }
  1319. TEST (rack_renderer_makes_sound_and_reuses_instruments)
  1320. {
  1321. auto song = lynx::Song::makeDefault();
  1322. song.bpm = 120.0;
  1323. const double sr = 48000.0;
  1324. auto state = lynx::RackState::build (song, nullptr, sr);
  1325. lynx::RackRenderer r;
  1326. r.prepare (sr);
  1327. std::vector<float> l (512), rr (512);
  1328. double tick = 0.0;
  1329. float peak = 0.0f;
  1330. int kicks = 0;
  1331. for (int block = 0; block < 93; ++block) // 47616 samples: logo antes de 1 s
  1332. {
  1333. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  1334. for (auto& e : r.lastEvents())
  1335. if (e.type == lynx::NoteEvent::Type::on && e.channel == 0)
  1336. ++kicks;
  1337. for (int i = 0; i < 512; ++i)
  1338. {
  1339. CHECK (std::isfinite (l[(std::size_t) i]));
  1340. peak = std::max (peak, std::abs (l[(std::size_t) i]));
  1341. }
  1342. tick += 512 * lynx::ticksPerSample (song.bpm, sr);
  1343. }
  1344. CHECK (peak > 0.1f && peak < 4.0f);
  1345. CHECK (kicks == 2); // 120 BPM: tempos em 0 e 0,5 s
  1346. // editar a música preserva os instrumentos de canais que não mudaram de tipo
  1347. song.channels[4].instrument = lynx::InstrumentKind::kick;
  1348. auto next = lynx::RackState::build (song, state.get(), sr);
  1349. CHECK (next->instruments[0] == state->instruments[0]);
  1350. CHECK (next->instruments[4] != state->instruments[4]);
  1351. // parar silencia o synth e não dispara notas novas
  1352. r.process (next.get(), false, tick, 512, l.data(), rr.data());
  1353. CHECK (r.lastEvents().size() == 0);
  1354. }
  1355. TEST (flp_import_maps_channels_and_rescales)
  1356. {
  1357. flp::Project p;
  1358. p.header.ppq = 96;
  1359. p.tempo = 150.0;
  1360. p.channels = { { 0, flp::ChannelType::sampler, "Kick 808", "", "", 1 },
  1361. { 1, flp::ChannelType::audioClip, "Vocal", "", "", 2 },
  1362. { 2, flp::ChannelType::instrument, "Lead", "FLEX", "", 3 } };
  1363. flp::Pattern pat;
  1364. pat.index = 1;
  1365. flp::Note n;
  1366. n.position = 96;
  1367. n.length = 0;
  1368. n.channel = 2;
  1369. n.key = 72;
  1370. n.velocity = 64;
  1371. pat.notes.push_back (n);
  1372. p.patterns.push_back (pat);
  1373. const auto s = lynx::importFlp (p);
  1374. CHECK (s.bpm == 150.0);
  1375. CHECK (s.channels.size() == 3); // canais de clip de áudio ficam no rack, como no FL
  1376. CHECK (s.channels[0].instrument == lynx::InstrumentKind::kick);
  1377. CHECK (s.channels[1].instrument == lynx::InstrumentKind::audioClip);
  1378. CHECK (s.channels[2].instrument == lynx::InstrumentKind::synth);
  1379. CHECK (s.patterns.size() == 1);
  1380. CHECK (s.patterns[0].notes[0].start == lynx::ppq); // 96 @ PPQ 96 = 1 tempo
  1381. CHECK (s.patterns[0].notes[0].channel == 2);
  1382. CHECK (s.patterns[0].notes[0].length == lynx::ticksPerStep); // nota de step
  1383. CHECK (std::abs (s.patterns[0].notes[0].velocity - 0.5f) < 1e-6f);
  1384. }
  1385. TEST (live_queue_is_fifo_and_bounded)
  1386. {
  1387. lynx::LiveEventQueue q;
  1388. lynx::NoteEvent e;
  1389. CHECK (! q.pop (e));
  1390. for (int i = 0; i < 10; ++i)
  1391. {
  1392. lynx::NoteEvent in;
  1393. in.key = i;
  1394. CHECK (q.push (in));
  1395. }
  1396. for (int i = 0; i < 10; ++i)
  1397. CHECK (q.pop (e) && e.key == i);
  1398. int pushed = 0;
  1399. while (q.push (e))
  1400. ++pushed;
  1401. CHECK (pushed == (int) lynx::LiveEventQueue::capacity - 1); // uma vaga fica livre para distinguir cheio de vazio
  1402. }
  1403. TEST (sampler_plays_pitched_one_shot)
  1404. {
  1405. // sample de 1000 frames com rampa: dá para medir a posição pela amplitude
  1406. auto data = std::make_shared<lynx::SampleData>();
  1407. data->sampleRate = 48000.0;
  1408. for (int i = 0; i < 1000; ++i)
  1409. data->left.push_back (1.0f);
  1410. auto sampler = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  1411. sampler->prepare (48000.0);
  1412. std::vector<float> l (2048, 0.0f), r (2048, 0.0f);
  1413. sampler->noteOn (60, 1.0f);
  1414. sampler->noteOff (60); // one-shot: noteOff não corta
  1415. sampler->render (l.data(), r.data(), 2048, 1.0f, 1.0f);
  1416. int sounding = 0;
  1417. for (auto s : l)
  1418. sounding += s > 0.5f;
  1419. CHECK (sounding >= 995 && sounding <= 1000); // toca o sample inteiro na altura original
  1420. std::fill (l.begin(), l.end(), 0.0f);
  1421. sampler->noteOn (72, 1.0f); // uma oitava acima: metade da duração
  1422. sampler->render (l.data(), r.data(), 2048, 1.0f, 1.0f);
  1423. sounding = 0;
  1424. for (auto s : l)
  1425. sounding += s > 0.5f;
  1426. CHECK (sounding >= 495 && sounding <= 500);
  1427. CHECK (r[10] > 0.5f); // mono vai para os dois lados
  1428. auto silent = lynx::makeInstrument (lynx::InstrumentKind::sampler, nullptr);
  1429. silent->prepare (48000.0);
  1430. silent->noteOn (60, 1.0f);
  1431. std::fill (l.begin(), l.end(), 0.0f);
  1432. silent->render (l.data(), r.data(), 64, 1.0f, 1.0f);
  1433. CHECK (l[0] == 0.0f);
  1434. }
  1435. TEST (rack_live_notes_and_sample_provider)
  1436. {
  1437. lynx::Song song;
  1438. lynx::ChannelDef c;
  1439. c.name = "Smp";
  1440. c.instrument = lynx::InstrumentKind::sampler;
  1441. c.samplePath = "a.wav";
  1442. song.channels.push_back (c);
  1443. song.patterns.emplace_back();
  1444. int loads = 0;
  1445. auto provider = [&] (const std::string& path) -> std::shared_ptr<const lynx::SampleData> {
  1446. ++loads;
  1447. CHECK (path == "a.wav");
  1448. auto d = std::make_shared<lynx::SampleData>();
  1449. d->left.assign (4800, 0.5f);
  1450. return d;
  1451. };
  1452. auto state = lynx::RackState::build (song, nullptr, 48000.0, provider);
  1453. CHECK (loads == 1);
  1454. lynx::RackRenderer renderer;
  1455. renderer.prepare (48000.0);
  1456. lynx::LiveEventQueue live;
  1457. lynx::NoteEvent on;
  1458. on.channel = 0;
  1459. on.velocity = 1.0f;
  1460. live.push (on);
  1461. std::vector<float> l (256), r (256);
  1462. renderer.process (state.get(), false, 0.0, 256, l.data(), r.data(), &live); // parado, mas a nota ao vivo toca
  1463. CHECK (l[0] > 0.1f);
  1464. // mesmo sample: reaproveita; sample diferente: recarrega
  1465. auto same = lynx::RackState::build (song, state.get(), 48000.0, provider);
  1466. CHECK (loads == 1 && same->instruments[0] == state->instruments[0]);
  1467. song.channels[0].samplePath = "b.wav";
  1468. auto other = lynx::RackState::build (song, state.get(), 48000.0, [&] (const std::string&) { ++loads; return nullptr; });
  1469. CHECK (loads == 2 && other->instruments[0] != state->instruments[0]);
  1470. }
  1471. TEST (flp_paths_resolve_and_samplers_import)
  1472. {
  1473. lynx::FlPathRoots roots { "C:\\FL", "C:\\FL\\Data", "D:\\User" };
  1474. CHECK (lynx::resolveFlPath ("%FLStudioFactoryData%\\Data\\x.wav", roots) == "C:\\FL\\Data\\x.wav");
  1475. CHECK (lynx::resolveFlPath ("%FLStudioData%\\Patches\\y.wav", roots) == "C:\\FL\\Data\\Patches\\y.wav");
  1476. CHECK (lynx::resolveFlPath ("%FLStudioUserData%\\z.wav", roots) == "D:\\User\\z.wav");
  1477. CHECK (lynx::resolveFlPath ("E:\\abs.wav", roots) == "E:\\abs.wav");
  1478. CHECK (lynx::resolveFlPath ("%FLStudioUserData%\\z.wav", {}) == "");
  1479. flp::Project p;
  1480. p.channels = { { 0, flp::ChannelType::sampler, "Kick", "", "%FLStudioData%\\k.wav", 1 },
  1481. { 1, flp::ChannelType::sampler, "Hat", "", "%FLStudioData%\\missing.wav", 1 } };
  1482. lynx::FlpImportOptions options;
  1483. options.roots = roots;
  1484. options.fileExists = [] (const std::string& path) { return path == "C:\\FL\\Data\\k.wav"; };
  1485. const auto s = lynx::importFlp (p, options);
  1486. CHECK (s.channels[0].instrument == lynx::InstrumentKind::sampler);
  1487. CHECK (s.channels[0].samplePath == "C:\\FL\\Data\\k.wav");
  1488. CHECK (s.channels[1].instrument == lynx::InstrumentKind::hat); // sem arquivo: instrumento interno
  1489. }
  1490. TEST (soft_clip_is_transparent_below_knee_and_bounded)
  1491. {
  1492. float s[] = { 0.5f, -0.89f, 1.5f, -3.0f, 0.95f };
  1493. lynx::softClip (s, 5);
  1494. CHECK (s[0] == 0.5f && s[1] == -0.89f);
  1495. CHECK (s[2] > 0.9f && s[2] <= 1.0f);
  1496. CHECK (s[3] < -0.9f && s[3] >= -1.0f);
  1497. CHECK (s[4] > 0.9f && s[4] < 0.95f);
  1498. }
  1499. TEST (song_scheduler_plays_clips_with_offset_and_cut)
  1500. {
  1501. lynx::Song s;
  1502. s.channels.resize (1);
  1503. auto& p = s.patterns.emplace_back();
  1504. for (int step : { 0, 4, 8, 12 }) // uma nota por tempo
  1505. p.toggleStep (0, step);
  1506. // clip no compasso 2 tocando só a segunda metade da pattern (tempos 3 e 4)
  1507. lynx::Clip c;
  1508. c.pattern = 0;
  1509. c.start = 4 * lynx::ppq;
  1510. c.length = 2 * lynx::ppq;
  1511. c.offset = 2 * lynx::ppq;
  1512. s.playlist.push_back (c);
  1513. CHECK (s.songLength() == 8 * lynx::ppq);
  1514. const double sr = 48000.0;
  1515. const auto tps = lynx::ticksPerSample (120.0, sr); // 1 tempo = 24000 samples
  1516. lynx::EventBuffer ev;
  1517. // música inteira em um bloco só (8 tempos = 192000 samples)
  1518. lynx::scheduleSong (s, 0.0, 192000, tps, ev);
  1519. std::vector<int> ons;
  1520. for (auto& e : ev)
  1521. if (e.type == lynx::NoteEvent::Type::on)
  1522. ons.push_back (e.sampleOffset);
  1523. CHECK (ons.size() == 2);
  1524. CHECK (ons.size() == 2 && ons[0] == 4 * 24000 && ons[1] == 5 * 24000);
  1525. // atravessando o loop: o compasso 1 está vazio, então nada no começo do segundo giro
  1526. ev.clear();
  1527. lynx::scheduleSong (s, 8.0 * lynx::ppq - 100 * tps, 200, tps, ev);
  1528. CHECK (ev.size() == 0);
  1529. // nota mais longa que o clip é cortada no fim do clip
  1530. p.notes[3].length = 4 * lynx::ppq;
  1531. ev.clear();
  1532. lynx::scheduleSong (s, 0.0, 192000, tps, ev);
  1533. int lastOff = -1;
  1534. for (auto& e : ev)
  1535. if (e.type == lynx::NoteEvent::Type::off)
  1536. lastOff = std::max (lastOff, e.sampleOffset);
  1537. CHECK (lastOff == 6 * 24000);
  1538. }
  1539. TEST (remove_pattern_fixes_clips)
  1540. {
  1541. lynx::Song s;
  1542. s.patterns.resize (3);
  1543. s.currentPattern = 2;
  1544. s.playlist = { { 0, 0, 0, 100, 0 }, { 1, 0, 100, 100, 0 }, { 2, 1, 0, 100, 0 } };
  1545. s.removePattern (1);
  1546. CHECK (s.patterns.size() == 2);
  1547. CHECK (s.playlist.size() == 2 && s.playlist[1].pattern == 1);
  1548. CHECK (s.currentPattern == 1);
  1549. }
  1550. TEST (flp_import_3x_osc_state_and_channel_filter)
  1551. {
  1552. // patch novo do 3x Osc (versão 14): osc 2 mix 64 coarse -12, osc 3 mix 32 coarse -24
  1553. std::vector<std::uint8_t> blob (460, 0);
  1554. auto put = [&] (std::size_t off, std::int32_t v) {
  1555. for (int b = 0; b < 4; ++b)
  1556. blob[off + (std::size_t) b] = (std::uint8_t) ((std::uint32_t) v >> (8 * b));
  1557. };
  1558. put (0x00, 14);
  1559. put (0x08, 3); // osc 1 serra
  1560. put (0x10, 7); // osc 1 fine +7
  1561. put (0x04, -32); // osc 1 pan -0,5
  1562. put (0x1C, 64); // osc 2 mix
  1563. put (0x28, -12); // osc 2 coarse
  1564. put (0x38, 32); // osc 3 mix
  1565. put (0x40, 2); // osc 3 quadrada
  1566. put (0x44, -19); // osc 3 coarse: -1 oitava e -7 semitons
  1567. lynx::SynthSettings s;
  1568. CHECK (lynx::synthFrom3xOsc (blob, s));
  1569. 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);
  1570. CHECK (s.osc[0].wave == lynx::Waveform::saw && s.osc[0].detune == 7.0f && s.osc[0].pan == -0.5f);
  1571. CHECK (s.osc[1].wave == lynx::Waveform::sine && s.osc[1].octave == -1 && s.osc[1].semitones == 0);
  1572. CHECK (s.osc[2].wave == lynx::Waveform::square && s.osc[2].octave == -1 && s.osc[2].semitones == -7);
  1573. CHECK (! lynx::synthFrom3xOsc (std::vector<std::uint8_t> (40, 0), s));
  1574. // filtro do canal: padrão aberto; LP com Mod X 128 ~ 2,71 kHz; Fast LP com Mod X 128 ~ 280 Hz
  1575. float hz = 0.0f, res = 1.0f;
  1576. int mode = -1;
  1577. lynx::synthFilterFromChannel (256, 0, 0, hz, res, mode);
  1578. CHECK (hz >= 19999.0f && res == 0.0f);
  1579. lynx::synthFilterFromChannel (128, 0, 1, hz, res, mode);
  1580. CHECK (std::abs (hz - 2710.0f) < 30.0f && res == 0.0f);
  1581. lynx::synthFilterFromChannel (128, 0, 0, hz, res, mode);
  1582. CHECK (hz > 240.0f && hz < 320.0f);
  1583. lynx::synthFilterFromChannel (128, 256, 1, hz, res, mode);
  1584. CHECK (res > 0.8f);
  1585. CHECK (mode == 0);
  1586. lynx::synthFilterFromChannel (64, 0, 3, hz, res, mode); // passa-altas em ~840 Hz
  1587. CHECK (mode == 2 && std::abs (hz - 840.0f) < 40.0f);
  1588. lynx::synthFilterFromChannel (128, 0, 2, hz, res, mode); // passa-banda
  1589. CHECK (mode == 1);
  1590. }
  1591. TEST (synth_pitch_and_filter_envelopes)
  1592. {
  1593. auto render = [] (const lynx::SynthSettings& s, int frames) {
  1594. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  1595. inst->prepare (48000.0);
  1596. lynx::ChannelDef c;
  1597. c.synth = s;
  1598. inst->configure (c, 120.0);
  1599. inst->noteOn (45, 1.0f); // A2 = 110 Hz
  1600. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  1601. inst->render (l.data(), r.data(), frames, 1.0f, 1.0f);
  1602. return l;
  1603. };
  1604. auto crossings = [] (const std::vector<float>& b, int from, int to) {
  1605. int n = 0;
  1606. for (int i = from + 1; i < to; ++i)
  1607. n += (b[(std::size_t) i - 1] < 0.0f) != (b[(std::size_t) i] < 0.0f);
  1608. return n;
  1609. };
  1610. // "kick" do 3x Osc: seno com envelope de afinação +24 st caindo rápido
  1611. lynx::SynthSettings kick;
  1612. kick.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  1613. kick.cutoff = 20000.0f;
  1614. kick.pitchEnv = { 24.0f, 0.0f, 0.0f, 0.05f, 0.0f, 0.05f };
  1615. const auto k = render (kick, 48000);
  1616. const auto early = crossings (k, 0, 2400); // 50 ms iniciais: bem acima de 110 Hz
  1617. const auto late = crossings (k, 24000, 48000); // depois volta aos 110 Hz (~110 cruzamentos em 0,5 s)
  1618. CHECK (early > 20); // reta de +24 st em 50 ms: ~2,2x a frequência média (11 cruzamentos sem envelope)
  1619. CHECK (std::abs (late - 110) < 4);
  1620. // envelope de corte: serra fechada em 200 Hz abre +5 oitavas no ataque e fecha de novo
  1621. lynx::SynthSettings pluck;
  1622. pluck.cutoff = 200.0f;
  1623. pluck.filterEnv = { 5.0f, 0.0f, 0.0f, 0.1f, 0.0f, 0.1f };
  1624. const auto p = render (pluck, 48000);
  1625. auto hf = [&] (int from, int to) { // energia da diferença (agudos)
  1626. double e = 0.0;
  1627. for (int i = from + 1; i < to; ++i)
  1628. e += std::pow ((double) p[(std::size_t) i] - p[(std::size_t) i - 1], 2.0);
  1629. return e;
  1630. };
  1631. CHECK (hf (0, 2400) > 4.0 * hf (40000, 42400));
  1632. }
  1633. TEST (synth_mono_reuses_the_sounding_voice)
  1634. {
  1635. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  1636. inst->prepare (48000.0);
  1637. lynx::ChannelDef c;
  1638. c.synth.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  1639. c.synth.cutoff = 20000.0f;
  1640. c.synth.mono = true;
  1641. inst->configure (c, 120.0);
  1642. std::vector<float> l (48000), r (48000);
  1643. inst->noteOn (57, 1.0f);
  1644. inst->render (l.data(), r.data(), 4800, 1.0f, 1.0f);
  1645. inst->noteOn (69, 1.0f); // A4 assume a voz do A3: só uma nota soando
  1646. inst->render (l.data() + 4800, r.data() + 4800, 43200, 1.0f, 1.0f);
  1647. int crossings = 0;
  1648. float peak = 0.0f;
  1649. for (std::size_t i = 24001; i < 48000; ++i)
  1650. {
  1651. crossings += (l[i - 1] < 0.0f) != (l[i] < 0.0f);
  1652. peak = std::max (peak, std::abs (l[i]));
  1653. }
  1654. CHECK (std::abs (crossings - 440) < 4); // 0,5 s de 440 Hz, sem o A3 por baixo
  1655. CHECK (peak < 0.35f); // uma voz (0,3 de nível), não duas somadas
  1656. // sem estalo na troca: o salto entre samples vizinhos fica no tamanho do seno
  1657. float jump = 0.0f;
  1658. for (std::size_t i = 4790; i < 4810; ++i)
  1659. jump = std::max (jump, std::abs (l[i] - l[i - 1]));
  1660. CHECK (jump < 0.05f);
  1661. }
  1662. TEST (synth_porta_glides_and_am_modulates)
  1663. {
  1664. auto make = [] (const lynx::SynthSettings& s) {
  1665. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  1666. inst->prepare (48000.0);
  1667. lynx::ChannelDef c;
  1668. c.synth = s;
  1669. inst->configure (c, 120.0);
  1670. return inst;
  1671. };
  1672. auto crossings = [] (const std::vector<float>& b, std::size_t from, std::size_t to) {
  1673. int n = 0;
  1674. for (auto i = from + 1; i < to; ++i)
  1675. n += (b[i - 1] < 0.0f) != (b[i] < 0.0f);
  1676. return n;
  1677. };
  1678. // mono + porta de 1 tempo (0,5 s a 120 BPM): de A3 para A4, no meio do caminho ~E4 (329,6 Hz)
  1679. lynx::SynthSettings s;
  1680. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  1681. s.cutoff = 20000.0f;
  1682. s.mono = true;
  1683. s.porta = true;
  1684. s.portaBeats = 1.0f;
  1685. auto inst = make (s);
  1686. std::vector<float> l (96000), r (96000);
  1687. inst->noteOn (57, 1.0f);
  1688. inst->render (l.data(), r.data(), 4800, 1.0f, 1.0f);
  1689. inst->noteOn (69, 1.0f);
  1690. inst->render (l.data() + 4800, r.data() + 4800, 91200, 1.0f, 1.0f);
  1691. const auto middle = crossings (l, 4800 + 12000 - 2400, 4800 + 12000 + 2400); // 0,1 s em volta de 0,25 s
  1692. CHECK (std::abs (middle - 66) < 6); // ~330 Hz * 0,1 s * 2
  1693. CHECK (std::abs (crossings (l, 48000, 96000) - 880) < 4); // chegou no A4 (1 s = 880 cruzamentos)
  1694. // AM: osc 3 em 1,0 de nível, seno lento, modula o osc 1 (o nível médio cai, a soma não ganha o osc 3)
  1695. lynx::SynthSettings am;
  1696. am.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  1697. am.osc[2] = { lynx::Waveform::sine, -3, 0.0f, 1.0f };
  1698. am.cutoff = 20000.0f;
  1699. am.am = true;
  1700. auto modulated = make (am);
  1701. modulated->noteOn (69, 1.0f);
  1702. std::fill (l.begin(), l.end(), 0.0f);
  1703. modulated->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  1704. float peak = 0.0f;
  1705. for (std::size_t i = 4800; i < 48000; ++i)
  1706. peak = std::max (peak, std::abs (l[i]));
  1707. CHECK (peak > 0.45f && peak < 0.65f); // 0,3 · (1 + 1) no máximo: (1 − o3) vai até 2
  1708. }
  1709. TEST (channel_lfo_vibrato_and_tremolo)
  1710. {
  1711. auto render = [] (const lynx::SynthSettings& s) {
  1712. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  1713. inst->prepare (48000.0);
  1714. lynx::ChannelDef c;
  1715. c.synth = s;
  1716. inst->configure (c, 120.0);
  1717. inst->noteOn (69, 1.0f);
  1718. std::vector<float> l (48000), r (48000);
  1719. inst->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  1720. return l;
  1721. };
  1722. lynx::SynthSettings s;
  1723. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  1724. s.cutoff = 20000.0f;
  1725. // tremolo: LFO de volume 100% a 4 Hz (período 0,25 s) -> o envelope de amplitude vai de ~0 a ~2x
  1726. auto tremolo = s;
  1727. tremolo.lfo[lynx::lfoVolume] = { 1.0f, 0.25f, false, 0, 0.0f, 0.0f };
  1728. const auto t = render (tremolo);
  1729. float lowest = 1.0f, highest = 0.0f;
  1730. for (std::size_t w = 4800; w + 480 <= 48000; w += 480) // janelas de 10 ms (4,4 ciclos de 440 Hz)
  1731. {
  1732. float peak = 0.0f;
  1733. for (auto i = w; i < w + 480; ++i)
  1734. peak = std::max (peak, std::abs (t[i]));
  1735. lowest = std::min (lowest, peak);
  1736. highest = std::max (highest, peak);
  1737. }
  1738. CHECK (lowest < 0.08f && highest > 0.5f);
  1739. // vibrato sincronizado: ±1 semitom, período 1 tempo (0,5 s a 120 BPM); a média fica em 440 Hz
  1740. auto vibrato = s;
  1741. vibrato.lfo[lynx::lfoPitch] = { 1.0f, 1.0f, true, 0, 0.0f, 0.0f };
  1742. const auto v = render (vibrato);
  1743. int crossings = 0;
  1744. for (std::size_t i = 1; i < 48000; ++i)
  1745. crossings += (v[i - 1] < 0.0f) != (v[i] < 0.0f);
  1746. CHECK (std::abs (crossings - 880) < 12);
  1747. int firstQuarter = 0; // primeiro quarto do ciclo: seno subindo -> mais agudo que 440
  1748. for (std::size_t i = 1; i < 6000; ++i)
  1749. firstQuarter += (v[i - 1] < 0.0f) != (v[i] < 0.0f);
  1750. CHECK (firstQuarter > 112);
  1751. }
  1752. TEST (sampler_porta_glides_from_previous_note)
  1753. {
  1754. auto data = std::make_shared<lynx::SampleData>();
  1755. data->sampleRate = 48000.0;
  1756. data->left.resize (96000);
  1757. for (std::size_t i = 0; i < data->left.size(); ++i)
  1758. data->left[i] = 0.5f * (float) std::sin (6.283185307 * 220.0 * (double) i / 48000.0);
  1759. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  1760. inst->prepare (48000.0);
  1761. lynx::ChannelDef c;
  1762. c.sampler.cut = true;
  1763. c.sampler.porta = true;
  1764. c.sampler.portaBeats = 1.0f; // 0,5 s a 120 BPM
  1765. inst->configure (c, 120.0);
  1766. std::vector<float> l (24000), r (24000);
  1767. inst->noteOn (60, 1.0f);
  1768. inst->render (l.data(), r.data(), 2400, 1.0f, 1.0f);
  1769. inst->noteOn (72, 1.0f); // uma oitava acima: começa em 220 Hz e sobe
  1770. std::fill (l.begin(), l.end(), 0.0f);
  1771. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  1772. auto crossings = [&] (std::size_t from, std::size_t to) {
  1773. int n = 0;
  1774. for (auto i = from + 1; i < to; ++i)
  1775. n += (l[i - 1] < 0.0f) != (l[i] < 0.0f);
  1776. return n;
  1777. };
  1778. const auto start = crossings (600, 2400); // 37,5 ms ainda perto de 220 Hz: ~17 cruzamentos (440 Hz daria 33)
  1779. const auto end = crossings (21600, 24000); // 50 ms no fim do deslize: perto de 440 Hz (~44; 220 Hz daria 22)
  1780. CHECK (start < 22);
  1781. CHECK (end > 36);
  1782. }
  1783. TEST (zoned_sampler_picks_zone_by_key_and_velocity)
  1784. {
  1785. auto sine = [] (double hz, float amp) {
  1786. auto d = std::make_shared<lynx::SampleData>();
  1787. d->sampleRate = 48000.0;
  1788. d->left.resize (48000);
  1789. for (std::size_t i = 0; i < d->left.size(); ++i)
  1790. d->left[i] = amp * (float) std::sin (6.283185307 * hz * (double) i / 48000.0);
  1791. return d;
  1792. };
  1793. // graves: seno de 220 Hz gravado como A3 (57), até a tecla 69; agudos: 880 Hz como A5 (81)
  1794. // camada forte nos agudos: mesma afinação, mais alta
  1795. std::vector<lynx::LoadedZone> zones {
  1796. { { "graves.wav", 57, 0, 69, 0, 127, 0.0f, 1.0f }, sine (220.0, 0.5f) },
  1797. { { "agudos.wav", 81, 70, 127, 0, 99, 0.0f, 1.0f }, sine (880.0, 0.25f) },
  1798. { { "agudos forte.wav", 81, 70, 127, 100, 127, 0.0f, 1.0f }, sine (880.0, 0.9f) },
  1799. };
  1800. auto inst = lynx::makeZonedSampler (zones);
  1801. inst->prepare (48000.0);
  1802. inst->configure (lynx::ChannelDef {}, 120.0);
  1803. auto play = [&] (int key, float velocity) {
  1804. inst->allNotesOff();
  1805. std::vector<float> l (24000), r (24000);
  1806. inst->render (l.data(), r.data(), 2000, 1.0f, 1.0f); // deixa as vozes antigas sumirem
  1807. std::fill (l.begin(), l.end(), 0.0f);
  1808. inst->noteOn (key, velocity);
  1809. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  1810. int crossings = 0;
  1811. float peak = 0.0f;
  1812. for (std::size_t i = 1; i < 24000; ++i)
  1813. {
  1814. crossings += (l[i - 1] < 0.0f) != (l[i] < 0.0f);
  1815. peak = std::max (peak, std::abs (l[i]));
  1816. }
  1817. return std::pair { crossings, peak };
  1818. };
  1819. const auto low = play (69, 0.5f); // A4 a partir da raiz A3: 440 Hz -> 440 cruzamentos em 0,5 s
  1820. CHECK (std::abs (low.first - 440) < 4);
  1821. const auto soft = play (81, 0.5f); // zona de agudos na raiz: 880 Hz
  1822. CHECK (std::abs (soft.first - 880) < 6);
  1823. const auto hard = play (81, 0.95f); // velocity alta: camada forte
  1824. CHECK (hard.second > soft.second * 2.0f);
  1825. // camadas sobrepostas se revezam: duas zonas iguais de níveis diferentes, notas alternam
  1826. auto rr = lynx::makeZonedSampler ({ { { "a.wav", 60 }, sine (440.0, 0.2f) }, { { "b.wav", 60 }, sine (440.0, 0.8f) } });
  1827. rr->prepare (48000.0);
  1828. rr->configure (lynx::ChannelDef {}, 120.0);
  1829. float peaks[2] {};
  1830. for (int k = 0; k < 2; ++k)
  1831. {
  1832. rr->allNotesOff();
  1833. std::vector<float> l (4800), r (4800);
  1834. rr->render (l.data(), r.data(), 2000, 1.0f, 1.0f);
  1835. std::fill (l.begin(), l.end(), 0.0f);
  1836. rr->noteOn (60, 1.0f);
  1837. rr->render (l.data(), r.data(), 4800, 1.0f, 1.0f);
  1838. for (auto v : l)
  1839. peaks[k] = std::max (peaks[k], std::abs (v));
  1840. }
  1841. CHECK (std::abs (peaks[0] - peaks[1]) > 0.3f);
  1842. }
  1843. TEST (zoned_sampler_loops_while_held)
  1844. {
  1845. // sample de 0,1 s com loop no meio: segurando a nota ela continua soando muito além do fim do arquivo;
  1846. // soltando, sai do loop e acaba
  1847. auto data = std::make_shared<lynx::SampleData>();
  1848. data->sampleRate = 48000.0;
  1849. data->left.resize (4800);
  1850. for (std::size_t i = 0; i < data->left.size(); ++i)
  1851. data->left[i] = 0.5f * (float) std::sin (6.283185307 * 480.0 * (double) i / 48000.0); // 100 quadros por ciclo
  1852. lynx::SampleZone zone { "loop.wav", 60 };
  1853. zone.loopStart = 1000;
  1854. zone.loopEnd = 3000;
  1855. zone.loopMode = 2;
  1856. auto inst = lynx::makeZonedSampler ({ { zone, data } });
  1857. inst->prepare (48000.0);
  1858. lynx::ChannelDef c;
  1859. c.sampler.release = 0.01f;
  1860. inst->configure (c, 120.0);
  1861. inst->noteOn (60, 1.0f);
  1862. std::vector<float> l (48000), r (48000);
  1863. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f); // 0,5 s segurando
  1864. float held = 0.0f;
  1865. for (std::size_t i = 20000; i < 24000; ++i)
  1866. held = std::max (held, std::abs (l[i]));
  1867. CHECK (held > 0.3f);
  1868. inst->noteOff (60);
  1869. inst->render (l.data() + 24000, r.data() + 24000, 24000, 1.0f, 1.0f);
  1870. float after = 0.0f;
  1871. for (std::size_t i = 40000; i < 48000; ++i)
  1872. after = std::max (after, std::abs (l[i]));
  1873. CHECK (after == 0.0f);
  1874. }
  1875. TEST (global_lfo_follows_song_position)
  1876. {
  1877. // LFO de volume global (período 1 tempo): uma nota no meio do ciclo começa no meio da onda; a
  1878. // mesma nota com o LFO por nota começa na fase 0
  1879. auto first = [] (bool global, double songTicks) {
  1880. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  1881. inst->prepare (48000.0);
  1882. lynx::ChannelDef c;
  1883. c.synth.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  1884. c.synth.cutoff = 20000.0f;
  1885. c.synth.lfo[lynx::lfoVolume] = { 1.0f, 1.0f, true, 2, 0.0f, 0.0f, global }; // pulso: +1 na 1ª metade
  1886. inst->configure (c, 120.0);
  1887. inst->setSongPosition (songTicks);
  1888. inst->noteOn (69, 1.0f);
  1889. std::vector<float> l (4800), r (4800);
  1890. inst->render (l.data(), r.data(), 4800, 1.0f, 1.0f);
  1891. float peak = 0.0f;
  1892. for (std::size_t i = 2400; i < 4800; ++i)
  1893. peak = std::max (peak, std::abs (l[i]));
  1894. return peak;
  1895. };
  1896. // no meio do ciclo (fase 0,6) o pulso está em −1: volume ~0; por nota (fase 0) está em +1: ~2x
  1897. const auto globalLate = first (true, 0.6 * lynx::ppq);
  1898. const auto perNote = first (false, 0.6 * lynx::ppq);
  1899. CHECK (globalLate < 0.05f);
  1900. CHECK (perNote > 0.4f);
  1901. }
  1902. TEST (sampler_channel_filter_darkens_and_bypasses_when_open)
  1903. {
  1904. // ruído branco no sampler: com corte em 300 Hz a energia cai muito; aberto passa igual
  1905. auto data = std::make_shared<lynx::SampleData>();
  1906. data->sampleRate = 48000.0;
  1907. data->left.resize (48000);
  1908. std::uint32_t seed = 7;
  1909. for (auto& v : data->left)
  1910. {
  1911. seed = seed * 1664525u + 1013904223u;
  1912. v = ((float) (seed >> 8) / 16777216.0f - 0.5f);
  1913. }
  1914. data->right = data->left;
  1915. auto energy = [&] (float cutoff) {
  1916. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  1917. inst->prepare (48000.0);
  1918. lynx::ChannelDef c;
  1919. c.sampler.cutoff = cutoff;
  1920. inst->configure (c, 120.0);
  1921. inst->noteOn (60, 1.0f);
  1922. std::vector<float> l (24000), r (24000);
  1923. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  1924. double e = 0.0;
  1925. for (auto v : l)
  1926. e += (double) v * v;
  1927. return e;
  1928. };
  1929. const auto open = energy (20000.0f), dark = energy (300.0f);
  1930. {
  1931. // passa-altas em 10 kHz: tira a maior parte da energia do ruído também, mas pelo outro lado
  1932. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  1933. inst->prepare (48000.0);
  1934. lynx::ChannelDef hp;
  1935. hp.sampler.cutoff = 10000.0f;
  1936. hp.sampler.filterType = 2;
  1937. inst->configure (hp, 120.0);
  1938. inst->noteOn (60, 1.0f);
  1939. std::vector<float> l (24000), r (24000);
  1940. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  1941. double e = 0.0, lowE = 0.0;
  1942. float lp = 0.0f;
  1943. for (auto v : l)
  1944. {
  1945. e += (double) v * v;
  1946. lp += 0.01f * (v - lp); // passa-baixas grosseiro: quase nada deve sobrar embaixo
  1947. lowE += (double) lp * lp;
  1948. }
  1949. CHECK (e > 10.0 && e < 0.7 * energy (20000.0f));
  1950. CHECK (lowE < e * 0.01);
  1951. }
  1952. CHECK (open > 100.0);
  1953. CHECK (dark < open * 0.05);
  1954. // envelope de afinação +12 st com sustentação 1: o sample corre no dobro da velocidade
  1955. // e acaba na metade do tempo (1 s de sample -> 0,5 s)
  1956. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  1957. inst->prepare (48000.0);
  1958. lynx::ChannelDef c;
  1959. c.sampler.pitchEnv = { 12.0f, 0.0f, 0.0f, 0.1f, 1.0f, 0.1f };
  1960. inst->configure (c, 120.0);
  1961. inst->noteOn (60, 1.0f);
  1962. std::vector<float> l (48000), r (48000);
  1963. inst->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  1964. float tail = 0.0f, body = 0.0f;
  1965. for (std::size_t i = 20000; i < 23000; ++i)
  1966. body = std::max (body, std::abs (l[i]));
  1967. for (std::size_t i = 25000; i < 48000; ++i)
  1968. tail = std::max (tail, std::abs (l[i]));
  1969. CHECK (body > 0.1f);
  1970. CHECK (tail == 0.0f);
  1971. }
  1972. TEST (synth_oscillator_pan_and_semitones)
  1973. {
  1974. auto render = [] (lynx::SynthSettings s, std::vector<float>& l, std::vector<float>& r) {
  1975. auto synth = lynx::makeInstrument (lynx::InstrumentKind::synth);
  1976. synth->prepare (48000.0);
  1977. lynx::ChannelDef c;
  1978. c.synth = s;
  1979. synth->configure (c, 120.0);
  1980. synth->noteOn (69, 1.0f);
  1981. l.assign (24000, 0.0f);
  1982. r.assign (24000, 0.0f);
  1983. synth->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  1984. };
  1985. lynx::SynthSettings s;
  1986. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f, 7, 1.0f }; // quinta acima, todo à direita
  1987. s.cutoff = 20000.0f;
  1988. std::vector<float> l, r;
  1989. render (s, l, r);
  1990. float peakL = 0.0f, peakR = 0.0f;
  1991. int crossings = 0;
  1992. for (std::size_t i = 4800; i < 24000; ++i)
  1993. {
  1994. peakL = std::max (peakL, std::abs (l[i]));
  1995. peakR = std::max (peakR, std::abs (r[i]));
  1996. crossings += (r[i - 1] < 0.0f) != (r[i] < 0.0f);
  1997. }
  1998. CHECK (peakL < 1e-4f && peakR > 0.1f);
  1999. // 440 * 2^(7/12) = 659,3 Hz; 0,4 s = 263,7 ciclos = ~527 cruzamentos
  2000. CHECK (std::abs (crossings - 527) < 6);
  2001. }
  2002. TEST (fl_wrapper_state_parses_records_and_vst3_state)
  2003. {
  2004. // blob do Fruity Wrapper (versão 12): tipo VST3 gerador, class ID, nome, caminho e estado
  2005. std::vector<std::uint8_t> blob;
  2006. 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))); };
  2007. auto record = [&] (std::vector<std::uint8_t>& b, std::uint32_t id, const std::vector<std::uint8_t>& payload) {
  2008. u32 (b, id);
  2009. u32 (b, (std::uint32_t) payload.size());
  2010. u32 (b, 0);
  2011. b.insert (b.end(), payload.begin(), payload.end());
  2012. };
  2013. auto bytes = [] (const std::string& s) { return std::vector<std::uint8_t> (s.begin(), s.end()); };
  2014. std::vector<std::uint8_t> vst3State;
  2015. u32 (vst3State, 1);
  2016. record (vst3State, 1, std::vector<std::uint8_t> (64, 0));
  2017. record (vst3State, 3, bytes ("COMPONENTE"));
  2018. record (vst3State, 2, bytes ("CONTROLADOR"));
  2019. u32 (blob, 12);
  2020. record (blob, 0x01, std::vector<std::uint8_t> (20, 0xFF));
  2021. record (blob, 0x32, { 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });
  2022. std::vector<std::uint8_t> cid;
  2023. for (int i = 0; i < 16; ++i)
  2024. cid.push_back ((std::uint8_t) (0xA0 + i));
  2025. record (blob, 0x34, cid);
  2026. record (blob, 0x36, bytes ("Surge XT"));
  2027. record (blob, 0x37, bytes ("C:/Program Files/Common Files/VST3/Surge XT.vst3"));
  2028. record (blob, 0x35, vst3State);
  2029. lynx::ForeignPlugin p;
  2030. CHECK (lynx::parseFlWrapper (blob, p));
  2031. CHECK (p.format == lynx::ForeignPlugin::Format::vst3);
  2032. CHECK (p.hasClassId && p.classId[0] == 0xA0 && p.classId[15] == 0xAF);
  2033. CHECK (p.name == "Surge XT" && p.path.find ("Surge XT.vst3") != std::string::npos);
  2034. std::vector<std::uint8_t> component, controller;
  2035. CHECK (lynx::splitFlVst3State (p.state, component, controller));
  2036. CHECK (component == bytes ("COMPONENTE") && controller == bytes ("CONTROLADOR"));
  2037. // versão fora da faixa ou sem tipo: não é um wrapper que dá para usar
  2038. blob[0] = 13;
  2039. CHECK (! lynx::parseFlWrapper (blob, p));
  2040. CHECK (! lynx::parseFlWrapper ({ 12, 0, 0, 0 }, p));
  2041. }
  2042. TEST (schedule_index_matches_full_scan)
  2043. {
  2044. // música aleatória (notas longas, swing, clips com offset); o agendamento com índice tem que dar
  2045. // exatamente os mesmos eventos que a varredura completa, inclusive no bloco que dá a volta
  2046. lynx::Song s = lynx::Song::makeDefault();
  2047. s.swing = 0.6f;
  2048. std::uint32_t seed = 12345;
  2049. auto rnd = [&] (int n) { seed = seed * 1664525u + 1013904223u; return (int) ((seed >> 8) % (std::uint32_t) n); };
  2050. s.patterns.resize (3);
  2051. for (auto& p : s.patterns)
  2052. {
  2053. p.notes.clear();
  2054. for (int i = 0; i < 60; ++i)
  2055. {
  2056. lynx::Note n;
  2057. n.start = rnd (16 * lynx::ppq);
  2058. n.length = rnd (5) == 0 ? rnd (12 * lynx::ppq) + 1 : rnd (lynx::ppq) + 1;
  2059. n.channel = rnd (4);
  2060. n.key = 40 + rnd (40);
  2061. n.slide = rnd (20) == 0;
  2062. p.notes.push_back (n);
  2063. }
  2064. p.sortNotes();
  2065. }
  2066. s.playlist.clear();
  2067. for (int i = 0; i < 12; ++i)
  2068. {
  2069. lynx::Clip c;
  2070. c.pattern = rnd (3);
  2071. c.track = rnd (4);
  2072. c.start = rnd (40) * lynx::ppq;
  2073. c.length = (rnd (12) + 1) * lynx::ppq;
  2074. c.offset = rnd (4) * lynx::ppq;
  2075. s.playlist.push_back (c);
  2076. }
  2077. s.mode = lynx::PlayMode::song;
  2078. const auto index = lynx::makeScheduleIndex (s);
  2079. const auto tps = lynx::ticksPerSample (140.0, 48000.0);
  2080. const auto loop = (double) s.songLength();
  2081. int mismatches = 0, events = 0;
  2082. for (int block = 0; block < 400; ++block)
  2083. {
  2084. const auto start = block == 0 ? loop - 100.0 * tps : (double) rnd ((int) loop * 2);
  2085. const auto samples = 64 + rnd (24000); // até ~1 tempo por bloco
  2086. lynx::EventBuffer a, b;
  2087. lynx::scheduleSong (s, start, samples, tps, a, false, nullptr);
  2088. lynx::scheduleSong (s, start, samples, tps, b, false, &index);
  2089. events += a.size();
  2090. if (a.size() != b.size())
  2091. {
  2092. ++mismatches;
  2093. continue;
  2094. }
  2095. for (int i = 0; i < a.size(); ++i)
  2096. {
  2097. const auto& x = *(a.begin() + i);
  2098. const auto& y = *(b.begin() + i);
  2099. mismatches += x.sampleOffset != y.sampleOffset || x.type != y.type || x.key != y.key || x.channel != y.channel;
  2100. }
  2101. }
  2102. CHECK (events > 500);
  2103. CHECK (mismatches == 0);
  2104. }
  2105. TEST (mixer_track_eq_defaults_and_boost)
  2106. {
  2107. // os padrões do FL: 90 Hz, 1,5 kHz e 8 kHz; Q do pico 0,632; inclinação das prateleiras 0,607
  2108. lynx::TrackEq eq;
  2109. CHECK (std::abs (lynx::TrackEq::peakQ (eq.width[1]) - 0.632) < 0.01);
  2110. CHECK (std::abs (lynx::TrackEq::shelfSlope (eq.width[0]) - 0.607) < 0.01);
  2111. CHECK (! eq.active());
  2112. // +12 dB no pico em 1,5 kHz numa trilha: um seno de 1,5 kHz sobe ~4x
  2113. lynx::Song song = lynx::Song::makeDefault();
  2114. song.mixer[1].eq.gainDb[1] = 12.0f;
  2115. for (auto& c : song.channels)
  2116. c.mixerTrack = 1;
  2117. song.channels[4].instrument = lynx::InstrumentKind::synth;
  2118. song.channels[4].synth = {};
  2119. song.channels[4].synth.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  2120. song.channels[4].synth.cutoff = 20000.0f;
  2121. auto render = [] (const lynx::Song& s) {
  2122. auto state = lynx::RackState::build (s, nullptr, 48000.0);
  2123. lynx::RackRenderer renderer;
  2124. renderer.prepare (48000.0);
  2125. lynx::LiveEventQueue live;
  2126. lynx::NoteEvent on; // 1,5 kHz ~ tecla 90,6: usa a 91 (1568 Hz), ainda no pico largo
  2127. on.channel = 4;
  2128. on.key = 91;
  2129. on.velocity = 1.0f;
  2130. live.push (on);
  2131. std::vector<float> l (24000), r (24000);
  2132. for (int pos = 0; pos < 24000; pos += 480)
  2133. renderer.process (state.get(), false, 0.0, 480, l.data() + pos, r.data() + pos, pos == 0 ? &live : nullptr);
  2134. float peak = 0.0f;
  2135. for (std::size_t i = 12000; i < 24000; ++i)
  2136. peak = std::max (peak, std::abs (l[i]));
  2137. return peak;
  2138. };
  2139. const auto boosted = render (song);
  2140. song.mixer[1].eq.gainDb[1] = 0.0f;
  2141. const auto flat = render (song);
  2142. CHECK (flat > 0.01f);
  2143. CHECK (boosted / flat > 3.0f && boosted / flat < 4.2f);
  2144. }
  2145. TEST (bars_follow_time_signature_markers)
  2146. {
  2147. lynx::Song song;
  2148. song.beatsPerBar = 4;
  2149. const auto bar4 = (std::int64_t) lynx::ppq * 4;
  2150. auto bars = song.barsBetween (0, bar4 * 3);
  2151. CHECK (bars.size() == 3 && bars[2].tick == bar4 * 2 && bars[2].number == 3);
  2152. // 7/4 a partir do compasso 3, e 3/4 no meio de um compasso de 7 (corta e recomeça)
  2153. song.addMarker ({ bar4 * 2, "Verso", 7, 4 });
  2154. song.addMarker ({ bar4, "Nome só", 0, 4 });
  2155. const auto seven = (std::int64_t) lynx::ppq * 7;
  2156. song.addMarker ({ bar4 * 2 + seven + lynx::ppq * 2, "", 3, 4 });
  2157. bars = song.barsBetween (0, bar4 * 2 + seven * 2);
  2158. CHECK (bars.size() >= 5);
  2159. CHECK (bars[1].length == bar4 && bars[2].tick == bar4 * 2 && bars[2].length == seven);
  2160. CHECK (bars[3].length == lynx::ppq * 2); // cortado pela mudança
  2161. CHECK (bars[4].length == lynx::ppq * 3 && bars[4].number == 5);
  2162. CHECK (song.markers()[0].name == "Nome só"); // ordenados por tick
  2163. // de longe: começa no compasso certo sem perder a numeração
  2164. const auto far = song.barsBetween (lynx::ppq * 3000, lynx::ppq * 3001);
  2165. CHECK (far.size() == 1 && far[0].length == lynx::ppq * 3);
  2166. CHECK (song.barAt (lynx::ppq * 3000).number == far[0].number);
  2167. CHECK ((lynx::ppq * 3000 - far[0].tick) < far[0].length);
  2168. }
  2169. TEST (split_drum_channel_moves_notes_to_pads)
  2170. {
  2171. lynx::Song song = lynx::Song::makeDefault();
  2172. const auto channels = (int) song.channels.size();
  2173. song.patterns[0].notes.clear();
  2174. song.patterns[0].notes.push_back ({ 0, 240, 1, 36, 0.9f }); // kick do kit (canal 1)
  2175. song.patterns[0].notes.push_back ({ 240, 240, 1, 38, 0.8f }); // caixa
  2176. song.patterns[0].notes.push_back ({ 480, 240, 1, 50, 0.8f }); // tecla sem pad: some
  2177. song.patterns[0].notes.push_back ({ 480, 240, 3, 60, 0.8f }); // outro canal: anda 1 posição
  2178. lynx::Automation a;
  2179. a.target = { lynx::AutomationTargetKind::channelVolume, 3, 0, 0 };
  2180. song.automations.push_back (a);
  2181. std::vector<lynx::DrumPad> pads (2);
  2182. pads[0].name = "Kick";
  2183. pads[0].key = 36;
  2184. pads[0].layers = { { "kick.wav" } };
  2185. pads[1].name = "Snare";
  2186. pads[1].key = 38;
  2187. pads[1].layers = { { "snare soft.wav", 60, 0, 127, 0, 90 }, { "snare hard.wav", 60, 0, 127, 91, 127 } };
  2188. pads[1].cutGroup = 2;
  2189. pads[1].cutBy = 2;
  2190. lynx::splitDrumChannel (song, 1, pads);
  2191. CHECK ((int) song.channels.size() == channels + 1);
  2192. CHECK (song.channels[1].samplePath == "kick.wav" && song.channels[1].instrument == lynx::InstrumentKind::sampler);
  2193. CHECK (song.channels[2].zones.size() == 2 && song.channels[2].cutGroup == song.channels[2].cutBy && song.channels[2].cutGroup != 0);
  2194. const auto& notes = song.patterns[0].notes;
  2195. CHECK (notes.size() == 3);
  2196. CHECK (notes[0].channel == 1 && notes[0].key == 60);
  2197. CHECK (notes[1].channel == 2 && notes[1].key == 60);
  2198. CHECK (notes[2].channel == 4); // o antigo canal 3
  2199. CHECK (song.automations[0].target.index == 4);
  2200. }
  2201. TEST (flp_import_brings_playlist)
  2202. {
  2203. flp::Project p;
  2204. p.header.ppq = 96;
  2205. p.channels = { { 0, flp::ChannelType::sampler, "Kick", "", "", 1 } };
  2206. flp::Pattern empty;
  2207. empty.index = 1;
  2208. flp::Pattern full;
  2209. full.index = 2;
  2210. flp::Note n;
  2211. n.channel = 0;
  2212. full.notes.push_back (n);
  2213. p.patterns = { empty, full };
  2214. flp::Arrangement a;
  2215. flp::PlaylistItem item;
  2216. item.kind = flp::PlaylistItem::Kind::pattern;
  2217. item.index = 2;
  2218. item.position = 384;
  2219. item.length = 192;
  2220. item.track = 3;
  2221. item.patternStartTick = 96;
  2222. a.items.push_back (item);
  2223. item.index = 1; // pattern vazia: descartada
  2224. a.items.push_back (item);
  2225. item.kind = flp::PlaylistItem::Kind::channelClip; // áudio: ainda não suportado
  2226. a.items.push_back (item);
  2227. p.arrangements.push_back (a);
  2228. const auto s = lynx::importFlp (p);
  2229. CHECK (s.mode == lynx::PlayMode::song);
  2230. CHECK (s.playlist.size() == 1);
  2231. CHECK (s.playlist[0].pattern == 0 && s.playlist[0].track == 3);
  2232. CHECK (s.playlist[0].start == 4 * lynx::ppq && s.playlist[0].length == 2 * lynx::ppq && s.playlist[0].offset == lynx::ppq);
  2233. }
  2234. TEST (rack_releases_notes_on_position_jump)
  2235. {
  2236. lynx::Song s;
  2237. lynx::ChannelDef c;
  2238. c.instrument = lynx::InstrumentKind::synth;
  2239. s.channels.push_back (c);
  2240. auto& p = s.patterns.emplace_back();
  2241. lynx::Note n;
  2242. n.start = 0;
  2243. n.length = 4 * lynx::ppq; // nota longa
  2244. p.notes.push_back (n);
  2245. s.bpm = 120.0;
  2246. auto state = lynx::RackState::build (s, nullptr, 48000.0);
  2247. lynx::RackRenderer r;
  2248. r.prepare (48000.0);
  2249. std::vector<float> l (512), rr (512);
  2250. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  2251. double tick = 0.0;
  2252. for (int i = 0; i < 20; ++i, tick += 512 * tps)
  2253. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  2254. // salto para o tick 2000 (no meio da nota, sem "on" novo): o synth precisa calar
  2255. for (int i = 0; i < 40; ++i)
  2256. r.process (state.get(), true, 2000.0 + i * 512 * tps, 512, l.data(), rr.data());
  2257. float tail = 0.0f;
  2258. for (auto v : l)
  2259. tail = std::max (tail, std::abs (v));
  2260. CHECK (tail < 0.001f);
  2261. }
  2262. namespace
  2263. {
  2264. // Dois samplers de sinal constante 0,5 em inserts diferentes; retorna o pico da saída.
  2265. float juce_db (float gain)
  2266. {
  2267. return 20.0f * std::log10 (gain);
  2268. }
  2269. float renderMixerCase (const std::function<void (lynx::Song&)>& tweak, lynx::MeterBank* meters = nullptr)
  2270. {
  2271. lynx::Song s;
  2272. s.mixer = lynx::Song::defaultMixer (4);
  2273. for (int i = 0; i < 2; ++i)
  2274. {
  2275. lynx::ChannelDef c;
  2276. c.instrument = lynx::InstrumentKind::sampler;
  2277. c.samplePath = "dc";
  2278. c.volume = 1.0f;
  2279. c.mixerTrack = i + 1;
  2280. s.channels.push_back (c);
  2281. }
  2282. s.patterns.emplace_back();
  2283. tweak (s);
  2284. auto provider = [] (const std::string&) {
  2285. auto d = std::make_shared<lynx::SampleData>();
  2286. d->left.assign (48000, 0.5f);
  2287. return std::shared_ptr<const lynx::SampleData> (d);
  2288. };
  2289. auto state = lynx::RackState::build (s, nullptr, 48000.0, provider);
  2290. lynx::RackRenderer r;
  2291. r.prepare (48000.0, 256);
  2292. lynx::LiveEventQueue live;
  2293. for (int ch = 0; ch < 2; ++ch)
  2294. {
  2295. lynx::NoteEvent on;
  2296. on.channel = ch;
  2297. on.velocity = 1.0f;
  2298. live.push (on);
  2299. }
  2300. std::vector<float> l (1000), rr (1000); // maior que o bloco do mixer: testa os pedaços
  2301. r.process (state.get(), false, 0.0, 1000, l.data(), rr.data(), &live, meters);
  2302. return std::max (std::abs (l[999]), std::abs (rr[999]));
  2303. }
  2304. } // namespace
  2305. TEST (mixer_routes_mutes_solos_and_meters)
  2306. {
  2307. // dois canais de 0,5 somados no Master em 0 dB
  2308. CHECK (std::abs (renderMixerCase ([] (lynx::Song&) {}) - 1.0f) < 1e-4f);
  2309. // mute do insert 1: sobra só o canal 2
  2310. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.mixer[1].muted = true; }) - 0.5f) < 1e-4f);
  2311. // solo no insert 2: idem
  2312. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.mixer[2].solo = true; }) - 0.5f) < 1e-4f);
  2313. // curva do fader do FL: 0,8 = 0 dB, máximo ≈ +5,6 dB, metade do curso ≈ -12,7 dB
  2314. CHECK (std::abs (lynx::faderGain (0.8f) - 1.0f) < 1e-5f);
  2315. CHECK (std::abs (juce_db (lynx::faderGain (1.0f)) - 5.59f) < 0.05f);
  2316. CHECK (lynx::faderGain (0.0f) == 0.0f);
  2317. // fader do Master no máximo
  2318. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.mixer[0].volume = 1.0f; }) - lynx::faderGain (1.0f)) < 1e-4f);
  2319. // os dois canais no mesmo insert, insert com fader em 0,4
  2320. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) {
  2321. s.channels[1].mixerTrack = 1;
  2322. s.mixer[1].volume = 0.4f;
  2323. }) - lynx::faderGain (0.4f)) < 1e-4f);
  2324. // rota fora do mixer cai no último insert existente, sem travar
  2325. CHECK (renderMixerCase ([] (lynx::Song& s) { s.channels[0].mixerTrack = 100; }) > 0.9f);
  2326. // sem mixer: tudo direto na saída em 0 dB
  2327. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.mixer.clear(); }) - 1.0f) < 1e-4f);
  2328. lynx::MeterBank meters;
  2329. renderMixerCase ([] (lynx::Song&) {}, &meters);
  2330. CHECK (std::abs (meters.takePeak (1, 0) - 0.5f) < 1e-4f);
  2331. CHECK (std::abs (meters.takePeak (0, 1) - 1.0f) < 1e-4f);
  2332. CHECK (meters.takePeak (1, 0) == 0.0f); // ler zera
  2333. CHECK (meters.takePeak (3, 0) == 0.0f); // insert sem canal
  2334. }
  2335. TEST (next_free_insert_and_flp_mixer_import)
  2336. {
  2337. auto s = lynx::Song::makeDefault();
  2338. CHECK (s.mixer.size() == 17 && s.mixer[0].name == "Master");
  2339. CHECK (s.nextFreeInsert() == 6); // os 5 canais padrão ocupam 1..5
  2340. flp::Project p;
  2341. p.channels = { { 0, flp::ChannelType::sampler, "Kick", "", "", 30 } };
  2342. p.mixer = { { 0, "" }, { 30, "Drums" } };
  2343. const auto song = lynx::importFlp (p);
  2344. CHECK (song.channels[0].mixerTrack == 30);
  2345. CHECK (song.mixer.size() == 31);
  2346. CHECK (song.mixer[30].name == "Drums" && song.mixer[0].name == "Master");
  2347. }
  2348. namespace
  2349. {
  2350. float runEffectOnSine (lynx::EffectKind kind, const std::function<void (lynx::EffectSlot&)>& tweak, double hz, float amp,
  2351. int frames = 48000)
  2352. {
  2353. auto fx = lynx::makeEffect (kind);
  2354. fx->prepare (48000.0);
  2355. auto slot = lynx::makeEffectSlot (kind);
  2356. tweak (slot);
  2357. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  2358. for (int i = 0; i < frames; ++i)
  2359. l[(std::size_t) i] = r[(std::size_t) i] = amp * (float) std::sin (6.283185307 * hz * i / 48000.0);
  2360. for (int i = 0; i < frames; i += 480)
  2361. fx->process (l.data() + i, r.data() + i, std::min (480, frames - i), slot.params, 120.0);
  2362. float peak = 0.0f;
  2363. for (int i = frames / 2; i < frames; ++i) // segunda metade: já estabilizado
  2364. {
  2365. CHECK (std::isfinite (l[(std::size_t) i]));
  2366. peak = std::max (peak, std::abs (l[(std::size_t) i]));
  2367. }
  2368. return peak;
  2369. }
  2370. } // namespace
  2371. TEST (parametric_eq_bands_and_response)
  2372. {
  2373. // padrão: transparente
  2374. auto slot = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  2375. CHECK (std::abs (lynx::peq::responseDb (slot.params, 48000.0, 1000.0)) < 0.01);
  2376. CHECK (std::abs (runEffectOnSine (lynx::EffectKind::parametricEq, [] (auto&) {}, 1000.0, 0.5f) - 0.5f) < 0.005f);
  2377. // pico de +12 dB em 1 kHz na banda 4: a resposta e o sinal concordam
  2378. auto boost = [] (lynx::EffectSlot& s) {
  2379. s.params[(std::size_t) lynx::peq::param (3, 1)] = lynx::peq::hzValue (1000.0);
  2380. s.params[(std::size_t) lynx::peq::param (3, 2)] = lynx::peq::gainValue (12.0);
  2381. };
  2382. boost (slot);
  2383. CHECK (std::abs (lynx::peq::responseDb (slot.params, 48000.0, 1000.0) - 12.0) < 0.2);
  2384. CHECK (std::abs (lynx::peq::responseDb (slot.params, 48000.0, 100.0)) < 1.0);
  2385. const auto peak = runEffectOnSine (lynx::EffectKind::parametricEq, boost, 1000.0, 0.1f);
  2386. CHECK (std::abs (peak - 0.1f * std::pow (10.0f, 12.0f / 20.0f)) < 0.01f);
  2387. // corta graves a 48 dB/oit em 200 Hz: 50 Hz (2 oitavas abaixo) cai ~96 dB; 2 kHz passa
  2388. auto cut = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  2389. cut.params[(std::size_t) lynx::peq::param (0, 0)] = lynx::peq::typeValue (lynx::peq::BandType::lowCut);
  2390. cut.params[(std::size_t) lynx::peq::param (0, 1)] = lynx::peq::hzValue (200.0);
  2391. cut.params[(std::size_t) lynx::peq::param (0, 3)] = lynx::peq::qValue (0.70710678); // Butterworth
  2392. cut.params[(std::size_t) (lynx::peq::slopeParam + 0)] = 1.0f;
  2393. CHECK (lynx::peq::responseDb (cut.params, 48000.0, 50.0) < -80.0);
  2394. CHECK (std::abs (lynx::peq::responseDb (cut.params, 48000.0, 200.0) + 3.0) < 0.5); // -3 dB no corte (Butterworth)
  2395. CHECK (std::abs (lynx::peq::responseDb (cut.params, 48000.0, 2000.0)) < 0.1);
  2396. // conversões ida e volta
  2397. CHECK (std::abs (lynx::peq::hz (lynx::peq::hzValue (440.0)) - 440.0) < 0.5);
  2398. CHECK (std::abs (lynx::peq::q (lynx::peq::qValue (2.5)) - 2.5) < 0.01);
  2399. CHECK (lynx::peq::type (lynx::peq::typeValue (lynx::peq::BandType::notch)) == lynx::peq::BandType::notch);
  2400. }
  2401. TEST (fl_parametric_eq2_state_maps_to_bands)
  2402. {
  2403. // blob v8: banda 1 corta graves a 100 Hz "Steep 8", banda 4 pico +6 dB em 1 kHz, saída −3 dB
  2404. std::vector<std::uint8_t> blob (354, 0);
  2405. auto put = [&] (std::size_t off, std::int32_t v) { std::memcpy (blob.data() + off, &v, 4); };
  2406. put (0, 8);
  2407. auto param = [&] (int i, std::int32_t v) { put (4 + 4 * (std::size_t) i, v); };
  2408. auto hzRaw = [] (double hz) { return (std::int32_t) std::lround (std::log (hz / 20.0) / std::log (1000.0) * 65536.0); };
  2409. for (int b = 0; b < 7; ++b)
  2410. param (21 + b, 0); // tudo desligado
  2411. param (21 + 0, 3); // high pass (= corta graves)
  2412. param (7 + 0, hzRaw (100.0));
  2413. param (14 + 0, 40124); // largura padrão -> Q ~0,68
  2414. param (28 + 0, -3); // Steep 8 -> 4 biquads
  2415. param (21 + 3, 6); // peaking
  2416. param (7 + 3, hzRaw (1000.0));
  2417. param (3, 600); // +6 dB
  2418. param (14 + 3, 25412);
  2419. param (35, -300); // main level −3 dB
  2420. put (0x13E, 0x7F);
  2421. const auto slot = lynx::effectFromFl ("Fruity Parametric EQ 2", blob);
  2422. CHECK (slot.has_value() && slot->kind == lynx::EffectKind::parametricEq);
  2423. const auto& p = slot->params;
  2424. CHECK (lynx::peq::type (p[(std::size_t) lynx::peq::param (0, 0)]) == lynx::peq::BandType::lowCut);
  2425. CHECK (lynx::peq::slopeStages (p[(std::size_t) lynx::peq::slopeParam]) == 4);
  2426. CHECK (lynx::peq::type (p[(std::size_t) lynx::peq::param (3, 0)]) == lynx::peq::BandType::peak);
  2427. CHECK (lynx::peq::type (p[(std::size_t) lynx::peq::param (1, 0)]) == lynx::peq::BandType::off);
  2428. CHECK (std::abs (lynx::peq::responseDb (p, 48000.0, 1000.0) - 3.0) < 0.3); // +6 do pico −3 da saída
  2429. CHECK (lynx::peq::responseDb (p, 48000.0, 30.0) < -40.0); // 48 dB/oit abaixo de 100 Hz
  2430. CHECK (std::abs (lynx::peq::responseDb (p, 48000.0, 8000.0) + 3.0) < 0.3);
  2431. // banda mutada pela máscara não soa
  2432. put (0x13E, 0x7F & ~(1 << 3));
  2433. const auto muted = lynx::effectFromFl ("Fruity Parametric EQ 2", blob);
  2434. CHECK (lynx::peq::type (muted->params[(std::size_t) lynx::peq::param (3, 0)]) == lynx::peq::BandType::off);
  2435. }
  2436. TEST (reverb_low_cut_and_predelay)
  2437. {
  2438. // impulso: com predelay de 100 ms o molhado só começa depois; com corte de graves em 3 kHz um
  2439. // seno de 100 Hz quase não entra no reverb
  2440. auto run = [] (const std::function<void (lynx::EffectSlot&)>& tweak, double hz, bool impulse) {
  2441. auto fx = lynx::makeEffect (lynx::EffectKind::reverb);
  2442. fx->prepare (48000.0);
  2443. auto slot = lynx::makeEffectSlot (lynx::EffectKind::reverb);
  2444. slot.params[4] = 0.0f; // só o molhado
  2445. slot.params[3] = 1.0f;
  2446. tweak (slot);
  2447. std::vector<float> l (48000), r (48000);
  2448. for (int i = 0; i < 48000; ++i)
  2449. 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);
  2450. for (int i = 0; i < 48000; i += 480)
  2451. fx->process (l.data() + i, r.data() + i, 480, slot.params, 120.0);
  2452. return l;
  2453. };
  2454. const auto delayed = run ([] (auto& s) { s.params[7] = 0.1f; }, 0.0, true);
  2455. float early = 0.0f, later = 0.0f;
  2456. for (std::size_t i = 0; i < 4800; ++i)
  2457. early = std::max (early, std::abs (delayed[i]));
  2458. for (std::size_t i = 4800; i < 24000; ++i)
  2459. later = std::max (later, std::abs (delayed[i]));
  2460. CHECK (early == 0.0f && later > 0.0f);
  2461. 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; };
  2462. const auto open = energy (run ([] (auto&) {}, 100.0, false));
  2463. const auto cut = energy (run ([] (auto& s) { s.params[5] = 1.0f; }, 100.0, false));
  2464. CHECK (cut < open * 0.01);
  2465. }
  2466. TEST (utility_effect_and_fl_stereo_tools)
  2467. {
  2468. // padrão transparente; balanço todo à direita cala a esquerda
  2469. CHECK (std::abs (runEffectOnSine (lynx::EffectKind::utility, [] (auto&) {}, 440.0, 0.5f) - 0.5f) < 0.001f);
  2470. CHECK (runEffectOnSine (lynx::EffectKind::utility, [] (auto& s) { s.params[1] = 1.0f; }, 440.0, 0.5f) < 0.001f);
  2471. // Stereo Shaper em "mono": cada saída = 0,5 L + 0,5 R
  2472. std::vector<std::uint8_t> blob (36, 0);
  2473. auto put = [&] (std::size_t off, std::int32_t v) { std::memcpy (blob.data() + off, &v, 4); };
  2474. put (4, 6400); put (8, 6400); put (12, 6400); put (16, 6400);
  2475. const auto slot = lynx::effectFromFl ("Fruity Stereo Shaper", blob);
  2476. CHECK (slot && slot->kind == lynx::EffectKind::utility);
  2477. auto fx = lynx::makeEffect (lynx::EffectKind::utility);
  2478. float l = 1.0f, r = 0.0f;
  2479. fx->process (&l, &r, 1, slot->params, 120.0);
  2480. CHECK (std::abs (l - 0.5f) < 1e-4f && std::abs (r - 0.5f) < 1e-4f);
  2481. // Balance: volume 256 = 0 dB, pan −128 = toda à esquerda
  2482. std::vector<std::uint8_t> bal (8, 0);
  2483. std::int32_t pan = -128, vol = 256;
  2484. std::memcpy (bal.data(), &pan, 4);
  2485. std::memcpy (bal.data() + 4, &vol, 4);
  2486. const auto b = lynx::effectFromFl ("Fruity Balance", bal);
  2487. l = 0.5f; r = 0.5f;
  2488. fx->process (&l, &r, 1, b->params, 120.0);
  2489. CHECK (std::abs (l - 0.5f) < 1e-3f && std::abs (r) < 1e-4f);
  2490. }
  2491. TEST (effects_eq_compressor_behave)
  2492. {
  2493. // EQ no padrão é transparente
  2494. CHECK (std::abs (runEffectOnSine (lynx::EffectKind::eq, [] (auto&) {}, 1000.0, 0.5f) - 0.5f) < 0.01f);
  2495. // +18 dB nos graves: 60 Hz sobe bastante, 5 kHz quase nada
  2496. CHECK (runEffectOnSine (lynx::EffectKind::eq, [] (auto& s) { s.params[0] = 1.0f; }, 60.0, 0.05f) > 0.3f);
  2497. CHECK (runEffectOnSine (lynx::EffectKind::eq, [] (auto& s) { s.params[0] = 1.0f; }, 5000.0, 0.05f) < 0.06f);
  2498. // compressor: threshold -20 dB, ratio 20:1 achata um sinal de 0 dBFS para perto do threshold
  2499. const auto squashed = runEffectOnSine (lynx::EffectKind::compressor, [] (auto& s) {
  2500. s.params[0] = 40.0f / 60.0f;
  2501. s.params[1] = 1.0f;
  2502. }, 200.0, 1.0f);
  2503. CHECK (squashed < 0.2f && squashed > 0.05f);
  2504. // sinal abaixo do threshold passa intacto
  2505. CHECK (std::abs (runEffectOnSine (lynx::EffectKind::compressor, [] (auto& s) { s.params[0] = 1.0f; }, 200.0, 0.3f) - 0.3f) < 0.01f);
  2506. }
  2507. TEST (effects_delay_echoes_on_tempo_and_reverb_has_tail)
  2508. {
  2509. auto delay = lynx::makeEffect (lynx::EffectKind::delay);
  2510. delay->prepare (48000.0);
  2511. auto slot = lynx::makeEffectSlot (lynx::EffectKind::delay);
  2512. slot.params[0] = 3.5f / 8.0f; // índice 3 = 1/4 = 0,5 s a 120 BPM
  2513. slot.params[1] = 0.0f; // sem feedback: um eco só
  2514. slot.params[2] = 1.0f;
  2515. slot.params[4] = 0.0f; // sem abafar
  2516. std::vector<float> l (48000, 0.0f), r (48000, 0.0f);
  2517. l[0] = r[0] = 1.0f;
  2518. delay->process (l.data(), r.data(), 48000, slot.params, 120.0);
  2519. CHECK (std::abs (l[24000] - 1.0f) < 1e-4f);
  2520. CHECK (std::abs (l[12000]) < 1e-6f);
  2521. auto reverb = lynx::makeEffect (lynx::EffectKind::reverb);
  2522. reverb->prepare (48000.0);
  2523. auto rs = lynx::makeEffectSlot (lynx::EffectKind::reverb);
  2524. rs.params[3] = 1.0f;
  2525. std::fill (l.begin(), l.end(), 0.0f);
  2526. std::fill (r.begin(), r.end(), 0.0f);
  2527. l[0] = r[0] = 1.0f;
  2528. reverb->process (l.data(), r.data(), 48000, rs.params, 120.0);
  2529. float tail = 0.0f;
  2530. for (int i = 4800; i < 9600; ++i) // entre 100 e 200 ms depois do impulso
  2531. tail = std::max (tail, std::abs (l[(std::size_t) i]));
  2532. CHECK (tail > 1e-4f && tail < 1.0f);
  2533. CHECK (lynx::formatEffectParam (lynx::EffectKind::delay, 0, slot.params[0], 120.0) == "1/4 (500 ms)");
  2534. }
  2535. TEST (rack_runs_insert_effects_and_reuses_them)
  2536. {
  2537. // insert com EQ a -inf não existe; usamos a saída do EQ em -18 dB para ver o efeito agir
  2538. const auto quiet = renderMixerCase ([] (lynx::Song& s) {
  2539. auto eq = lynx::makeEffectSlot (lynx::EffectKind::eq);
  2540. eq.params[4] = 0.0f; // saída -18 dB
  2541. s.mixer[1].effects.push_back (eq);
  2542. });
  2543. CHECK (quiet > 0.55f && quiet < 0.6f); // 0,5 do canal 2 + 0,5 * 0,126 do canal 1
  2544. const auto bypassed = renderMixerCase ([] (lynx::Song& s) {
  2545. auto eq = lynx::makeEffectSlot (lynx::EffectKind::eq);
  2546. eq.params[4] = 0.0f;
  2547. eq.enabled = false;
  2548. s.mixer[1].effects.push_back (eq);
  2549. });
  2550. CHECK (std::abs (bypassed - 1.0f) < 1e-4f);
  2551. auto s = lynx::Song::makeDefault();
  2552. s.mixer[2].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::reverb));
  2553. auto a = lynx::RackState::build (s, nullptr, 48000.0);
  2554. s.mixer[2].effects[0].params[0] = 0.9f; // mexer num knob não recria o efeito
  2555. auto b = lynx::RackState::build (s, a.get(), 48000.0);
  2556. CHECK (b->effects[2][0] == a->effects[2][0]);
  2557. s.mixer[2].effects[0] = lynx::makeEffectSlot (lynx::EffectKind::delay);
  2558. auto c = lynx::RackState::build (s, b.get(), 48000.0);
  2559. CHECK (c->effects[2][0] != b->effects[2][0]);
  2560. }
  2561. TEST (audio_clips_trigger_cut_and_resume)
  2562. {
  2563. lynx::Song s;
  2564. s.bpm = 120.0; // 1 tempo = 0,5 s = 24000 samples a 48 kHz
  2565. lynx::ChannelDef c;
  2566. c.instrument = lynx::InstrumentKind::audioClip;
  2567. c.samplePath = "ramp";
  2568. c.volume = 1.0f;
  2569. s.channels.push_back (c);
  2570. s.patterns.emplace_back();
  2571. lynx::Clip clip;
  2572. clip.kind = lynx::ClipKind::audio;
  2573. clip.channel = 0;
  2574. clip.start = lynx::ppq; // começa no tempo 2
  2575. clip.length = 2 * lynx::ppq; // dura 2 tempos
  2576. clip.offset = lynx::ppq; // pula o primeiro tempo do áudio
  2577. s.playlist.push_back (clip);
  2578. s.mode = lynx::PlayMode::song;
  2579. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  2580. lynx::EventBuffer ev;
  2581. lynx::scheduleSong (s, 0.0, 4 * 24000, tps, ev);
  2582. CHECK (ev.size() == 2);
  2583. CHECK (ev[0].type == lynx::NoteEvent::Type::on && ev[0].sampleOffset == 24000 && std::abs (ev[0].startSeconds - 0.5) < 1e-9);
  2584. CHECK (ev[1].type == lynx::NoteEvent::Type::off && ev[1].sampleOffset == 3 * 24000);
  2585. // seek para o meio do clip (tempo 2,5): com resume, começa no primeiro sample do bloco
  2586. ev.clear();
  2587. lynx::scheduleSong (s, 1.5 * lynx::ppq, 256, tps, ev, true);
  2588. CHECK (ev.size() == 1 && ev[0].sampleOffset == 0 && std::abs (ev[0].startSeconds - 0.75) < 1e-9);
  2589. ev.clear();
  2590. lynx::scheduleSong (s, 1.5 * lynx::ppq, 256, tps, ev, false);
  2591. CHECK (ev.size() == 0);
  2592. // sample com valor = posição em segundos: dá para conferir de onde ele começou a tocar
  2593. auto provider = [] (const std::string&) {
  2594. auto d = std::make_shared<lynx::SampleData>();
  2595. d->sampleRate = 48000.0;
  2596. for (int i = 0; i < 48000 * 3; ++i)
  2597. d->left.push_back ((float) i / 48000.0f);
  2598. return std::shared_ptr<const lynx::SampleData> (d);
  2599. };
  2600. auto state = lynx::RackState::build (s, nullptr, 48000.0, provider);
  2601. lynx::RackRenderer r;
  2602. r.prepare (48000.0, 512);
  2603. std::vector<float> l (256), rr (256);
  2604. // primeiro bloco tocando já no meio do clip
  2605. r.process (state.get(), true, 1.5 * lynx::ppq, 256, l.data(), rr.data());
  2606. CHECK (std::abs (l[0] - 0.75f) < 0.001f);
  2607. // o clip acaba no tempo 3: depois do fade curto, silêncio (o sample ainda teria áudio)
  2608. double tick = 3.0 * lynx::ppq - 10 * tps;
  2609. r.process (state.get(), false, tick, 256, l.data(), rr.data()); // para (fade)
  2610. for (int i = 0; i < 4; ++i)
  2611. r.process (state.get(), false, tick, 256, l.data(), rr.data());
  2612. CHECK (std::abs (l[255]) < 1e-6f);
  2613. }
  2614. TEST (remove_channel_fixes_notes_and_audio_clips)
  2615. {
  2616. lynx::Song s;
  2617. s.channels.resize (3);
  2618. s.patterns.resize (1);
  2619. s.patterns[0].notes = { { 0, 240, 0, 60, 1.0f }, { 0, 240, 1, 60, 1.0f }, { 0, 240, 2, 60, 1.0f } };
  2620. lynx::Clip a;
  2621. a.kind = lynx::ClipKind::audio;
  2622. a.channel = 1;
  2623. a.length = 100;
  2624. lynx::Clip b = a;
  2625. b.channel = 2;
  2626. s.playlist = { a, b };
  2627. s.removeChannel (1);
  2628. CHECK (s.channels.size() == 2);
  2629. CHECK (s.patterns[0].notes.size() == 2 && s.patterns[0].notes[1].channel == 1);
  2630. CHECK (s.playlist.size() == 1 && s.playlist[0].channel == 1);
  2631. }
  2632. TEST (flp_import_audio_clips_with_offsets)
  2633. {
  2634. flp::Project p;
  2635. p.header.ppq = 96;
  2636. p.tempo = 120.0;
  2637. p.channels = { { 0, flp::ChannelType::audioClip, "Vocal", "", "%FLStudioData%\\v.wav", 2 },
  2638. { 1, flp::ChannelType::audioClip, "Loop", "", "%FLStudioData%\\l.wav", 3 } };
  2639. flp::Arrangement arr;
  2640. flp::PlaylistItem beats; // offset em tempos: fim - início = duração em tempos
  2641. beats.kind = flp::PlaylistItem::Kind::channelClip;
  2642. beats.index = 0;
  2643. beats.position = 192;
  2644. beats.length = 384; // 4 tempos
  2645. beats.startOffset = 2.0f;
  2646. beats.endOffset = 6.0f;
  2647. flp::PlaylistItem ms = beats; // offset em ms: 4 tempos a 120 BPM = 2000 ms
  2648. ms.index = 1;
  2649. ms.startOffset = 500.0f;
  2650. ms.endOffset = 2500.0f;
  2651. arr.items = { beats, ms };
  2652. p.arrangements.push_back (arr);
  2653. lynx::FlpImportOptions options;
  2654. options.roots = { "C:\\FL", "C:\\FL\\Data", "" };
  2655. options.fileExists = [] (const std::string&) { return true; };
  2656. const auto s = lynx::importFlp (p, options);
  2657. CHECK (s.channels.size() == 2 && s.channels[0].instrument == lynx::InstrumentKind::audioClip);
  2658. CHECK (s.channels[0].samplePath == "C:\\FL\\Data\\v.wav");
  2659. CHECK (s.playlist.size() == 2);
  2660. CHECK (s.playlist[0].kind == lynx::ClipKind::audio && s.playlist[0].start == 2 * lynx::ppq);
  2661. CHECK (s.playlist[0].offset == 2 * lynx::ppq);
  2662. CHECK (s.playlist[1].offset == lynx::ppq); // 500 ms a 120 BPM = 1 tempo
  2663. CHECK (s.mode == lynx::PlayMode::song);
  2664. }
  2665. TEST (plugin_factories_create_reuse_and_fallback)
  2666. {
  2667. lynx::Song s;
  2668. s.mixer = lynx::Song::defaultMixer (2);
  2669. lynx::ChannelDef c;
  2670. c.instrument = lynx::InstrumentKind::plugin;
  2671. c.plugin.id = "VST3-Synth-123";
  2672. c.mixerTrack = 1;
  2673. s.channels.push_back (c);
  2674. lynx::ChannelDef missing = c;
  2675. missing.plugin.id = "VST3-Ausente-0";
  2676. s.channels.push_back (missing);
  2677. lynx::EffectSlot fx;
  2678. fx.kind = lynx::EffectKind::plugin;
  2679. fx.plugin.id = "VST3-Reverb-9";
  2680. s.mixer[1].effects.push_back (fx);
  2681. s.patterns.emplace_back();
  2682. int instrumentsMade = 0, effectsMade = 0;
  2683. lynx::RackState::Factories f;
  2684. f.pluginInstruments = [&] (const lynx::PluginRef& ref, double) -> std::shared_ptr<lynx::Instrument> {
  2685. if (ref.id != "VST3-Synth-123")
  2686. return nullptr;
  2687. ++instrumentsMade;
  2688. auto synth = lynx::makeInstrument (lynx::InstrumentKind::synth);
  2689. synth->prepare (48000.0);
  2690. return synth;
  2691. };
  2692. f.pluginEffects = [&] (const lynx::PluginRef&, double) -> std::shared_ptr<lynx::Effect> {
  2693. ++effectsMade;
  2694. auto eq = lynx::makeEffect (lynx::EffectKind::eq);
  2695. eq->prepare (48000.0);
  2696. return eq;
  2697. };
  2698. auto a = lynx::RackState::build (s, nullptr, 48000.0, f);
  2699. CHECK (instrumentsMade == 1 && effectsMade == 1);
  2700. CHECK (a->instruments.size() == 2 && a->instruments[1] != nullptr); // ausente: mudo, mas existe
  2701. // mudar o estado salvo não recria; trocar o plugin recria
  2702. s.channels[0].plugin.state = "abc";
  2703. auto b = lynx::RackState::build (s, a.get(), 48000.0, f);
  2704. CHECK (instrumentsMade == 1 && b->instruments[0] == a->instruments[0] && b->effects[1][0] == a->effects[1][0]);
  2705. s.mixer[1].effects[0].plugin.id = "VST3-Outro-1";
  2706. auto c2 = lynx::RackState::build (s, b.get(), 48000.0, f);
  2707. CHECK (effectsMade == 2);
  2708. // renderizar com plugin ausente e slot de plugin não quebra nada
  2709. lynx::RackRenderer r;
  2710. r.prepare (48000.0, 256);
  2711. lynx::LiveEventQueue live;
  2712. lynx::NoteEvent on;
  2713. on.channel = 0;
  2714. on.velocity = 1.0f;
  2715. live.push (on);
  2716. on.channel = 1;
  2717. live.push (on);
  2718. std::vector<float> l (256), rr (256);
  2719. r.process (c2.get(), false, 0.0, 256, l.data(), rr.data(), &live);
  2720. float peak = 0.0f;
  2721. for (auto v : l)
  2722. {
  2723. CHECK (std::isfinite (v));
  2724. peak = std::max (peak, std::abs (v));
  2725. }
  2726. CHECK (peak > 0.0f);
  2727. }
  2728. TEST (export_song_adds_silent_tail_and_never_restarts)
  2729. {
  2730. auto s = lynx::Song::makeDefault();
  2731. s.playlist.clear();
  2732. std::int64_t length = 0;
  2733. auto pat = lynx::makeExportSong (s, true, lynx::ppq * 8, length); // Playlist vazia: usa a pattern
  2734. CHECK (length == lynx::ppq * 4);
  2735. CHECK (pat.mode == lynx::PlayMode::song && pat.playlist.size() == 2);
  2736. CHECK (pat.songLength() >= length + lynx::ppq * 8);
  2737. // nenhuma nota nova depois do fim da música, só silêncio até o fim da cauda
  2738. lynx::EventBuffer events;
  2739. const auto tps = lynx::ticksPerSample (pat.bpm, 48000.0);
  2740. int onsAfterEnd = 0, onsBefore = 0;
  2741. for (double tick = 0.0; tick < (double) (length + lynx::ppq * 8); tick += 512 * tps)
  2742. {
  2743. events.clear();
  2744. lynx::scheduleSong (pat, tick, 512, tps, events);
  2745. for (const auto& e : events)
  2746. if (e.type == lynx::NoteEvent::Type::on)
  2747. (tick + e.sampleOffset * tps >= (double) length ? onsAfterEnd : onsBefore)++;
  2748. }
  2749. CHECK (onsBefore == (int) s.patterns[0].notes.size());
  2750. CHECK (onsAfterEnd == 0);
  2751. // com Playlist: o fim é o do último clip, sem arredondar
  2752. s.playlist.push_back ({ 0, 0, lynx::ppq * 2, lynx::ppq * 3, 0 });
  2753. auto song = lynx::makeExportSong (s, true, 0, length);
  2754. CHECK (length == lynx::ppq * 5 && song.playlist.size() == 1);
  2755. song = lynx::makeExportSong (s, false, 0, length);
  2756. CHECK (length == lynx::ppq * 4 && song.playlist[0].start == 0);
  2757. }
  2758. TEST (note_edit_selection_operations)
  2759. {
  2760. namespace ne = lynx::noteedit;
  2761. lynx::Pattern p;
  2762. p.notes = { { 0, 240, 0, 60 }, { 480, 240, 0, 64 }, { 960, 480, 1, 67 } };
  2763. // ordenar acompanha os índices
  2764. p.notes[0].start = 1200;
  2765. std::vector<int> tracked { 0, 2 };
  2766. ne::sortTracking (p, tracked);
  2767. CHECK (p.notes[2].start == 1200 && p.notes[(std::size_t) tracked[0]].start == 1200);
  2768. CHECK (p.notes[(std::size_t) tracked[1]].key == 67);
  2769. // mover em grupo respeita os limites
  2770. std::int64_t dt = -5000;
  2771. int dk = 100;
  2772. ne::move (p, { 0, 1 }, dt, dk);
  2773. CHECK (dt == -480 && dk == 127 - 67 && p.notes[0].start == 0 && p.notes[1].key == 127);
  2774. // duplicar: logo depois do trecho, arredondado à grade
  2775. lynx::Pattern q;
  2776. q.notes = { { 0, 240, 0, 60 }, { 240, 300, 0, 62 } }; // trecho de 540 ticks
  2777. const auto added = ne::duplicate (q, { 0, 1 }, 960);
  2778. CHECK (added.size() == 2 && q.notes[(std::size_t) added[0]].start == 960 && q.notes[(std::size_t) added[1]].start == 1200);
  2779. // colar em outro canal com deslocamento
  2780. const auto pasted = ne::paste (q, ne::copy (q, { 1 }), 100, 3);
  2781. CHECK (pasted.size() == 1 && q.notes.back().channel == 3 && q.notes.back().start == 340);
  2782. // quantizar arredonda para o mais próximo
  2783. q.notes[0].start = 130;
  2784. q.notes[1].start = 100;
  2785. ne::quantize (q, { 0, 1 }, 240);
  2786. CHECK (q.notes[0].start == 240 && q.notes[1].start == 0);
  2787. // remover vários (ordem e repetidos não importam)
  2788. const auto before = q.notes.size();
  2789. ne::remove (q, { 1, 0, 1 });
  2790. CHECK (q.notes.size() == before - 2);
  2791. }
  2792. TEST (recorder_builds_notes_in_pattern_and_song_mode)
  2793. {
  2794. auto song = lynx::Song::makeDefault();
  2795. const auto loop = song.patterns[0].effectiveLength (4); // 1 compasso = 3840
  2796. lynx::NoteRecorder r;
  2797. r.add (song, { 100.0, 4, 60, 0.5f, true }); // sem tomada: ignorado
  2798. CHECK (r.takeFinished().empty());
  2799. r.begin (loop);
  2800. r.add (song, { 4000.0, 4, 60, 0.5f, true }); // segunda volta do loop
  2801. r.add (song, { 4480.0, 4, 60, 0.0f, false });
  2802. r.add (song, { 5000.0, 4, 64, 0.9f, true }); // presa até parar
  2803. r.end (song, 5240.0);
  2804. const auto notes = r.takeFinished();
  2805. CHECK (notes.size() == 2);
  2806. CHECK (notes[0].start == 4000 - 3840 && notes[0].length == 480 && notes[0].velocity == 0.5f && notes[0].channel == 4);
  2807. CHECK (notes[1].key == 64 && notes[1].start == 5000 - 3840 && notes[1].length == 240);
  2808. // modo song: posição dentro do clip da pattern atual (com offset)
  2809. song.mode = lynx::PlayMode::song;
  2810. song.playlist = { { 0, 0, 7680, 3840, 960 } };
  2811. CHECK (lynx::patternPositionForTick (song, 7680.0 + 100.0, loop) == 1060);
  2812. CHECK (lynx::patternPositionForTick (song, 100.0, loop) == 100); // fora do clip: como loop
  2813. }
  2814. TEST (automation_curve_and_playback)
  2815. {
  2816. lynx::Automation a;
  2817. a.points = { { 0, 0.0f }, { 960, 1.0f }, { 1920, 0.5f, 0.0f } };
  2818. CHECK (a.valueAt (-10.0) == 0.0f && a.valueAt (480.0) == 0.5f && a.valueAt (5000.0) == 0.5f);
  2819. CHECK (a.length() == 1920);
  2820. a.points[0].tension = 1.0f; // curva: começa devagar
  2821. CHECK (a.valueAt (480.0) < 0.2f && a.valueAt (480.0) > 0.0f);
  2822. // Master automatizado: silêncio no primeiro compasso, som no segundo, e o último valor
  2823. // fica valendo depois do fim do clip de automação
  2824. auto song = lynx::Song::makeDefault();
  2825. song.bpm = 120.0;
  2826. song.mode = lynx::PlayMode::song;
  2827. const auto bar = (std::int64_t) lynx::ppq * 4;
  2828. for (int b = 0; b < 3; ++b)
  2829. song.playlist.push_back ({ 0, 0, bar * b, bar, 0 });
  2830. lynx::Automation master;
  2831. master.target = { lynx::AutomationTargetKind::mixerVolume, 0 };
  2832. master.points = { { 0, 0.0f }, { bar - 1, 0.0f }, { bar, 0.8f } };
  2833. song.automations.push_back (master);
  2834. lynx::Clip ac;
  2835. ac.kind = lynx::ClipKind::automation;
  2836. ac.automation = 0;
  2837. ac.track = 1;
  2838. ac.length = bar + bar / 2;
  2839. song.playlist.push_back (ac);
  2840. const double sr = 48000.0;
  2841. auto state = lynx::RackState::build (song, nullptr, sr);
  2842. CHECK (state->hasAutomation && state->mixerVolumeAuto[0] == 0 && state->automationClips[0].size() == 1);
  2843. lynx::RackRenderer r;
  2844. r.prepare (sr, 512);
  2845. std::vector<float> l (512), rr (512);
  2846. const auto tps = lynx::ticksPerSample (song.bpm, sr);
  2847. float peakBar1 = 0.0f, peakBar2 = 0.0f, peakBar3 = 0.0f;
  2848. for (double tick = 0.0; tick < (double) (bar * 3); tick += 512 * tps)
  2849. {
  2850. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  2851. auto& peak = tick < (double) bar - 512 * tps ? peakBar1 : tick < (double) bar * 2 ? peakBar2 : peakBar3;
  2852. for (auto v : l)
  2853. peak = std::max (peak, std::abs (v));
  2854. }
  2855. CHECK (peakBar1 < 1.0e-6f);
  2856. CHECK (peakBar2 > 0.05f);
  2857. CHECK (peakBar3 > 0.05f); // depois do clip: segue no último valor
  2858. // alvo removido: automação some das tabelas
  2859. song.removeChannel (0);
  2860. song.automations[0].target = { lynx::AutomationTargetKind::channelVolume, 0 };
  2861. song.removeChannel (0);
  2862. CHECK (song.automations[0].target.kind == lynx::AutomationTargetKind::none);
  2863. song.removeAutomation (0);
  2864. CHECK (song.automations.empty() && song.playlist.size() == 3);
  2865. }
  2866. TEST (mixer_sends_between_inserts)
  2867. {
  2868. // insert 1 vai só para o 3; o 3 vai ao Master: soma igual (0,5 + 0,5)
  2869. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.setRoute (1, 3, true); s.setRoute (1, 0, false); }) - 1.0f) < 1e-4f);
  2870. // envio a 50% e destino mudo
  2871. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.setRoute (1, 3, true, 0.5f); s.setRoute (1, 0, false); }) - 0.75f) < 1e-4f);
  2872. 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);
  2873. // indo ao Master e ao 3: o sinal dobra
  2874. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.setRoute (1, 3, true); }) - 1.5f) < 1e-4f);
  2875. // solo no 3 deixa soar quem chega nele (insert 1), mas não o 2
  2876. 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);
  2877. // solo no 1 deixa soar o caminho até o Master (o 3)
  2878. 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);
  2879. // ordem e ciclos
  2880. auto song = lynx::Song::makeDefault();
  2881. song.setRoute (4, 2, true);
  2882. song.setRoute (2, 1, true);
  2883. CHECK (! song.canRoute (1, 4) && ! song.canRoute (1, 2) && song.canRoute (1, 5));
  2884. song.setRoute (1, 4, true); // ignorado: criaria ciclo
  2885. CHECK (! song.routes (1, 4));
  2886. const auto order = song.mixerOrder();
  2887. const auto pos = [&] (int t) { return std::find (order.begin(), order.end(), t) - order.begin(); };
  2888. CHECK ((int) order.size() == (int) song.mixer.size() - 1);
  2889. CHECK (pos (4) < pos (2) && pos (2) < pos (1));
  2890. song.setRoute (4, 2, false);
  2891. CHECK (! song.routes (4, 2) && song.routes (4, 0));
  2892. }
  2893. namespace
  2894. {
  2895. // Efeito de teste: atrasa o sinal em `latency` samples e informa essa latência (como um plugin com lookahead).
  2896. class LatentEffect final : public lynx::Effect
  2897. {
  2898. public:
  2899. explicit LatentEffect (int samples) : latency (samples), line (samples) {}
  2900. void prepare (double) noexcept override {}
  2901. void reset() noexcept override {}
  2902. void process (float* l, float* r, int n, const lynx::EffectParams&, double) noexcept override { line.process (l, r, n); }
  2903. int latencySamples() const noexcept override { return latency; }
  2904. private:
  2905. int latency;
  2906. lynx::DelayLine line;
  2907. };
  2908. } // namespace
  2909. TEST (delay_line_mix_into_matches_process_and_drains_tail)
  2910. {
  2911. // mixInto = process sobre source*level, somado no destino; em trechos que cruzam o anel
  2912. lynx::DelayLine a (37), b (37);
  2913. std::vector<float> sl (300), sr (300), dl (300, 0.5f), dr (300, -0.5f), xl (300), xr (300);
  2914. for (int i = 0; i < 300; ++i)
  2915. {
  2916. sl[(std::size_t) i] = (float) std::sin (i * 0.1);
  2917. sr[(std::size_t) i] = (float) std::cos (i * 0.07);
  2918. }
  2919. for (int start = 0; start < 300; start += 100)
  2920. {
  2921. b.mixInto (sl.data() + start, sr.data() + start, 0.25f, dl.data() + start, dr.data() + start, 100);
  2922. for (int i = start; i < start + 100; ++i)
  2923. {
  2924. xl[(std::size_t) i] = sl[(std::size_t) i] * 0.25f;
  2925. xr[(std::size_t) i] = sr[(std::size_t) i] * 0.25f;
  2926. }
  2927. a.process (xl.data() + start, xr.data() + start, 100);
  2928. }
  2929. float worst = 0.0f;
  2930. for (int i = 0; i < 300; ++i)
  2931. worst = std::max ({ worst, std::abs (dl[(std::size_t) i] - 0.5f - xl[(std::size_t) i]),
  2932. std::abs (dr[(std::size_t) i] + 0.5f - xr[(std::size_t) i]) });
  2933. CHECK (worst < 1e-6f);
  2934. // fonte calada: a cauda que estava na linha ainda sai, depois não sobra nada
  2935. std::vector<float> tl (64, 0.0f), tr (64, 0.0f);
  2936. b.mixInto (nullptr, nullptr, 1.0f, tl.data(), tr.data(), 64);
  2937. CHECK (std::abs (tl[0] - sl[263] * 0.25f) < 1e-6f);
  2938. std::vector<float> zl (64, 0.0f), zr (64, 0.0f);
  2939. b.mixInto (nullptr, nullptr, 1.0f, zl.data(), zr.data(), 64);
  2940. CHECK (*std::max_element (zl.begin(), zl.end()) == 0.0f && *std::min_element (zl.begin(), zl.end()) == 0.0f);
  2941. }
  2942. TEST (limiter_lookahead_holds_ceiling_on_bursts)
  2943. {
  2944. // rajadas curtas sobre um fundo baixo: o máximo deslizante precisa ver cada pico antes de sair
  2945. auto fx = lynx::makeEffect (lynx::EffectKind::limiter);
  2946. fx->prepare (48000.0);
  2947. auto slot = lynx::makeEffectSlot (lynx::EffectKind::limiter);
  2948. slot.params[2] = 0.0f; // release de 10 ms
  2949. std::vector<float> l (48000), r (48000);
  2950. std::uint32_t seed = 1;
  2951. for (int i = 0; i < 48000; ++i)
  2952. {
  2953. seed = seed * 1664525u + 1013904223u;
  2954. const auto noise = ((float) (seed >> 8) / 16777216.0f - 0.5f) * 0.1f;
  2955. l[(std::size_t) i] = noise + ((i % 9973) < 3 ? 3.0f : 0.0f);
  2956. r[(std::size_t) i] = -noise;
  2957. }
  2958. for (int i = 0; i < 48000; i += 333)
  2959. fx->process (l.data() + i, r.data() + i, std::min (333, 48000 - i), slot.params, 120.0);
  2960. float peak = 0.0f, quiet = 0.0f;
  2961. for (int i = 0; i < 48000; ++i)
  2962. peak = std::max (peak, std::abs (l[(std::size_t) i]));
  2963. for (int i = 9973 * 2 + 2000; i < 9973 * 2 + 2400; ++i) // 40 ms depois da rajada o ganho já voltou
  2964. quiet = std::max (quiet, std::abs (r[(std::size_t) i]));
  2965. const auto ceiling = 1.0f; // o teto padrão fica em 0 dBFS ou abaixo
  2966. CHECK (peak <= ceiling + 1e-5f);
  2967. CHECK (quiet > 0.03f);
  2968. }
  2969. TEST (pdc_aligns_paths_through_latent_effects)
  2970. {
  2971. // plano: canal 0 -> insert 1 (efeito de 100) -> insert 3; canal 1 -> insert 2 -> Master
  2972. lynx::Song s;
  2973. s.mixer = lynx::Song::defaultMixer (4);
  2974. s.channels.resize (3);
  2975. s.channels[0].mixerTrack = 1;
  2976. s.channels[1].mixerTrack = 2;
  2977. s.channels[2].mixerTrack = 3;
  2978. s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::eq));
  2979. s.setRoute (1, 3, true);
  2980. s.setRoute (1, 0, false);
  2981. auto plan = lynx::computePdc (s, { 0, 0, 30 }, { {}, { 100 } });
  2982. CHECK (plan.inAlign[1] == 0 && plan.outLat[1] == 100);
  2983. CHECK (plan.inAlign[3] == 100 && plan.channelDelay[2] == 70); // instrumento de 30 no insert 3
  2984. CHECK (plan.sendDelay[1][1] == 0); // o caminho mais lento não atrasa
  2985. CHECK (plan.sendDelay[2][0] == 100 && plan.sendDelay[3][0] == 0 && plan.total == 100);
  2986. // bypass zera a latência do slot
  2987. s.mixer[1].effects[0].enabled = false;
  2988. CHECK (lynx::computePdc (s, { 0, 0, 30 }, { {}, { 100 } }).total == 30);
  2989. // renderizado: dois impulsos tocados juntos saem juntos
  2990. lynx::Song r;
  2991. r.mixer = lynx::Song::defaultMixer (2);
  2992. for (int i = 0; i < 2; ++i)
  2993. {
  2994. lynx::ChannelDef c;
  2995. c.instrument = lynx::InstrumentKind::sampler;
  2996. c.samplePath = "impulso";
  2997. c.volume = 1.0f;
  2998. c.mixerTrack = i + 1;
  2999. r.channels.push_back (c);
  3000. }
  3001. r.patterns.emplace_back();
  3002. lynx::EffectSlot fx;
  3003. fx.kind = lynx::EffectKind::plugin;
  3004. fx.plugin.id = "latente";
  3005. r.mixer[1].effects.push_back (fx);
  3006. lynx::RackState::Factories f;
  3007. f.samples = [] (const std::string&) {
  3008. auto d = std::make_shared<lynx::SampleData>();
  3009. d->left.assign (64, 0.0f);
  3010. d->left[0] = 1.0f;
  3011. return std::shared_ptr<const lynx::SampleData> (d);
  3012. };
  3013. f.pluginEffects = [] (const lynx::PluginRef&, double) -> std::shared_ptr<lynx::Effect> { return std::make_shared<LatentEffect> (100); };
  3014. auto state = lynx::RackState::build (r, nullptr, 48000.0, f);
  3015. CHECK (state->pdc.total == 100 && state->sendDelays[2][0] != nullptr && state->sendDelays[2][0]->length() == 100);
  3016. lynx::RackRenderer renderer;
  3017. renderer.prepare (48000.0, 256);
  3018. lynx::LiveEventQueue live;
  3019. for (int ch = 0; ch < 2; ++ch)
  3020. {
  3021. lynx::NoteEvent on;
  3022. on.channel = ch;
  3023. on.key = 60;
  3024. on.velocity = 1.0f;
  3025. live.push (on);
  3026. }
  3027. std::vector<float> l (256), rr (256);
  3028. renderer.process (state.get(), false, 0.0, 256, l.data(), rr.data(), &live);
  3029. int first = -1;
  3030. for (int i = 0; i < 256 && first < 0; ++i)
  3031. if (std::abs (l[(std::size_t) i]) > 0.01f)
  3032. first = i;
  3033. CHECK (first == 100 && std::abs (l[100] - 2.0f) < 1e-3f); // os dois impulsos chegam juntos, somados
  3034. // editar sem mudar as latências reaproveita as linhas
  3035. r.channels[0].volume = 0.5f;
  3036. auto next = lynx::RackState::build (r, state.get(), 48000.0, f);
  3037. CHECK (next->sendDelays[2][0] == state->sendDelays[2][0]);
  3038. }
  3039. TEST (mixer_mute_fades_instead_of_clicking)
  3040. {
  3041. lynx::Song s;
  3042. s.mixer = lynx::Song::defaultMixer (2);
  3043. lynx::ChannelDef c;
  3044. c.instrument = lynx::InstrumentKind::sampler;
  3045. c.samplePath = "dc";
  3046. c.volume = 1.0f;
  3047. c.mixerTrack = 1;
  3048. s.channels.push_back (c);
  3049. s.patterns.emplace_back();
  3050. auto provider = [] (const std::string&) {
  3051. auto d = std::make_shared<lynx::SampleData>();
  3052. d->left.assign (48000, 0.5f);
  3053. return std::shared_ptr<const lynx::SampleData> (d);
  3054. };
  3055. auto on = lynx::RackState::build (s, nullptr, 48000.0, provider);
  3056. s.mixer[1].muted = true;
  3057. auto off = lynx::RackState::build (s, on.get(), 48000.0, provider);
  3058. lynx::RackRenderer r;
  3059. r.prepare (48000.0, 256);
  3060. lynx::LiveEventQueue live;
  3061. lynx::NoteEvent note;
  3062. note.velocity = 1.0f;
  3063. live.push (note);
  3064. std::vector<float> l (256), rr (256);
  3065. r.process (on.get(), false, 0.0, 256, l.data(), rr.data(), &live);
  3066. CHECK (std::abs (l[255] - 0.5f) < 1e-3f);
  3067. r.process (off.get(), false, 0.0, 256, l.data(), rr.data());
  3068. CHECK (l[0] > 0.45f && l[128] > 0.2f && l[128] < 0.3f && std::abs (l[255]) < 1e-6f); // rampa até zero
  3069. r.process (off.get(), false, 0.0, 256, l.data(), rr.data());
  3070. CHECK (std::abs (l[0]) < 1e-9f);
  3071. }
  3072. TEST (dither_quantizes_to_lsb_grid_with_small_error)
  3073. {
  3074. lynx::Dither d (16);
  3075. std::vector<float> x (4800);
  3076. for (std::size_t i = 0; i < x.size(); ++i)
  3077. x[i] = 0.25f * std::sin ((float) i * 0.05f);
  3078. auto y = x;
  3079. d.process (y.data(), (int) y.size(), 0);
  3080. double errorSum = 0.0;
  3081. bool onGrid = true;
  3082. for (std::size_t i = 0; i < x.size(); ++i)
  3083. {
  3084. const auto steps = y[i] * 32768.0f;
  3085. onGrid = onGrid && std::abs (steps - std::round (steps)) < 1e-3f;
  3086. errorSum += std::abs (y[i] - x[i]);
  3087. }
  3088. CHECK (onGrid);
  3089. CHECK (errorSum / (double) x.size() < 4.0 / 32768.0); // poucos LSB de ruído em média
  3090. }
  3091. TEST (parallel_rendering_matches_sequential)
  3092. {
  3093. // 32 canais (vale a pena paralelizar), inserts com envios em cadeia
  3094. auto song = lynx::Song::makeDefault();
  3095. song.mixer = lynx::Song::defaultMixer (16);
  3096. for (int i = 5; i < 32; ++i)
  3097. {
  3098. lynx::ChannelDef c;
  3099. c.instrument = i % 2 ? lynx::InstrumentKind::synth : lynx::InstrumentKind::hat;
  3100. c.mixerTrack = 1 + i % 12;
  3101. c.volume = 0.3f;
  3102. song.channels.push_back (c);
  3103. for (int step = i % 4; step < 16; step += 3)
  3104. song.patterns[0].notes.push_back ({ (std::int64_t) step * lynx::ticksPerStep, 200, i, 48 + i, 0.7f });
  3105. }
  3106. song.patterns[0].sortNotes();
  3107. song.setRoute (3, 7, true, 0.6f);
  3108. song.setRoute (7, 9, true, 0.5f);
  3109. song.setRoute (2, 9, true);
  3110. song.mixer[9].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::reverb));
  3111. auto seqState = lynx::RackState::build (song, nullptr, 48000.0);
  3112. auto parState = lynx::RackState::build (song, nullptr, 48000.0);
  3113. CHECK (parState->parallel && parState->mixerLayers.size() == 3);
  3114. lynx::WorkerPool pool (3);
  3115. lynx::RackRenderer seq, par;
  3116. seq.prepare (48000.0, 512);
  3117. par.prepare (48000.0, 512);
  3118. par.setWorkerPool (&pool);
  3119. std::vector<float> l1 (512), r1 (512), l2 (512), r2 (512);
  3120. const auto tps = lynx::ticksPerSample (song.bpm, 48000.0);
  3121. bool same = true;
  3122. float peak = 0.0f;
  3123. for (int block = 0; block < 200; ++block)
  3124. {
  3125. seq.process (seqState.get(), true, block * 512 * tps, 512, l1.data(), r1.data());
  3126. par.process (parState.get(), true, block * 512 * tps, 512, l2.data(), r2.data());
  3127. same = same && l1 == l2 && r1 == r2;
  3128. for (auto v : l1)
  3129. peak = std::max (peak, std::abs (v));
  3130. }
  3131. CHECK (same);
  3132. CHECK (peak > 0.05f);
  3133. // o pool aguenta muitas rodadas pequenas seguidas
  3134. std::atomic<int> sum { 0 };
  3135. auto add = [&sum] (int i) { sum.fetch_add (i + 1); };
  3136. for (int round = 0; round < 2000; ++round)
  3137. pool.parallelFor (5, add);
  3138. CHECK (sum.load() == 2000 * 15);
  3139. }
  3140. TEST (arrangements_switch_and_keep_clip_indices)
  3141. {
  3142. auto s = lynx::Song::makeDefault();
  3143. s.patterns.emplace_back().name = "B";
  3144. s.playlist = { { 1, 0, 0, 960, 0 } };
  3145. s.loopEnd = 960;
  3146. CHECK (s.arrangements.size() == 1 && s.currentArrangement == 0);
  3147. const auto second = s.addArrangement ("Versão curta", true);
  3148. CHECK (second == 1 && s.currentArrangement == 1 && s.playlist.size() == 1 && s.loopEnd == 960);
  3149. s.playlist.push_back ({ 0, 1, 960, 960, 0 });
  3150. s.loopEnd = 0;
  3151. s.selectArrangement (0);
  3152. CHECK (s.playlist.size() == 1 && s.loopEnd == 960 && s.arrangements[1].clips.size() == 2);
  3153. // remover a pattern 0 conserta os clips guardados no outro arrangement
  3154. s.removePattern (0);
  3155. CHECK (s.playlist.size() == 1 && s.playlist[0].pattern == 0);
  3156. CHECK (s.arrangements[1].clips.size() == 1 && s.arrangements[1].clips[0].pattern == 0);
  3157. s.removeArrangement (0);
  3158. CHECK (s.arrangements.size() == 1 && s.currentArrangement == 0 && s.playlist.size() == 1 && s.loopEnd == 0);
  3159. }
  3160. namespace
  3161. {
  3162. // Efeito de teste que inverte o sinal e conta quantas vezes processou.
  3163. class CountingInverter final : public lynx::Effect
  3164. {
  3165. public:
  3166. void prepare (double) noexcept override {}
  3167. void reset() noexcept override {}
  3168. void process (float* l, float* r, int n, const lynx::EffectParams&, double) noexcept override
  3169. {
  3170. ++calls;
  3171. for (int i = 0; i < n; ++i)
  3172. {
  3173. l[i] = -l[i];
  3174. r[i] = -r[i];
  3175. }
  3176. }
  3177. int calls = 0;
  3178. };
  3179. } // namespace
  3180. TEST (keyboard_controller_outputs_key_value)
  3181. {
  3182. std::vector<std::uint8_t> blob (554, 0);
  3183. const std::uint32_t version = 3;
  3184. std::memcpy (blob.data(), &version, 4);
  3185. const float key60 = 0.7f, off = 0.2f;
  3186. std::memcpy (blob.data() + 12 + 60 * 4, &key60, 4);
  3187. std::memcpy (blob.data() + 548, &off, 4);
  3188. blob[552] = 1; // auto release
  3189. lynx::ChannelDef c;
  3190. c.instrument = lynx::InstrumentKind::controller;
  3191. c.controllerState = blob;
  3192. auto inst = lynx::makeInstrument (lynx::InstrumentKind::controller);
  3193. inst->prepare (48000.0);
  3194. inst->configure (c, 120.0);
  3195. std::vector<float> l (64), r (64);
  3196. inst->noteOn (60, 1.0f);
  3197. inst->render (l.data(), r.data(), 64, 1.0f, 1.0f);
  3198. CHECK (std::abs (inst->controlOutput (0) - 0.7f) < 1e-6f);
  3199. inst->noteOff (60);
  3200. CHECK (std::abs (inst->controlOutput (0) - 0.2f) < 1e-6f);
  3201. }
  3202. TEST (envelope_controller_ducks_on_each_note)
  3203. {
  3204. // um articulador unipolar como o "Basic Sidechain": base 0,05, cai a 0 na nota e sobe a 1 em 0,3 s
  3205. lynx::ControllerArticulator a;
  3206. a.envOn = true;
  3207. a.base = 0.05f;
  3208. a.envLevel = 1.0f;
  3209. a.count = 3;
  3210. a.time = { 0.0f, 0.2f, 0.3f };
  3211. a.level = { 0.0f, 0.75f, 1.0f };
  3212. CHECK (std::abs (lynx::controllerValue (a, 0.0, -1.0) - 0.05f) < 1e-4f);
  3213. CHECK (std::abs (lynx::controllerValue (a, 0.1, -1.0) - 0.425f) < 1e-3f);
  3214. CHECK (lynx::controllerValue (a, 1.0, -1.0) > 0.99f); // sem sustain: corre até o fim e fica
  3215. a.sustain = 1;
  3216. CHECK (std::abs (lynx::controllerValue (a, 1.0, -1.0) - 0.8f) < 1e-3f); // preso no sustain
  3217. CHECK (lynx::controllerValue (a, 1.0, 0.5) > 0.99f); // soltou: segue até o fim
  3218. a.bipolar = true;
  3219. a.base = 0.5f;
  3220. a.sustain = -1;
  3221. CHECK (std::abs (lynx::controllerValue (a, 0.0, -1.0) - 0.0f) < 1e-4f); // bipolar: 0,5 + (0 − 0,5)
  3222. }
  3223. TEST (peak_controller_drives_live_automation)
  3224. {
  3225. // trilha 1: fonte (DC 0,5) com Peak Controller; trilha 2: DC 0,5 com o volume ligado ao controlador
  3226. auto render = [] (bool linked) {
  3227. lynx::Song s;
  3228. s.mixer = lynx::Song::defaultMixer (2);
  3229. for (int t = 1; t <= 2; ++t)
  3230. {
  3231. lynx::ChannelDef c;
  3232. c.instrument = lynx::InstrumentKind::sampler;
  3233. c.samplePath = "dc";
  3234. c.volume = 1.0f;
  3235. c.mixerTrack = t;
  3236. s.channels.push_back (c);
  3237. }
  3238. s.patterns.emplace_back();
  3239. auto peak = lynx::makeEffectSlot (lynx::EffectKind::peakController);
  3240. peak.params[0] = 1.0f; // base 1
  3241. peak.params[1] = 0.0f; // quantidade −1: 1 − pico
  3242. peak.params[2] = 0.5f; // sem tensão
  3243. s.mixer[1].effects.push_back (peak);
  3244. if (linked)
  3245. {
  3246. lynx::Automation a;
  3247. a.name = "Peak";
  3248. a.target = { lynx::AutomationTargetKind::mixerVolume, 2 };
  3249. a.source = { 1, 0, 0 };
  3250. s.automations.push_back (a);
  3251. }
  3252. lynx::RackState::Factories f;
  3253. f.samples = [] (const std::string&) {
  3254. auto d = std::make_shared<lynx::SampleData>();
  3255. d->left.assign (48000, 0.5f);
  3256. return std::shared_ptr<const lynx::SampleData> (d);
  3257. };
  3258. auto state = lynx::RackState::build (s, nullptr, 48000.0, f);
  3259. lynx::RackRenderer r;
  3260. r.prepare (48000.0, 512);
  3261. lynx::LiveEventQueue live;
  3262. for (int ch = 0; ch < 2; ++ch)
  3263. {
  3264. lynx::NoteEvent on;
  3265. on.channel = ch;
  3266. on.velocity = 1.0f;
  3267. live.push (on);
  3268. }
  3269. std::vector<float> l (4800), rr (4800);
  3270. r.process (state.get(), false, 0.0, 4800, l.data(), rr.data(), &live);
  3271. return l[4000];
  3272. };
  3273. const auto free = render (false), ducked = render (true);
  3274. CHECK (std::isfinite (ducked) && ducked > 0.0f);
  3275. CHECK (ducked < free - 0.05f); // o pico de 0,5 na trilha 1 abaixa o volume da trilha 2
  3276. }
  3277. TEST (effect_slot_dry_wet_and_smart_disable)
  3278. {
  3279. lynx::Song s;
  3280. s.mixer = lynx::Song::defaultMixer (1);
  3281. lynx::ChannelDef c;
  3282. c.instrument = lynx::InstrumentKind::sampler;
  3283. c.samplePath = "dc";
  3284. c.volume = 1.0f;
  3285. c.mixerTrack = 1;
  3286. s.channels.push_back (c);
  3287. s.patterns.emplace_back();
  3288. lynx::EffectSlot fx;
  3289. fx.kind = lynx::EffectKind::plugin;
  3290. fx.plugin.id = "inversor";
  3291. fx.mix = 0.25f; // 75% seco (+0,5) e 25% molhado (-0,5) = +0,25
  3292. s.mixer[1].effects.push_back (fx);
  3293. auto inverter = std::make_shared<CountingInverter>();
  3294. lynx::RackState::Factories f;
  3295. f.samples = [] (const std::string&) {
  3296. auto d = std::make_shared<lynx::SampleData>();
  3297. d->left.assign (4800, 0.5f);
  3298. return std::shared_ptr<const lynx::SampleData> (d);
  3299. };
  3300. f.pluginEffects = [inverter] (const lynx::PluginRef&, double) -> std::shared_ptr<lynx::Effect> { return inverter; };
  3301. auto state = lynx::RackState::build (s, nullptr, 48000.0, f);
  3302. lynx::RackRenderer r;
  3303. r.prepare (48000.0, 512);
  3304. lynx::LiveEventQueue live;
  3305. lynx::NoteEvent on;
  3306. on.velocity = 1.0f;
  3307. live.push (on);
  3308. std::vector<float> l (480), rr (480);
  3309. r.process (state.get(), false, 0.0, 480, l.data(), rr.data(), &live);
  3310. CHECK (std::abs (l[100] - 0.25f) < 1e-4f);
  3311. // depois que o sample acaba: 4 s de silêncio e o plugin deixa de ser chamado
  3312. for (int i = 0; i < 100 * 6; ++i) // 6 s
  3313. r.process (state.get(), false, 0.0, 480, l.data(), rr.data());
  3314. const auto callsAfterSilence = inverter->calls;
  3315. for (int i = 0; i < 100; ++i)
  3316. r.process (state.get(), false, 0.0, 480, l.data(), rr.data());
  3317. CHECK (inverter->calls == callsAfterSilence);
  3318. CHECK (callsAfterSilence < 100 * 6);
  3319. // som de novo: volta a processar no mesmo bloco
  3320. live.push (on);
  3321. r.process (state.get(), false, 0.0, 480, l.data(), rr.data(), &live);
  3322. CHECK (inverter->calls == callsAfterSilence + 1 && std::abs (l[100] - 0.25f) < 1e-4f);
  3323. }
  3324. TEST (swing_delays_offbeat_sixteenths)
  3325. {
  3326. CHECK (lynx::swingDelay (0, 1.0f) == 0);
  3327. CHECK (lynx::swingDelay (lynx::ticksPerStep, 1.0f) == lynx::ticksPerStep / 2);
  3328. CHECK (lynx::swingDelay (lynx::ticksPerStep * 2, 1.0f) == 0);
  3329. CHECK (lynx::swingDelay (lynx::ticksPerStep + 10, 1.0f) == (lynx::ticksPerStep - 20) / 2); // fora da grade: peso triangular (FL)
  3330. CHECK (lynx::swingDelay (lynx::ticksPerStep, 1.0f, 0.5f) == lynx::ticksPerStep / 4); // mix do canal
  3331. CHECK (lynx::swingDelay (lynx::ticksPerStep * 3, 0.5f) == lynx::ticksPerStep / 4);
  3332. lynx::Pattern p;
  3333. p.notes = { { 0, 100, 0, 60 }, { lynx::ticksPerStep, 100, 0, 62 } };
  3334. lynx::EventBuffer ev;
  3335. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  3336. lynx::schedulePatternLoop (p, p.effectiveLength (4), 0.0, 12000, tps, ev, 1.0f);
  3337. int onOffset = -1;
  3338. for (auto& e : ev)
  3339. if (e.type == lynx::NoteEvent::Type::on && e.key == 62)
  3340. onOffset = e.sampleOffset;
  3341. CHECK (onOffset == (int) std::floor ((lynx::ticksPerStep * 1.5) / tps));
  3342. }
  3343. TEST (sampler_settings_pitch_reverse_envelope_cut)
  3344. {
  3345. auto ramp = std::make_shared<lynx::SampleData>();
  3346. for (int i = 0; i < 48000; ++i)
  3347. ramp->left.push_back ((float) i / 48000.0f); // rampa: o valor diz onde a leitura está
  3348. ramp->sampleRate = 48000.0;
  3349. auto play = [&] (const lynx::SamplerSettings& s, int key, int frames, bool releaseAfterHalf) {
  3350. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  3351. inst->prepare (48000.0);
  3352. lynx::ChannelDef c;
  3353. c.sampler = s;
  3354. inst->configure (c, 120.0);
  3355. inst->noteOn (key, 1.0f);
  3356. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  3357. inst->render (l.data(), r.data(), frames / 2, 1.0f, 1.0f);
  3358. if (releaseAfterHalf)
  3359. inst->noteOff (key);
  3360. inst->render (l.data() + frames / 2, r.data() + frames / 2, frames - frames / 2, 1.0f, 1.0f);
  3361. return l;
  3362. };
  3363. // +12 semitons: lê o dobro
  3364. lynx::SamplerSettings up;
  3365. up.pitch = 12.0f;
  3366. CHECK (std::abs (play (up, 60, 1000, false)[999] - 2.0f * 999.0f / 48000.0f) < 1e-3f);
  3367. // ao contrário: começa do fim
  3368. lynx::SamplerSettings back;
  3369. back.reverse = true;
  3370. CHECK (play (back, 60, 100, false)[10] > 0.99f);
  3371. // ataque de 10 ms: começa em silêncio e chega ao nível cheio
  3372. lynx::SamplerSettings slow;
  3373. slow.attack = 0.01f;
  3374. const auto a = play (slow, 60, 2000, false);
  3375. CHECK (a[10] < 0.2f * (10.0f / 48000.0f) + 1e-6f && std::abs (a[1500] - 1500.0f / 48000.0f) < 1e-4f);
  3376. // release de 5 ms: some logo depois de soltar; sem release toca inteiro
  3377. lynx::SamplerSettings rel;
  3378. rel.release = 0.005f;
  3379. CHECK (play (rel, 60, 2000, true)[1999] == 0.0f);
  3380. CHECK (play (lynx::SamplerSettings {}, 60, 2000, true)[1999] > 0.0f);
  3381. // cut itself: a segunda nota corta a primeira (sobra uma voz)
  3382. lynx::SamplerSettings cut;
  3383. cut.cut = true;
  3384. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  3385. inst->prepare (48000.0);
  3386. lynx::ChannelDef cutChannel;
  3387. cutChannel.sampler = cut;
  3388. inst->configure (cutChannel, 120.0);
  3389. inst->noteOn (60, 1.0f);
  3390. std::vector<float> l (2000), r (2000);
  3391. inst->render (l.data(), r.data(), 1000, 1.0f, 1.0f);
  3392. inst->noteOn (60, 1.0f);
  3393. std::fill (l.begin(), l.end(), 0.0f);
  3394. inst->render (l.data(), r.data(), 2000, 1.0f, 1.0f);
  3395. CHECK (std::abs (l[1999] - 1999.0f / 48000.0f) < 1e-4f); // só a nota nova
  3396. }
  3397. TEST (playlist_split_and_track_mute)
  3398. {
  3399. lynx::Clip c { 0, 3, 960, 3840, 480 };
  3400. const auto rest = lynx::splitClip (c, 2000);
  3401. CHECK (c.start == 960 && c.length == 1040 && c.offset == 480);
  3402. CHECK (rest.start == 2000 && rest.length == 2800 && rest.offset == 480 + 1040 && rest.track == 3);
  3403. auto s = lynx::Song::makeDefault();
  3404. s.mode = lynx::PlayMode::song;
  3405. s.playlist = { { 0, 0, 0, 3840, 0 } };
  3406. lynx::EventBuffer ev;
  3407. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  3408. lynx::scheduleSong (s, 0.0, 48000, tps, ev);
  3409. CHECK (ev.size() > 0);
  3410. s.playlistTracks.resize (1);
  3411. s.playlistTracks[0].muted = true;
  3412. ev.clear();
  3413. lynx::scheduleSong (s, 0.0, 48000, tps, ev);
  3414. CHECK (ev.size() == 0);
  3415. }
  3416. TEST (note_pan_pitch_and_mute)
  3417. {
  3418. lynx::Pattern p;
  3419. lynx::Note a { 0, 240, 0, 60 };
  3420. a.pan = -1.0f;
  3421. a.finePitch = 50.0f;
  3422. lynx::Note b { 240, 240, 0, 62 };
  3423. b.muted = true;
  3424. p.notes = { a, b };
  3425. lynx::EventBuffer ev;
  3426. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  3427. lynx::schedulePatternLoop (p, p.effectiveLength (4), 0.0, 48000, tps, ev);
  3428. int ons = 0;
  3429. for (auto& e : ev)
  3430. if (e.type == lynx::NoteEvent::Type::on)
  3431. {
  3432. ++ons;
  3433. CHECK (e.key == 60 && e.pan == -1.0f && e.cents == 50.0f);
  3434. }
  3435. CHECK (ons == 1); // a mutada não toca
  3436. // pan da nota no sampler: tudo à esquerda
  3437. auto dc = std::make_shared<lynx::SampleData>();
  3438. dc->left.assign (4800, 0.5f);
  3439. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, dc);
  3440. inst->prepare (48000.0);
  3441. inst->setNextNoteExpression (-1.0f, 0.0f);
  3442. inst->noteOn (60, 1.0f);
  3443. std::vector<float> l (100), r (100);
  3444. inst->render (l.data(), r.data(), 100, 1.0f, 1.0f);
  3445. CHECK (l[50] > 0.6f && std::abs (r[50]) < 1e-6f);
  3446. }
  3447. TEST (tempo_automation_changes_speed_and_duration)
  3448. {
  3449. auto song = lynx::Song::makeDefault();
  3450. song.bpm = 120.0;
  3451. song.mode = lynx::PlayMode::song;
  3452. const auto bar = (std::int64_t) lynx::ppq * 4;
  3453. song.playlist = { { 0, 0, 0, bar, 0 }, { 0, 0, bar, bar, 0 } };
  3454. lynx::Automation tempo;
  3455. tempo.target = { lynx::AutomationTargetKind::tempo, 0 };
  3456. const auto v120 = lynx::valueFromTempo (120.0), v240 = lynx::valueFromTempo (240.0);
  3457. tempo.points = { { 0, v120 }, { bar - 1, v120 }, { bar, v240 } }; // degrau: 120 -> 240 no 2º compasso
  3458. song.automations.push_back (tempo);
  3459. lynx::Clip clip;
  3460. clip.kind = lynx::ClipKind::automation;
  3461. clip.automation = 0;
  3462. clip.track = 1;
  3463. clip.length = bar * 2;
  3464. song.playlist.push_back (clip);
  3465. CHECK (std::abs (song.tempoAt (100.0) - 120.0) < 0.01 && std::abs (song.tempoAt ((double) bar + 100.0) - 240.0) < 0.01);
  3466. // 1 compasso a 120 (2 s) + 1 a 240 (1 s)
  3467. CHECK (std::abs (song.secondsForTicks (bar * 2) - 3.0) < 0.01);
  3468. auto state = lynx::RackState::build (song, nullptr, 48000.0);
  3469. CHECK (state->tempoAutomation == 0);
  3470. lynx::RackRenderer r;
  3471. r.prepare (48000.0, 512);
  3472. std::vector<float> l (512), rr (512);
  3473. r.process (state.get(), true, 10.0, 512, l.data(), rr.data());
  3474. CHECK (std::abs (r.currentBpm() - 120.0) < 0.01);
  3475. r.process (state.get(), true, (double) bar + 10.0, 512, l.data(), rr.data());
  3476. CHECK (std::abs (r.currentBpm() - 240.0) < 0.01);
  3477. }
  3478. TEST (bounce_insert_song_and_apply)
  3479. {
  3480. auto s = lynx::Song::makeDefault();
  3481. s.setRoute (3, 7, true, 0.5f);
  3482. s.mixer[0].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::reverb));
  3483. s.mixer[2].solo = true;
  3484. const auto b = lynx::makeBounceSong (s, 3);
  3485. CHECK (b.mixer[3].solo && ! b.mixer[2].solo && b.mixer[3].toMaster && b.mixer[3].sends.empty());
  3486. CHECK (b.mixer[0].effects.empty() && b.mode == lynx::PlayMode::song);
  3487. const auto audible = b.soloAudible();
  3488. CHECK (audible[3] && ! audible[1] && ! audible[7]);
  3489. const auto channels = s.channels.size();
  3490. const auto inserts = s.mixer.size();
  3491. const auto created = lynx::applyBounce (s, 3, "C:/x.wav", 3840);
  3492. CHECK (created == (int) inserts && s.mixer.size() == inserts + 1 && s.mixer[3].muted);
  3493. CHECK (s.mixer[(std::size_t) created].sends.size() == 1 && s.mixer[(std::size_t) created].sends[0].target == 7);
  3494. CHECK (s.channels.size() == channels + 1 && s.channels.back().mixerTrack == created);
  3495. CHECK (s.playlist.back().kind == lynx::ClipKind::audio && s.playlist.back().length == 3840);
  3496. }
  3497. TEST (mixer_stereo_separation_phase_swap)
  3498. {
  3499. lynx::MixerTrack t;
  3500. std::vector<float> l { 1.0f }, r { 0.0f };
  3501. t.stereo = 1.0f; // mono
  3502. lynx::RackRenderer::applyStereoForTest (t, l.data(), r.data(), 1);
  3503. CHECK (std::abs (l[0] - 0.5f) < 1e-6f && std::abs (r[0] - 0.5f) < 1e-6f);
  3504. l = { 1.0f };
  3505. r = { 0.0f };
  3506. t.stereo = -1.0f; // lado dobrado: 1,5 L - 0,5 R
  3507. lynx::RackRenderer::applyStereoForTest (t, l.data(), r.data(), 1);
  3508. CHECK (std::abs (l[0] - 1.5f) < 1e-6f && std::abs (r[0] + 0.5f) < 1e-6f);
  3509. l = { 1.0f };
  3510. r = { 0.25f };
  3511. t.stereo = 0.0f;
  3512. t.swapChannels = true;
  3513. t.invertPhase = true;
  3514. lynx::RackRenderer::applyStereoForTest (t, l.data(), r.data(), 1);
  3515. CHECK (l[0] == -0.25f && r[0] == -1.0f);
  3516. }
  3517. TEST (effects_limiter_filter_distortion_chorus)
  3518. {
  3519. const double sr = 48000.0;
  3520. auto sine = [] (float hz, float amp, int n) {
  3521. std::vector<float> v ((std::size_t) n);
  3522. for (int i = 0; i < n; ++i)
  3523. v[(std::size_t) i] = amp * std::sin (2.0f * 3.14159265f * hz * (float) i / 48000.0f);
  3524. return v;
  3525. };
  3526. auto peak = [] (const std::vector<float>& v, int from) {
  3527. float p = 0.0f;
  3528. for (std::size_t i = (std::size_t) from; i < v.size(); ++i)
  3529. p = std::max (p, std::abs (v[i]));
  3530. return p;
  3531. };
  3532. // limiter: +12 dB num seno de 0,9 nunca passa do teto (-1 dB) e informa a latência
  3533. auto lim = lynx::makeEffect (lynx::EffectKind::limiter);
  3534. lim->prepare (sr);
  3535. auto slot = lynx::makeEffectSlot (lynx::EffectKind::limiter);
  3536. slot.params[0] = 11.0f / 12.0f; // -1 dB
  3537. slot.params[1] = 0.5f; // +12 dB
  3538. auto l = sine (100.0f, 0.9f, 48000), r = l;
  3539. lim->process (l.data(), r.data(), 48000, slot.params, 120.0);
  3540. CHECK (peak (l, 0) <= std::pow (10.0f, -1.0f / 20.0f) + 1e-4f);
  3541. CHECK (peak (l, 4800) > 0.8f);
  3542. CHECK (lim->latencySamples() == 72);
  3543. // filtro passa-baixas em 500 Hz derruba um seno de 8 kHz
  3544. auto lp = lynx::makeEffect (lynx::EffectKind::filter);
  3545. lp->prepare (sr);
  3546. auto fs = lynx::makeEffectSlot (lynx::EffectKind::filter);
  3547. fs.params[1] = std::log (500.0f / 20.0f) / std::log (1000.0f);
  3548. l = sine (8000.0f, 1.0f, 9600);
  3549. r = l;
  3550. lp->process (l.data(), r.data(), 9600, fs.params, 120.0);
  3551. CHECK (peak (l, 4800) < 0.05f);
  3552. // distorção e chorus: saída finita e com som
  3553. for (auto kind : { lynx::EffectKind::distortion, lynx::EffectKind::chorus })
  3554. {
  3555. auto fx = lynx::makeEffect (kind);
  3556. fx->prepare (sr);
  3557. auto ps = lynx::makeEffectSlot (kind);
  3558. l = sine (220.0f, 0.5f, 9600);
  3559. r = l;
  3560. fx->process (l.data(), r.data(), 9600, ps.params, 120.0);
  3561. bool finite = true;
  3562. for (auto v : l)
  3563. finite = finite && std::isfinite (v);
  3564. CHECK (finite && peak (l, 2400) > 0.1f && peak (l, 0) < 2.0f);
  3565. }
  3566. }
  3567. TEST (slide_notes_glide_without_retrigger)
  3568. {
  3569. // sampler com rampa: a velocidade de leitura dobra depois do slide de uma oitava
  3570. auto ramp = std::make_shared<lynx::SampleData>();
  3571. for (int i = 0; i < 96000; ++i)
  3572. ramp->left.push_back ((float) i / 96000.0f);
  3573. ramp->sampleRate = 48000.0;
  3574. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  3575. inst->prepare (48000.0);
  3576. inst->noteOn (60, 1.0f);
  3577. std::vector<float> l (2000), r (2000);
  3578. inst->render (l.data(), r.data(), 1000, 1.0f, 1.0f);
  3579. const auto stepBefore = l[999] - l[998];
  3580. inst->slideTo (72, 0.0f, 100.0f);
  3581. std::fill (l.begin(), l.end(), 0.0f);
  3582. inst->render (l.data(), r.data(), 1000, 1.0f, 1.0f);
  3583. const auto stepAfter = l[999] - l[998];
  3584. CHECK (std::abs (stepAfter / stepBefore - 2.0f) < 0.01f);
  3585. // o sequenciador manda "slide" (sem off) para a nota slide
  3586. lynx::Pattern p;
  3587. lynx::Note base { 0, 960, 0, 48 };
  3588. lynx::Note glide { 480, 240, 0, 55 };
  3589. glide.slide = true;
  3590. p.notes = { base, glide };
  3591. lynx::EventBuffer ev;
  3592. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  3593. lynx::schedulePatternLoop (p, p.effectiveLength (4), 0.0, 30000, tps, ev);
  3594. int ons = 0, offs = 0, slides = 0;
  3595. for (auto& e : ev)
  3596. {
  3597. ons += e.type == lynx::NoteEvent::Type::on;
  3598. offs += e.type == lynx::NoteEvent::Type::off;
  3599. if (e.type == lynx::NoteEvent::Type::slide)
  3600. {
  3601. ++slides;
  3602. CHECK (e.key == 55 && std::abs (e.slideSamples - 240.0f / (float) tps) < 1.0f);
  3603. }
  3604. }
  3605. CHECK (ons == 1 && offs == 1 && slides == 1);
  3606. }
  3607. TEST (synth_fm_phase_modulation)
  3608. {
  3609. auto render = [] (const lynx::SynthSettings& s) {
  3610. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  3611. inst->prepare (48000.0);
  3612. lynx::ChannelDef c;
  3613. c.synth = s;
  3614. inst->configure (c, 120.0);
  3615. inst->noteOn (69, 1.0f); // 440 Hz
  3616. std::vector<float> l (48000), r (48000);
  3617. inst->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  3618. return l;
  3619. };
  3620. // energia (Goertzel) na frequência f entre os quadros [from, to)
  3621. auto energy = [] (const std::vector<float>& x, double f, int from, int to) {
  3622. const auto w = 2.0 * 3.141592653589793 * f / 48000.0, k = 2.0 * std::cos (w);
  3623. double s1 = 0.0, s2 = 0.0;
  3624. for (int i = from; i < to; ++i)
  3625. {
  3626. const auto s0 = x[(std::size_t) i] + k * s1 - s2;
  3627. s2 = s1;
  3628. s1 = s0;
  3629. }
  3630. return s1 * s1 + s2 * s2 - k * s1 * s2;
  3631. };
  3632. lynx::SynthSettings plain;
  3633. plain.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  3634. plain.osc[2] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  3635. plain.cutoff = 20000.0f;
  3636. auto fm = plain;
  3637. fm.fm = 1.0f;
  3638. const auto a = render (plain), b = render (fm);
  3639. // sem FM: o osc 3 soma (mesma altura) e não há 2º harmônico; com FM aparecem as bandas laterais
  3640. CHECK (energy (a, 880.0, 4800, 24000) < 1e-3 * energy (a, 440.0, 4800, 24000));
  3641. CHECK (energy (b, 880.0, 4800, 24000) > 0.1 * energy (b, 440.0, 4800, 24000));
  3642. CHECK (energy (b, 1320.0, 4800, 24000) > 0.01 * energy (b, 440.0, 4800, 24000));
  3643. for (auto v : b)
  3644. CHECK (std::isfinite (v) && std::abs (v) < 1.0f);
  3645. // índice que decai até 0: o começo é brilhante, o fim volta a ser quase um seno
  3646. auto decaying = fm;
  3647. decaying.fmDecay = 0.1f;
  3648. decaying.fmSustain = 0.0f;
  3649. const auto c = render (decaying);
  3650. const auto early = energy (c, 880.0, 0, 2400) / energy (c, 440.0, 0, 2400);
  3651. const auto late = energy (c, 880.0, 36000, 48000) / energy (c, 440.0, 36000, 48000);
  3652. CHECK (early > 0.05 && late < 1e-3);
  3653. }
  3654. TEST (synth_three_oscillators_adsr_filter)
  3655. {
  3656. auto render = [] (const lynx::SynthSettings& s, int frames, int releaseAt) {
  3657. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  3658. inst->prepare (48000.0);
  3659. lynx::ChannelDef c;
  3660. c.synth = s;
  3661. inst->configure (c, 120.0);
  3662. inst->noteOn (69, 1.0f); // A4 = 440 Hz
  3663. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  3664. inst->render (l.data(), r.data(), releaseAt, 1.0f, 1.0f);
  3665. inst->noteOff (69);
  3666. inst->render (l.data() + releaseAt, r.data() + releaseAt, frames - releaseAt, 1.0f, 1.0f);
  3667. return l;
  3668. };
  3669. auto peakIn = [] (const std::vector<float>& v, int from, int to) {
  3670. float p = 0.0f;
  3671. for (int i = from; i < to; ++i)
  3672. p = std::max (p, std::abs (v[(std::size_t) i]));
  3673. return p;
  3674. };
  3675. // padrão: soa e some depois do release
  3676. const lynx::SynthSettings standard;
  3677. const auto a = render (standard, 48000, 24000);
  3678. CHECK (peakIn (a, 1000, 20000) > 0.05f && peakIn (a, 40000, 48000) < 1e-3f);
  3679. // seno puro com filtro aberto: a contagem de cruzamentos por zero dá ~440 Hz
  3680. lynx::SynthSettings sine;
  3681. sine.osc[0].wave = lynx::Waveform::sine;
  3682. sine.cutoff = 20000.0f;
  3683. const auto b = render (sine, 48000, 47000);
  3684. int crossings = 0;
  3685. for (int i = 4800; i < 4800 + 48000 / 2; ++i)
  3686. crossings += (b[(std::size_t) i - 1] < 0.0f) != (b[(std::size_t) i] < 0.0f);
  3687. CHECK (std::abs (crossings - 440) < 6); // meio segundo = 220 ciclos = 440 cruzamentos
  3688. float sinePeak = 0.0f;
  3689. for (int i = 4800; i < 9600; ++i)
  3690. sinePeak = std::max (sinePeak, std::abs (b[(std::size_t) i]));
  3691. CHECK (sinePeak > 0.2f && sinePeak < 0.35f); // 0,3 de nível, seno aproximado sem estouro
  3692. // segundo oscilador uma oitava acima soma energia; sustain 0 faz a nota decair sozinha
  3693. lynx::SynthSettings two = sine;
  3694. two.osc[1] = { lynx::Waveform::sine, 1, 0.0f, 1.0f };
  3695. two.sustain = 0.0f;
  3696. two.decay = 0.1f;
  3697. const auto c = render (two, 48000, 47000);
  3698. CHECK (peakIn (c, 100, 2000) > peakIn (b, 100, 2000) && peakIn (c, 30000, 40000) < 1e-3f);
  3699. }
  3700. TEST (set_target_value_round_trips)
  3701. {
  3702. auto s = lynx::Song::makeDefault();
  3703. s.mixer[2].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay));
  3704. const lynx::AutomationTarget targets[] = {
  3705. { lynx::AutomationTargetKind::channelVolume, 1 }, { lynx::AutomationTargetKind::channelPan, 2 },
  3706. { lynx::AutomationTargetKind::mixerVolume, 3 }, { lynx::AutomationTargetKind::mixerPan, 0 },
  3707. { lynx::AutomationTargetKind::effectParam, 2, 0, 1 }, { lynx::AutomationTargetKind::tempo, 0 },
  3708. };
  3709. for (const auto& t : targets)
  3710. {
  3711. CHECK (s.setTargetValue (t, 0.25f));
  3712. CHECK (std::abs (s.targetValue (t) - 0.25f) < 1e-5f);
  3713. }
  3714. CHECK (! s.setTargetValue ({ lynx::AutomationTargetKind::channelParam, 0, 0, 3 }, 0.5f)); // mora no plugin
  3715. }
  3716. TEST (cut_groups_stretch_and_envelope_import)
  3717. {
  3718. // hat aberto (cut by 1) é cortado quando o fechado (grupo 1) toca
  3719. lynx::Song s;
  3720. s.mixer = lynx::Song::defaultMixer (2);
  3721. for (int i = 0; i < 2; ++i)
  3722. {
  3723. lynx::ChannelDef c;
  3724. c.instrument = lynx::InstrumentKind::sampler;
  3725. c.samplePath = "dc";
  3726. c.volume = 1.0f;
  3727. c.mixerTrack = i + 1;
  3728. s.channels.push_back (c);
  3729. }
  3730. s.channels[0].cutBy = 1; // aberto
  3731. s.channels[1].cutGroup = 1; // fechado
  3732. auto& p = s.patterns.emplace_back();
  3733. p.notes = { { 0, 100, 0, 60 }, { 960, 100, 1, 60 } };
  3734. auto provider = [] (const std::string&) {
  3735. auto d = std::make_shared<lynx::SampleData>();
  3736. d->left.assign (96000, 0.5f);
  3737. return std::shared_ptr<const lynx::SampleData> (d);
  3738. };
  3739. auto state = lynx::RackState::build (s, nullptr, 48000.0, provider);
  3740. CHECK (state->hasCutGroups && state->cutTargets[1].size() == 1 && state->cutTargets[1][0] == 0);
  3741. lynx::RackRenderer r;
  3742. r.prepare (48000.0, 512);
  3743. std::vector<float> l (512), rr (512);
  3744. const auto tps = lynx::ticksPerSample (s.bpm, 48000.0);
  3745. float afterCut = 0.0f;
  3746. for (double tick = 0.0; tick < 960.0 * 3; tick += 512 * tps)
  3747. {
  3748. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  3749. if (tick > 960.0 * 2) // o fechado segue; o aberto já parou
  3750. afterCut = std::max (afterCut, std::abs (l[256]));
  3751. }
  3752. CHECK (std::abs (afterCut - 0.5f * 0.78f) < 0.01f); // só o fechado (velocity padrão 0,78)
  3753. // stretch por reamostragem: 1 s de sample esticado para 4 tempos a 120 BPM = 2 s
  3754. auto ramp = std::make_shared<lynx::SampleData>();
  3755. for (int i = 0; i < 48000; ++i)
  3756. ramp->left.push_back ((float) i / 48000.0f);
  3757. ramp->sampleRate = 48000.0;
  3758. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  3759. inst->prepare (48000.0);
  3760. lynx::ChannelDef c;
  3761. c.sampler.stretchBeats = 4.0f;
  3762. inst->configure (c, 120.0);
  3763. inst->noteOn (72, 1.0f); // a altura da nota não muda a velocidade
  3764. std::vector<float> a (48000), b (48000);
  3765. inst->render (a.data(), b.data(), 48000, 1.0f, 1.0f);
  3766. CHECK (std::abs (a[47999] - 0.5f) < 0.01f); // depois de 1 s leu metade
  3767. // tempo do envelope do FL: 32950 = 2 s; < 101 = 0
  3768. CHECK (std::abs (flp::Channel::envelopeTime (32950) - 2.0) < 0.01 && flp::Channel::envelopeTime (50) == 0.0);
  3769. }
  3770. TEST (time_stretch_keeps_pitch)
  3771. {
  3772. lynx::SampleData sine;
  3773. sine.sampleRate = 48000.0;
  3774. for (int i = 0; i < 48000; ++i)
  3775. sine.left.push_back (0.5f * std::sin (2.0f * 3.14159265f * 440.0f * (float) i / 48000.0f));
  3776. auto crossingsPerSecond = [] (const lynx::SampleData& d) {
  3777. int c = 0;
  3778. const auto n = (int) d.frames();
  3779. for (int i = 4800; i < n - 4800; ++i)
  3780. c += (d.left[(std::size_t) i - 1] < 0.0f) != (d.left[(std::size_t) i] < 0.0f);
  3781. return (double) c / ((double) (n - 9600) / d.sampleRate);
  3782. };
  3783. for (double ratio : { 2.0, 0.5, 1.37 })
  3784. {
  3785. const auto out = lynx::timeStretch (sine, ratio);
  3786. CHECK (std::abs ((double) out->frames() - 48000.0 * ratio) < 2.0);
  3787. CHECK (std::abs (crossingsPerSecond (*out) - 880.0) < 15.0); // 440 Hz continua 440 Hz
  3788. float peak = 0.0f;
  3789. for (std::size_t i = 4800; i + 4800 < out->frames(); ++i)
  3790. peak = std::max (peak, std::abs (out->left[i]));
  3791. CHECK (peak > 0.4f && peak < 0.6f); // sem buracos nem estouro na sobreposição
  3792. }
  3793. }
  3794. TEST (sampler_region_start_and_end)
  3795. {
  3796. auto ramp = std::make_shared<lynx::SampleData>();
  3797. for (int i = 0; i < 10000; ++i)
  3798. ramp->left.push_back ((float) i / 10000.0f);
  3799. ramp->sampleRate = 48000.0;
  3800. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  3801. inst->prepare (48000.0);
  3802. lynx::ChannelDef c;
  3803. c.sampler.regionStart = 0.25f;
  3804. c.sampler.regionEnd = 0.5f;
  3805. inst->configure (c, 120.0);
  3806. inst->noteOn (60, 1.0f);
  3807. std::vector<float> l (6000), r (6000);
  3808. inst->render (l.data(), r.data(), 6000, 1.0f, 1.0f);
  3809. CHECK (std::abs (l[0] - 0.25f) < 0.001f); // começa no início do trecho
  3810. CHECK (l[2400] > 0.48f && l[2600] == 0.0f); // e para no fim dele
  3811. }
  3812. TEST (arpeggiator_plays_held_chord_in_steps)
  3813. {
  3814. auto song = lynx::Song::makeDefault();
  3815. song.bpm = 120.0;
  3816. song.patterns[0].notes.clear();
  3817. for (int key : { 60, 64, 67 })
  3818. song.patterns[0].notes.push_back ({ 0, lynx::ppq * 4, 4, key, 0.8f }); // acorde segurado 1 compasso
  3819. song.channels[4].arp.direction = 1; // sobe
  3820. song.channels[4].arp.stepBeats = 0.25f;
  3821. auto state = lynx::RackState::build (song, nullptr, 48000.0);
  3822. CHECK (state->arpeggiators[4] != nullptr && state->arpeggiators[0] == nullptr);
  3823. // o arpejador gera as notas; contamos o que ele entrega ao instrumento
  3824. auto& arp = *state->arpeggiators[4];
  3825. const auto tps = lynx::ticksPerSample (song.bpm, 48000.0);
  3826. std::vector<int> keys;
  3827. lynx::EventBuffer ev;
  3828. for (double tick = 0.0; tick < lynx::ppq * 2.0; tick += 512 * tps)
  3829. {
  3830. ev.clear();
  3831. lynx::schedulePatternLoop (song.patterns[0], song.patterns[0].effectiveLength (4), tick, 512, tps, ev);
  3832. int in = 0, out = 0;
  3833. for (auto& e : ev)
  3834. if (e.channel == 4)
  3835. arp.input[(std::size_t) in++] = e;
  3836. arp.process (4, arp.input.data(), in, tick, tps, 512, song.channels[4].arp, arp.output.data(), out);
  3837. for (int i = 0; i < out; ++i)
  3838. if (arp.output[(std::size_t) i].type == lynx::NoteEvent::Type::on)
  3839. keys.push_back (arp.output[(std::size_t) i].key);
  3840. }
  3841. // 2 tempos = 8 passos de semicolcheia: 60 64 67 60 64 67 60 64
  3842. CHECK (keys.size() >= 8); // o último bloco passa um pouco dos 2 tempos
  3843. const int expected[] = { 60, 64, 67, 60, 64, 67, 60, 64 };
  3844. for (std::size_t i = 0; i < keys.size() && i < 8; ++i)
  3845. CHECK (keys[i] == expected[i]);
  3846. // renderizando de verdade também soa
  3847. lynx::RackRenderer r;
  3848. r.prepare (48000.0, 512);
  3849. std::vector<float> l (512), rr (512);
  3850. float peak = 0.0f;
  3851. for (double tick = 0.0; tick < lynx::ppq; tick += 512 * tps)
  3852. {
  3853. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  3854. for (auto v : l)
  3855. peak = std::max (peak, std::abs (v));
  3856. }
  3857. CHECK (peak > 0.01f);
  3858. }
  3859. TEST (audio_clip_fades_and_gain)
  3860. {
  3861. lynx::Song s;
  3862. s.bpm = 120.0;
  3863. s.mode = lynx::PlayMode::song;
  3864. s.mixer = lynx::Song::defaultMixer (1);
  3865. lynx::ChannelDef c;
  3866. c.instrument = lynx::InstrumentKind::audioClip;
  3867. c.samplePath = "dc";
  3868. c.volume = 1.0f;
  3869. c.mixerTrack = 1;
  3870. s.channels.push_back (c);
  3871. s.patterns.emplace_back();
  3872. lynx::Clip clip;
  3873. clip.kind = lynx::ClipKind::audio;
  3874. clip.channel = 0;
  3875. clip.length = lynx::ppq * 4; // 2 s a 120 BPM
  3876. clip.fadeIn = lynx::ppq; // 0,5 s
  3877. clip.fadeOut = lynx::ppq;
  3878. clip.gain = 0.5f;
  3879. s.playlist.push_back (clip);
  3880. auto provider = [] (const std::string&) {
  3881. auto d = std::make_shared<lynx::SampleData>();
  3882. d->left.assign (48000 * 4, 1.0f);
  3883. return std::shared_ptr<const lynx::SampleData> (d);
  3884. };
  3885. auto state = lynx::RackState::build (s, nullptr, 48000.0, provider);
  3886. lynx::RackRenderer r;
  3887. r.prepare (48000.0, 512);
  3888. std::vector<float> all;
  3889. std::vector<float> l (512), rr (512);
  3890. const auto tps = lynx::ticksPerSample (s.bpm, 48000.0);
  3891. for (double tick = 0.0; tick < lynx::ppq * 4.0; tick += 512 * tps)
  3892. {
  3893. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  3894. all.insert (all.end(), l.begin(), l.end());
  3895. }
  3896. CHECK (all[100] < 0.01f); // começo do fade-in
  3897. CHECK (std::abs (all[12000] - 0.25f) < 0.02f); // meio do fade-in: metade de 0,5
  3898. CHECK (std::abs (all[48000] - 0.5f) < 0.01f); // corpo: o ganho do clip
  3899. CHECK (std::abs (all[96000 - 12000] - 0.25f) < 0.02f); // meio do fade-out
  3900. }
  3901. TEST (slicer_detects_hits_and_plays_slices_by_key)
  3902. {
  3903. // 4 batidas (ruído com decaimento) a cada 0,25 s
  3904. lynx::SampleData loop;
  3905. loop.sampleRate = 48000.0;
  3906. loop.left.assign (48000, 0.0f);
  3907. lynx::Noise noise;
  3908. for (int hit = 0; hit < 4; ++hit)
  3909. for (int i = 0; i < 6000; ++i)
  3910. loop.left[(std::size_t) (hit * 12000 + i)] = noise.next() * 0.8f * std::exp (-(float) i / 1500.0f);
  3911. const auto slices = lynx::detectSlices (loop, 0.5f);
  3912. CHECK (slices.size() == 4);
  3913. for (std::size_t i = 0; i < slices.size(); ++i)
  3914. CHECK (std::abs (slices[i] - 0.25f * (float) i) < 0.01f);
  3915. // a tecla 61 toca a segunda fatia, que começa em 0,25 e acaba antes de 0,5
  3916. auto ramp = std::make_shared<lynx::SampleData>();
  3917. for (int i = 0; i < 48000; ++i)
  3918. ramp->left.push_back ((float) i / 48000.0f);
  3919. ramp->sampleRate = 48000.0;
  3920. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  3921. inst->prepare (48000.0);
  3922. lynx::ChannelDef c;
  3923. c.sampler.slices = slices;
  3924. inst->configure (c, 120.0);
  3925. inst->noteOn (61, 1.0f);
  3926. std::vector<float> l (20000), r (20000);
  3927. inst->render (l.data(), r.data(), 20000, 1.0f, 1.0f);
  3928. CHECK (std::abs (l[0] - 0.25f) < 0.01f && l[11000] > 0.45f && l[13000] == 0.0f);
  3929. }
  3930. TEST (project_templates_render_sound)
  3931. {
  3932. const auto names = lynx::templateNames();
  3933. CHECK (names.size() == 4);
  3934. for (int t = 1; t < (int) names.size(); ++t)
  3935. {
  3936. auto song = lynx::makeTemplate (t);
  3937. auto state = lynx::RackState::build (song, nullptr, 48000.0);
  3938. lynx::RackRenderer r;
  3939. r.prepare (48000.0, 512);
  3940. std::vector<float> l (512), rr (512);
  3941. const auto tps = lynx::ticksPerSample (song.bpm, 48000.0);
  3942. float peak = 0.0f;
  3943. for (double tick = 0.0; tick < lynx::ppq * 4.0; tick += 512 * tps)
  3944. {
  3945. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  3946. for (auto v : l)
  3947. peak = std::max (peak, std::abs (v));
  3948. }
  3949. CHECK (peak > 0.05f && peak < 4.0f);
  3950. }
  3951. CHECK (lynx::makeTemplate (0).patterns[0].notes.empty());
  3952. }
  3953. int main (int argc, char** argv)
  3954. {
  3955. if (argc > 1)
  3956. realFlpDir = argv[1];
  3957. for (auto& [name, fn] : registry())
  3958. {
  3959. std::printf ("%s\n", name);
  3960. fn();
  3961. }
  3962. std::printf ("\n%d verificações, %d falhas\n", checks, failures);
  3963. return failures == 0 ? 0 : 1;
  3964. }
  3965. TEST (synth_cutoff_keytrack)
  3966. {
  3967. // o corte acompanha a nota a partir da tecla 48 (130,81 Hz), como o "Key to filter frequency" do Harmor
  3968. auto rms = [] (float keyTrack, int key) {
  3969. lynx::SynthSettings s;
  3970. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  3971. s.cutoff = 130.81f;
  3972. s.keyTrack = keyTrack;
  3973. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  3974. inst->prepare (48000.0);
  3975. lynx::ChannelDef c;
  3976. c.synth = s;
  3977. inst->configure (c, 120.0);
  3978. inst->noteOn (key, 1.0f);
  3979. std::vector<float> l (24000), r (24000);
  3980. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  3981. double e = 0.0;
  3982. for (int i = 4800; i < 24000; ++i)
  3983. e += (double) l[(std::size_t) i] * l[(std::size_t) i];
  3984. return std::sqrt (e / 19200.0);
  3985. };
  3986. const auto fixed = rms (0.0f, 72), tracked = rms (1.0f, 72);
  3987. CHECK (tracked > 4.0 * fixed); // 2 oitavas acima: sem keytrack o passa-baixas corta
  3988. CHECK (std::abs (rms (1.0f, 48) - rms (0.0f, 48)) < 0.05 * rms (0.0f, 48)); // na tecla de referência não muda
  3989. }
  3990. namespace
  3991. {
  3992. std::vector<float> renderSynthNote (const lynx::SynthSettings& s, int key, int frames)
  3993. {
  3994. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  3995. inst->prepare (48000.0);
  3996. lynx::ChannelDef c;
  3997. c.synth = s;
  3998. inst->configure (c, 120.0);
  3999. inst->noteOn (key, 1.0f);
  4000. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  4001. inst->render (l.data(), r.data(), frames, 1.0f, 1.0f);
  4002. return l;
  4003. }
  4004. double goertzel (const std::vector<float>& x, double f, int from, int to)
  4005. {
  4006. const auto w = 2.0 * 3.141592653589793 * f / 48000.0, k = 2.0 * std::cos (w);
  4007. double s1 = 0.0, s2 = 0.0;
  4008. for (int i = from; i < to; ++i)
  4009. {
  4010. const auto s0 = x[(std::size_t) i] + k * s1 - s2;
  4011. s2 = s1;
  4012. s1 = s0;
  4013. }
  4014. return s1 * s1 + s2 * s2 - k * s1 * s2;
  4015. }
  4016. } // namespace
  4017. TEST (synth_pitch_sweep_ring_and_bands)
  4018. {
  4019. lynx::SynthSettings sine;
  4020. sine.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  4021. sine.cutoff = 20000.0f;
  4022. // varredura: começa em f·(1 + sweep) e volta a f (constante de tempo de s = 10 ms; s⁴ cai 4× mais rápido)
  4023. auto sweep = sine;
  4024. sweep.sweep = 1.0f;
  4025. sweep.sweepTime = 0.01f;
  4026. const auto a = renderSynthNote (sweep, 69, 24000);
  4027. auto crossings = [] (const std::vector<float>& x, int to) {
  4028. int n = 0;
  4029. for (int i = 1; i < to; ++i)
  4030. n += (x[(std::size_t) i - 1] < 0.0f) != (x[(std::size_t) i] < 0.0f);
  4031. return n;
  4032. };
  4033. CHECK (crossings (a, 480) > 1.3 * crossings (renderSynthNote (sine, 69, 480), 480)); // 10 ms: bem mais agudo
  4034. CHECK (goertzel (a, 440.0, 12000, 24000) > 100.0 * goertzel (a, 880.0, 12000, 24000));
  4035. // anel com |a| = 1: portadora 440 × modulador 110 -> só 330 e 550, sem 440
  4036. auto ring = sine;
  4037. ring.am = ring.ring = true;
  4038. ring.osc[2] = { lynx::Waveform::sine, -2, 0.0f, 1.0f };
  4039. const auto b = renderSynthNote (ring, 69, 24000);
  4040. CHECK (goertzel (b, 330.0, 4800, 24000) > 100.0 * goertzel (b, 440.0, 4800, 24000));
  4041. CHECK (goertzel (b, 550.0, 4800, 24000) > 100.0 * goertzel (b, 440.0, 4800, 24000));
  4042. // 3 bandas: calar o agudo derruba uma nota de 4 kHz e quase não mexe numa de 80 Hz
  4043. auto bands = sine;
  4044. bands.bandGain = { 1.0f, 1.0f, 0.0f };
  4045. auto rms = [] (const std::vector<float>& x) {
  4046. double e = 0.0;
  4047. for (std::size_t i = 4800; i < x.size(); ++i)
  4048. e += (double) x[i] * x[i];
  4049. return std::sqrt (e / (double) (x.size() - 4800));
  4050. };
  4051. CHECK (rms (renderSynthNote (bands, 107, 24000)) < 0.3 * rms (renderSynthNote (sine, 107, 24000)));
  4052. CHECK (rms (renderSynthNote (bands, 28, 24000)) > 0.85 * rms (renderSynthNote (sine, 28, 24000)));
  4053. }
  4054. TEST (love_philter_map_evaluation)
  4055. {
  4056. lynx::LovePhilterMap line { { { 0.0, 0.0 }, { 1.0, 1.0 } } };
  4057. CHECK (std::abs (lynx::lovePhilterMapAt (line, 0.5) - 0.5) < 1e-9);
  4058. CHECK (std::abs (lynx::lovePhilterMapAt (line, 1.0) - 1.0) < 1e-9);
  4059. // degraus (Δx = 0): 1 até 0,4375, rampa até 0 em 0,5, depois 0
  4060. lynx::LovePhilterMap steps { { { 0.0, 1.0 }, { 0.4375, 1.0 }, { 0.0625, 0.0 }, { 0.5, 0.0 } } };
  4061. CHECK (lynx::lovePhilterMapAt (steps, 0.27) == 1.0);
  4062. CHECK (lynx::lovePhilterMapAt (steps, 0.75) == 0.0);
  4063. CHECK (std::abs (lynx::lovePhilterMapAt (steps, 0.46875) - 0.5) < 1e-9);
  4064. CHECK (lynx::lovePhilterMapAt ({}, 0.3) == 1.0);
  4065. }
  4066. TEST (lofi_holds_and_quantizes)
  4067. {
  4068. auto fx = lynx::makeEffect (lynx::EffectKind::lofi);
  4069. fx->prepare (48000.0);
  4070. auto slot = lynx::makeEffectSlot (lynx::EffectKind::lofi);
  4071. slot.params[0] = 0.5f; // 128·0,125 + 1 = 17 amostras
  4072. slot.params[1] = 1.0f; // 65536/2049 ≈ 32 níveis
  4073. std::vector<float> l (170), r (170);
  4074. for (std::size_t i = 0; i < l.size(); ++i)
  4075. l[i] = r[i] = 0.9f * (float) std::sin (0.05 * (double) i);
  4076. const auto original = l;
  4077. fx->process (l.data(), r.data(), 170, slot.params, 120.0);
  4078. for (int i = 0; i < 17; ++i)
  4079. CHECK (l[(std::size_t) i] == l[0]);
  4080. CHECK (l[17] != l[16]);
  4081. const auto step = 2.0f * 2049.0f / 65536.0f;
  4082. for (auto v : l)
  4083. CHECK (std::abs (v / step - std::round (v / step)) < 1e-3f);
  4084. CHECK (std::abs (l[0] - original[0]) <= step);
  4085. CHECK (lynx::formatEffectParam (lynx::EffectKind::lofi, 1, 0.0f, 120.0) == "16.0 bits");
  4086. }
  4087. namespace
  4088. {
  4089. lynx::EffectParams effectorParams (int type, float x, float y)
  4090. {
  4091. auto slot = lynx::makeEffectSlot (lynx::EffectKind::effector);
  4092. slot.params[0] = (float) type / 11.0f;
  4093. slot.params[3] = x;
  4094. slot.params[4] = y;
  4095. return slot.params;
  4096. }
  4097. } // namespace
  4098. TEST (effector_algorithms)
  4099. {
  4100. CHECK (lynx::effector::typeOf (8.0f / 11.0f) == 8);
  4101. CHECK (std::string (lynx::effector::typeName (11)) == "Ring");
  4102. CHECK (std::abs (lynx::effector::rateBeats (0.5f, 0.0f) - 0.75) < 1e-9); // trunc(8·0,5 + 0,5) = 4 -> 3/4
  4103. CHECK (std::abs (lynx::effector::rateBeats (1.0f, 0.5f) - 2.0) < 1e-9); // 8 × (1 − 0,5)²
  4104. auto run = [] (const lynx::EffectParams& p, std::vector<float> in, double bpm = 120.0) {
  4105. auto fx = lynx::makeEffect (lynx::EffectKind::effector);
  4106. fx->prepare (48000.0);
  4107. fx->setSongPosition (0.0);
  4108. auto r = in;
  4109. fx->process (in.data(), r.data(), (int) in.size(), p, bpm);
  4110. return in;
  4111. };
  4112. // Distort com Y = 1 (tudo vai para a cascata): 0,5 sai 0,5 (compensação G = 0,5/F(0,5))
  4113. {
  4114. auto p = effectorParams (0, 0.5f, 1.0f);
  4115. const auto out = run (p, std::vector<float> (4800, 0.5f));
  4116. CHECK (std::abs (out.back() - 0.5f) < 1e-3f);
  4117. const auto small = run (p, std::vector<float> (4800, 0.05f));
  4118. CHECK (small.back() > 0.45f && small.back() < 0.5f); // satura perto de ±0,5
  4119. }
  4120. // Ring: DC 1 vira o seno do portador, 2^(8,7·0 + 5) = 32 Hz -> 32 ciclos por segundo
  4121. {
  4122. auto p = effectorParams (11, 0.0f, 0.0f);
  4123. const auto out = run (p, std::vector<float> (48000, 1.0f));
  4124. int crossings = 0;
  4125. for (std::size_t i = 4800; i < out.size(); ++i)
  4126. crossings += (out[i - 1] < 0.0f) != (out[i] < 0.0f);
  4127. CHECK (crossings >= 56 && crossings <= 60); // 0,9 s × 32 Hz × 2
  4128. }
  4129. // Trancer, Y = 0: no começo do período o ganho cai a zero; X = 1 volta só no fim do período
  4130. {
  4131. auto p = effectorParams (8, 1.0f, 0.0f);
  4132. p[5] = 1.0f; // 8/1 = 8 tempos = 4 s a 120 BPM
  4133. const auto out = run (p, std::vector<float> (48000, 1.0f));
  4134. CHECK (out[100] > 0.3f); // ainda subindo o "e" (1 % do período = 40 ms)
  4135. CHECK (out[24000] < 0.05f); // 0,5 s: vale
  4136. }
  4137. // Reverb com Wet = 0: o seco passa intacto
  4138. {
  4139. auto p = effectorParams (6, 0.5f, 0.5f);
  4140. p[2] = 0.0f;
  4141. std::vector<float> in (4800);
  4142. for (std::size_t i = 0; i < in.size(); ++i)
  4143. in[i] = (float) std::sin (0.01 * (double) i);
  4144. const auto out = run (p, in);
  4145. for (std::size_t i = 0; i < in.size(); ++i)
  4146. CHECK (std::abs (out[i] - in[i]) < 1e-6f);
  4147. }
  4148. // Delay: o eco chega depois do período do Mod Rate (1/4 de tempo a 120 BPM = 125 ms), com nível X²
  4149. {
  4150. auto p = effectorParams (5, 0.7f, 0.5f);
  4151. p[5] = 1.0f / 8.0f; // índice 1 = 1/4
  4152. std::vector<float> in (12000, 0.0f);
  4153. in[0] = 1.0f;
  4154. const auto out = run (p, in);
  4155. CHECK (std::abs (out[6000] - 0.49f) < 0.02f);
  4156. CHECK (std::abs (out[3000]) < 1e-6f);
  4157. }
  4158. // Stutter: repete o começo gravado a cada período
  4159. {
  4160. auto p = effectorParams (9, 0.0f, 0.0f);
  4161. p[5] = 0.0f; // 1/8 de tempo = 62,5 ms = 3000 amostras
  4162. std::vector<float> in (9000);
  4163. for (std::size_t i = 0; i < in.size(); ++i)
  4164. in[i] = (float) i / 9000.0f;
  4165. const auto out = run (p, in);
  4166. CHECK (std::abs (out[3000 + 500] - in[500]) < 0.01f); // depois do crossfade, é o começo de novo
  4167. CHECK (std::abs (out[1000] - in[1000]) < 1e-6f);
  4168. }
  4169. }