4
0

tests.cpp 127 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263
  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/FlpImport.h"
  15. #include "core/FlEffects.h"
  16. #include "core/FlWrapper.h"
  17. #include "core/LiveEventQueue.h"
  18. #include "core/RackRenderer.h"
  19. #include "core/Scheduler.h"
  20. #include "core/SnapshotExchange.h"
  21. #include "core/SoftClip.h"
  22. #include "core/Slicer.h"
  23. #include "core/Templates.h"
  24. #include "core/TimeStretch.h"
  25. #include "core/WorkerPool.h"
  26. #include "core/Song.h"
  27. #include "core/NoteEdit.h"
  28. #include "core/Recorder.h"
  29. #include "flp/Flp.h"
  30. namespace
  31. {
  32. int failures = 0;
  33. int checks = 0;
  34. std::vector<std::pair<const char*, std::function<void()>>>& registry()
  35. {
  36. static std::vector<std::pair<const char*, std::function<void()>>> r;
  37. return r;
  38. }
  39. struct Register
  40. {
  41. Register (const char* name, std::function<void()> fn) { registry().emplace_back (name, std::move (fn)); }
  42. };
  43. #define TEST(name) \
  44. static void name(); \
  45. static Register reg_##name (#name, name); \
  46. static void name()
  47. #define CHECK(cond) \
  48. do \
  49. { \
  50. ++checks; \
  51. if (! (cond)) \
  52. { \
  53. ++failures; \
  54. std::printf (" FALHOU %s:%d: %s\n", __FILE__, __LINE__, #cond); \
  55. } \
  56. } while (false)
  57. std::string realFlpDir;
  58. // --- utilitários para montar .flp sintéticos -------------------------------
  59. struct FlpBuilder
  60. {
  61. std::vector<std::uint8_t> bytes;
  62. FlpBuilder (std::uint16_t ppq = 96)
  63. {
  64. put ("FLhd");
  65. u32 (6);
  66. u16 (0);
  67. u16 (1);
  68. u16 (ppq);
  69. put ("FLdt");
  70. u32 (0); // tamanho não é usado pelo leitor
  71. }
  72. void put (const char* s) { bytes.insert (bytes.end(), s, s + std::strlen (s)); }
  73. void u8 (std::uint8_t v) { bytes.push_back (v); }
  74. void u16 (std::uint16_t v) { u8 ((std::uint8_t) v); u8 ((std::uint8_t) (v >> 8)); }
  75. void u32 (std::uint32_t v) { u16 ((std::uint16_t) v); u16 ((std::uint16_t) (v >> 16)); }
  76. void varint (std::size_t n)
  77. {
  78. do
  79. {
  80. auto b = (std::uint8_t) (n & 0x7F);
  81. n >>= 7;
  82. u8 (n ? (std::uint8_t) (b | 0x80) : b);
  83. } while (n);
  84. }
  85. void data (std::uint8_t id, const std::vector<std::uint8_t>& payload)
  86. {
  87. u8 (id);
  88. varint (payload.size());
  89. bytes.insert (bytes.end(), payload.begin(), payload.end());
  90. }
  91. void ascii (std::uint8_t id, const std::string& s)
  92. {
  93. std::vector<std::uint8_t> p (s.begin(), s.end());
  94. p.push_back (0);
  95. data (id, p);
  96. }
  97. void utf16 (std::uint8_t id, const std::u16string& s)
  98. {
  99. std::vector<std::uint8_t> p;
  100. for (auto c : s)
  101. {
  102. p.push_back ((std::uint8_t) c);
  103. p.push_back ((std::uint8_t) (c >> 8));
  104. }
  105. p.push_back (0);
  106. p.push_back (0);
  107. data (id, p);
  108. }
  109. };
  110. std::vector<std::uint8_t> noteRecord (std::uint32_t pos, std::uint16_t channel, std::uint32_t len, std::uint16_t key,
  111. std::uint8_t velocity)
  112. {
  113. std::vector<std::uint8_t> r (24, 0);
  114. std::memcpy (&r[0], &pos, 4);
  115. std::memcpy (&r[6], &channel, 2);
  116. std::memcpy (&r[8], &len, 4);
  117. std::memcpy (&r[12], &key, 2);
  118. r[16] = 120;
  119. r[20] = 64;
  120. r[21] = velocity;
  121. return r;
  122. }
  123. } // namespace
  124. // ---------------------------------------------------------------------------
  125. // FLP
  126. TEST (flp_rejects_garbage)
  127. {
  128. std::vector<std::uint8_t> junk (64, 0x41);
  129. bool threw = false;
  130. try { flp::EventReader r (junk); } catch (const flp::Error&) { threw = true; }
  131. CHECK (threw);
  132. }
  133. TEST (flp_reads_size_classes_varint_and_extended_ids)
  134. {
  135. FlpBuilder b;
  136. b.u8 (0x15); b.u8 (2); // u8
  137. b.u8 (0x40); b.u16 (513); // u16
  138. b.u8 (0x9C); b.u32 (128500); // u32
  139. b.data (0xD5, std::vector<std::uint8_t> (300, 7)); // varint de 2 bytes
  140. b.u8 (0xAC); b.u32 (0xC0000100); b.varint (3); b.u8 (1); b.u8 (2); b.u8 (3); // ID estendido
  141. flp::EventReader r (b.bytes);
  142. flp::Event e;
  143. CHECK (r.header().ppq == 96);
  144. CHECK (r.next (e) && e.id == 0x15 && e.value == 2);
  145. CHECK (r.next (e) && e.id == 0x40 && e.value == 513);
  146. CHECK (r.next (e) && e.id == 0x9C && e.value == 128500);
  147. CHECK (r.next (e) && e.id == 0xD5 && e.data.size() == 300 && e.data[299] == 7);
  148. CHECK (r.next (e) && e.id == 0xC0000100 && e.isData() && e.data.size() == 3 && e.data[2] == 3);
  149. CHECK (! r.next (e));
  150. }
  151. TEST (flp_truncated_file_throws)
  152. {
  153. FlpBuilder b;
  154. b.u8 (0x9C); b.u8 (1); // u32 com só 1 byte
  155. flp::EventReader r (b.bytes);
  156. flp::Event e;
  157. bool threw = false;
  158. try { r.next (e); } catch (const flp::Error&) { threw = true; }
  159. CHECK (threw);
  160. }
  161. TEST (flp_version_numbers)
  162. {
  163. CHECK (flp::parseVersionNumber ("25.2.5.5319") == 25002005u);
  164. CHECK (flp::parseVersionNumber ("20.99.3000.3031") == 20102000u);
  165. CHECK (flp::parseVersionNumber ("11.0.3") == 11000003u);
  166. }
  167. TEST (flp_playlist_record_size_by_version)
  168. {
  169. CHECK (flp::playlistRecordSize (12009003, 64) == 32);
  170. CHECK (flp::playlistRecordSize (21000000, 120) == 60);
  171. CHECK (flp::playlistRecordSize (25002005, 160) == 80);
  172. CHECK (flp::playlistRecordSize (25002005, 60) == 60); // tamanho não bate com a versão → tenta os outros
  173. CHECK (flp::playlistRecordSize (25002005, 7) == 0);
  174. }
  175. TEST (flp_parses_project_model)
  176. {
  177. FlpBuilder b (96);
  178. b.ascii (0xC7, "25.2.5.5319");
  179. b.u8 (0x9C); b.u32 (174500);
  180. b.utf16 (0xC2, u"Título");
  181. b.u8 (0x41); b.u16 (3);
  182. b.u8 (0x96); b.u32 (0x00A14547); // BGR no arquivo
  183. auto notes = noteRecord (96, 1, 48, 64, 100);
  184. auto n2 = noteRecord (0, 0, 0, 60, 128);
  185. notes.insert (notes.end(), n2.begin(), n2.end());
  186. b.data (0xE0, notes);
  187. b.u8 (0x40); b.u16 (0);
  188. b.u8 (0x15); b.u8 (0);
  189. b.utf16 (0xCB, u"Kick");
  190. {
  191. std::vector<std::uint8_t> levels (24, 0);
  192. const std::int32_t lv[] = { 3200, 12800, -150 };
  193. std::memcpy (levels.data(), lv, sizeof (lv));
  194. b.data (0xDB, levels);
  195. }
  196. b.u8 (0x68); b.u16 (5);
  197. b.u8 (0x40); b.u16 (1);
  198. b.u8 (0x15); b.u8 (2);
  199. b.utf16 (0xC9, u"FLEX");
  200. b.utf16 (0xCB, u"Lead");
  201. b.u8 (0x63); b.u16 (0);
  202. std::vector<std::uint8_t> item (80, 0);
  203. std::uint32_t pos = 384, len = 768;
  204. std::uint16_t base = 20480, idx = 20480 + 3, rv = 499 - 2;
  205. std::memcpy (&item[0], &pos, 4);
  206. std::memcpy (&item[4], &base, 2);
  207. std::memcpy (&item[6], &idx, 2);
  208. std::memcpy (&item[8], &len, 4);
  209. std::memcpy (&item[12], &rv, 2);
  210. b.data (0xE9, item);
  211. b.utf16 (0xCC, u"Drums");
  212. b.data (0xEC, std::vector<std::uint8_t> (12, 0));
  213. b.data (0xEC, std::vector<std::uint8_t> (12, 0));
  214. const auto p = flp::parseProject (b.bytes);
  215. CHECK (p.version == "25.2.5.5319");
  216. CHECK (std::abs (p.tempo - 174.5) < 1e-9);
  217. CHECK (p.title == "Título");
  218. CHECK (p.channels.size() == 2);
  219. CHECK (p.channels[0].name == "Kick" && p.channels[0].mixerTrack == 5);
  220. CHECK (p.channels[0].hasLevels && p.channels[0].pan == 3200 && p.channels[0].volume == 12800 && p.channels[0].pitchCents == -150);
  221. CHECK (p.channels[1].type == flp::ChannelType::instrument && p.channels[1].pluginName == "FLEX");
  222. CHECK (p.patterns.size() == 1 && p.patterns[0].index == 3);
  223. CHECK (p.patterns[0].colour && *p.patterns[0].colour == 0x4745A1);
  224. CHECK (p.patterns[0].notes.size() == 2 && p.patterns[0].notes[0].position == 0); // ordenadas
  225. CHECK (p.patterns[0].notes[1].key == 64 && p.patterns[0].notes[1].length == 48);
  226. CHECK (p.arrangements.size() == 1 && p.arrangements[0].items.size() == 1);
  227. const auto& it = p.arrangements[0].items[0];
  228. CHECK (it.kind == flp::PlaylistItem::Kind::pattern && it.index == 3 && it.track == 2 && it.position == 384);
  229. CHECK (p.mixer.size() == 2 && p.mixer[0].name == "Drums" && p.mixer[1].name.empty());
  230. CHECK (p.warnings.empty());
  231. }
  232. TEST (flp_real_files)
  233. {
  234. if (realFlpDir.empty())
  235. {
  236. std::printf (" (pulado: passe uma pasta com .flp como argumento)\n");
  237. return;
  238. }
  239. int files = 0, withNotes = 0, withPlaylist = 0, automations = 0, automationsWithTarget = 0, sends = 0;
  240. int threeOsc = 0, threeOscDecoded = 0, wrapped = 0, wrappedParsed = 0, markers = 0, signatures = 0, trackEqs = 0;
  241. int peqSlots = 0, peqShaped = 0, reverbs = 0, reverbsDryless = 0, reverbsLowCut = 0;
  242. for (auto& entry : std::filesystem::recursive_directory_iterator (realFlpDir))
  243. {
  244. if (entry.path().extension() != ".flp")
  245. continue;
  246. std::ifstream in (entry.path(), std::ios::binary);
  247. std::vector<std::uint8_t> bytes ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  248. ++files;
  249. try
  250. {
  251. const auto p = flp::parseProject (bytes);
  252. CHECK (! p.version.empty());
  253. CHECK (p.tempo > 10.0 && p.tempo < 1000.0);
  254. const auto song = lynx::importFlp (p);
  255. CHECK (! song.patterns.empty());
  256. const auto peqDefaults = lynx::makeEffectSlot (lynx::EffectKind::parametricEq).params;
  257. for (const auto& t : song.mixer)
  258. for (const auto& fx : t.effects)
  259. {
  260. if (fx.kind == lynx::EffectKind::parametricEq)
  261. {
  262. ++peqSlots;
  263. peqShaped += fx.params != peqDefaults;
  264. for (double hz : { 50.0, 1000.0, 10000.0 })
  265. CHECK (std::isfinite (lynx::peq::responseDb (fx.params, 48000.0, hz)));
  266. }
  267. if (fx.kind == lynx::EffectKind::reverb)
  268. {
  269. ++reverbs;
  270. reverbsDryless += fx.params[4] < 0.01f;
  271. reverbsLowCut += fx.params[5] > 0.0f;
  272. }
  273. }
  274. for (const auto& t : song.mixer)
  275. if (t.eq.active())
  276. {
  277. ++trackEqs;
  278. for (std::size_t b = 0; b < 3; ++b)
  279. CHECK (t.eq.hz[b] >= 10.0f && t.eq.hz[b] <= 16000.0f && std::abs (t.eq.gainDb[b]) <= 18.0f);
  280. }
  281. for (const auto& a : song.arrangements)
  282. for (const auto& m : a.markers)
  283. {
  284. ++markers;
  285. signatures += m.isSignature();
  286. CHECK (m.tick >= 0);
  287. }
  288. // Fruity Wrapper (canais e slots do mixer): todo blob dos demos é lido
  289. auto countWrapper = [&] (const std::string& plugin, const std::vector<std::uint8_t>& state) {
  290. if (plugin != "Fruity Wrapper")
  291. return;
  292. ++wrapped;
  293. lynx::ForeignPlugin f;
  294. wrappedParsed += lynx::parseFlWrapper (state, f) && f.format != lynx::ForeignPlugin::Format::none && ! f.name.empty();
  295. };
  296. for (const auto& c : p.channels)
  297. countWrapper (c.pluginName, c.pluginState);
  298. for (const auto& insert : p.mixer)
  299. for (const auto& slot : insert.slots)
  300. countWrapper (slot.plugin, slot.state);
  301. // 3x Osc: todo estado dos demos decodifica, com níveis que somam no máximo 1
  302. for (const auto& c : p.channels)
  303. if (c.pluginName == "3x Osc")
  304. {
  305. ++threeOsc;
  306. lynx::SynthSettings s;
  307. if (lynx::synthFrom3xOsc (c.pluginState, s))
  308. {
  309. ++threeOscDecoded;
  310. // com AM o osc 3 é a profundidade da modulação e fica fora da soma
  311. const auto sum = s.osc[0].level + s.osc[1].level + (s.am ? 0.0f : s.osc[2].level);
  312. CHECK (sum <= 1.001f && s.osc[2].level <= 1.0f);
  313. for (const auto& o : s.osc)
  314. CHECK (o.octave >= -2 && o.octave <= 2 && std::abs (o.semitones) <= 11 && std::abs (o.pan) <= 1.0f);
  315. }
  316. }
  317. for (auto& pat : p.patterns)
  318. if (! pat.notes.empty())
  319. {
  320. ++withNotes;
  321. break;
  322. }
  323. for (auto& a : p.arrangements)
  324. for (auto& item : a.items)
  325. CHECK (item.track >= 0 && item.track < 500);
  326. for (auto& clip : song.playlist)
  327. {
  328. CHECK (clip.pattern >= 0 && clip.pattern < (int) song.patterns.size());
  329. CHECK (clip.length > 0 && clip.offset >= 0);
  330. if (clip.kind == lynx::ClipKind::automation)
  331. CHECK (clip.automation >= 0 && clip.automation < (int) song.automations.size());
  332. }
  333. for (auto& a : song.automations)
  334. {
  335. ++automations;
  336. automationsWithTarget += a.target.kind != lynx::AutomationTargetKind::none;
  337. CHECK (! a.points.empty());
  338. for (std::size_t i = 1; i < a.points.size(); ++i)
  339. CHECK (a.points[i].tick >= a.points[i - 1].tick);
  340. }
  341. // roteamento importado sem ciclos e com destinos válidos
  342. CHECK (song.mixerOrder().size() + 1 == song.mixer.size());
  343. for (auto& t : song.mixer)
  344. for (auto& s : t.sends)
  345. {
  346. ++sends;
  347. CHECK (s.target > 0 && s.target < (int) song.mixer.size());
  348. }
  349. if (! song.playlist.empty())
  350. ++withPlaylist;
  351. }
  352. catch (const flp::Error& e)
  353. {
  354. ++failures;
  355. std::printf (" FALHOU %s: %s\n", entry.path().string().c_str(), e.what());
  356. }
  357. }
  358. CHECK (threeOscDecoded == threeOsc);
  359. // presets de canal do 3x Osc que vêm com o FL (.fst): todos viram ajustes do synth
  360. int presets = 0, presetsDecoded = 0;
  361. const auto presetDir = std::filesystem::path (realFlpDir) / "Patches" / "Channel presets" / "3x Osc";
  362. if (std::filesystem::is_directory (presetDir))
  363. for (auto& entry : std::filesystem::directory_iterator (presetDir))
  364. if (entry.path().extension() == ".fst")
  365. {
  366. ++presets;
  367. std::ifstream in (entry.path(), std::ios::binary);
  368. std::vector<std::uint8_t> bytes ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  369. if (auto synth = lynx::synthFromFlPreset (bytes))
  370. {
  371. ++presetsDecoded;
  372. CHECK (synth->osc[0].level + synth->osc[1].level + (synth->am ? 0.0f : synth->osc[2].level) <= 1.001f);
  373. }
  374. }
  375. std::printf (" %d presets de 3x Osc, %d lidos\n", presets, presetsDecoded);
  376. CHECK (presetsDecoded == presets);
  377. // presets de efeito do FL que viram efeitos internos
  378. int fxPresets = 0, fxDecoded = 0;
  379. for (auto kind : { lynx::EffectKind::parametricEq, lynx::EffectKind::limiter, lynx::EffectKind::reverb, lynx::EffectKind::delay,
  380. lynx::EffectKind::utility })
  381. for (const auto& plugin : lynx::flPluginsForEffect (kind))
  382. {
  383. const auto dir = std::filesystem::path (realFlpDir) / "Patches" / "Plugin presets" / "Effects" / plugin;
  384. if (! std::filesystem::is_directory (dir))
  385. continue;
  386. for (auto& entry : std::filesystem::recursive_directory_iterator (dir))
  387. if (entry.path().extension() == ".fst")
  388. {
  389. ++fxPresets;
  390. std::ifstream in (entry.path(), std::ios::binary);
  391. std::vector<std::uint8_t> bytes ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  392. fxDecoded += lynx::effectFromFlPreset (bytes).has_value();
  393. }
  394. }
  395. std::printf (" %d presets de efeito do FL, %d lidos\n", fxPresets, fxDecoded);
  396. CHECK (fxDecoded == fxPresets);
  397. CHECK (wrappedParsed == wrapped);
  398. std::printf (" %d plugins no Fruity Wrapper, %d lidos\n", wrapped, wrappedParsed);
  399. std::printf (" %d marcadores, %d mudanças de compasso, %d trilhas com EQ\n", markers, signatures, trackEqs);
  400. std::printf (" %d EQs paramétricos (%d com ajustes do FL), %d reverbs (%d sem seco)\n", peqSlots, peqShaped, reverbs, reverbsDryless);
  401. CHECK (peqSlots > 1000 && peqShaped > 900 && reverbsDryless > 20 && reverbsLowCut > 250);
  402. CHECK (markers > 300 && signatures > 60);
  403. std::printf (" %d canais 3x Osc, %d decodificados\n", threeOsc, threeOscDecoded);
  404. std::printf (" %d arquivos .flp lidos, %d com notas, %d com playlist, %d automações (%d com alvo), %d envios\n",
  405. files, withNotes, withPlaylist, automations, automationsWithTarget, sends);
  406. CHECK (files > 0);
  407. CHECK (automations > 0 && sends > 0);
  408. }
  409. // ---------------------------------------------------------------------------
  410. // Sequenciador
  411. TEST (pattern_toggle_step_and_length)
  412. {
  413. lynx::Pattern p;
  414. CHECK (! p.hasStep (0, 4));
  415. p.toggleStep (0, 4);
  416. CHECK (p.hasStep (0, 4));
  417. CHECK (p.notes.size() == 1 && p.notes[0].start == 4 * lynx::ticksPerStep);
  418. CHECK (p.effectiveLength (4) == 4 * lynx::ppq); // um compasso
  419. p.toggleStep (1, 20); // segundo compasso
  420. CHECK (p.effectiveLength (4) == 8 * lynx::ppq);
  421. p.toggleStep (0, 4);
  422. CHECK (! p.hasStep (0, 4) && p.notes.size() == 1);
  423. }
  424. TEST (scheduler_places_events_at_exact_samples)
  425. {
  426. lynx::Pattern p;
  427. p.toggleStep (0, 0);
  428. p.toggleStep (0, 4); // tick 960 = 1 tempo
  429. const double sr = 48000.0, bpm = 120.0; // 1 tempo = 0,5 s = 24000 samples
  430. const auto tps = lynx::ticksPerSample (bpm, sr);
  431. lynx::EventBuffer ev;
  432. lynx::schedulePatternLoop (p, p.effectiveLength (4), 23900.0 * tps, 512, tps, ev);
  433. // a nota do tempo 2 começa no sample 24000 → offset 100 neste bloco
  434. int ons = 0;
  435. for (auto& e : ev)
  436. if (e.type == lynx::NoteEvent::Type::on)
  437. {
  438. ++ons;
  439. CHECK (e.sampleOffset == 100);
  440. }
  441. CHECK (ons == 1);
  442. }
  443. TEST (scheduler_wraps_the_loop)
  444. {
  445. lynx::Pattern p;
  446. p.toggleStep (2, 0);
  447. const auto len = p.effectiveLength (4); // 3840 ticks
  448. const double sr = 48000.0;
  449. const auto tps = lynx::ticksPerSample (120.0, sr);
  450. lynx::EventBuffer ev;
  451. // bloco que atravessa o fim do loop: começa 10 samples antes
  452. const auto start = (double) len - 10.0 * tps;
  453. lynx::schedulePatternLoop (p, len, start, 64, tps, ev);
  454. bool found = false;
  455. for (auto& e : ev)
  456. if (e.type == lynx::NoteEvent::Type::on && e.channel == 2)
  457. {
  458. found = true;
  459. CHECK (e.sampleOffset == 10);
  460. }
  461. CHECK (found);
  462. }
  463. TEST (scheduler_off_before_on_at_same_sample)
  464. {
  465. lynx::Pattern p;
  466. lynx::Note a;
  467. a.start = 0; a.length = 240; a.channel = 0;
  468. lynx::Note b = a;
  469. b.start = 240;
  470. p.notes = { a, b };
  471. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  472. lynx::EventBuffer ev;
  473. lynx::schedulePatternLoop (p, p.effectiveLength (4), 200.0, 4000, tps, ev);
  474. CHECK (ev.size() >= 2);
  475. CHECK (ev[0].type == lynx::NoteEvent::Type::off);
  476. CHECK (ev[1].type == lynx::NoteEvent::Type::on);
  477. CHECK (ev[0].sampleOffset == ev[1].sampleOffset);
  478. }
  479. TEST (snapshot_exchange_hands_over_and_recycles)
  480. {
  481. struct Counted
  482. {
  483. int value;
  484. int* alive;
  485. Counted (int v, int* a) : value (v), alive (a) { ++*alive; }
  486. ~Counted() { --*alive; }
  487. };
  488. int alive = 0;
  489. {
  490. lynx::SnapshotExchange<Counted> x;
  491. CHECK (x.acquire() == nullptr);
  492. x.publish (std::make_unique<Counted> (1, &alive));
  493. CHECK (x.acquire()->value == 1);
  494. x.publish (std::make_unique<Counted> (2, &alive));
  495. x.publish (std::make_unique<Counted> (3, &alive)); // 2 nunca foi lido: liberado na hora
  496. CHECK (alive == 2);
  497. CHECK (x.acquire()->value == 3);
  498. CHECK (alive == 2); // o 1 foi devolvido, mas só a UI libera
  499. x.collectGarbage();
  500. CHECK (alive == 1);
  501. // sem coleta, as vagas de devolução enchem e o áudio segura o atual
  502. for (int i = 0; i < 20; ++i)
  503. {
  504. x.publish (std::make_unique<Counted> (10 + i, &alive));
  505. CHECK (x.acquire() != nullptr);
  506. }
  507. }
  508. CHECK (alive == 0);
  509. }
  510. TEST (rack_renderer_makes_sound_and_reuses_instruments)
  511. {
  512. auto song = lynx::Song::makeDefault();
  513. song.bpm = 120.0;
  514. const double sr = 48000.0;
  515. auto state = lynx::RackState::build (song, nullptr, sr);
  516. lynx::RackRenderer r;
  517. r.prepare (sr);
  518. std::vector<float> l (512), rr (512);
  519. double tick = 0.0;
  520. float peak = 0.0f;
  521. int kicks = 0;
  522. for (int block = 0; block < 93; ++block) // 47616 samples: logo antes de 1 s
  523. {
  524. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  525. for (auto& e : r.lastEvents())
  526. if (e.type == lynx::NoteEvent::Type::on && e.channel == 0)
  527. ++kicks;
  528. for (int i = 0; i < 512; ++i)
  529. {
  530. CHECK (std::isfinite (l[(std::size_t) i]));
  531. peak = std::max (peak, std::abs (l[(std::size_t) i]));
  532. }
  533. tick += 512 * lynx::ticksPerSample (song.bpm, sr);
  534. }
  535. CHECK (peak > 0.1f && peak < 4.0f);
  536. CHECK (kicks == 2); // 120 BPM: tempos em 0 e 0,5 s
  537. // editar a música preserva os instrumentos de canais que não mudaram de tipo
  538. song.channels[4].instrument = lynx::InstrumentKind::kick;
  539. auto next = lynx::RackState::build (song, state.get(), sr);
  540. CHECK (next->instruments[0] == state->instruments[0]);
  541. CHECK (next->instruments[4] != state->instruments[4]);
  542. // parar silencia o synth e não dispara notas novas
  543. r.process (next.get(), false, tick, 512, l.data(), rr.data());
  544. CHECK (r.lastEvents().size() == 0);
  545. }
  546. TEST (flp_import_maps_channels_and_rescales)
  547. {
  548. flp::Project p;
  549. p.header.ppq = 96;
  550. p.tempo = 150.0;
  551. p.channels = { { 0, flp::ChannelType::sampler, "Kick 808", "", "", 1 },
  552. { 1, flp::ChannelType::audioClip, "Vocal", "", "", 2 },
  553. { 2, flp::ChannelType::instrument, "Lead", "FLEX", "", 3 } };
  554. flp::Pattern pat;
  555. pat.index = 1;
  556. flp::Note n;
  557. n.position = 96;
  558. n.length = 0;
  559. n.channel = 2;
  560. n.key = 72;
  561. n.velocity = 64;
  562. pat.notes.push_back (n);
  563. p.patterns.push_back (pat);
  564. const auto s = lynx::importFlp (p);
  565. CHECK (s.bpm == 150.0);
  566. CHECK (s.channels.size() == 3); // canais de clip de áudio ficam no rack, como no FL
  567. CHECK (s.channels[0].instrument == lynx::InstrumentKind::kick);
  568. CHECK (s.channels[1].instrument == lynx::InstrumentKind::audioClip);
  569. CHECK (s.channels[2].instrument == lynx::InstrumentKind::synth);
  570. CHECK (s.patterns.size() == 1);
  571. CHECK (s.patterns[0].notes[0].start == lynx::ppq); // 96 @ PPQ 96 = 1 tempo
  572. CHECK (s.patterns[0].notes[0].channel == 2);
  573. CHECK (s.patterns[0].notes[0].length == lynx::ticksPerStep); // nota de step
  574. CHECK (std::abs (s.patterns[0].notes[0].velocity - 0.5f) < 1e-6f);
  575. }
  576. TEST (live_queue_is_fifo_and_bounded)
  577. {
  578. lynx::LiveEventQueue q;
  579. lynx::NoteEvent e;
  580. CHECK (! q.pop (e));
  581. for (int i = 0; i < 10; ++i)
  582. {
  583. lynx::NoteEvent in;
  584. in.key = i;
  585. CHECK (q.push (in));
  586. }
  587. for (int i = 0; i < 10; ++i)
  588. CHECK (q.pop (e) && e.key == i);
  589. int pushed = 0;
  590. while (q.push (e))
  591. ++pushed;
  592. CHECK (pushed == (int) lynx::LiveEventQueue::capacity - 1); // uma vaga fica livre para distinguir cheio de vazio
  593. }
  594. TEST (sampler_plays_pitched_one_shot)
  595. {
  596. // sample de 1000 frames com rampa: dá para medir a posição pela amplitude
  597. auto data = std::make_shared<lynx::SampleData>();
  598. data->sampleRate = 48000.0;
  599. for (int i = 0; i < 1000; ++i)
  600. data->left.push_back (1.0f);
  601. auto sampler = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  602. sampler->prepare (48000.0);
  603. std::vector<float> l (2048, 0.0f), r (2048, 0.0f);
  604. sampler->noteOn (60, 1.0f);
  605. sampler->noteOff (60); // one-shot: noteOff não corta
  606. sampler->render (l.data(), r.data(), 2048, 1.0f, 1.0f);
  607. int sounding = 0;
  608. for (auto s : l)
  609. sounding += s > 0.5f;
  610. CHECK (sounding >= 995 && sounding <= 1000); // toca o sample inteiro na altura original
  611. std::fill (l.begin(), l.end(), 0.0f);
  612. sampler->noteOn (72, 1.0f); // uma oitava acima: metade da duração
  613. sampler->render (l.data(), r.data(), 2048, 1.0f, 1.0f);
  614. sounding = 0;
  615. for (auto s : l)
  616. sounding += s > 0.5f;
  617. CHECK (sounding >= 495 && sounding <= 500);
  618. CHECK (r[10] > 0.5f); // mono vai para os dois lados
  619. auto silent = lynx::makeInstrument (lynx::InstrumentKind::sampler, nullptr);
  620. silent->prepare (48000.0);
  621. silent->noteOn (60, 1.0f);
  622. std::fill (l.begin(), l.end(), 0.0f);
  623. silent->render (l.data(), r.data(), 64, 1.0f, 1.0f);
  624. CHECK (l[0] == 0.0f);
  625. }
  626. TEST (rack_live_notes_and_sample_provider)
  627. {
  628. lynx::Song song;
  629. lynx::ChannelDef c;
  630. c.name = "Smp";
  631. c.instrument = lynx::InstrumentKind::sampler;
  632. c.samplePath = "a.wav";
  633. song.channels.push_back (c);
  634. song.patterns.emplace_back();
  635. int loads = 0;
  636. auto provider = [&] (const std::string& path) -> std::shared_ptr<const lynx::SampleData> {
  637. ++loads;
  638. CHECK (path == "a.wav");
  639. auto d = std::make_shared<lynx::SampleData>();
  640. d->left.assign (4800, 0.5f);
  641. return d;
  642. };
  643. auto state = lynx::RackState::build (song, nullptr, 48000.0, provider);
  644. CHECK (loads == 1);
  645. lynx::RackRenderer renderer;
  646. renderer.prepare (48000.0);
  647. lynx::LiveEventQueue live;
  648. lynx::NoteEvent on;
  649. on.channel = 0;
  650. on.velocity = 1.0f;
  651. live.push (on);
  652. std::vector<float> l (256), r (256);
  653. renderer.process (state.get(), false, 0.0, 256, l.data(), r.data(), &live); // parado, mas a nota ao vivo toca
  654. CHECK (l[0] > 0.1f);
  655. // mesmo sample: reaproveita; sample diferente: recarrega
  656. auto same = lynx::RackState::build (song, state.get(), 48000.0, provider);
  657. CHECK (loads == 1 && same->instruments[0] == state->instruments[0]);
  658. song.channels[0].samplePath = "b.wav";
  659. auto other = lynx::RackState::build (song, state.get(), 48000.0, [&] (const std::string&) { ++loads; return nullptr; });
  660. CHECK (loads == 2 && other->instruments[0] != state->instruments[0]);
  661. }
  662. TEST (flp_paths_resolve_and_samplers_import)
  663. {
  664. lynx::FlPathRoots roots { "C:\\FL", "C:\\FL\\Data", "D:\\User" };
  665. CHECK (lynx::resolveFlPath ("%FLStudioFactoryData%\\Data\\x.wav", roots) == "C:\\FL\\Data\\x.wav");
  666. CHECK (lynx::resolveFlPath ("%FLStudioData%\\Patches\\y.wav", roots) == "C:\\FL\\Data\\Patches\\y.wav");
  667. CHECK (lynx::resolveFlPath ("%FLStudioUserData%\\z.wav", roots) == "D:\\User\\z.wav");
  668. CHECK (lynx::resolveFlPath ("E:\\abs.wav", roots) == "E:\\abs.wav");
  669. CHECK (lynx::resolveFlPath ("%FLStudioUserData%\\z.wav", {}) == "");
  670. flp::Project p;
  671. p.channels = { { 0, flp::ChannelType::sampler, "Kick", "", "%FLStudioData%\\k.wav", 1 },
  672. { 1, flp::ChannelType::sampler, "Hat", "", "%FLStudioData%\\missing.wav", 1 } };
  673. lynx::FlpImportOptions options;
  674. options.roots = roots;
  675. options.fileExists = [] (const std::string& path) { return path == "C:\\FL\\Data\\k.wav"; };
  676. const auto s = lynx::importFlp (p, options);
  677. CHECK (s.channels[0].instrument == lynx::InstrumentKind::sampler);
  678. CHECK (s.channels[0].samplePath == "C:\\FL\\Data\\k.wav");
  679. CHECK (s.channels[1].instrument == lynx::InstrumentKind::hat); // sem arquivo: instrumento interno
  680. }
  681. TEST (soft_clip_is_transparent_below_knee_and_bounded)
  682. {
  683. float s[] = { 0.5f, -0.89f, 1.5f, -3.0f, 0.95f };
  684. lynx::softClip (s, 5);
  685. CHECK (s[0] == 0.5f && s[1] == -0.89f);
  686. CHECK (s[2] > 0.9f && s[2] <= 1.0f);
  687. CHECK (s[3] < -0.9f && s[3] >= -1.0f);
  688. CHECK (s[4] > 0.9f && s[4] < 0.95f);
  689. }
  690. TEST (song_scheduler_plays_clips_with_offset_and_cut)
  691. {
  692. lynx::Song s;
  693. s.channels.resize (1);
  694. auto& p = s.patterns.emplace_back();
  695. for (int step : { 0, 4, 8, 12 }) // uma nota por tempo
  696. p.toggleStep (0, step);
  697. // clip no compasso 2 tocando só a segunda metade da pattern (tempos 3 e 4)
  698. lynx::Clip c;
  699. c.pattern = 0;
  700. c.start = 4 * lynx::ppq;
  701. c.length = 2 * lynx::ppq;
  702. c.offset = 2 * lynx::ppq;
  703. s.playlist.push_back (c);
  704. CHECK (s.songLength() == 8 * lynx::ppq);
  705. const double sr = 48000.0;
  706. const auto tps = lynx::ticksPerSample (120.0, sr); // 1 tempo = 24000 samples
  707. lynx::EventBuffer ev;
  708. // música inteira em um bloco só (8 tempos = 192000 samples)
  709. lynx::scheduleSong (s, 0.0, 192000, tps, ev);
  710. std::vector<int> ons;
  711. for (auto& e : ev)
  712. if (e.type == lynx::NoteEvent::Type::on)
  713. ons.push_back (e.sampleOffset);
  714. CHECK (ons.size() == 2);
  715. CHECK (ons.size() == 2 && ons[0] == 4 * 24000 && ons[1] == 5 * 24000);
  716. // atravessando o loop: o compasso 1 está vazio, então nada no começo do segundo giro
  717. ev.clear();
  718. lynx::scheduleSong (s, 8.0 * lynx::ppq - 100 * tps, 200, tps, ev);
  719. CHECK (ev.size() == 0);
  720. // nota mais longa que o clip é cortada no fim do clip
  721. p.notes[3].length = 4 * lynx::ppq;
  722. ev.clear();
  723. lynx::scheduleSong (s, 0.0, 192000, tps, ev);
  724. int lastOff = -1;
  725. for (auto& e : ev)
  726. if (e.type == lynx::NoteEvent::Type::off)
  727. lastOff = std::max (lastOff, e.sampleOffset);
  728. CHECK (lastOff == 6 * 24000);
  729. }
  730. TEST (remove_pattern_fixes_clips)
  731. {
  732. lynx::Song s;
  733. s.patterns.resize (3);
  734. s.currentPattern = 2;
  735. s.playlist = { { 0, 0, 0, 100, 0 }, { 1, 0, 100, 100, 0 }, { 2, 1, 0, 100, 0 } };
  736. s.removePattern (1);
  737. CHECK (s.patterns.size() == 2);
  738. CHECK (s.playlist.size() == 2 && s.playlist[1].pattern == 1);
  739. CHECK (s.currentPattern == 1);
  740. }
  741. TEST (flp_import_3x_osc_state_and_channel_filter)
  742. {
  743. // patch novo do 3x Osc (versão 14): osc 2 mix 64 coarse -12, osc 3 mix 32 coarse -24
  744. std::vector<std::uint8_t> blob (460, 0);
  745. auto put = [&] (std::size_t off, std::int32_t v) {
  746. for (int b = 0; b < 4; ++b)
  747. blob[off + (std::size_t) b] = (std::uint8_t) ((std::uint32_t) v >> (8 * b));
  748. };
  749. put (0x00, 14);
  750. put (0x08, 3); // osc 1 serra
  751. put (0x10, 7); // osc 1 fine +7
  752. put (0x04, -32); // osc 1 pan -0,5
  753. put (0x1C, 64); // osc 2 mix
  754. put (0x28, -12); // osc 2 coarse
  755. put (0x38, 32); // osc 3 mix
  756. put (0x40, 2); // osc 3 quadrada
  757. put (0x44, -19); // osc 3 coarse: -1 oitava e -7 semitons
  758. lynx::SynthSettings s;
  759. CHECK (lynx::synthFrom3xOsc (blob, s));
  760. 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);
  761. CHECK (s.osc[0].wave == lynx::Waveform::saw && s.osc[0].detune == 7.0f && s.osc[0].pan == -0.5f);
  762. CHECK (s.osc[1].wave == lynx::Waveform::sine && s.osc[1].octave == -1 && s.osc[1].semitones == 0);
  763. CHECK (s.osc[2].wave == lynx::Waveform::square && s.osc[2].octave == -1 && s.osc[2].semitones == -7);
  764. CHECK (! lynx::synthFrom3xOsc (std::vector<std::uint8_t> (40, 0), s));
  765. // filtro do canal: padrão aberto; LP com Mod X 128 ~ 2,71 kHz; Fast LP com Mod X 128 ~ 280 Hz
  766. float hz = 0.0f, res = 1.0f;
  767. int mode = -1;
  768. lynx::synthFilterFromChannel (256, 0, 0, hz, res, mode);
  769. CHECK (hz >= 19999.0f && res == 0.0f);
  770. lynx::synthFilterFromChannel (128, 0, 1, hz, res, mode);
  771. CHECK (std::abs (hz - 2710.0f) < 30.0f && res == 0.0f);
  772. lynx::synthFilterFromChannel (128, 0, 0, hz, res, mode);
  773. CHECK (hz > 240.0f && hz < 320.0f);
  774. lynx::synthFilterFromChannel (128, 256, 1, hz, res, mode);
  775. CHECK (res > 0.8f);
  776. CHECK (mode == 0);
  777. lynx::synthFilterFromChannel (64, 0, 3, hz, res, mode); // passa-altas em ~840 Hz
  778. CHECK (mode == 2 && std::abs (hz - 840.0f) < 40.0f);
  779. lynx::synthFilterFromChannel (128, 0, 2, hz, res, mode); // passa-banda
  780. CHECK (mode == 1);
  781. }
  782. TEST (synth_pitch_and_filter_envelopes)
  783. {
  784. auto render = [] (const lynx::SynthSettings& s, int frames) {
  785. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  786. inst->prepare (48000.0);
  787. lynx::ChannelDef c;
  788. c.synth = s;
  789. inst->configure (c, 120.0);
  790. inst->noteOn (45, 1.0f); // A2 = 110 Hz
  791. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  792. inst->render (l.data(), r.data(), frames, 1.0f, 1.0f);
  793. return l;
  794. };
  795. auto crossings = [] (const std::vector<float>& b, int from, int to) {
  796. int n = 0;
  797. for (int i = from + 1; i < to; ++i)
  798. n += (b[(std::size_t) i - 1] < 0.0f) != (b[(std::size_t) i] < 0.0f);
  799. return n;
  800. };
  801. // "kick" do 3x Osc: seno com envelope de afinação +24 st caindo rápido
  802. lynx::SynthSettings kick;
  803. kick.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  804. kick.cutoff = 20000.0f;
  805. kick.pitchEnv = { 24.0f, 0.0f, 0.0f, 0.05f, 0.0f, 0.05f };
  806. const auto k = render (kick, 48000);
  807. const auto early = crossings (k, 0, 2400); // 50 ms iniciais: bem acima de 110 Hz
  808. const auto late = crossings (k, 24000, 48000); // depois volta aos 110 Hz (~110 cruzamentos em 0,5 s)
  809. CHECK (early > 20); // reta de +24 st em 50 ms: ~2,2x a frequência média (11 cruzamentos sem envelope)
  810. CHECK (std::abs (late - 110) < 4);
  811. // envelope de corte: serra fechada em 200 Hz abre +5 oitavas no ataque e fecha de novo
  812. lynx::SynthSettings pluck;
  813. pluck.cutoff = 200.0f;
  814. pluck.filterEnv = { 5.0f, 0.0f, 0.0f, 0.1f, 0.0f, 0.1f };
  815. const auto p = render (pluck, 48000);
  816. auto hf = [&] (int from, int to) { // energia da diferença (agudos)
  817. double e = 0.0;
  818. for (int i = from + 1; i < to; ++i)
  819. e += std::pow ((double) p[(std::size_t) i] - p[(std::size_t) i - 1], 2.0);
  820. return e;
  821. };
  822. CHECK (hf (0, 2400) > 4.0 * hf (40000, 42400));
  823. }
  824. TEST (synth_mono_reuses_the_sounding_voice)
  825. {
  826. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  827. inst->prepare (48000.0);
  828. lynx::ChannelDef c;
  829. c.synth.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  830. c.synth.cutoff = 20000.0f;
  831. c.synth.mono = true;
  832. inst->configure (c, 120.0);
  833. std::vector<float> l (48000), r (48000);
  834. inst->noteOn (57, 1.0f);
  835. inst->render (l.data(), r.data(), 4800, 1.0f, 1.0f);
  836. inst->noteOn (69, 1.0f); // A4 assume a voz do A3: só uma nota soando
  837. inst->render (l.data() + 4800, r.data() + 4800, 43200, 1.0f, 1.0f);
  838. int crossings = 0;
  839. float peak = 0.0f;
  840. for (std::size_t i = 24001; i < 48000; ++i)
  841. {
  842. crossings += (l[i - 1] < 0.0f) != (l[i] < 0.0f);
  843. peak = std::max (peak, std::abs (l[i]));
  844. }
  845. CHECK (std::abs (crossings - 440) < 4); // 0,5 s de 440 Hz, sem o A3 por baixo
  846. CHECK (peak < 0.35f); // uma voz (0,3 de nível), não duas somadas
  847. // sem estalo na troca: o salto entre samples vizinhos fica no tamanho do seno
  848. float jump = 0.0f;
  849. for (std::size_t i = 4790; i < 4810; ++i)
  850. jump = std::max (jump, std::abs (l[i] - l[i - 1]));
  851. CHECK (jump < 0.05f);
  852. }
  853. TEST (synth_porta_glides_and_am_modulates)
  854. {
  855. auto make = [] (const lynx::SynthSettings& s) {
  856. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  857. inst->prepare (48000.0);
  858. lynx::ChannelDef c;
  859. c.synth = s;
  860. inst->configure (c, 120.0);
  861. return inst;
  862. };
  863. auto crossings = [] (const std::vector<float>& b, std::size_t from, std::size_t to) {
  864. int n = 0;
  865. for (auto i = from + 1; i < to; ++i)
  866. n += (b[i - 1] < 0.0f) != (b[i] < 0.0f);
  867. return n;
  868. };
  869. // mono + porta de 1 tempo (0,5 s a 120 BPM): de A3 para A4, no meio do caminho ~E4 (329,6 Hz)
  870. lynx::SynthSettings s;
  871. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  872. s.cutoff = 20000.0f;
  873. s.mono = true;
  874. s.porta = true;
  875. s.portaBeats = 1.0f;
  876. auto inst = make (s);
  877. std::vector<float> l (96000), r (96000);
  878. inst->noteOn (57, 1.0f);
  879. inst->render (l.data(), r.data(), 4800, 1.0f, 1.0f);
  880. inst->noteOn (69, 1.0f);
  881. inst->render (l.data() + 4800, r.data() + 4800, 91200, 1.0f, 1.0f);
  882. const auto middle = crossings (l, 4800 + 12000 - 2400, 4800 + 12000 + 2400); // 0,1 s em volta de 0,25 s
  883. CHECK (std::abs (middle - 66) < 6); // ~330 Hz * 0,1 s * 2
  884. CHECK (std::abs (crossings (l, 48000, 96000) - 880) < 4); // chegou no A4 (1 s = 880 cruzamentos)
  885. // 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)
  886. lynx::SynthSettings am;
  887. am.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  888. am.osc[2] = { lynx::Waveform::sine, -3, 0.0f, 1.0f };
  889. am.cutoff = 20000.0f;
  890. am.am = true;
  891. auto modulated = make (am);
  892. modulated->noteOn (69, 1.0f);
  893. std::fill (l.begin(), l.end(), 0.0f);
  894. modulated->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  895. float peak = 0.0f;
  896. for (std::size_t i = 4800; i < 48000; ++i)
  897. peak = std::max (peak, std::abs (l[i]));
  898. CHECK (peak > 0.45f && peak < 0.65f); // 0,3 · (1 + 1) no máximo: (1 − o3) vai até 2
  899. }
  900. TEST (channel_lfo_vibrato_and_tremolo)
  901. {
  902. auto render = [] (const lynx::SynthSettings& s) {
  903. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  904. inst->prepare (48000.0);
  905. lynx::ChannelDef c;
  906. c.synth = s;
  907. inst->configure (c, 120.0);
  908. inst->noteOn (69, 1.0f);
  909. std::vector<float> l (48000), r (48000);
  910. inst->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  911. return l;
  912. };
  913. lynx::SynthSettings s;
  914. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  915. s.cutoff = 20000.0f;
  916. // tremolo: LFO de volume 100% a 4 Hz (período 0,25 s) -> o envelope de amplitude vai de ~0 a ~2x
  917. auto tremolo = s;
  918. tremolo.lfo[lynx::lfoVolume] = { 1.0f, 0.25f, false, 0, 0.0f, 0.0f };
  919. const auto t = render (tremolo);
  920. float lowest = 1.0f, highest = 0.0f;
  921. for (std::size_t w = 4800; w + 480 <= 48000; w += 480) // janelas de 10 ms (4,4 ciclos de 440 Hz)
  922. {
  923. float peak = 0.0f;
  924. for (auto i = w; i < w + 480; ++i)
  925. peak = std::max (peak, std::abs (t[i]));
  926. lowest = std::min (lowest, peak);
  927. highest = std::max (highest, peak);
  928. }
  929. CHECK (lowest < 0.08f && highest > 0.5f);
  930. // vibrato sincronizado: ±1 semitom, período 1 tempo (0,5 s a 120 BPM); a média fica em 440 Hz
  931. auto vibrato = s;
  932. vibrato.lfo[lynx::lfoPitch] = { 1.0f, 1.0f, true, 0, 0.0f, 0.0f };
  933. const auto v = render (vibrato);
  934. int crossings = 0;
  935. for (std::size_t i = 1; i < 48000; ++i)
  936. crossings += (v[i - 1] < 0.0f) != (v[i] < 0.0f);
  937. CHECK (std::abs (crossings - 880) < 12);
  938. int firstQuarter = 0; // primeiro quarto do ciclo: seno subindo -> mais agudo que 440
  939. for (std::size_t i = 1; i < 6000; ++i)
  940. firstQuarter += (v[i - 1] < 0.0f) != (v[i] < 0.0f);
  941. CHECK (firstQuarter > 112);
  942. }
  943. TEST (sampler_porta_glides_from_previous_note)
  944. {
  945. auto data = std::make_shared<lynx::SampleData>();
  946. data->sampleRate = 48000.0;
  947. data->left.resize (96000);
  948. for (std::size_t i = 0; i < data->left.size(); ++i)
  949. data->left[i] = 0.5f * (float) std::sin (6.283185307 * 220.0 * (double) i / 48000.0);
  950. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  951. inst->prepare (48000.0);
  952. lynx::ChannelDef c;
  953. c.sampler.cut = true;
  954. c.sampler.porta = true;
  955. c.sampler.portaBeats = 1.0f; // 0,5 s a 120 BPM
  956. inst->configure (c, 120.0);
  957. std::vector<float> l (24000), r (24000);
  958. inst->noteOn (60, 1.0f);
  959. inst->render (l.data(), r.data(), 2400, 1.0f, 1.0f);
  960. inst->noteOn (72, 1.0f); // uma oitava acima: começa em 220 Hz e sobe
  961. std::fill (l.begin(), l.end(), 0.0f);
  962. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  963. auto crossings = [&] (std::size_t from, std::size_t to) {
  964. int n = 0;
  965. for (auto i = from + 1; i < to; ++i)
  966. n += (l[i - 1] < 0.0f) != (l[i] < 0.0f);
  967. return n;
  968. };
  969. const auto start = crossings (600, 2400); // 37,5 ms ainda perto de 220 Hz: ~17 cruzamentos (440 Hz daria 33)
  970. const auto end = crossings (21600, 24000); // 50 ms no fim do deslize: perto de 440 Hz (~44; 220 Hz daria 22)
  971. CHECK (start < 22);
  972. CHECK (end > 36);
  973. }
  974. TEST (zoned_sampler_picks_zone_by_key_and_velocity)
  975. {
  976. auto sine = [] (double hz, float amp) {
  977. auto d = std::make_shared<lynx::SampleData>();
  978. d->sampleRate = 48000.0;
  979. d->left.resize (48000);
  980. for (std::size_t i = 0; i < d->left.size(); ++i)
  981. d->left[i] = amp * (float) std::sin (6.283185307 * hz * (double) i / 48000.0);
  982. return d;
  983. };
  984. // graves: seno de 220 Hz gravado como A3 (57), até a tecla 69; agudos: 880 Hz como A5 (81)
  985. // camada forte nos agudos: mesma afinação, mais alta
  986. std::vector<lynx::LoadedZone> zones {
  987. { { "graves.wav", 57, 0, 69, 0, 127, 0.0f, 1.0f }, sine (220.0, 0.5f) },
  988. { { "agudos.wav", 81, 70, 127, 0, 99, 0.0f, 1.0f }, sine (880.0, 0.25f) },
  989. { { "agudos forte.wav", 81, 70, 127, 100, 127, 0.0f, 1.0f }, sine (880.0, 0.9f) },
  990. };
  991. auto inst = lynx::makeZonedSampler (zones);
  992. inst->prepare (48000.0);
  993. inst->configure (lynx::ChannelDef {}, 120.0);
  994. auto play = [&] (int key, float velocity) {
  995. inst->allNotesOff();
  996. std::vector<float> l (24000), r (24000);
  997. inst->render (l.data(), r.data(), 2000, 1.0f, 1.0f); // deixa as vozes antigas sumirem
  998. std::fill (l.begin(), l.end(), 0.0f);
  999. inst->noteOn (key, velocity);
  1000. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  1001. int crossings = 0;
  1002. float peak = 0.0f;
  1003. for (std::size_t i = 1; i < 24000; ++i)
  1004. {
  1005. crossings += (l[i - 1] < 0.0f) != (l[i] < 0.0f);
  1006. peak = std::max (peak, std::abs (l[i]));
  1007. }
  1008. return std::pair { crossings, peak };
  1009. };
  1010. const auto low = play (69, 0.5f); // A4 a partir da raiz A3: 440 Hz -> 440 cruzamentos em 0,5 s
  1011. CHECK (std::abs (low.first - 440) < 4);
  1012. const auto soft = play (81, 0.5f); // zona de agudos na raiz: 880 Hz
  1013. CHECK (std::abs (soft.first - 880) < 6);
  1014. const auto hard = play (81, 0.95f); // velocity alta: camada forte
  1015. CHECK (hard.second > soft.second * 2.0f);
  1016. }
  1017. TEST (sampler_channel_filter_darkens_and_bypasses_when_open)
  1018. {
  1019. // ruído branco no sampler: com corte em 300 Hz a energia cai muito; aberto passa igual
  1020. auto data = std::make_shared<lynx::SampleData>();
  1021. data->sampleRate = 48000.0;
  1022. data->left.resize (48000);
  1023. std::uint32_t seed = 7;
  1024. for (auto& v : data->left)
  1025. {
  1026. seed = seed * 1664525u + 1013904223u;
  1027. v = ((float) (seed >> 8) / 16777216.0f - 0.5f);
  1028. }
  1029. data->right = data->left;
  1030. auto energy = [&] (float cutoff) {
  1031. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  1032. inst->prepare (48000.0);
  1033. lynx::ChannelDef c;
  1034. c.sampler.cutoff = cutoff;
  1035. inst->configure (c, 120.0);
  1036. inst->noteOn (60, 1.0f);
  1037. std::vector<float> l (24000), r (24000);
  1038. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  1039. double e = 0.0;
  1040. for (auto v : l)
  1041. e += (double) v * v;
  1042. return e;
  1043. };
  1044. const auto open = energy (20000.0f), dark = energy (300.0f);
  1045. {
  1046. // passa-altas em 10 kHz: tira a maior parte da energia do ruído também, mas pelo outro lado
  1047. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  1048. inst->prepare (48000.0);
  1049. lynx::ChannelDef hp;
  1050. hp.sampler.cutoff = 10000.0f;
  1051. hp.sampler.filterType = 2;
  1052. inst->configure (hp, 120.0);
  1053. inst->noteOn (60, 1.0f);
  1054. std::vector<float> l (24000), r (24000);
  1055. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  1056. double e = 0.0, lowE = 0.0;
  1057. float lp = 0.0f;
  1058. for (auto v : l)
  1059. {
  1060. e += (double) v * v;
  1061. lp += 0.01f * (v - lp); // passa-baixas grosseiro: quase nada deve sobrar embaixo
  1062. lowE += (double) lp * lp;
  1063. }
  1064. CHECK (e > 10.0 && e < 0.7 * energy (20000.0f));
  1065. CHECK (lowE < e * 0.01);
  1066. }
  1067. CHECK (open > 100.0);
  1068. CHECK (dark < open * 0.05);
  1069. // envelope de afinação +12 st com sustentação 1: o sample corre no dobro da velocidade
  1070. // e acaba na metade do tempo (1 s de sample -> 0,5 s)
  1071. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  1072. inst->prepare (48000.0);
  1073. lynx::ChannelDef c;
  1074. c.sampler.pitchEnv = { 12.0f, 0.0f, 0.0f, 0.1f, 1.0f, 0.1f };
  1075. inst->configure (c, 120.0);
  1076. inst->noteOn (60, 1.0f);
  1077. std::vector<float> l (48000), r (48000);
  1078. inst->render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  1079. float tail = 0.0f, body = 0.0f;
  1080. for (std::size_t i = 20000; i < 23000; ++i)
  1081. body = std::max (body, std::abs (l[i]));
  1082. for (std::size_t i = 25000; i < 48000; ++i)
  1083. tail = std::max (tail, std::abs (l[i]));
  1084. CHECK (body > 0.1f);
  1085. CHECK (tail == 0.0f);
  1086. }
  1087. TEST (synth_oscillator_pan_and_semitones)
  1088. {
  1089. auto render = [] (lynx::SynthSettings s, std::vector<float>& l, std::vector<float>& r) {
  1090. auto synth = lynx::makeInstrument (lynx::InstrumentKind::synth);
  1091. synth->prepare (48000.0);
  1092. lynx::ChannelDef c;
  1093. c.synth = s;
  1094. synth->configure (c, 120.0);
  1095. synth->noteOn (69, 1.0f);
  1096. l.assign (24000, 0.0f);
  1097. r.assign (24000, 0.0f);
  1098. synth->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  1099. };
  1100. lynx::SynthSettings s;
  1101. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f, 7, 1.0f }; // quinta acima, todo à direita
  1102. s.cutoff = 20000.0f;
  1103. std::vector<float> l, r;
  1104. render (s, l, r);
  1105. float peakL = 0.0f, peakR = 0.0f;
  1106. int crossings = 0;
  1107. for (std::size_t i = 4800; i < 24000; ++i)
  1108. {
  1109. peakL = std::max (peakL, std::abs (l[i]));
  1110. peakR = std::max (peakR, std::abs (r[i]));
  1111. crossings += (r[i - 1] < 0.0f) != (r[i] < 0.0f);
  1112. }
  1113. CHECK (peakL < 1e-4f && peakR > 0.1f);
  1114. // 440 * 2^(7/12) = 659,3 Hz; 0,4 s = 263,7 ciclos = ~527 cruzamentos
  1115. CHECK (std::abs (crossings - 527) < 6);
  1116. }
  1117. TEST (fl_wrapper_state_parses_records_and_vst3_state)
  1118. {
  1119. // blob do Fruity Wrapper (versão 12): tipo VST3 gerador, class ID, nome, caminho e estado
  1120. std::vector<std::uint8_t> blob;
  1121. 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))); };
  1122. auto record = [&] (std::vector<std::uint8_t>& b, std::uint32_t id, const std::vector<std::uint8_t>& payload) {
  1123. u32 (b, id);
  1124. u32 (b, (std::uint32_t) payload.size());
  1125. u32 (b, 0);
  1126. b.insert (b.end(), payload.begin(), payload.end());
  1127. };
  1128. auto bytes = [] (const std::string& s) { return std::vector<std::uint8_t> (s.begin(), s.end()); };
  1129. std::vector<std::uint8_t> vst3State;
  1130. u32 (vst3State, 1);
  1131. record (vst3State, 1, std::vector<std::uint8_t> (64, 0));
  1132. record (vst3State, 3, bytes ("COMPONENTE"));
  1133. record (vst3State, 2, bytes ("CONTROLADOR"));
  1134. u32 (blob, 12);
  1135. record (blob, 0x01, std::vector<std::uint8_t> (20, 0xFF));
  1136. record (blob, 0x32, { 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });
  1137. std::vector<std::uint8_t> cid;
  1138. for (int i = 0; i < 16; ++i)
  1139. cid.push_back ((std::uint8_t) (0xA0 + i));
  1140. record (blob, 0x34, cid);
  1141. record (blob, 0x36, bytes ("Surge XT"));
  1142. record (blob, 0x37, bytes ("C:/Program Files/Common Files/VST3/Surge XT.vst3"));
  1143. record (blob, 0x35, vst3State);
  1144. lynx::ForeignPlugin p;
  1145. CHECK (lynx::parseFlWrapper (blob, p));
  1146. CHECK (p.format == lynx::ForeignPlugin::Format::vst3);
  1147. CHECK (p.hasClassId && p.classId[0] == 0xA0 && p.classId[15] == 0xAF);
  1148. CHECK (p.name == "Surge XT" && p.path.find ("Surge XT.vst3") != std::string::npos);
  1149. std::vector<std::uint8_t> component, controller;
  1150. CHECK (lynx::splitFlVst3State (p.state, component, controller));
  1151. CHECK (component == bytes ("COMPONENTE") && controller == bytes ("CONTROLADOR"));
  1152. // versão fora da faixa ou sem tipo: não é um wrapper que dá para usar
  1153. blob[0] = 13;
  1154. CHECK (! lynx::parseFlWrapper (blob, p));
  1155. CHECK (! lynx::parseFlWrapper ({ 12, 0, 0, 0 }, p));
  1156. }
  1157. TEST (schedule_index_matches_full_scan)
  1158. {
  1159. // música aleatória (notas longas, swing, clips com offset); o agendamento com índice tem que dar
  1160. // exatamente os mesmos eventos que a varredura completa, inclusive no bloco que dá a volta
  1161. lynx::Song s = lynx::Song::makeDefault();
  1162. s.swing = 0.6f;
  1163. std::uint32_t seed = 12345;
  1164. auto rnd = [&] (int n) { seed = seed * 1664525u + 1013904223u; return (int) ((seed >> 8) % (std::uint32_t) n); };
  1165. s.patterns.resize (3);
  1166. for (auto& p : s.patterns)
  1167. {
  1168. p.notes.clear();
  1169. for (int i = 0; i < 60; ++i)
  1170. {
  1171. lynx::Note n;
  1172. n.start = rnd (16 * lynx::ppq);
  1173. n.length = rnd (5) == 0 ? rnd (12 * lynx::ppq) + 1 : rnd (lynx::ppq) + 1;
  1174. n.channel = rnd (4);
  1175. n.key = 40 + rnd (40);
  1176. n.slide = rnd (20) == 0;
  1177. p.notes.push_back (n);
  1178. }
  1179. p.sortNotes();
  1180. }
  1181. s.playlist.clear();
  1182. for (int i = 0; i < 12; ++i)
  1183. {
  1184. lynx::Clip c;
  1185. c.pattern = rnd (3);
  1186. c.track = rnd (4);
  1187. c.start = rnd (40) * lynx::ppq;
  1188. c.length = (rnd (12) + 1) * lynx::ppq;
  1189. c.offset = rnd (4) * lynx::ppq;
  1190. s.playlist.push_back (c);
  1191. }
  1192. s.mode = lynx::PlayMode::song;
  1193. const auto index = lynx::makeScheduleIndex (s);
  1194. const auto tps = lynx::ticksPerSample (140.0, 48000.0);
  1195. const auto loop = (double) s.songLength();
  1196. int mismatches = 0, events = 0;
  1197. for (int block = 0; block < 400; ++block)
  1198. {
  1199. const auto start = block == 0 ? loop - 100.0 * tps : (double) rnd ((int) loop * 2);
  1200. const auto samples = 64 + rnd (24000); // até ~1 tempo por bloco
  1201. lynx::EventBuffer a, b;
  1202. lynx::scheduleSong (s, start, samples, tps, a, false, nullptr);
  1203. lynx::scheduleSong (s, start, samples, tps, b, false, &index);
  1204. events += a.size();
  1205. if (a.size() != b.size())
  1206. {
  1207. ++mismatches;
  1208. continue;
  1209. }
  1210. for (int i = 0; i < a.size(); ++i)
  1211. {
  1212. const auto& x = *(a.begin() + i);
  1213. const auto& y = *(b.begin() + i);
  1214. mismatches += x.sampleOffset != y.sampleOffset || x.type != y.type || x.key != y.key || x.channel != y.channel;
  1215. }
  1216. }
  1217. CHECK (events > 500);
  1218. CHECK (mismatches == 0);
  1219. }
  1220. TEST (mixer_track_eq_defaults_and_boost)
  1221. {
  1222. // os padrões do FL: 90 Hz, 1,5 kHz e 8 kHz; Q do pico 0,632; inclinação das prateleiras 0,607
  1223. lynx::TrackEq eq;
  1224. CHECK (std::abs (lynx::TrackEq::peakQ (eq.width[1]) - 0.632) < 0.01);
  1225. CHECK (std::abs (lynx::TrackEq::shelfSlope (eq.width[0]) - 0.607) < 0.01);
  1226. CHECK (! eq.active());
  1227. // +12 dB no pico em 1,5 kHz numa trilha: um seno de 1,5 kHz sobe ~4x
  1228. lynx::Song song = lynx::Song::makeDefault();
  1229. song.mixer[1].eq.gainDb[1] = 12.0f;
  1230. for (auto& c : song.channels)
  1231. c.mixerTrack = 1;
  1232. song.channels[4].instrument = lynx::InstrumentKind::synth;
  1233. song.channels[4].synth = {};
  1234. song.channels[4].synth.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f };
  1235. song.channels[4].synth.cutoff = 20000.0f;
  1236. auto render = [] (const lynx::Song& s) {
  1237. auto state = lynx::RackState::build (s, nullptr, 48000.0);
  1238. lynx::RackRenderer renderer;
  1239. renderer.prepare (48000.0);
  1240. lynx::LiveEventQueue live;
  1241. lynx::NoteEvent on; // 1,5 kHz ~ tecla 90,6: usa a 91 (1568 Hz), ainda no pico largo
  1242. on.channel = 4;
  1243. on.key = 91;
  1244. on.velocity = 1.0f;
  1245. live.push (on);
  1246. std::vector<float> l (24000), r (24000);
  1247. for (int pos = 0; pos < 24000; pos += 480)
  1248. renderer.process (state.get(), false, 0.0, 480, l.data() + pos, r.data() + pos, pos == 0 ? &live : nullptr);
  1249. float peak = 0.0f;
  1250. for (std::size_t i = 12000; i < 24000; ++i)
  1251. peak = std::max (peak, std::abs (l[i]));
  1252. return peak;
  1253. };
  1254. const auto boosted = render (song);
  1255. song.mixer[1].eq.gainDb[1] = 0.0f;
  1256. const auto flat = render (song);
  1257. CHECK (flat > 0.01f);
  1258. CHECK (boosted / flat > 3.0f && boosted / flat < 4.2f);
  1259. }
  1260. TEST (bars_follow_time_signature_markers)
  1261. {
  1262. lynx::Song song;
  1263. song.beatsPerBar = 4;
  1264. const auto bar4 = (std::int64_t) lynx::ppq * 4;
  1265. auto bars = song.barsBetween (0, bar4 * 3);
  1266. CHECK (bars.size() == 3 && bars[2].tick == bar4 * 2 && bars[2].number == 3);
  1267. // 7/4 a partir do compasso 3, e 3/4 no meio de um compasso de 7 (corta e recomeça)
  1268. song.addMarker ({ bar4 * 2, "Verso", 7, 4 });
  1269. song.addMarker ({ bar4, "Nome só", 0, 4 });
  1270. const auto seven = (std::int64_t) lynx::ppq * 7;
  1271. song.addMarker ({ bar4 * 2 + seven + lynx::ppq * 2, "", 3, 4 });
  1272. bars = song.barsBetween (0, bar4 * 2 + seven * 2);
  1273. CHECK (bars.size() >= 5);
  1274. CHECK (bars[1].length == bar4 && bars[2].tick == bar4 * 2 && bars[2].length == seven);
  1275. CHECK (bars[3].length == lynx::ppq * 2); // cortado pela mudança
  1276. CHECK (bars[4].length == lynx::ppq * 3 && bars[4].number == 5);
  1277. CHECK (song.markers()[0].name == "Nome só"); // ordenados por tick
  1278. // de longe: começa no compasso certo sem perder a numeração
  1279. const auto far = song.barsBetween (lynx::ppq * 3000, lynx::ppq * 3001);
  1280. CHECK (far.size() == 1 && far[0].length == lynx::ppq * 3);
  1281. CHECK (song.barAt (lynx::ppq * 3000).number == far[0].number);
  1282. CHECK ((lynx::ppq * 3000 - far[0].tick) < far[0].length);
  1283. }
  1284. TEST (split_drum_channel_moves_notes_to_pads)
  1285. {
  1286. lynx::Song song = lynx::Song::makeDefault();
  1287. const auto channels = (int) song.channels.size();
  1288. song.patterns[0].notes.clear();
  1289. song.patterns[0].notes.push_back ({ 0, 240, 1, 36, 0.9f }); // kick do kit (canal 1)
  1290. song.patterns[0].notes.push_back ({ 240, 240, 1, 38, 0.8f }); // caixa
  1291. song.patterns[0].notes.push_back ({ 480, 240, 1, 50, 0.8f }); // tecla sem pad: some
  1292. song.patterns[0].notes.push_back ({ 480, 240, 3, 60, 0.8f }); // outro canal: anda 1 posição
  1293. lynx::Automation a;
  1294. a.target = { lynx::AutomationTargetKind::channelVolume, 3, 0, 0 };
  1295. song.automations.push_back (a);
  1296. std::vector<lynx::DrumPad> pads (2);
  1297. pads[0].name = "Kick";
  1298. pads[0].key = 36;
  1299. pads[0].layers = { { "kick.wav" } };
  1300. pads[1].name = "Snare";
  1301. pads[1].key = 38;
  1302. pads[1].layers = { { "snare soft.wav", 60, 0, 127, 0, 90 }, { "snare hard.wav", 60, 0, 127, 91, 127 } };
  1303. pads[1].cutGroup = 2;
  1304. lynx::splitDrumChannel (song, 1, pads);
  1305. CHECK ((int) song.channels.size() == channels + 1);
  1306. CHECK (song.channels[1].samplePath == "kick.wav" && song.channels[1].instrument == lynx::InstrumentKind::sampler);
  1307. CHECK (song.channels[2].zones.size() == 2 && song.channels[2].cutGroup == song.channels[2].cutBy && song.channels[2].cutGroup != 0);
  1308. const auto& notes = song.patterns[0].notes;
  1309. CHECK (notes.size() == 3);
  1310. CHECK (notes[0].channel == 1 && notes[0].key == 60);
  1311. CHECK (notes[1].channel == 2 && notes[1].key == 60);
  1312. CHECK (notes[2].channel == 4); // o antigo canal 3
  1313. CHECK (song.automations[0].target.index == 4);
  1314. }
  1315. TEST (flp_import_brings_playlist)
  1316. {
  1317. flp::Project p;
  1318. p.header.ppq = 96;
  1319. p.channels = { { 0, flp::ChannelType::sampler, "Kick", "", "", 1 } };
  1320. flp::Pattern empty;
  1321. empty.index = 1;
  1322. flp::Pattern full;
  1323. full.index = 2;
  1324. flp::Note n;
  1325. n.channel = 0;
  1326. full.notes.push_back (n);
  1327. p.patterns = { empty, full };
  1328. flp::Arrangement a;
  1329. flp::PlaylistItem item;
  1330. item.kind = flp::PlaylistItem::Kind::pattern;
  1331. item.index = 2;
  1332. item.position = 384;
  1333. item.length = 192;
  1334. item.track = 3;
  1335. item.patternStartTick = 96;
  1336. a.items.push_back (item);
  1337. item.index = 1; // pattern vazia: descartada
  1338. a.items.push_back (item);
  1339. item.kind = flp::PlaylistItem::Kind::channelClip; // áudio: ainda não suportado
  1340. a.items.push_back (item);
  1341. p.arrangements.push_back (a);
  1342. const auto s = lynx::importFlp (p);
  1343. CHECK (s.mode == lynx::PlayMode::song);
  1344. CHECK (s.playlist.size() == 1);
  1345. CHECK (s.playlist[0].pattern == 0 && s.playlist[0].track == 3);
  1346. CHECK (s.playlist[0].start == 4 * lynx::ppq && s.playlist[0].length == 2 * lynx::ppq && s.playlist[0].offset == lynx::ppq);
  1347. }
  1348. TEST (rack_releases_notes_on_position_jump)
  1349. {
  1350. lynx::Song s;
  1351. lynx::ChannelDef c;
  1352. c.instrument = lynx::InstrumentKind::synth;
  1353. s.channels.push_back (c);
  1354. auto& p = s.patterns.emplace_back();
  1355. lynx::Note n;
  1356. n.start = 0;
  1357. n.length = 4 * lynx::ppq; // nota longa
  1358. p.notes.push_back (n);
  1359. s.bpm = 120.0;
  1360. auto state = lynx::RackState::build (s, nullptr, 48000.0);
  1361. lynx::RackRenderer r;
  1362. r.prepare (48000.0);
  1363. std::vector<float> l (512), rr (512);
  1364. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  1365. double tick = 0.0;
  1366. for (int i = 0; i < 20; ++i, tick += 512 * tps)
  1367. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  1368. // salto para o tick 2000 (no meio da nota, sem "on" novo): o synth precisa calar
  1369. for (int i = 0; i < 40; ++i)
  1370. r.process (state.get(), true, 2000.0 + i * 512 * tps, 512, l.data(), rr.data());
  1371. float tail = 0.0f;
  1372. for (auto v : l)
  1373. tail = std::max (tail, std::abs (v));
  1374. CHECK (tail < 0.001f);
  1375. }
  1376. namespace
  1377. {
  1378. // Dois samplers de sinal constante 0,5 em inserts diferentes; retorna o pico da saída.
  1379. float juce_db (float gain)
  1380. {
  1381. return 20.0f * std::log10 (gain);
  1382. }
  1383. float renderMixerCase (const std::function<void (lynx::Song&)>& tweak, lynx::MeterBank* meters = nullptr)
  1384. {
  1385. lynx::Song s;
  1386. s.mixer = lynx::Song::defaultMixer (4);
  1387. for (int i = 0; i < 2; ++i)
  1388. {
  1389. lynx::ChannelDef c;
  1390. c.instrument = lynx::InstrumentKind::sampler;
  1391. c.samplePath = "dc";
  1392. c.volume = 1.0f;
  1393. c.mixerTrack = i + 1;
  1394. s.channels.push_back (c);
  1395. }
  1396. s.patterns.emplace_back();
  1397. tweak (s);
  1398. auto provider = [] (const std::string&) {
  1399. auto d = std::make_shared<lynx::SampleData>();
  1400. d->left.assign (48000, 0.5f);
  1401. return std::shared_ptr<const lynx::SampleData> (d);
  1402. };
  1403. auto state = lynx::RackState::build (s, nullptr, 48000.0, provider);
  1404. lynx::RackRenderer r;
  1405. r.prepare (48000.0, 256);
  1406. lynx::LiveEventQueue live;
  1407. for (int ch = 0; ch < 2; ++ch)
  1408. {
  1409. lynx::NoteEvent on;
  1410. on.channel = ch;
  1411. on.velocity = 1.0f;
  1412. live.push (on);
  1413. }
  1414. std::vector<float> l (1000), rr (1000); // maior que o bloco do mixer: testa os pedaços
  1415. r.process (state.get(), false, 0.0, 1000, l.data(), rr.data(), &live, meters);
  1416. return std::max (std::abs (l[999]), std::abs (rr[999]));
  1417. }
  1418. } // namespace
  1419. TEST (mixer_routes_mutes_solos_and_meters)
  1420. {
  1421. // dois canais de 0,5 somados no Master em 0 dB
  1422. CHECK (std::abs (renderMixerCase ([] (lynx::Song&) {}) - 1.0f) < 1e-4f);
  1423. // mute do insert 1: sobra só o canal 2
  1424. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.mixer[1].muted = true; }) - 0.5f) < 1e-4f);
  1425. // solo no insert 2: idem
  1426. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.mixer[2].solo = true; }) - 0.5f) < 1e-4f);
  1427. // curva do fader do FL: 0,8 = 0 dB, máximo ≈ +5,6 dB, metade do curso ≈ -12,7 dB
  1428. CHECK (std::abs (lynx::faderGain (0.8f) - 1.0f) < 1e-5f);
  1429. CHECK (std::abs (juce_db (lynx::faderGain (1.0f)) - 5.59f) < 0.05f);
  1430. CHECK (lynx::faderGain (0.0f) == 0.0f);
  1431. // fader do Master no máximo
  1432. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.mixer[0].volume = 1.0f; }) - lynx::faderGain (1.0f)) < 1e-4f);
  1433. // os dois canais no mesmo insert, insert com fader em 0,4
  1434. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) {
  1435. s.channels[1].mixerTrack = 1;
  1436. s.mixer[1].volume = 0.4f;
  1437. }) - lynx::faderGain (0.4f)) < 1e-4f);
  1438. // rota fora do mixer cai no último insert existente, sem travar
  1439. CHECK (renderMixerCase ([] (lynx::Song& s) { s.channels[0].mixerTrack = 100; }) > 0.9f);
  1440. // sem mixer: tudo direto na saída em 0 dB
  1441. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.mixer.clear(); }) - 1.0f) < 1e-4f);
  1442. lynx::MeterBank meters;
  1443. renderMixerCase ([] (lynx::Song&) {}, &meters);
  1444. CHECK (std::abs (meters.takePeak (1, 0) - 0.5f) < 1e-4f);
  1445. CHECK (std::abs (meters.takePeak (0, 1) - 1.0f) < 1e-4f);
  1446. CHECK (meters.takePeak (1, 0) == 0.0f); // ler zera
  1447. CHECK (meters.takePeak (3, 0) == 0.0f); // insert sem canal
  1448. }
  1449. TEST (next_free_insert_and_flp_mixer_import)
  1450. {
  1451. auto s = lynx::Song::makeDefault();
  1452. CHECK (s.mixer.size() == 17 && s.mixer[0].name == "Master");
  1453. CHECK (s.nextFreeInsert() == 6); // os 5 canais padrão ocupam 1..5
  1454. flp::Project p;
  1455. p.channels = { { 0, flp::ChannelType::sampler, "Kick", "", "", 30 } };
  1456. p.mixer = { { 0, "" }, { 30, "Drums" } };
  1457. const auto song = lynx::importFlp (p);
  1458. CHECK (song.channels[0].mixerTrack == 30);
  1459. CHECK (song.mixer.size() == 31);
  1460. CHECK (song.mixer[30].name == "Drums" && song.mixer[0].name == "Master");
  1461. }
  1462. namespace
  1463. {
  1464. float runEffectOnSine (lynx::EffectKind kind, const std::function<void (lynx::EffectSlot&)>& tweak, double hz, float amp,
  1465. int frames = 48000)
  1466. {
  1467. auto fx = lynx::makeEffect (kind);
  1468. fx->prepare (48000.0);
  1469. auto slot = lynx::makeEffectSlot (kind);
  1470. tweak (slot);
  1471. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  1472. for (int i = 0; i < frames; ++i)
  1473. l[(std::size_t) i] = r[(std::size_t) i] = amp * (float) std::sin (6.283185307 * hz * i / 48000.0);
  1474. for (int i = 0; i < frames; i += 480)
  1475. fx->process (l.data() + i, r.data() + i, std::min (480, frames - i), slot.params, 120.0);
  1476. float peak = 0.0f;
  1477. for (int i = frames / 2; i < frames; ++i) // segunda metade: já estabilizado
  1478. {
  1479. CHECK (std::isfinite (l[(std::size_t) i]));
  1480. peak = std::max (peak, std::abs (l[(std::size_t) i]));
  1481. }
  1482. return peak;
  1483. }
  1484. } // namespace
  1485. TEST (parametric_eq_bands_and_response)
  1486. {
  1487. // padrão: transparente
  1488. auto slot = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  1489. CHECK (std::abs (lynx::peq::responseDb (slot.params, 48000.0, 1000.0)) < 0.01);
  1490. CHECK (std::abs (runEffectOnSine (lynx::EffectKind::parametricEq, [] (auto&) {}, 1000.0, 0.5f) - 0.5f) < 0.005f);
  1491. // pico de +12 dB em 1 kHz na banda 4: a resposta e o sinal concordam
  1492. auto boost = [] (lynx::EffectSlot& s) {
  1493. s.params[(std::size_t) lynx::peq::param (3, 1)] = lynx::peq::hzValue (1000.0);
  1494. s.params[(std::size_t) lynx::peq::param (3, 2)] = lynx::peq::gainValue (12.0);
  1495. };
  1496. boost (slot);
  1497. CHECK (std::abs (lynx::peq::responseDb (slot.params, 48000.0, 1000.0) - 12.0) < 0.2);
  1498. CHECK (std::abs (lynx::peq::responseDb (slot.params, 48000.0, 100.0)) < 1.0);
  1499. const auto peak = runEffectOnSine (lynx::EffectKind::parametricEq, boost, 1000.0, 0.1f);
  1500. CHECK (std::abs (peak - 0.1f * std::pow (10.0f, 12.0f / 20.0f)) < 0.01f);
  1501. // corta graves a 48 dB/oit em 200 Hz: 50 Hz (2 oitavas abaixo) cai ~96 dB; 2 kHz passa
  1502. auto cut = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  1503. cut.params[(std::size_t) lynx::peq::param (0, 0)] = lynx::peq::typeValue (lynx::peq::BandType::lowCut);
  1504. cut.params[(std::size_t) lynx::peq::param (0, 1)] = lynx::peq::hzValue (200.0);
  1505. cut.params[(std::size_t) lynx::peq::param (0, 3)] = lynx::peq::qValue (0.70710678); // Butterworth
  1506. cut.params[(std::size_t) (lynx::peq::slopeParam + 0)] = 1.0f;
  1507. CHECK (lynx::peq::responseDb (cut.params, 48000.0, 50.0) < -80.0);
  1508. CHECK (std::abs (lynx::peq::responseDb (cut.params, 48000.0, 200.0) + 3.0) < 0.5); // -3 dB no corte (Butterworth)
  1509. CHECK (std::abs (lynx::peq::responseDb (cut.params, 48000.0, 2000.0)) < 0.1);
  1510. // conversões ida e volta
  1511. CHECK (std::abs (lynx::peq::hz (lynx::peq::hzValue (440.0)) - 440.0) < 0.5);
  1512. CHECK (std::abs (lynx::peq::q (lynx::peq::qValue (2.5)) - 2.5) < 0.01);
  1513. CHECK (lynx::peq::type (lynx::peq::typeValue (lynx::peq::BandType::notch)) == lynx::peq::BandType::notch);
  1514. }
  1515. TEST (fl_parametric_eq2_state_maps_to_bands)
  1516. {
  1517. // blob v8: banda 1 corta graves a 100 Hz "Steep 8", banda 4 pico +6 dB em 1 kHz, saída −3 dB
  1518. std::vector<std::uint8_t> blob (354, 0);
  1519. auto put = [&] (std::size_t off, std::int32_t v) { std::memcpy (blob.data() + off, &v, 4); };
  1520. put (0, 8);
  1521. auto param = [&] (int i, std::int32_t v) { put (4 + 4 * (std::size_t) i, v); };
  1522. auto hzRaw = [] (double hz) { return (std::int32_t) std::lround (std::log (hz / 20.0) / std::log (1000.0) * 65536.0); };
  1523. for (int b = 0; b < 7; ++b)
  1524. param (21 + b, 0); // tudo desligado
  1525. param (21 + 0, 3); // high pass (= corta graves)
  1526. param (7 + 0, hzRaw (100.0));
  1527. param (14 + 0, 40124); // largura padrão -> Q ~0,68
  1528. param (28 + 0, -3); // Steep 8 -> 4 biquads
  1529. param (21 + 3, 6); // peaking
  1530. param (7 + 3, hzRaw (1000.0));
  1531. param (3, 600); // +6 dB
  1532. param (14 + 3, 25412);
  1533. param (35, -300); // main level −3 dB
  1534. put (0x13E, 0x7F);
  1535. const auto slot = lynx::effectFromFl ("Fruity Parametric EQ 2", blob);
  1536. CHECK (slot.has_value() && slot->kind == lynx::EffectKind::parametricEq);
  1537. const auto& p = slot->params;
  1538. CHECK (lynx::peq::type (p[(std::size_t) lynx::peq::param (0, 0)]) == lynx::peq::BandType::lowCut);
  1539. CHECK (lynx::peq::slopeStages (p[(std::size_t) lynx::peq::slopeParam]) == 4);
  1540. CHECK (lynx::peq::type (p[(std::size_t) lynx::peq::param (3, 0)]) == lynx::peq::BandType::peak);
  1541. CHECK (lynx::peq::type (p[(std::size_t) lynx::peq::param (1, 0)]) == lynx::peq::BandType::off);
  1542. CHECK (std::abs (lynx::peq::responseDb (p, 48000.0, 1000.0) - 3.0) < 0.3); // +6 do pico −3 da saída
  1543. CHECK (lynx::peq::responseDb (p, 48000.0, 30.0) < -40.0); // 48 dB/oit abaixo de 100 Hz
  1544. CHECK (std::abs (lynx::peq::responseDb (p, 48000.0, 8000.0) + 3.0) < 0.3);
  1545. // banda mutada pela máscara não soa
  1546. put (0x13E, 0x7F & ~(1 << 3));
  1547. const auto muted = lynx::effectFromFl ("Fruity Parametric EQ 2", blob);
  1548. CHECK (lynx::peq::type (muted->params[(std::size_t) lynx::peq::param (3, 0)]) == lynx::peq::BandType::off);
  1549. }
  1550. TEST (reverb_low_cut_and_predelay)
  1551. {
  1552. // impulso: com predelay de 100 ms o molhado só começa depois; com corte de graves em 3 kHz um
  1553. // seno de 100 Hz quase não entra no reverb
  1554. auto run = [] (const std::function<void (lynx::EffectSlot&)>& tweak, double hz, bool impulse) {
  1555. auto fx = lynx::makeEffect (lynx::EffectKind::reverb);
  1556. fx->prepare (48000.0);
  1557. auto slot = lynx::makeEffectSlot (lynx::EffectKind::reverb);
  1558. slot.params[4] = 0.0f; // só o molhado
  1559. slot.params[3] = 1.0f;
  1560. tweak (slot);
  1561. std::vector<float> l (48000), r (48000);
  1562. for (int i = 0; i < 48000; ++i)
  1563. 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);
  1564. for (int i = 0; i < 48000; i += 480)
  1565. fx->process (l.data() + i, r.data() + i, 480, slot.params, 120.0);
  1566. return l;
  1567. };
  1568. const auto delayed = run ([] (auto& s) { s.params[7] = 0.1f; }, 0.0, true);
  1569. float early = 0.0f, later = 0.0f;
  1570. for (std::size_t i = 0; i < 4800; ++i)
  1571. early = std::max (early, std::abs (delayed[i]));
  1572. for (std::size_t i = 4800; i < 24000; ++i)
  1573. later = std::max (later, std::abs (delayed[i]));
  1574. CHECK (early == 0.0f && later > 0.0f);
  1575. 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; };
  1576. const auto open = energy (run ([] (auto&) {}, 100.0, false));
  1577. const auto cut = energy (run ([] (auto& s) { s.params[5] = 1.0f; }, 100.0, false));
  1578. CHECK (cut < open * 0.01);
  1579. }
  1580. TEST (utility_effect_and_fl_stereo_tools)
  1581. {
  1582. // padrão transparente; balanço todo à direita cala a esquerda
  1583. CHECK (std::abs (runEffectOnSine (lynx::EffectKind::utility, [] (auto&) {}, 440.0, 0.5f) - 0.5f) < 0.001f);
  1584. CHECK (runEffectOnSine (lynx::EffectKind::utility, [] (auto& s) { s.params[1] = 1.0f; }, 440.0, 0.5f) < 0.001f);
  1585. // Stereo Shaper em "mono": cada saída = 0,5 L + 0,5 R
  1586. std::vector<std::uint8_t> blob (36, 0);
  1587. auto put = [&] (std::size_t off, std::int32_t v) { std::memcpy (blob.data() + off, &v, 4); };
  1588. put (4, 6400); put (8, 6400); put (12, 6400); put (16, 6400);
  1589. const auto slot = lynx::effectFromFl ("Fruity Stereo Shaper", blob);
  1590. CHECK (slot && slot->kind == lynx::EffectKind::utility);
  1591. auto fx = lynx::makeEffect (lynx::EffectKind::utility);
  1592. float l = 1.0f, r = 0.0f;
  1593. fx->process (&l, &r, 1, slot->params, 120.0);
  1594. CHECK (std::abs (l - 0.5f) < 1e-4f && std::abs (r - 0.5f) < 1e-4f);
  1595. // Balance: volume 256 = 0 dB, pan −128 = toda à esquerda
  1596. std::vector<std::uint8_t> bal (8, 0);
  1597. std::int32_t pan = -128, vol = 256;
  1598. std::memcpy (bal.data(), &pan, 4);
  1599. std::memcpy (bal.data() + 4, &vol, 4);
  1600. const auto b = lynx::effectFromFl ("Fruity Balance", bal);
  1601. l = 0.5f; r = 0.5f;
  1602. fx->process (&l, &r, 1, b->params, 120.0);
  1603. CHECK (std::abs (l - 0.5f) < 1e-3f && std::abs (r) < 1e-4f);
  1604. }
  1605. TEST (effects_eq_compressor_behave)
  1606. {
  1607. // EQ no padrão é transparente
  1608. CHECK (std::abs (runEffectOnSine (lynx::EffectKind::eq, [] (auto&) {}, 1000.0, 0.5f) - 0.5f) < 0.01f);
  1609. // +18 dB nos graves: 60 Hz sobe bastante, 5 kHz quase nada
  1610. CHECK (runEffectOnSine (lynx::EffectKind::eq, [] (auto& s) { s.params[0] = 1.0f; }, 60.0, 0.05f) > 0.3f);
  1611. CHECK (runEffectOnSine (lynx::EffectKind::eq, [] (auto& s) { s.params[0] = 1.0f; }, 5000.0, 0.05f) < 0.06f);
  1612. // compressor: threshold -20 dB, ratio 20:1 achata um sinal de 0 dBFS para perto do threshold
  1613. const auto squashed = runEffectOnSine (lynx::EffectKind::compressor, [] (auto& s) {
  1614. s.params[0] = 40.0f / 60.0f;
  1615. s.params[1] = 1.0f;
  1616. }, 200.0, 1.0f);
  1617. CHECK (squashed < 0.2f && squashed > 0.05f);
  1618. // sinal abaixo do threshold passa intacto
  1619. CHECK (std::abs (runEffectOnSine (lynx::EffectKind::compressor, [] (auto& s) { s.params[0] = 1.0f; }, 200.0, 0.3f) - 0.3f) < 0.01f);
  1620. }
  1621. TEST (effects_delay_echoes_on_tempo_and_reverb_has_tail)
  1622. {
  1623. auto delay = lynx::makeEffect (lynx::EffectKind::delay);
  1624. delay->prepare (48000.0);
  1625. auto slot = lynx::makeEffectSlot (lynx::EffectKind::delay);
  1626. slot.params[0] = 3.5f / 8.0f; // índice 3 = 1/4 = 0,5 s a 120 BPM
  1627. slot.params[1] = 0.0f; // sem feedback: um eco só
  1628. slot.params[2] = 1.0f;
  1629. slot.params[4] = 0.0f; // sem abafar
  1630. std::vector<float> l (48000, 0.0f), r (48000, 0.0f);
  1631. l[0] = r[0] = 1.0f;
  1632. delay->process (l.data(), r.data(), 48000, slot.params, 120.0);
  1633. CHECK (std::abs (l[24000] - 1.0f) < 1e-4f);
  1634. CHECK (std::abs (l[12000]) < 1e-6f);
  1635. auto reverb = lynx::makeEffect (lynx::EffectKind::reverb);
  1636. reverb->prepare (48000.0);
  1637. auto rs = lynx::makeEffectSlot (lynx::EffectKind::reverb);
  1638. rs.params[3] = 1.0f;
  1639. std::fill (l.begin(), l.end(), 0.0f);
  1640. std::fill (r.begin(), r.end(), 0.0f);
  1641. l[0] = r[0] = 1.0f;
  1642. reverb->process (l.data(), r.data(), 48000, rs.params, 120.0);
  1643. float tail = 0.0f;
  1644. for (int i = 4800; i < 9600; ++i) // entre 100 e 200 ms depois do impulso
  1645. tail = std::max (tail, std::abs (l[(std::size_t) i]));
  1646. CHECK (tail > 1e-4f && tail < 1.0f);
  1647. CHECK (lynx::formatEffectParam (lynx::EffectKind::delay, 0, slot.params[0], 120.0) == "1/4 (500 ms)");
  1648. }
  1649. TEST (rack_runs_insert_effects_and_reuses_them)
  1650. {
  1651. // insert com EQ a -inf não existe; usamos a saída do EQ em -18 dB para ver o efeito agir
  1652. const auto quiet = renderMixerCase ([] (lynx::Song& s) {
  1653. auto eq = lynx::makeEffectSlot (lynx::EffectKind::eq);
  1654. eq.params[4] = 0.0f; // saída -18 dB
  1655. s.mixer[1].effects.push_back (eq);
  1656. });
  1657. CHECK (quiet > 0.55f && quiet < 0.6f); // 0,5 do canal 2 + 0,5 * 0,126 do canal 1
  1658. const auto bypassed = renderMixerCase ([] (lynx::Song& s) {
  1659. auto eq = lynx::makeEffectSlot (lynx::EffectKind::eq);
  1660. eq.params[4] = 0.0f;
  1661. eq.enabled = false;
  1662. s.mixer[1].effects.push_back (eq);
  1663. });
  1664. CHECK (std::abs (bypassed - 1.0f) < 1e-4f);
  1665. auto s = lynx::Song::makeDefault();
  1666. s.mixer[2].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::reverb));
  1667. auto a = lynx::RackState::build (s, nullptr, 48000.0);
  1668. s.mixer[2].effects[0].params[0] = 0.9f; // mexer num knob não recria o efeito
  1669. auto b = lynx::RackState::build (s, a.get(), 48000.0);
  1670. CHECK (b->effects[2][0] == a->effects[2][0]);
  1671. s.mixer[2].effects[0] = lynx::makeEffectSlot (lynx::EffectKind::delay);
  1672. auto c = lynx::RackState::build (s, b.get(), 48000.0);
  1673. CHECK (c->effects[2][0] != b->effects[2][0]);
  1674. }
  1675. TEST (audio_clips_trigger_cut_and_resume)
  1676. {
  1677. lynx::Song s;
  1678. s.bpm = 120.0; // 1 tempo = 0,5 s = 24000 samples a 48 kHz
  1679. lynx::ChannelDef c;
  1680. c.instrument = lynx::InstrumentKind::audioClip;
  1681. c.samplePath = "ramp";
  1682. c.volume = 1.0f;
  1683. s.channels.push_back (c);
  1684. s.patterns.emplace_back();
  1685. lynx::Clip clip;
  1686. clip.kind = lynx::ClipKind::audio;
  1687. clip.channel = 0;
  1688. clip.start = lynx::ppq; // começa no tempo 2
  1689. clip.length = 2 * lynx::ppq; // dura 2 tempos
  1690. clip.offset = lynx::ppq; // pula o primeiro tempo do áudio
  1691. s.playlist.push_back (clip);
  1692. s.mode = lynx::PlayMode::song;
  1693. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  1694. lynx::EventBuffer ev;
  1695. lynx::scheduleSong (s, 0.0, 4 * 24000, tps, ev);
  1696. CHECK (ev.size() == 2);
  1697. CHECK (ev[0].type == lynx::NoteEvent::Type::on && ev[0].sampleOffset == 24000 && std::abs (ev[0].startSeconds - 0.5) < 1e-9);
  1698. CHECK (ev[1].type == lynx::NoteEvent::Type::off && ev[1].sampleOffset == 3 * 24000);
  1699. // seek para o meio do clip (tempo 2,5): com resume, começa no primeiro sample do bloco
  1700. ev.clear();
  1701. lynx::scheduleSong (s, 1.5 * lynx::ppq, 256, tps, ev, true);
  1702. CHECK (ev.size() == 1 && ev[0].sampleOffset == 0 && std::abs (ev[0].startSeconds - 0.75) < 1e-9);
  1703. ev.clear();
  1704. lynx::scheduleSong (s, 1.5 * lynx::ppq, 256, tps, ev, false);
  1705. CHECK (ev.size() == 0);
  1706. // sample com valor = posição em segundos: dá para conferir de onde ele começou a tocar
  1707. auto provider = [] (const std::string&) {
  1708. auto d = std::make_shared<lynx::SampleData>();
  1709. d->sampleRate = 48000.0;
  1710. for (int i = 0; i < 48000 * 3; ++i)
  1711. d->left.push_back ((float) i / 48000.0f);
  1712. return std::shared_ptr<const lynx::SampleData> (d);
  1713. };
  1714. auto state = lynx::RackState::build (s, nullptr, 48000.0, provider);
  1715. lynx::RackRenderer r;
  1716. r.prepare (48000.0, 512);
  1717. std::vector<float> l (256), rr (256);
  1718. // primeiro bloco tocando já no meio do clip
  1719. r.process (state.get(), true, 1.5 * lynx::ppq, 256, l.data(), rr.data());
  1720. CHECK (std::abs (l[0] - 0.75f) < 0.001f);
  1721. // o clip acaba no tempo 3: depois do fade curto, silêncio (o sample ainda teria áudio)
  1722. double tick = 3.0 * lynx::ppq - 10 * tps;
  1723. r.process (state.get(), false, tick, 256, l.data(), rr.data()); // para (fade)
  1724. for (int i = 0; i < 4; ++i)
  1725. r.process (state.get(), false, tick, 256, l.data(), rr.data());
  1726. CHECK (std::abs (l[255]) < 1e-6f);
  1727. }
  1728. TEST (remove_channel_fixes_notes_and_audio_clips)
  1729. {
  1730. lynx::Song s;
  1731. s.channels.resize (3);
  1732. s.patterns.resize (1);
  1733. s.patterns[0].notes = { { 0, 240, 0, 60, 1.0f }, { 0, 240, 1, 60, 1.0f }, { 0, 240, 2, 60, 1.0f } };
  1734. lynx::Clip a;
  1735. a.kind = lynx::ClipKind::audio;
  1736. a.channel = 1;
  1737. a.length = 100;
  1738. lynx::Clip b = a;
  1739. b.channel = 2;
  1740. s.playlist = { a, b };
  1741. s.removeChannel (1);
  1742. CHECK (s.channels.size() == 2);
  1743. CHECK (s.patterns[0].notes.size() == 2 && s.patterns[0].notes[1].channel == 1);
  1744. CHECK (s.playlist.size() == 1 && s.playlist[0].channel == 1);
  1745. }
  1746. TEST (flp_import_audio_clips_with_offsets)
  1747. {
  1748. flp::Project p;
  1749. p.header.ppq = 96;
  1750. p.tempo = 120.0;
  1751. p.channels = { { 0, flp::ChannelType::audioClip, "Vocal", "", "%FLStudioData%\\v.wav", 2 },
  1752. { 1, flp::ChannelType::audioClip, "Loop", "", "%FLStudioData%\\l.wav", 3 } };
  1753. flp::Arrangement arr;
  1754. flp::PlaylistItem beats; // offset em tempos: fim - início = duração em tempos
  1755. beats.kind = flp::PlaylistItem::Kind::channelClip;
  1756. beats.index = 0;
  1757. beats.position = 192;
  1758. beats.length = 384; // 4 tempos
  1759. beats.startOffset = 2.0f;
  1760. beats.endOffset = 6.0f;
  1761. flp::PlaylistItem ms = beats; // offset em ms: 4 tempos a 120 BPM = 2000 ms
  1762. ms.index = 1;
  1763. ms.startOffset = 500.0f;
  1764. ms.endOffset = 2500.0f;
  1765. arr.items = { beats, ms };
  1766. p.arrangements.push_back (arr);
  1767. lynx::FlpImportOptions options;
  1768. options.roots = { "C:\\FL", "C:\\FL\\Data", "" };
  1769. options.fileExists = [] (const std::string&) { return true; };
  1770. const auto s = lynx::importFlp (p, options);
  1771. CHECK (s.channels.size() == 2 && s.channels[0].instrument == lynx::InstrumentKind::audioClip);
  1772. CHECK (s.channels[0].samplePath == "C:\\FL\\Data\\v.wav");
  1773. CHECK (s.playlist.size() == 2);
  1774. CHECK (s.playlist[0].kind == lynx::ClipKind::audio && s.playlist[0].start == 2 * lynx::ppq);
  1775. CHECK (s.playlist[0].offset == 2 * lynx::ppq);
  1776. CHECK (s.playlist[1].offset == lynx::ppq); // 500 ms a 120 BPM = 1 tempo
  1777. CHECK (s.mode == lynx::PlayMode::song);
  1778. }
  1779. TEST (plugin_factories_create_reuse_and_fallback)
  1780. {
  1781. lynx::Song s;
  1782. s.mixer = lynx::Song::defaultMixer (2);
  1783. lynx::ChannelDef c;
  1784. c.instrument = lynx::InstrumentKind::plugin;
  1785. c.plugin.id = "VST3-Synth-123";
  1786. c.mixerTrack = 1;
  1787. s.channels.push_back (c);
  1788. lynx::ChannelDef missing = c;
  1789. missing.plugin.id = "VST3-Ausente-0";
  1790. s.channels.push_back (missing);
  1791. lynx::EffectSlot fx;
  1792. fx.kind = lynx::EffectKind::plugin;
  1793. fx.plugin.id = "VST3-Reverb-9";
  1794. s.mixer[1].effects.push_back (fx);
  1795. s.patterns.emplace_back();
  1796. int instrumentsMade = 0, effectsMade = 0;
  1797. lynx::RackState::Factories f;
  1798. f.pluginInstruments = [&] (const lynx::PluginRef& ref, double) -> std::shared_ptr<lynx::Instrument> {
  1799. if (ref.id != "VST3-Synth-123")
  1800. return nullptr;
  1801. ++instrumentsMade;
  1802. auto synth = lynx::makeInstrument (lynx::InstrumentKind::synth);
  1803. synth->prepare (48000.0);
  1804. return synth;
  1805. };
  1806. f.pluginEffects = [&] (const lynx::PluginRef&, double) -> std::shared_ptr<lynx::Effect> {
  1807. ++effectsMade;
  1808. auto eq = lynx::makeEffect (lynx::EffectKind::eq);
  1809. eq->prepare (48000.0);
  1810. return eq;
  1811. };
  1812. auto a = lynx::RackState::build (s, nullptr, 48000.0, f);
  1813. CHECK (instrumentsMade == 1 && effectsMade == 1);
  1814. CHECK (a->instruments.size() == 2 && a->instruments[1] != nullptr); // ausente: mudo, mas existe
  1815. // mudar o estado salvo não recria; trocar o plugin recria
  1816. s.channels[0].plugin.state = "abc";
  1817. auto b = lynx::RackState::build (s, a.get(), 48000.0, f);
  1818. CHECK (instrumentsMade == 1 && b->instruments[0] == a->instruments[0] && b->effects[1][0] == a->effects[1][0]);
  1819. s.mixer[1].effects[0].plugin.id = "VST3-Outro-1";
  1820. auto c2 = lynx::RackState::build (s, b.get(), 48000.0, f);
  1821. CHECK (effectsMade == 2);
  1822. // renderizar com plugin ausente e slot de plugin não quebra nada
  1823. lynx::RackRenderer r;
  1824. r.prepare (48000.0, 256);
  1825. lynx::LiveEventQueue live;
  1826. lynx::NoteEvent on;
  1827. on.channel = 0;
  1828. on.velocity = 1.0f;
  1829. live.push (on);
  1830. on.channel = 1;
  1831. live.push (on);
  1832. std::vector<float> l (256), rr (256);
  1833. r.process (c2.get(), false, 0.0, 256, l.data(), rr.data(), &live);
  1834. float peak = 0.0f;
  1835. for (auto v : l)
  1836. {
  1837. CHECK (std::isfinite (v));
  1838. peak = std::max (peak, std::abs (v));
  1839. }
  1840. CHECK (peak > 0.0f);
  1841. }
  1842. TEST (export_song_adds_silent_tail_and_never_restarts)
  1843. {
  1844. auto s = lynx::Song::makeDefault();
  1845. s.playlist.clear();
  1846. std::int64_t length = 0;
  1847. auto pat = lynx::makeExportSong (s, true, lynx::ppq * 8, length); // Playlist vazia: usa a pattern
  1848. CHECK (length == lynx::ppq * 4);
  1849. CHECK (pat.mode == lynx::PlayMode::song && pat.playlist.size() == 2);
  1850. CHECK (pat.songLength() >= length + lynx::ppq * 8);
  1851. // nenhuma nota nova depois do fim da música, só silêncio até o fim da cauda
  1852. lynx::EventBuffer events;
  1853. const auto tps = lynx::ticksPerSample (pat.bpm, 48000.0);
  1854. int onsAfterEnd = 0, onsBefore = 0;
  1855. for (double tick = 0.0; tick < (double) (length + lynx::ppq * 8); tick += 512 * tps)
  1856. {
  1857. events.clear();
  1858. lynx::scheduleSong (pat, tick, 512, tps, events);
  1859. for (const auto& e : events)
  1860. if (e.type == lynx::NoteEvent::Type::on)
  1861. (tick + e.sampleOffset * tps >= (double) length ? onsAfterEnd : onsBefore)++;
  1862. }
  1863. CHECK (onsBefore == (int) s.patterns[0].notes.size());
  1864. CHECK (onsAfterEnd == 0);
  1865. // com Playlist: o fim é o do último clip, sem arredondar
  1866. s.playlist.push_back ({ 0, 0, lynx::ppq * 2, lynx::ppq * 3, 0 });
  1867. auto song = lynx::makeExportSong (s, true, 0, length);
  1868. CHECK (length == lynx::ppq * 5 && song.playlist.size() == 1);
  1869. song = lynx::makeExportSong (s, false, 0, length);
  1870. CHECK (length == lynx::ppq * 4 && song.playlist[0].start == 0);
  1871. }
  1872. TEST (note_edit_selection_operations)
  1873. {
  1874. namespace ne = lynx::noteedit;
  1875. lynx::Pattern p;
  1876. p.notes = { { 0, 240, 0, 60 }, { 480, 240, 0, 64 }, { 960, 480, 1, 67 } };
  1877. // ordenar acompanha os índices
  1878. p.notes[0].start = 1200;
  1879. std::vector<int> tracked { 0, 2 };
  1880. ne::sortTracking (p, tracked);
  1881. CHECK (p.notes[2].start == 1200 && p.notes[(std::size_t) tracked[0]].start == 1200);
  1882. CHECK (p.notes[(std::size_t) tracked[1]].key == 67);
  1883. // mover em grupo respeita os limites
  1884. std::int64_t dt = -5000;
  1885. int dk = 100;
  1886. ne::move (p, { 0, 1 }, dt, dk);
  1887. CHECK (dt == -480 && dk == 127 - 67 && p.notes[0].start == 0 && p.notes[1].key == 127);
  1888. // duplicar: logo depois do trecho, arredondado à grade
  1889. lynx::Pattern q;
  1890. q.notes = { { 0, 240, 0, 60 }, { 240, 300, 0, 62 } }; // trecho de 540 ticks
  1891. const auto added = ne::duplicate (q, { 0, 1 }, 960);
  1892. CHECK (added.size() == 2 && q.notes[(std::size_t) added[0]].start == 960 && q.notes[(std::size_t) added[1]].start == 1200);
  1893. // colar em outro canal com deslocamento
  1894. const auto pasted = ne::paste (q, ne::copy (q, { 1 }), 100, 3);
  1895. CHECK (pasted.size() == 1 && q.notes.back().channel == 3 && q.notes.back().start == 340);
  1896. // quantizar arredonda para o mais próximo
  1897. q.notes[0].start = 130;
  1898. q.notes[1].start = 100;
  1899. ne::quantize (q, { 0, 1 }, 240);
  1900. CHECK (q.notes[0].start == 240 && q.notes[1].start == 0);
  1901. // remover vários (ordem e repetidos não importam)
  1902. const auto before = q.notes.size();
  1903. ne::remove (q, { 1, 0, 1 });
  1904. CHECK (q.notes.size() == before - 2);
  1905. }
  1906. TEST (recorder_builds_notes_in_pattern_and_song_mode)
  1907. {
  1908. auto song = lynx::Song::makeDefault();
  1909. const auto loop = song.patterns[0].effectiveLength (4); // 1 compasso = 3840
  1910. lynx::NoteRecorder r;
  1911. r.add (song, { 100.0, 4, 60, 0.5f, true }); // sem tomada: ignorado
  1912. CHECK (r.takeFinished().empty());
  1913. r.begin (loop);
  1914. r.add (song, { 4000.0, 4, 60, 0.5f, true }); // segunda volta do loop
  1915. r.add (song, { 4480.0, 4, 60, 0.0f, false });
  1916. r.add (song, { 5000.0, 4, 64, 0.9f, true }); // presa até parar
  1917. r.end (song, 5240.0);
  1918. const auto notes = r.takeFinished();
  1919. CHECK (notes.size() == 2);
  1920. CHECK (notes[0].start == 4000 - 3840 && notes[0].length == 480 && notes[0].velocity == 0.5f && notes[0].channel == 4);
  1921. CHECK (notes[1].key == 64 && notes[1].start == 5000 - 3840 && notes[1].length == 240);
  1922. // modo song: posição dentro do clip da pattern atual (com offset)
  1923. song.mode = lynx::PlayMode::song;
  1924. song.playlist = { { 0, 0, 7680, 3840, 960 } };
  1925. CHECK (lynx::patternPositionForTick (song, 7680.0 + 100.0, loop) == 1060);
  1926. CHECK (lynx::patternPositionForTick (song, 100.0, loop) == 100); // fora do clip: como loop
  1927. }
  1928. TEST (automation_curve_and_playback)
  1929. {
  1930. lynx::Automation a;
  1931. a.points = { { 0, 0.0f }, { 960, 1.0f }, { 1920, 0.5f, 0.0f } };
  1932. CHECK (a.valueAt (-10.0) == 0.0f && a.valueAt (480.0) == 0.5f && a.valueAt (5000.0) == 0.5f);
  1933. CHECK (a.length() == 1920);
  1934. a.points[0].tension = 1.0f; // curva: começa devagar
  1935. CHECK (a.valueAt (480.0) < 0.2f && a.valueAt (480.0) > 0.0f);
  1936. // Master automatizado: silêncio no primeiro compasso, som no segundo, e o último valor
  1937. // fica valendo depois do fim do clip de automação
  1938. auto song = lynx::Song::makeDefault();
  1939. song.bpm = 120.0;
  1940. song.mode = lynx::PlayMode::song;
  1941. const auto bar = (std::int64_t) lynx::ppq * 4;
  1942. for (int b = 0; b < 3; ++b)
  1943. song.playlist.push_back ({ 0, 0, bar * b, bar, 0 });
  1944. lynx::Automation master;
  1945. master.target = { lynx::AutomationTargetKind::mixerVolume, 0 };
  1946. master.points = { { 0, 0.0f }, { bar - 1, 0.0f }, { bar, 0.8f } };
  1947. song.automations.push_back (master);
  1948. lynx::Clip ac;
  1949. ac.kind = lynx::ClipKind::automation;
  1950. ac.automation = 0;
  1951. ac.track = 1;
  1952. ac.length = bar + bar / 2;
  1953. song.playlist.push_back (ac);
  1954. const double sr = 48000.0;
  1955. auto state = lynx::RackState::build (song, nullptr, sr);
  1956. CHECK (state->hasAutomation && state->mixerVolumeAuto[0] == 0 && state->automationClips[0].size() == 1);
  1957. lynx::RackRenderer r;
  1958. r.prepare (sr, 512);
  1959. std::vector<float> l (512), rr (512);
  1960. const auto tps = lynx::ticksPerSample (song.bpm, sr);
  1961. float peakBar1 = 0.0f, peakBar2 = 0.0f, peakBar3 = 0.0f;
  1962. for (double tick = 0.0; tick < (double) (bar * 3); tick += 512 * tps)
  1963. {
  1964. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  1965. auto& peak = tick < (double) bar - 512 * tps ? peakBar1 : tick < (double) bar * 2 ? peakBar2 : peakBar3;
  1966. for (auto v : l)
  1967. peak = std::max (peak, std::abs (v));
  1968. }
  1969. CHECK (peakBar1 < 1.0e-6f);
  1970. CHECK (peakBar2 > 0.05f);
  1971. CHECK (peakBar3 > 0.05f); // depois do clip: segue no último valor
  1972. // alvo removido: automação some das tabelas
  1973. song.removeChannel (0);
  1974. song.automations[0].target = { lynx::AutomationTargetKind::channelVolume, 0 };
  1975. song.removeChannel (0);
  1976. CHECK (song.automations[0].target.kind == lynx::AutomationTargetKind::none);
  1977. song.removeAutomation (0);
  1978. CHECK (song.automations.empty() && song.playlist.size() == 3);
  1979. }
  1980. TEST (mixer_sends_between_inserts)
  1981. {
  1982. // insert 1 vai só para o 3; o 3 vai ao Master: soma igual (0,5 + 0,5)
  1983. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.setRoute (1, 3, true); s.setRoute (1, 0, false); }) - 1.0f) < 1e-4f);
  1984. // envio a 50% e destino mudo
  1985. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.setRoute (1, 3, true, 0.5f); s.setRoute (1, 0, false); }) - 0.75f) < 1e-4f);
  1986. 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);
  1987. // indo ao Master e ao 3: o sinal dobra
  1988. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.setRoute (1, 3, true); }) - 1.5f) < 1e-4f);
  1989. // solo no 3 deixa soar quem chega nele (insert 1), mas não o 2
  1990. 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);
  1991. // solo no 1 deixa soar o caminho até o Master (o 3)
  1992. 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);
  1993. // ordem e ciclos
  1994. auto song = lynx::Song::makeDefault();
  1995. song.setRoute (4, 2, true);
  1996. song.setRoute (2, 1, true);
  1997. CHECK (! song.canRoute (1, 4) && ! song.canRoute (1, 2) && song.canRoute (1, 5));
  1998. song.setRoute (1, 4, true); // ignorado: criaria ciclo
  1999. CHECK (! song.routes (1, 4));
  2000. const auto order = song.mixerOrder();
  2001. const auto pos = [&] (int t) { return std::find (order.begin(), order.end(), t) - order.begin(); };
  2002. CHECK ((int) order.size() == (int) song.mixer.size() - 1);
  2003. CHECK (pos (4) < pos (2) && pos (2) < pos (1));
  2004. song.setRoute (4, 2, false);
  2005. CHECK (! song.routes (4, 2) && song.routes (4, 0));
  2006. }
  2007. namespace
  2008. {
  2009. // Efeito de teste: atrasa o sinal em `latency` samples e informa essa latência (como um plugin com lookahead).
  2010. class LatentEffect final : public lynx::Effect
  2011. {
  2012. public:
  2013. explicit LatentEffect (int samples) : latency (samples), line (samples) {}
  2014. void prepare (double) noexcept override {}
  2015. void reset() noexcept override {}
  2016. void process (float* l, float* r, int n, const lynx::EffectParams&, double) noexcept override { line.process (l, r, n); }
  2017. int latencySamples() const noexcept override { return latency; }
  2018. private:
  2019. int latency;
  2020. lynx::DelayLine line;
  2021. };
  2022. } // namespace
  2023. TEST (delay_line_mix_into_matches_process_and_drains_tail)
  2024. {
  2025. // mixInto = process sobre source*level, somado no destino; em trechos que cruzam o anel
  2026. lynx::DelayLine a (37), b (37);
  2027. std::vector<float> sl (300), sr (300), dl (300, 0.5f), dr (300, -0.5f), xl (300), xr (300);
  2028. for (int i = 0; i < 300; ++i)
  2029. {
  2030. sl[(std::size_t) i] = (float) std::sin (i * 0.1);
  2031. sr[(std::size_t) i] = (float) std::cos (i * 0.07);
  2032. }
  2033. for (int start = 0; start < 300; start += 100)
  2034. {
  2035. b.mixInto (sl.data() + start, sr.data() + start, 0.25f, dl.data() + start, dr.data() + start, 100);
  2036. for (int i = start; i < start + 100; ++i)
  2037. {
  2038. xl[(std::size_t) i] = sl[(std::size_t) i] * 0.25f;
  2039. xr[(std::size_t) i] = sr[(std::size_t) i] * 0.25f;
  2040. }
  2041. a.process (xl.data() + start, xr.data() + start, 100);
  2042. }
  2043. float worst = 0.0f;
  2044. for (int i = 0; i < 300; ++i)
  2045. worst = std::max ({ worst, std::abs (dl[(std::size_t) i] - 0.5f - xl[(std::size_t) i]),
  2046. std::abs (dr[(std::size_t) i] + 0.5f - xr[(std::size_t) i]) });
  2047. CHECK (worst < 1e-6f);
  2048. // fonte calada: a cauda que estava na linha ainda sai, depois não sobra nada
  2049. std::vector<float> tl (64, 0.0f), tr (64, 0.0f);
  2050. b.mixInto (nullptr, nullptr, 1.0f, tl.data(), tr.data(), 64);
  2051. CHECK (std::abs (tl[0] - sl[263] * 0.25f) < 1e-6f);
  2052. std::vector<float> zl (64, 0.0f), zr (64, 0.0f);
  2053. b.mixInto (nullptr, nullptr, 1.0f, zl.data(), zr.data(), 64);
  2054. CHECK (*std::max_element (zl.begin(), zl.end()) == 0.0f && *std::min_element (zl.begin(), zl.end()) == 0.0f);
  2055. }
  2056. TEST (limiter_lookahead_holds_ceiling_on_bursts)
  2057. {
  2058. // rajadas curtas sobre um fundo baixo: o máximo deslizante precisa ver cada pico antes de sair
  2059. auto fx = lynx::makeEffect (lynx::EffectKind::limiter);
  2060. fx->prepare (48000.0);
  2061. auto slot = lynx::makeEffectSlot (lynx::EffectKind::limiter);
  2062. slot.params[2] = 0.0f; // release de 10 ms
  2063. std::vector<float> l (48000), r (48000);
  2064. std::uint32_t seed = 1;
  2065. for (int i = 0; i < 48000; ++i)
  2066. {
  2067. seed = seed * 1664525u + 1013904223u;
  2068. const auto noise = ((float) (seed >> 8) / 16777216.0f - 0.5f) * 0.1f;
  2069. l[(std::size_t) i] = noise + ((i % 9973) < 3 ? 3.0f : 0.0f);
  2070. r[(std::size_t) i] = -noise;
  2071. }
  2072. for (int i = 0; i < 48000; i += 333)
  2073. fx->process (l.data() + i, r.data() + i, std::min (333, 48000 - i), slot.params, 120.0);
  2074. float peak = 0.0f, quiet = 0.0f;
  2075. for (int i = 0; i < 48000; ++i)
  2076. peak = std::max (peak, std::abs (l[(std::size_t) i]));
  2077. for (int i = 9973 * 2 + 2000; i < 9973 * 2 + 2400; ++i) // 40 ms depois da rajada o ganho já voltou
  2078. quiet = std::max (quiet, std::abs (r[(std::size_t) i]));
  2079. const auto ceiling = 1.0f; // o teto padrão fica em 0 dBFS ou abaixo
  2080. CHECK (peak <= ceiling + 1e-5f);
  2081. CHECK (quiet > 0.03f);
  2082. }
  2083. TEST (pdc_aligns_paths_through_latent_effects)
  2084. {
  2085. // plano: canal 0 -> insert 1 (efeito de 100) -> insert 3; canal 1 -> insert 2 -> Master
  2086. lynx::Song s;
  2087. s.mixer = lynx::Song::defaultMixer (4);
  2088. s.channels.resize (3);
  2089. s.channels[0].mixerTrack = 1;
  2090. s.channels[1].mixerTrack = 2;
  2091. s.channels[2].mixerTrack = 3;
  2092. s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::eq));
  2093. s.setRoute (1, 3, true);
  2094. s.setRoute (1, 0, false);
  2095. auto plan = lynx::computePdc (s, { 0, 0, 30 }, { {}, { 100 } });
  2096. CHECK (plan.inAlign[1] == 0 && plan.outLat[1] == 100);
  2097. CHECK (plan.inAlign[3] == 100 && plan.channelDelay[2] == 70); // instrumento de 30 no insert 3
  2098. CHECK (plan.sendDelay[1][1] == 0); // o caminho mais lento não atrasa
  2099. CHECK (plan.sendDelay[2][0] == 100 && plan.sendDelay[3][0] == 0 && plan.total == 100);
  2100. // bypass zera a latência do slot
  2101. s.mixer[1].effects[0].enabled = false;
  2102. CHECK (lynx::computePdc (s, { 0, 0, 30 }, { {}, { 100 } }).total == 30);
  2103. // renderizado: dois impulsos tocados juntos saem juntos
  2104. lynx::Song r;
  2105. r.mixer = lynx::Song::defaultMixer (2);
  2106. for (int i = 0; i < 2; ++i)
  2107. {
  2108. lynx::ChannelDef c;
  2109. c.instrument = lynx::InstrumentKind::sampler;
  2110. c.samplePath = "impulso";
  2111. c.volume = 1.0f;
  2112. c.mixerTrack = i + 1;
  2113. r.channels.push_back (c);
  2114. }
  2115. r.patterns.emplace_back();
  2116. lynx::EffectSlot fx;
  2117. fx.kind = lynx::EffectKind::plugin;
  2118. fx.plugin.id = "latente";
  2119. r.mixer[1].effects.push_back (fx);
  2120. lynx::RackState::Factories f;
  2121. f.samples = [] (const std::string&) {
  2122. auto d = std::make_shared<lynx::SampleData>();
  2123. d->left.assign (64, 0.0f);
  2124. d->left[0] = 1.0f;
  2125. return std::shared_ptr<const lynx::SampleData> (d);
  2126. };
  2127. f.pluginEffects = [] (const lynx::PluginRef&, double) -> std::shared_ptr<lynx::Effect> { return std::make_shared<LatentEffect> (100); };
  2128. auto state = lynx::RackState::build (r, nullptr, 48000.0, f);
  2129. CHECK (state->pdc.total == 100 && state->sendDelays[2][0] != nullptr && state->sendDelays[2][0]->length() == 100);
  2130. lynx::RackRenderer renderer;
  2131. renderer.prepare (48000.0, 256);
  2132. lynx::LiveEventQueue live;
  2133. for (int ch = 0; ch < 2; ++ch)
  2134. {
  2135. lynx::NoteEvent on;
  2136. on.channel = ch;
  2137. on.key = 60;
  2138. on.velocity = 1.0f;
  2139. live.push (on);
  2140. }
  2141. std::vector<float> l (256), rr (256);
  2142. renderer.process (state.get(), false, 0.0, 256, l.data(), rr.data(), &live);
  2143. int first = -1;
  2144. for (int i = 0; i < 256 && first < 0; ++i)
  2145. if (std::abs (l[(std::size_t) i]) > 0.01f)
  2146. first = i;
  2147. CHECK (first == 100 && std::abs (l[100] - 2.0f) < 1e-3f); // os dois impulsos chegam juntos, somados
  2148. // editar sem mudar as latências reaproveita as linhas
  2149. r.channels[0].volume = 0.5f;
  2150. auto next = lynx::RackState::build (r, state.get(), 48000.0, f);
  2151. CHECK (next->sendDelays[2][0] == state->sendDelays[2][0]);
  2152. }
  2153. TEST (mixer_mute_fades_instead_of_clicking)
  2154. {
  2155. lynx::Song s;
  2156. s.mixer = lynx::Song::defaultMixer (2);
  2157. lynx::ChannelDef c;
  2158. c.instrument = lynx::InstrumentKind::sampler;
  2159. c.samplePath = "dc";
  2160. c.volume = 1.0f;
  2161. c.mixerTrack = 1;
  2162. s.channels.push_back (c);
  2163. s.patterns.emplace_back();
  2164. auto provider = [] (const std::string&) {
  2165. auto d = std::make_shared<lynx::SampleData>();
  2166. d->left.assign (48000, 0.5f);
  2167. return std::shared_ptr<const lynx::SampleData> (d);
  2168. };
  2169. auto on = lynx::RackState::build (s, nullptr, 48000.0, provider);
  2170. s.mixer[1].muted = true;
  2171. auto off = lynx::RackState::build (s, on.get(), 48000.0, provider);
  2172. lynx::RackRenderer r;
  2173. r.prepare (48000.0, 256);
  2174. lynx::LiveEventQueue live;
  2175. lynx::NoteEvent note;
  2176. note.velocity = 1.0f;
  2177. live.push (note);
  2178. std::vector<float> l (256), rr (256);
  2179. r.process (on.get(), false, 0.0, 256, l.data(), rr.data(), &live);
  2180. CHECK (std::abs (l[255] - 0.5f) < 1e-3f);
  2181. r.process (off.get(), false, 0.0, 256, l.data(), rr.data());
  2182. CHECK (l[0] > 0.45f && l[128] > 0.2f && l[128] < 0.3f && std::abs (l[255]) < 1e-6f); // rampa até zero
  2183. r.process (off.get(), false, 0.0, 256, l.data(), rr.data());
  2184. CHECK (std::abs (l[0]) < 1e-9f);
  2185. }
  2186. TEST (dither_quantizes_to_lsb_grid_with_small_error)
  2187. {
  2188. lynx::Dither d (16);
  2189. std::vector<float> x (4800);
  2190. for (std::size_t i = 0; i < x.size(); ++i)
  2191. x[i] = 0.25f * std::sin ((float) i * 0.05f);
  2192. auto y = x;
  2193. d.process (y.data(), (int) y.size(), 0);
  2194. double errorSum = 0.0;
  2195. bool onGrid = true;
  2196. for (std::size_t i = 0; i < x.size(); ++i)
  2197. {
  2198. const auto steps = y[i] * 32768.0f;
  2199. onGrid = onGrid && std::abs (steps - std::round (steps)) < 1e-3f;
  2200. errorSum += std::abs (y[i] - x[i]);
  2201. }
  2202. CHECK (onGrid);
  2203. CHECK (errorSum / (double) x.size() < 4.0 / 32768.0); // poucos LSB de ruído em média
  2204. }
  2205. TEST (parallel_rendering_matches_sequential)
  2206. {
  2207. // 32 canais (vale a pena paralelizar), inserts com envios em cadeia
  2208. auto song = lynx::Song::makeDefault();
  2209. song.mixer = lynx::Song::defaultMixer (16);
  2210. for (int i = 5; i < 32; ++i)
  2211. {
  2212. lynx::ChannelDef c;
  2213. c.instrument = i % 2 ? lynx::InstrumentKind::synth : lynx::InstrumentKind::hat;
  2214. c.mixerTrack = 1 + i % 12;
  2215. c.volume = 0.3f;
  2216. song.channels.push_back (c);
  2217. for (int step = i % 4; step < 16; step += 3)
  2218. song.patterns[0].notes.push_back ({ (std::int64_t) step * lynx::ticksPerStep, 200, i, 48 + i, 0.7f });
  2219. }
  2220. song.patterns[0].sortNotes();
  2221. song.setRoute (3, 7, true, 0.6f);
  2222. song.setRoute (7, 9, true, 0.5f);
  2223. song.setRoute (2, 9, true);
  2224. song.mixer[9].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::reverb));
  2225. auto seqState = lynx::RackState::build (song, nullptr, 48000.0);
  2226. auto parState = lynx::RackState::build (song, nullptr, 48000.0);
  2227. CHECK (parState->parallel && parState->mixerLayers.size() == 3);
  2228. lynx::WorkerPool pool (3);
  2229. lynx::RackRenderer seq, par;
  2230. seq.prepare (48000.0, 512);
  2231. par.prepare (48000.0, 512);
  2232. par.setWorkerPool (&pool);
  2233. std::vector<float> l1 (512), r1 (512), l2 (512), r2 (512);
  2234. const auto tps = lynx::ticksPerSample (song.bpm, 48000.0);
  2235. bool same = true;
  2236. float peak = 0.0f;
  2237. for (int block = 0; block < 200; ++block)
  2238. {
  2239. seq.process (seqState.get(), true, block * 512 * tps, 512, l1.data(), r1.data());
  2240. par.process (parState.get(), true, block * 512 * tps, 512, l2.data(), r2.data());
  2241. same = same && l1 == l2 && r1 == r2;
  2242. for (auto v : l1)
  2243. peak = std::max (peak, std::abs (v));
  2244. }
  2245. CHECK (same);
  2246. CHECK (peak > 0.05f);
  2247. // o pool aguenta muitas rodadas pequenas seguidas
  2248. std::atomic<int> sum { 0 };
  2249. auto add = [&sum] (int i) { sum.fetch_add (i + 1); };
  2250. for (int round = 0; round < 2000; ++round)
  2251. pool.parallelFor (5, add);
  2252. CHECK (sum.load() == 2000 * 15);
  2253. }
  2254. TEST (arrangements_switch_and_keep_clip_indices)
  2255. {
  2256. auto s = lynx::Song::makeDefault();
  2257. s.patterns.emplace_back().name = "B";
  2258. s.playlist = { { 1, 0, 0, 960, 0 } };
  2259. s.loopEnd = 960;
  2260. CHECK (s.arrangements.size() == 1 && s.currentArrangement == 0);
  2261. const auto second = s.addArrangement ("Versão curta", true);
  2262. CHECK (second == 1 && s.currentArrangement == 1 && s.playlist.size() == 1 && s.loopEnd == 960);
  2263. s.playlist.push_back ({ 0, 1, 960, 960, 0 });
  2264. s.loopEnd = 0;
  2265. s.selectArrangement (0);
  2266. CHECK (s.playlist.size() == 1 && s.loopEnd == 960 && s.arrangements[1].clips.size() == 2);
  2267. // remover a pattern 0 conserta os clips guardados no outro arrangement
  2268. s.removePattern (0);
  2269. CHECK (s.playlist.size() == 1 && s.playlist[0].pattern == 0);
  2270. CHECK (s.arrangements[1].clips.size() == 1 && s.arrangements[1].clips[0].pattern == 0);
  2271. s.removeArrangement (0);
  2272. CHECK (s.arrangements.size() == 1 && s.currentArrangement == 0 && s.playlist.size() == 1 && s.loopEnd == 0);
  2273. }
  2274. namespace
  2275. {
  2276. // Efeito de teste que inverte o sinal e conta quantas vezes processou.
  2277. class CountingInverter final : public lynx::Effect
  2278. {
  2279. public:
  2280. void prepare (double) noexcept override {}
  2281. void reset() noexcept override {}
  2282. void process (float* l, float* r, int n, const lynx::EffectParams&, double) noexcept override
  2283. {
  2284. ++calls;
  2285. for (int i = 0; i < n; ++i)
  2286. {
  2287. l[i] = -l[i];
  2288. r[i] = -r[i];
  2289. }
  2290. }
  2291. int calls = 0;
  2292. };
  2293. } // namespace
  2294. TEST (effect_slot_dry_wet_and_smart_disable)
  2295. {
  2296. lynx::Song s;
  2297. s.mixer = lynx::Song::defaultMixer (1);
  2298. lynx::ChannelDef c;
  2299. c.instrument = lynx::InstrumentKind::sampler;
  2300. c.samplePath = "dc";
  2301. c.volume = 1.0f;
  2302. c.mixerTrack = 1;
  2303. s.channels.push_back (c);
  2304. s.patterns.emplace_back();
  2305. lynx::EffectSlot fx;
  2306. fx.kind = lynx::EffectKind::plugin;
  2307. fx.plugin.id = "inversor";
  2308. fx.mix = 0.25f; // 75% seco (+0,5) e 25% molhado (-0,5) = +0,25
  2309. s.mixer[1].effects.push_back (fx);
  2310. auto inverter = std::make_shared<CountingInverter>();
  2311. lynx::RackState::Factories f;
  2312. f.samples = [] (const std::string&) {
  2313. auto d = std::make_shared<lynx::SampleData>();
  2314. d->left.assign (4800, 0.5f);
  2315. return std::shared_ptr<const lynx::SampleData> (d);
  2316. };
  2317. f.pluginEffects = [inverter] (const lynx::PluginRef&, double) -> std::shared_ptr<lynx::Effect> { return inverter; };
  2318. auto state = lynx::RackState::build (s, nullptr, 48000.0, f);
  2319. lynx::RackRenderer r;
  2320. r.prepare (48000.0, 512);
  2321. lynx::LiveEventQueue live;
  2322. lynx::NoteEvent on;
  2323. on.velocity = 1.0f;
  2324. live.push (on);
  2325. std::vector<float> l (480), rr (480);
  2326. r.process (state.get(), false, 0.0, 480, l.data(), rr.data(), &live);
  2327. CHECK (std::abs (l[100] - 0.25f) < 1e-4f);
  2328. // depois que o sample acaba: 4 s de silêncio e o plugin deixa de ser chamado
  2329. for (int i = 0; i < 100 * 6; ++i) // 6 s
  2330. r.process (state.get(), false, 0.0, 480, l.data(), rr.data());
  2331. const auto callsAfterSilence = inverter->calls;
  2332. for (int i = 0; i < 100; ++i)
  2333. r.process (state.get(), false, 0.0, 480, l.data(), rr.data());
  2334. CHECK (inverter->calls == callsAfterSilence);
  2335. CHECK (callsAfterSilence < 100 * 6);
  2336. // som de novo: volta a processar no mesmo bloco
  2337. live.push (on);
  2338. r.process (state.get(), false, 0.0, 480, l.data(), rr.data(), &live);
  2339. CHECK (inverter->calls == callsAfterSilence + 1 && std::abs (l[100] - 0.25f) < 1e-4f);
  2340. }
  2341. TEST (swing_delays_offbeat_sixteenths)
  2342. {
  2343. CHECK (lynx::swingDelay (0, 1.0f) == 0);
  2344. CHECK (lynx::swingDelay (lynx::ticksPerStep, 1.0f) == lynx::ticksPerStep / 2);
  2345. CHECK (lynx::swingDelay (lynx::ticksPerStep * 2, 1.0f) == 0);
  2346. CHECK (lynx::swingDelay (lynx::ticksPerStep + 10, 1.0f) == (lynx::ticksPerStep - 20) / 2); // fora da grade: peso triangular (FL)
  2347. CHECK (lynx::swingDelay (lynx::ticksPerStep, 1.0f, 0.5f) == lynx::ticksPerStep / 4); // mix do canal
  2348. CHECK (lynx::swingDelay (lynx::ticksPerStep * 3, 0.5f) == lynx::ticksPerStep / 4);
  2349. lynx::Pattern p;
  2350. p.notes = { { 0, 100, 0, 60 }, { lynx::ticksPerStep, 100, 0, 62 } };
  2351. lynx::EventBuffer ev;
  2352. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  2353. lynx::schedulePatternLoop (p, p.effectiveLength (4), 0.0, 12000, tps, ev, 1.0f);
  2354. int onOffset = -1;
  2355. for (auto& e : ev)
  2356. if (e.type == lynx::NoteEvent::Type::on && e.key == 62)
  2357. onOffset = e.sampleOffset;
  2358. CHECK (onOffset == (int) std::floor ((lynx::ticksPerStep * 1.5) / tps));
  2359. }
  2360. TEST (sampler_settings_pitch_reverse_envelope_cut)
  2361. {
  2362. auto ramp = std::make_shared<lynx::SampleData>();
  2363. for (int i = 0; i < 48000; ++i)
  2364. ramp->left.push_back ((float) i / 48000.0f); // rampa: o valor diz onde a leitura está
  2365. ramp->sampleRate = 48000.0;
  2366. auto play = [&] (const lynx::SamplerSettings& s, int key, int frames, bool releaseAfterHalf) {
  2367. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  2368. inst->prepare (48000.0);
  2369. lynx::ChannelDef c;
  2370. c.sampler = s;
  2371. inst->configure (c, 120.0);
  2372. inst->noteOn (key, 1.0f);
  2373. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  2374. inst->render (l.data(), r.data(), frames / 2, 1.0f, 1.0f);
  2375. if (releaseAfterHalf)
  2376. inst->noteOff (key);
  2377. inst->render (l.data() + frames / 2, r.data() + frames / 2, frames - frames / 2, 1.0f, 1.0f);
  2378. return l;
  2379. };
  2380. // +12 semitons: lê o dobro
  2381. lynx::SamplerSettings up;
  2382. up.pitch = 12.0f;
  2383. CHECK (std::abs (play (up, 60, 1000, false)[999] - 2.0f * 999.0f / 48000.0f) < 1e-3f);
  2384. // ao contrário: começa do fim
  2385. lynx::SamplerSettings back;
  2386. back.reverse = true;
  2387. CHECK (play (back, 60, 100, false)[10] > 0.99f);
  2388. // ataque de 10 ms: começa em silêncio e chega ao nível cheio
  2389. lynx::SamplerSettings slow;
  2390. slow.attack = 0.01f;
  2391. const auto a = play (slow, 60, 2000, false);
  2392. CHECK (a[10] < 0.2f * (10.0f / 48000.0f) + 1e-6f && std::abs (a[1500] - 1500.0f / 48000.0f) < 1e-4f);
  2393. // release de 5 ms: some logo depois de soltar; sem release toca inteiro
  2394. lynx::SamplerSettings rel;
  2395. rel.release = 0.005f;
  2396. CHECK (play (rel, 60, 2000, true)[1999] == 0.0f);
  2397. CHECK (play (lynx::SamplerSettings {}, 60, 2000, true)[1999] > 0.0f);
  2398. // cut itself: a segunda nota corta a primeira (sobra uma voz)
  2399. lynx::SamplerSettings cut;
  2400. cut.cut = true;
  2401. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  2402. inst->prepare (48000.0);
  2403. lynx::ChannelDef cutChannel;
  2404. cutChannel.sampler = cut;
  2405. inst->configure (cutChannel, 120.0);
  2406. inst->noteOn (60, 1.0f);
  2407. std::vector<float> l (2000), r (2000);
  2408. inst->render (l.data(), r.data(), 1000, 1.0f, 1.0f);
  2409. inst->noteOn (60, 1.0f);
  2410. std::fill (l.begin(), l.end(), 0.0f);
  2411. inst->render (l.data(), r.data(), 2000, 1.0f, 1.0f);
  2412. CHECK (std::abs (l[1999] - 1999.0f / 48000.0f) < 1e-4f); // só a nota nova
  2413. }
  2414. TEST (playlist_split_and_track_mute)
  2415. {
  2416. lynx::Clip c { 0, 3, 960, 3840, 480 };
  2417. const auto rest = lynx::splitClip (c, 2000);
  2418. CHECK (c.start == 960 && c.length == 1040 && c.offset == 480);
  2419. CHECK (rest.start == 2000 && rest.length == 2800 && rest.offset == 480 + 1040 && rest.track == 3);
  2420. auto s = lynx::Song::makeDefault();
  2421. s.mode = lynx::PlayMode::song;
  2422. s.playlist = { { 0, 0, 0, 3840, 0 } };
  2423. lynx::EventBuffer ev;
  2424. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  2425. lynx::scheduleSong (s, 0.0, 48000, tps, ev);
  2426. CHECK (ev.size() > 0);
  2427. s.playlistTracks.resize (1);
  2428. s.playlistTracks[0].muted = true;
  2429. ev.clear();
  2430. lynx::scheduleSong (s, 0.0, 48000, tps, ev);
  2431. CHECK (ev.size() == 0);
  2432. }
  2433. TEST (note_pan_pitch_and_mute)
  2434. {
  2435. lynx::Pattern p;
  2436. lynx::Note a { 0, 240, 0, 60 };
  2437. a.pan = -1.0f;
  2438. a.finePitch = 50.0f;
  2439. lynx::Note b { 240, 240, 0, 62 };
  2440. b.muted = true;
  2441. p.notes = { a, b };
  2442. lynx::EventBuffer ev;
  2443. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  2444. lynx::schedulePatternLoop (p, p.effectiveLength (4), 0.0, 48000, tps, ev);
  2445. int ons = 0;
  2446. for (auto& e : ev)
  2447. if (e.type == lynx::NoteEvent::Type::on)
  2448. {
  2449. ++ons;
  2450. CHECK (e.key == 60 && e.pan == -1.0f && e.cents == 50.0f);
  2451. }
  2452. CHECK (ons == 1); // a mutada não toca
  2453. // pan da nota no sampler: tudo à esquerda
  2454. auto dc = std::make_shared<lynx::SampleData>();
  2455. dc->left.assign (4800, 0.5f);
  2456. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, dc);
  2457. inst->prepare (48000.0);
  2458. inst->setNextNoteExpression (-1.0f, 0.0f);
  2459. inst->noteOn (60, 1.0f);
  2460. std::vector<float> l (100), r (100);
  2461. inst->render (l.data(), r.data(), 100, 1.0f, 1.0f);
  2462. CHECK (l[50] > 0.6f && std::abs (r[50]) < 1e-6f);
  2463. }
  2464. TEST (tempo_automation_changes_speed_and_duration)
  2465. {
  2466. auto song = lynx::Song::makeDefault();
  2467. song.bpm = 120.0;
  2468. song.mode = lynx::PlayMode::song;
  2469. const auto bar = (std::int64_t) lynx::ppq * 4;
  2470. song.playlist = { { 0, 0, 0, bar, 0 }, { 0, 0, bar, bar, 0 } };
  2471. lynx::Automation tempo;
  2472. tempo.target = { lynx::AutomationTargetKind::tempo, 0 };
  2473. const auto v120 = lynx::valueFromTempo (120.0), v240 = lynx::valueFromTempo (240.0);
  2474. tempo.points = { { 0, v120 }, { bar - 1, v120 }, { bar, v240 } }; // degrau: 120 -> 240 no 2º compasso
  2475. song.automations.push_back (tempo);
  2476. lynx::Clip clip;
  2477. clip.kind = lynx::ClipKind::automation;
  2478. clip.automation = 0;
  2479. clip.track = 1;
  2480. clip.length = bar * 2;
  2481. song.playlist.push_back (clip);
  2482. CHECK (std::abs (song.tempoAt (100.0) - 120.0) < 0.01 && std::abs (song.tempoAt ((double) bar + 100.0) - 240.0) < 0.01);
  2483. // 1 compasso a 120 (2 s) + 1 a 240 (1 s)
  2484. CHECK (std::abs (song.secondsForTicks (bar * 2) - 3.0) < 0.01);
  2485. auto state = lynx::RackState::build (song, nullptr, 48000.0);
  2486. CHECK (state->tempoAutomation == 0);
  2487. lynx::RackRenderer r;
  2488. r.prepare (48000.0, 512);
  2489. std::vector<float> l (512), rr (512);
  2490. r.process (state.get(), true, 10.0, 512, l.data(), rr.data());
  2491. CHECK (std::abs (r.currentBpm() - 120.0) < 0.01);
  2492. r.process (state.get(), true, (double) bar + 10.0, 512, l.data(), rr.data());
  2493. CHECK (std::abs (r.currentBpm() - 240.0) < 0.01);
  2494. }
  2495. TEST (bounce_insert_song_and_apply)
  2496. {
  2497. auto s = lynx::Song::makeDefault();
  2498. s.setRoute (3, 7, true, 0.5f);
  2499. s.mixer[0].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::reverb));
  2500. s.mixer[2].solo = true;
  2501. const auto b = lynx::makeBounceSong (s, 3);
  2502. CHECK (b.mixer[3].solo && ! b.mixer[2].solo && b.mixer[3].toMaster && b.mixer[3].sends.empty());
  2503. CHECK (b.mixer[0].effects.empty() && b.mode == lynx::PlayMode::song);
  2504. const auto audible = b.soloAudible();
  2505. CHECK (audible[3] && ! audible[1] && ! audible[7]);
  2506. const auto channels = s.channels.size();
  2507. const auto inserts = s.mixer.size();
  2508. const auto created = lynx::applyBounce (s, 3, "C:/x.wav", 3840);
  2509. CHECK (created == (int) inserts && s.mixer.size() == inserts + 1 && s.mixer[3].muted);
  2510. CHECK (s.mixer[(std::size_t) created].sends.size() == 1 && s.mixer[(std::size_t) created].sends[0].target == 7);
  2511. CHECK (s.channels.size() == channels + 1 && s.channels.back().mixerTrack == created);
  2512. CHECK (s.playlist.back().kind == lynx::ClipKind::audio && s.playlist.back().length == 3840);
  2513. }
  2514. TEST (mixer_stereo_separation_phase_swap)
  2515. {
  2516. lynx::MixerTrack t;
  2517. std::vector<float> l { 1.0f }, r { 0.0f };
  2518. t.stereo = 1.0f; // mono
  2519. lynx::RackRenderer::applyStereoForTest (t, l.data(), r.data(), 1);
  2520. CHECK (std::abs (l[0] - 0.5f) < 1e-6f && std::abs (r[0] - 0.5f) < 1e-6f);
  2521. l = { 1.0f };
  2522. r = { 0.0f };
  2523. t.stereo = -1.0f; // lado dobrado: 1,5 L - 0,5 R
  2524. lynx::RackRenderer::applyStereoForTest (t, l.data(), r.data(), 1);
  2525. CHECK (std::abs (l[0] - 1.5f) < 1e-6f && std::abs (r[0] + 0.5f) < 1e-6f);
  2526. l = { 1.0f };
  2527. r = { 0.25f };
  2528. t.stereo = 0.0f;
  2529. t.swapChannels = true;
  2530. t.invertPhase = true;
  2531. lynx::RackRenderer::applyStereoForTest (t, l.data(), r.data(), 1);
  2532. CHECK (l[0] == -0.25f && r[0] == -1.0f);
  2533. }
  2534. TEST (effects_limiter_filter_distortion_chorus)
  2535. {
  2536. const double sr = 48000.0;
  2537. auto sine = [] (float hz, float amp, int n) {
  2538. std::vector<float> v ((std::size_t) n);
  2539. for (int i = 0; i < n; ++i)
  2540. v[(std::size_t) i] = amp * std::sin (2.0f * 3.14159265f * hz * (float) i / 48000.0f);
  2541. return v;
  2542. };
  2543. auto peak = [] (const std::vector<float>& v, int from) {
  2544. float p = 0.0f;
  2545. for (std::size_t i = (std::size_t) from; i < v.size(); ++i)
  2546. p = std::max (p, std::abs (v[i]));
  2547. return p;
  2548. };
  2549. // limiter: +12 dB num seno de 0,9 nunca passa do teto (-1 dB) e informa a latência
  2550. auto lim = lynx::makeEffect (lynx::EffectKind::limiter);
  2551. lim->prepare (sr);
  2552. auto slot = lynx::makeEffectSlot (lynx::EffectKind::limiter);
  2553. slot.params[0] = 11.0f / 12.0f; // -1 dB
  2554. slot.params[1] = 0.5f; // +12 dB
  2555. auto l = sine (100.0f, 0.9f, 48000), r = l;
  2556. lim->process (l.data(), r.data(), 48000, slot.params, 120.0);
  2557. CHECK (peak (l, 0) <= std::pow (10.0f, -1.0f / 20.0f) + 1e-4f);
  2558. CHECK (peak (l, 4800) > 0.8f);
  2559. CHECK (lim->latencySamples() == 72);
  2560. // filtro passa-baixas em 500 Hz derruba um seno de 8 kHz
  2561. auto lp = lynx::makeEffect (lynx::EffectKind::filter);
  2562. lp->prepare (sr);
  2563. auto fs = lynx::makeEffectSlot (lynx::EffectKind::filter);
  2564. fs.params[1] = std::log (500.0f / 20.0f) / std::log (1000.0f);
  2565. l = sine (8000.0f, 1.0f, 9600);
  2566. r = l;
  2567. lp->process (l.data(), r.data(), 9600, fs.params, 120.0);
  2568. CHECK (peak (l, 4800) < 0.05f);
  2569. // distorção e chorus: saída finita e com som
  2570. for (auto kind : { lynx::EffectKind::distortion, lynx::EffectKind::chorus })
  2571. {
  2572. auto fx = lynx::makeEffect (kind);
  2573. fx->prepare (sr);
  2574. auto ps = lynx::makeEffectSlot (kind);
  2575. l = sine (220.0f, 0.5f, 9600);
  2576. r = l;
  2577. fx->process (l.data(), r.data(), 9600, ps.params, 120.0);
  2578. bool finite = true;
  2579. for (auto v : l)
  2580. finite = finite && std::isfinite (v);
  2581. CHECK (finite && peak (l, 2400) > 0.1f && peak (l, 0) < 2.0f);
  2582. }
  2583. }
  2584. TEST (slide_notes_glide_without_retrigger)
  2585. {
  2586. // sampler com rampa: a velocidade de leitura dobra depois do slide de uma oitava
  2587. auto ramp = std::make_shared<lynx::SampleData>();
  2588. for (int i = 0; i < 96000; ++i)
  2589. ramp->left.push_back ((float) i / 96000.0f);
  2590. ramp->sampleRate = 48000.0;
  2591. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  2592. inst->prepare (48000.0);
  2593. inst->noteOn (60, 1.0f);
  2594. std::vector<float> l (2000), r (2000);
  2595. inst->render (l.data(), r.data(), 1000, 1.0f, 1.0f);
  2596. const auto stepBefore = l[999] - l[998];
  2597. inst->slideTo (72, 0.0f, 100.0f);
  2598. std::fill (l.begin(), l.end(), 0.0f);
  2599. inst->render (l.data(), r.data(), 1000, 1.0f, 1.0f);
  2600. const auto stepAfter = l[999] - l[998];
  2601. CHECK (std::abs (stepAfter / stepBefore - 2.0f) < 0.01f);
  2602. // o sequenciador manda "slide" (sem off) para a nota slide
  2603. lynx::Pattern p;
  2604. lynx::Note base { 0, 960, 0, 48 };
  2605. lynx::Note glide { 480, 240, 0, 55 };
  2606. glide.slide = true;
  2607. p.notes = { base, glide };
  2608. lynx::EventBuffer ev;
  2609. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  2610. lynx::schedulePatternLoop (p, p.effectiveLength (4), 0.0, 30000, tps, ev);
  2611. int ons = 0, offs = 0, slides = 0;
  2612. for (auto& e : ev)
  2613. {
  2614. ons += e.type == lynx::NoteEvent::Type::on;
  2615. offs += e.type == lynx::NoteEvent::Type::off;
  2616. if (e.type == lynx::NoteEvent::Type::slide)
  2617. {
  2618. ++slides;
  2619. CHECK (e.key == 55 && std::abs (e.slideSamples - 240.0f / (float) tps) < 1.0f);
  2620. }
  2621. }
  2622. CHECK (ons == 1 && offs == 1 && slides == 1);
  2623. }
  2624. TEST (synth_three_oscillators_adsr_filter)
  2625. {
  2626. auto render = [] (const lynx::SynthSettings& s, int frames, int releaseAt) {
  2627. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  2628. inst->prepare (48000.0);
  2629. lynx::ChannelDef c;
  2630. c.synth = s;
  2631. inst->configure (c, 120.0);
  2632. inst->noteOn (69, 1.0f); // A4 = 440 Hz
  2633. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  2634. inst->render (l.data(), r.data(), releaseAt, 1.0f, 1.0f);
  2635. inst->noteOff (69);
  2636. inst->render (l.data() + releaseAt, r.data() + releaseAt, frames - releaseAt, 1.0f, 1.0f);
  2637. return l;
  2638. };
  2639. auto peakIn = [] (const std::vector<float>& v, int from, int to) {
  2640. float p = 0.0f;
  2641. for (int i = from; i < to; ++i)
  2642. p = std::max (p, std::abs (v[(std::size_t) i]));
  2643. return p;
  2644. };
  2645. // padrão: soa e some depois do release
  2646. const lynx::SynthSettings standard;
  2647. const auto a = render (standard, 48000, 24000);
  2648. CHECK (peakIn (a, 1000, 20000) > 0.05f && peakIn (a, 40000, 48000) < 1e-3f);
  2649. // seno puro com filtro aberto: a contagem de cruzamentos por zero dá ~440 Hz
  2650. lynx::SynthSettings sine;
  2651. sine.osc[0].wave = lynx::Waveform::sine;
  2652. sine.cutoff = 20000.0f;
  2653. const auto b = render (sine, 48000, 47000);
  2654. int crossings = 0;
  2655. for (int i = 4800; i < 4800 + 48000 / 2; ++i)
  2656. crossings += (b[(std::size_t) i - 1] < 0.0f) != (b[(std::size_t) i] < 0.0f);
  2657. CHECK (std::abs (crossings - 440) < 6); // meio segundo = 220 ciclos = 440 cruzamentos
  2658. float sinePeak = 0.0f;
  2659. for (int i = 4800; i < 9600; ++i)
  2660. sinePeak = std::max (sinePeak, std::abs (b[(std::size_t) i]));
  2661. CHECK (sinePeak > 0.2f && sinePeak < 0.35f); // 0,3 de nível, seno aproximado sem estouro
  2662. // segundo oscilador uma oitava acima soma energia; sustain 0 faz a nota decair sozinha
  2663. lynx::SynthSettings two = sine;
  2664. two.osc[1] = { lynx::Waveform::sine, 1, 0.0f, 1.0f };
  2665. two.sustain = 0.0f;
  2666. two.decay = 0.1f;
  2667. const auto c = render (two, 48000, 47000);
  2668. CHECK (peakIn (c, 100, 2000) > peakIn (b, 100, 2000) && peakIn (c, 30000, 40000) < 1e-3f);
  2669. }
  2670. TEST (set_target_value_round_trips)
  2671. {
  2672. auto s = lynx::Song::makeDefault();
  2673. s.mixer[2].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay));
  2674. const lynx::AutomationTarget targets[] = {
  2675. { lynx::AutomationTargetKind::channelVolume, 1 }, { lynx::AutomationTargetKind::channelPan, 2 },
  2676. { lynx::AutomationTargetKind::mixerVolume, 3 }, { lynx::AutomationTargetKind::mixerPan, 0 },
  2677. { lynx::AutomationTargetKind::effectParam, 2, 0, 1 }, { lynx::AutomationTargetKind::tempo, 0 },
  2678. };
  2679. for (const auto& t : targets)
  2680. {
  2681. CHECK (s.setTargetValue (t, 0.25f));
  2682. CHECK (std::abs (s.targetValue (t) - 0.25f) < 1e-5f);
  2683. }
  2684. CHECK (! s.setTargetValue ({ lynx::AutomationTargetKind::channelParam, 0, 0, 3 }, 0.5f)); // mora no plugin
  2685. }
  2686. TEST (cut_groups_stretch_and_envelope_import)
  2687. {
  2688. // hat aberto (cut by 1) é cortado quando o fechado (grupo 1) toca
  2689. lynx::Song s;
  2690. s.mixer = lynx::Song::defaultMixer (2);
  2691. for (int i = 0; i < 2; ++i)
  2692. {
  2693. lynx::ChannelDef c;
  2694. c.instrument = lynx::InstrumentKind::sampler;
  2695. c.samplePath = "dc";
  2696. c.volume = 1.0f;
  2697. c.mixerTrack = i + 1;
  2698. s.channels.push_back (c);
  2699. }
  2700. s.channels[0].cutBy = 1; // aberto
  2701. s.channels[1].cutGroup = 1; // fechado
  2702. auto& p = s.patterns.emplace_back();
  2703. p.notes = { { 0, 100, 0, 60 }, { 960, 100, 1, 60 } };
  2704. auto provider = [] (const std::string&) {
  2705. auto d = std::make_shared<lynx::SampleData>();
  2706. d->left.assign (96000, 0.5f);
  2707. return std::shared_ptr<const lynx::SampleData> (d);
  2708. };
  2709. auto state = lynx::RackState::build (s, nullptr, 48000.0, provider);
  2710. CHECK (state->hasCutGroups && state->cutTargets[1].size() == 1 && state->cutTargets[1][0] == 0);
  2711. lynx::RackRenderer r;
  2712. r.prepare (48000.0, 512);
  2713. std::vector<float> l (512), rr (512);
  2714. const auto tps = lynx::ticksPerSample (s.bpm, 48000.0);
  2715. float afterCut = 0.0f;
  2716. for (double tick = 0.0; tick < 960.0 * 3; tick += 512 * tps)
  2717. {
  2718. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  2719. if (tick > 960.0 * 2) // o fechado segue; o aberto já parou
  2720. afterCut = std::max (afterCut, std::abs (l[256]));
  2721. }
  2722. CHECK (std::abs (afterCut - 0.5f * 0.78f) < 0.01f); // só o fechado (velocity padrão 0,78)
  2723. // stretch por reamostragem: 1 s de sample esticado para 4 tempos a 120 BPM = 2 s
  2724. auto ramp = std::make_shared<lynx::SampleData>();
  2725. for (int i = 0; i < 48000; ++i)
  2726. ramp->left.push_back ((float) i / 48000.0f);
  2727. ramp->sampleRate = 48000.0;
  2728. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  2729. inst->prepare (48000.0);
  2730. lynx::ChannelDef c;
  2731. c.sampler.stretchBeats = 4.0f;
  2732. inst->configure (c, 120.0);
  2733. inst->noteOn (72, 1.0f); // a altura da nota não muda a velocidade
  2734. std::vector<float> a (48000), b (48000);
  2735. inst->render (a.data(), b.data(), 48000, 1.0f, 1.0f);
  2736. CHECK (std::abs (a[47999] - 0.5f) < 0.01f); // depois de 1 s leu metade
  2737. // tempo do envelope do FL: 32950 = 2 s; < 101 = 0
  2738. CHECK (std::abs (flp::Channel::envelopeTime (32950) - 2.0) < 0.01 && flp::Channel::envelopeTime (50) == 0.0);
  2739. }
  2740. TEST (time_stretch_keeps_pitch)
  2741. {
  2742. lynx::SampleData sine;
  2743. sine.sampleRate = 48000.0;
  2744. for (int i = 0; i < 48000; ++i)
  2745. sine.left.push_back (0.5f * std::sin (2.0f * 3.14159265f * 440.0f * (float) i / 48000.0f));
  2746. auto crossingsPerSecond = [] (const lynx::SampleData& d) {
  2747. int c = 0;
  2748. const auto n = (int) d.frames();
  2749. for (int i = 4800; i < n - 4800; ++i)
  2750. c += (d.left[(std::size_t) i - 1] < 0.0f) != (d.left[(std::size_t) i] < 0.0f);
  2751. return (double) c / ((double) (n - 9600) / d.sampleRate);
  2752. };
  2753. for (double ratio : { 2.0, 0.5, 1.37 })
  2754. {
  2755. const auto out = lynx::timeStretch (sine, ratio);
  2756. CHECK (std::abs ((double) out->frames() - 48000.0 * ratio) < 2.0);
  2757. CHECK (std::abs (crossingsPerSecond (*out) - 880.0) < 15.0); // 440 Hz continua 440 Hz
  2758. float peak = 0.0f;
  2759. for (std::size_t i = 4800; i + 4800 < out->frames(); ++i)
  2760. peak = std::max (peak, std::abs (out->left[i]));
  2761. CHECK (peak > 0.4f && peak < 0.6f); // sem buracos nem estouro na sobreposição
  2762. }
  2763. }
  2764. TEST (sampler_region_start_and_end)
  2765. {
  2766. auto ramp = std::make_shared<lynx::SampleData>();
  2767. for (int i = 0; i < 10000; ++i)
  2768. ramp->left.push_back ((float) i / 10000.0f);
  2769. ramp->sampleRate = 48000.0;
  2770. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  2771. inst->prepare (48000.0);
  2772. lynx::ChannelDef c;
  2773. c.sampler.regionStart = 0.25f;
  2774. c.sampler.regionEnd = 0.5f;
  2775. inst->configure (c, 120.0);
  2776. inst->noteOn (60, 1.0f);
  2777. std::vector<float> l (6000), r (6000);
  2778. inst->render (l.data(), r.data(), 6000, 1.0f, 1.0f);
  2779. CHECK (std::abs (l[0] - 0.25f) < 0.001f); // começa no início do trecho
  2780. CHECK (l[2400] > 0.48f && l[2600] == 0.0f); // e para no fim dele
  2781. }
  2782. TEST (arpeggiator_plays_held_chord_in_steps)
  2783. {
  2784. auto song = lynx::Song::makeDefault();
  2785. song.bpm = 120.0;
  2786. song.patterns[0].notes.clear();
  2787. for (int key : { 60, 64, 67 })
  2788. song.patterns[0].notes.push_back ({ 0, lynx::ppq * 4, 4, key, 0.8f }); // acorde segurado 1 compasso
  2789. song.channels[4].arp.direction = 1; // sobe
  2790. song.channels[4].arp.stepBeats = 0.25f;
  2791. auto state = lynx::RackState::build (song, nullptr, 48000.0);
  2792. CHECK (state->arpeggiators[4] != nullptr && state->arpeggiators[0] == nullptr);
  2793. // o arpejador gera as notas; contamos o que ele entrega ao instrumento
  2794. auto& arp = *state->arpeggiators[4];
  2795. const auto tps = lynx::ticksPerSample (song.bpm, 48000.0);
  2796. std::vector<int> keys;
  2797. lynx::EventBuffer ev;
  2798. for (double tick = 0.0; tick < lynx::ppq * 2.0; tick += 512 * tps)
  2799. {
  2800. ev.clear();
  2801. lynx::schedulePatternLoop (song.patterns[0], song.patterns[0].effectiveLength (4), tick, 512, tps, ev);
  2802. int in = 0, out = 0;
  2803. for (auto& e : ev)
  2804. if (e.channel == 4)
  2805. arp.input[(std::size_t) in++] = e;
  2806. arp.process (4, arp.input.data(), in, tick, tps, 512, song.channels[4].arp, arp.output.data(), out);
  2807. for (int i = 0; i < out; ++i)
  2808. if (arp.output[(std::size_t) i].type == lynx::NoteEvent::Type::on)
  2809. keys.push_back (arp.output[(std::size_t) i].key);
  2810. }
  2811. // 2 tempos = 8 passos de semicolcheia: 60 64 67 60 64 67 60 64
  2812. CHECK (keys.size() >= 8); // o último bloco passa um pouco dos 2 tempos
  2813. const int expected[] = { 60, 64, 67, 60, 64, 67, 60, 64 };
  2814. for (std::size_t i = 0; i < keys.size() && i < 8; ++i)
  2815. CHECK (keys[i] == expected[i]);
  2816. // renderizando de verdade também soa
  2817. lynx::RackRenderer r;
  2818. r.prepare (48000.0, 512);
  2819. std::vector<float> l (512), rr (512);
  2820. float peak = 0.0f;
  2821. for (double tick = 0.0; tick < lynx::ppq; tick += 512 * tps)
  2822. {
  2823. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  2824. for (auto v : l)
  2825. peak = std::max (peak, std::abs (v));
  2826. }
  2827. CHECK (peak > 0.01f);
  2828. }
  2829. TEST (audio_clip_fades_and_gain)
  2830. {
  2831. lynx::Song s;
  2832. s.bpm = 120.0;
  2833. s.mode = lynx::PlayMode::song;
  2834. s.mixer = lynx::Song::defaultMixer (1);
  2835. lynx::ChannelDef c;
  2836. c.instrument = lynx::InstrumentKind::audioClip;
  2837. c.samplePath = "dc";
  2838. c.volume = 1.0f;
  2839. c.mixerTrack = 1;
  2840. s.channels.push_back (c);
  2841. s.patterns.emplace_back();
  2842. lynx::Clip clip;
  2843. clip.kind = lynx::ClipKind::audio;
  2844. clip.channel = 0;
  2845. clip.length = lynx::ppq * 4; // 2 s a 120 BPM
  2846. clip.fadeIn = lynx::ppq; // 0,5 s
  2847. clip.fadeOut = lynx::ppq;
  2848. clip.gain = 0.5f;
  2849. s.playlist.push_back (clip);
  2850. auto provider = [] (const std::string&) {
  2851. auto d = std::make_shared<lynx::SampleData>();
  2852. d->left.assign (48000 * 4, 1.0f);
  2853. return std::shared_ptr<const lynx::SampleData> (d);
  2854. };
  2855. auto state = lynx::RackState::build (s, nullptr, 48000.0, provider);
  2856. lynx::RackRenderer r;
  2857. r.prepare (48000.0, 512);
  2858. std::vector<float> all;
  2859. std::vector<float> l (512), rr (512);
  2860. const auto tps = lynx::ticksPerSample (s.bpm, 48000.0);
  2861. for (double tick = 0.0; tick < lynx::ppq * 4.0; tick += 512 * tps)
  2862. {
  2863. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  2864. all.insert (all.end(), l.begin(), l.end());
  2865. }
  2866. CHECK (all[100] < 0.01f); // começo do fade-in
  2867. CHECK (std::abs (all[12000] - 0.25f) < 0.02f); // meio do fade-in: metade de 0,5
  2868. CHECK (std::abs (all[48000] - 0.5f) < 0.01f); // corpo: o ganho do clip
  2869. CHECK (std::abs (all[96000 - 12000] - 0.25f) < 0.02f); // meio do fade-out
  2870. }
  2871. TEST (slicer_detects_hits_and_plays_slices_by_key)
  2872. {
  2873. // 4 batidas (ruído com decaimento) a cada 0,25 s
  2874. lynx::SampleData loop;
  2875. loop.sampleRate = 48000.0;
  2876. loop.left.assign (48000, 0.0f);
  2877. lynx::Noise noise;
  2878. for (int hit = 0; hit < 4; ++hit)
  2879. for (int i = 0; i < 6000; ++i)
  2880. loop.left[(std::size_t) (hit * 12000 + i)] = noise.next() * 0.8f * std::exp (-(float) i / 1500.0f);
  2881. const auto slices = lynx::detectSlices (loop, 0.5f);
  2882. CHECK (slices.size() == 4);
  2883. for (std::size_t i = 0; i < slices.size(); ++i)
  2884. CHECK (std::abs (slices[i] - 0.25f * (float) i) < 0.01f);
  2885. // a tecla 61 toca a segunda fatia, que começa em 0,25 e acaba antes de 0,5
  2886. auto ramp = std::make_shared<lynx::SampleData>();
  2887. for (int i = 0; i < 48000; ++i)
  2888. ramp->left.push_back ((float) i / 48000.0f);
  2889. ramp->sampleRate = 48000.0;
  2890. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  2891. inst->prepare (48000.0);
  2892. lynx::ChannelDef c;
  2893. c.sampler.slices = slices;
  2894. inst->configure (c, 120.0);
  2895. inst->noteOn (61, 1.0f);
  2896. std::vector<float> l (20000), r (20000);
  2897. inst->render (l.data(), r.data(), 20000, 1.0f, 1.0f);
  2898. CHECK (std::abs (l[0] - 0.25f) < 0.01f && l[11000] > 0.45f && l[13000] == 0.0f);
  2899. }
  2900. TEST (project_templates_render_sound)
  2901. {
  2902. const auto names = lynx::templateNames();
  2903. CHECK (names.size() == 4);
  2904. for (int t = 1; t < (int) names.size(); ++t)
  2905. {
  2906. auto song = lynx::makeTemplate (t);
  2907. auto state = lynx::RackState::build (song, nullptr, 48000.0);
  2908. lynx::RackRenderer r;
  2909. r.prepare (48000.0, 512);
  2910. std::vector<float> l (512), rr (512);
  2911. const auto tps = lynx::ticksPerSample (song.bpm, 48000.0);
  2912. float peak = 0.0f;
  2913. for (double tick = 0.0; tick < lynx::ppq * 4.0; tick += 512 * tps)
  2914. {
  2915. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  2916. for (auto v : l)
  2917. peak = std::max (peak, std::abs (v));
  2918. }
  2919. CHECK (peak > 0.05f && peak < 4.0f);
  2920. }
  2921. CHECK (lynx::makeTemplate (0).patterns[0].notes.empty());
  2922. }
  2923. int main (int argc, char** argv)
  2924. {
  2925. if (argc > 1)
  2926. realFlpDir = argv[1];
  2927. for (auto& [name, fn] : registry())
  2928. {
  2929. std::printf ("%s\n", name);
  2930. fn();
  2931. }
  2932. std::printf ("\n%d verificações, %d falhas\n", checks, failures);
  2933. return failures == 0 ? 0 : 1;
  2934. }