tests.cpp 94 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527
  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/LiveEventQueue.h"
  16. #include "core/RackRenderer.h"
  17. #include "core/Scheduler.h"
  18. #include "core/SnapshotExchange.h"
  19. #include "core/SoftClip.h"
  20. #include "core/Slicer.h"
  21. #include "core/Templates.h"
  22. #include "core/TimeStretch.h"
  23. #include "core/WorkerPool.h"
  24. #include "core/Song.h"
  25. #include "core/NoteEdit.h"
  26. #include "core/Recorder.h"
  27. #include "flp/Flp.h"
  28. namespace
  29. {
  30. int failures = 0;
  31. int checks = 0;
  32. std::vector<std::pair<const char*, std::function<void()>>>& registry()
  33. {
  34. static std::vector<std::pair<const char*, std::function<void()>>> r;
  35. return r;
  36. }
  37. struct Register
  38. {
  39. Register (const char* name, std::function<void()> fn) { registry().emplace_back (name, std::move (fn)); }
  40. };
  41. #define TEST(name) \
  42. static void name(); \
  43. static Register reg_##name (#name, name); \
  44. static void name()
  45. #define CHECK(cond) \
  46. do \
  47. { \
  48. ++checks; \
  49. if (! (cond)) \
  50. { \
  51. ++failures; \
  52. std::printf (" FALHOU %s:%d: %s\n", __FILE__, __LINE__, #cond); \
  53. } \
  54. } while (false)
  55. std::string realFlpDir;
  56. // --- utilitários para montar .flp sintéticos -------------------------------
  57. struct FlpBuilder
  58. {
  59. std::vector<std::uint8_t> bytes;
  60. FlpBuilder (std::uint16_t ppq = 96)
  61. {
  62. put ("FLhd");
  63. u32 (6);
  64. u16 (0);
  65. u16 (1);
  66. u16 (ppq);
  67. put ("FLdt");
  68. u32 (0); // tamanho não é usado pelo leitor
  69. }
  70. void put (const char* s) { bytes.insert (bytes.end(), s, s + std::strlen (s)); }
  71. void u8 (std::uint8_t v) { bytes.push_back (v); }
  72. void u16 (std::uint16_t v) { u8 ((std::uint8_t) v); u8 ((std::uint8_t) (v >> 8)); }
  73. void u32 (std::uint32_t v) { u16 ((std::uint16_t) v); u16 ((std::uint16_t) (v >> 16)); }
  74. void varint (std::size_t n)
  75. {
  76. do
  77. {
  78. auto b = (std::uint8_t) (n & 0x7F);
  79. n >>= 7;
  80. u8 (n ? (std::uint8_t) (b | 0x80) : b);
  81. } while (n);
  82. }
  83. void data (std::uint8_t id, const std::vector<std::uint8_t>& payload)
  84. {
  85. u8 (id);
  86. varint (payload.size());
  87. bytes.insert (bytes.end(), payload.begin(), payload.end());
  88. }
  89. void ascii (std::uint8_t id, const std::string& s)
  90. {
  91. std::vector<std::uint8_t> p (s.begin(), s.end());
  92. p.push_back (0);
  93. data (id, p);
  94. }
  95. void utf16 (std::uint8_t id, const std::u16string& s)
  96. {
  97. std::vector<std::uint8_t> p;
  98. for (auto c : s)
  99. {
  100. p.push_back ((std::uint8_t) c);
  101. p.push_back ((std::uint8_t) (c >> 8));
  102. }
  103. p.push_back (0);
  104. p.push_back (0);
  105. data (id, p);
  106. }
  107. };
  108. std::vector<std::uint8_t> noteRecord (std::uint32_t pos, std::uint16_t channel, std::uint32_t len, std::uint16_t key,
  109. std::uint8_t velocity)
  110. {
  111. std::vector<std::uint8_t> r (24, 0);
  112. std::memcpy (&r[0], &pos, 4);
  113. std::memcpy (&r[6], &channel, 2);
  114. std::memcpy (&r[8], &len, 4);
  115. std::memcpy (&r[12], &key, 2);
  116. r[16] = 120;
  117. r[20] = 64;
  118. r[21] = velocity;
  119. return r;
  120. }
  121. } // namespace
  122. // ---------------------------------------------------------------------------
  123. // FLP
  124. TEST (flp_rejects_garbage)
  125. {
  126. std::vector<std::uint8_t> junk (64, 0x41);
  127. bool threw = false;
  128. try { flp::EventReader r (junk); } catch (const flp::Error&) { threw = true; }
  129. CHECK (threw);
  130. }
  131. TEST (flp_reads_size_classes_varint_and_extended_ids)
  132. {
  133. FlpBuilder b;
  134. b.u8 (0x15); b.u8 (2); // u8
  135. b.u8 (0x40); b.u16 (513); // u16
  136. b.u8 (0x9C); b.u32 (128500); // u32
  137. b.data (0xD5, std::vector<std::uint8_t> (300, 7)); // varint de 2 bytes
  138. b.u8 (0xAC); b.u32 (0xC0000100); b.varint (3); b.u8 (1); b.u8 (2); b.u8 (3); // ID estendido
  139. flp::EventReader r (b.bytes);
  140. flp::Event e;
  141. CHECK (r.header().ppq == 96);
  142. CHECK (r.next (e) && e.id == 0x15 && e.value == 2);
  143. CHECK (r.next (e) && e.id == 0x40 && e.value == 513);
  144. CHECK (r.next (e) && e.id == 0x9C && e.value == 128500);
  145. CHECK (r.next (e) && e.id == 0xD5 && e.data.size() == 300 && e.data[299] == 7);
  146. CHECK (r.next (e) && e.id == 0xC0000100 && e.isData() && e.data.size() == 3 && e.data[2] == 3);
  147. CHECK (! r.next (e));
  148. }
  149. TEST (flp_truncated_file_throws)
  150. {
  151. FlpBuilder b;
  152. b.u8 (0x9C); b.u8 (1); // u32 com só 1 byte
  153. flp::EventReader r (b.bytes);
  154. flp::Event e;
  155. bool threw = false;
  156. try { r.next (e); } catch (const flp::Error&) { threw = true; }
  157. CHECK (threw);
  158. }
  159. TEST (flp_version_numbers)
  160. {
  161. CHECK (flp::parseVersionNumber ("25.2.5.5319") == 25002005u);
  162. CHECK (flp::parseVersionNumber ("20.99.3000.3031") == 20102000u);
  163. CHECK (flp::parseVersionNumber ("11.0.3") == 11000003u);
  164. }
  165. TEST (flp_playlist_record_size_by_version)
  166. {
  167. CHECK (flp::playlistRecordSize (12009003, 64) == 32);
  168. CHECK (flp::playlistRecordSize (21000000, 120) == 60);
  169. CHECK (flp::playlistRecordSize (25002005, 160) == 80);
  170. CHECK (flp::playlistRecordSize (25002005, 60) == 60); // tamanho não bate com a versão → tenta os outros
  171. CHECK (flp::playlistRecordSize (25002005, 7) == 0);
  172. }
  173. TEST (flp_parses_project_model)
  174. {
  175. FlpBuilder b (96);
  176. b.ascii (0xC7, "25.2.5.5319");
  177. b.u8 (0x9C); b.u32 (174500);
  178. b.utf16 (0xC2, u"Título");
  179. b.u8 (0x41); b.u16 (3);
  180. b.u8 (0x96); b.u32 (0x00A14547); // BGR no arquivo
  181. auto notes = noteRecord (96, 1, 48, 64, 100);
  182. auto n2 = noteRecord (0, 0, 0, 60, 128);
  183. notes.insert (notes.end(), n2.begin(), n2.end());
  184. b.data (0xE0, notes);
  185. b.u8 (0x40); b.u16 (0);
  186. b.u8 (0x15); b.u8 (0);
  187. b.utf16 (0xCB, u"Kick");
  188. {
  189. std::vector<std::uint8_t> levels (24, 0);
  190. const std::int32_t lv[] = { 3200, 12800, -150 };
  191. std::memcpy (levels.data(), lv, sizeof (lv));
  192. b.data (0xDB, levels);
  193. }
  194. b.u8 (0x68); b.u16 (5);
  195. b.u8 (0x40); b.u16 (1);
  196. b.u8 (0x15); b.u8 (2);
  197. b.utf16 (0xC9, u"FLEX");
  198. b.utf16 (0xCB, u"Lead");
  199. b.u8 (0x63); b.u16 (0);
  200. std::vector<std::uint8_t> item (80, 0);
  201. std::uint32_t pos = 384, len = 768;
  202. std::uint16_t base = 20480, idx = 20480 + 3, rv = 499 - 2;
  203. std::memcpy (&item[0], &pos, 4);
  204. std::memcpy (&item[4], &base, 2);
  205. std::memcpy (&item[6], &idx, 2);
  206. std::memcpy (&item[8], &len, 4);
  207. std::memcpy (&item[12], &rv, 2);
  208. b.data (0xE9, item);
  209. b.utf16 (0xCC, u"Drums");
  210. b.data (0xEC, std::vector<std::uint8_t> (12, 0));
  211. b.data (0xEC, std::vector<std::uint8_t> (12, 0));
  212. const auto p = flp::parseProject (b.bytes);
  213. CHECK (p.version == "25.2.5.5319");
  214. CHECK (std::abs (p.tempo - 174.5) < 1e-9);
  215. CHECK (p.title == "Título");
  216. CHECK (p.channels.size() == 2);
  217. CHECK (p.channels[0].name == "Kick" && p.channels[0].mixerTrack == 5);
  218. CHECK (p.channels[0].hasLevels && p.channels[0].pan == 3200 && p.channels[0].volume == 12800 && p.channels[0].pitchCents == -150);
  219. CHECK (p.channels[1].type == flp::ChannelType::instrument && p.channels[1].pluginName == "FLEX");
  220. CHECK (p.patterns.size() == 1 && p.patterns[0].index == 3);
  221. CHECK (p.patterns[0].colour && *p.patterns[0].colour == 0x4745A1);
  222. CHECK (p.patterns[0].notes.size() == 2 && p.patterns[0].notes[0].position == 0); // ordenadas
  223. CHECK (p.patterns[0].notes[1].key == 64 && p.patterns[0].notes[1].length == 48);
  224. CHECK (p.arrangements.size() == 1 && p.arrangements[0].items.size() == 1);
  225. const auto& it = p.arrangements[0].items[0];
  226. CHECK (it.kind == flp::PlaylistItem::Kind::pattern && it.index == 3 && it.track == 2 && it.position == 384);
  227. CHECK (p.mixer.size() == 2 && p.mixer[0].name == "Drums" && p.mixer[1].name.empty());
  228. CHECK (p.warnings.empty());
  229. }
  230. TEST (flp_real_files)
  231. {
  232. if (realFlpDir.empty())
  233. {
  234. std::printf (" (pulado: passe uma pasta com .flp como argumento)\n");
  235. return;
  236. }
  237. int files = 0, withNotes = 0, withPlaylist = 0, automations = 0, automationsWithTarget = 0, sends = 0;
  238. int threeOsc = 0, threeOscDecoded = 0;
  239. for (auto& entry : std::filesystem::recursive_directory_iterator (realFlpDir))
  240. {
  241. if (entry.path().extension() != ".flp")
  242. continue;
  243. std::ifstream in (entry.path(), std::ios::binary);
  244. std::vector<std::uint8_t> bytes ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  245. ++files;
  246. try
  247. {
  248. const auto p = flp::parseProject (bytes);
  249. CHECK (! p.version.empty());
  250. CHECK (p.tempo > 10.0 && p.tempo < 1000.0);
  251. const auto song = lynx::importFlp (p);
  252. CHECK (! song.patterns.empty());
  253. // 3x Osc: todo estado dos demos decodifica, com níveis que somam no máximo 1
  254. for (const auto& c : p.channels)
  255. if (c.pluginName == "3x Osc")
  256. {
  257. ++threeOsc;
  258. lynx::SynthSettings s;
  259. if (lynx::synthFrom3xOsc (c.pluginState, s))
  260. {
  261. ++threeOscDecoded;
  262. const auto sum = s.osc[0].level + s.osc[1].level + s.osc[2].level;
  263. CHECK (sum <= 1.001f);
  264. for (const auto& o : s.osc)
  265. CHECK (o.octave >= -2 && o.octave <= 2 && std::abs (o.semitones) <= 11 && std::abs (o.pan) <= 1.0f);
  266. }
  267. }
  268. for (auto& pat : p.patterns)
  269. if (! pat.notes.empty())
  270. {
  271. ++withNotes;
  272. break;
  273. }
  274. for (auto& a : p.arrangements)
  275. for (auto& item : a.items)
  276. CHECK (item.track >= 0 && item.track < 500);
  277. for (auto& clip : song.playlist)
  278. {
  279. CHECK (clip.pattern >= 0 && clip.pattern < (int) song.patterns.size());
  280. CHECK (clip.length > 0 && clip.offset >= 0);
  281. if (clip.kind == lynx::ClipKind::automation)
  282. CHECK (clip.automation >= 0 && clip.automation < (int) song.automations.size());
  283. }
  284. for (auto& a : song.automations)
  285. {
  286. ++automations;
  287. automationsWithTarget += a.target.kind != lynx::AutomationTargetKind::none;
  288. CHECK (! a.points.empty());
  289. for (std::size_t i = 1; i < a.points.size(); ++i)
  290. CHECK (a.points[i].tick >= a.points[i - 1].tick);
  291. }
  292. // roteamento importado sem ciclos e com destinos válidos
  293. CHECK (song.mixerOrder().size() + 1 == song.mixer.size());
  294. for (auto& t : song.mixer)
  295. for (auto& s : t.sends)
  296. {
  297. ++sends;
  298. CHECK (s.target > 0 && s.target < (int) song.mixer.size());
  299. }
  300. if (! song.playlist.empty())
  301. ++withPlaylist;
  302. }
  303. catch (const flp::Error& e)
  304. {
  305. ++failures;
  306. std::printf (" FALHOU %s: %s\n", entry.path().string().c_str(), e.what());
  307. }
  308. }
  309. CHECK (threeOscDecoded == threeOsc);
  310. std::printf (" %d canais 3x Osc, %d decodificados\n", threeOsc, threeOscDecoded);
  311. std::printf (" %d arquivos .flp lidos, %d com notas, %d com playlist, %d automações (%d com alvo), %d envios\n",
  312. files, withNotes, withPlaylist, automations, automationsWithTarget, sends);
  313. CHECK (files > 0);
  314. CHECK (automations > 0 && sends > 0);
  315. }
  316. // ---------------------------------------------------------------------------
  317. // Sequenciador
  318. TEST (pattern_toggle_step_and_length)
  319. {
  320. lynx::Pattern p;
  321. CHECK (! p.hasStep (0, 4));
  322. p.toggleStep (0, 4);
  323. CHECK (p.hasStep (0, 4));
  324. CHECK (p.notes.size() == 1 && p.notes[0].start == 4 * lynx::ticksPerStep);
  325. CHECK (p.effectiveLength (4) == 4 * lynx::ppq); // um compasso
  326. p.toggleStep (1, 20); // segundo compasso
  327. CHECK (p.effectiveLength (4) == 8 * lynx::ppq);
  328. p.toggleStep (0, 4);
  329. CHECK (! p.hasStep (0, 4) && p.notes.size() == 1);
  330. }
  331. TEST (scheduler_places_events_at_exact_samples)
  332. {
  333. lynx::Pattern p;
  334. p.toggleStep (0, 0);
  335. p.toggleStep (0, 4); // tick 960 = 1 tempo
  336. const double sr = 48000.0, bpm = 120.0; // 1 tempo = 0,5 s = 24000 samples
  337. const auto tps = lynx::ticksPerSample (bpm, sr);
  338. lynx::EventBuffer ev;
  339. lynx::schedulePatternLoop (p, p.effectiveLength (4), 23900.0 * tps, 512, tps, ev);
  340. // a nota do tempo 2 começa no sample 24000 → offset 100 neste bloco
  341. int ons = 0;
  342. for (auto& e : ev)
  343. if (e.type == lynx::NoteEvent::Type::on)
  344. {
  345. ++ons;
  346. CHECK (e.sampleOffset == 100);
  347. }
  348. CHECK (ons == 1);
  349. }
  350. TEST (scheduler_wraps_the_loop)
  351. {
  352. lynx::Pattern p;
  353. p.toggleStep (2, 0);
  354. const auto len = p.effectiveLength (4); // 3840 ticks
  355. const double sr = 48000.0;
  356. const auto tps = lynx::ticksPerSample (120.0, sr);
  357. lynx::EventBuffer ev;
  358. // bloco que atravessa o fim do loop: começa 10 samples antes
  359. const auto start = (double) len - 10.0 * tps;
  360. lynx::schedulePatternLoop (p, len, start, 64, tps, ev);
  361. bool found = false;
  362. for (auto& e : ev)
  363. if (e.type == lynx::NoteEvent::Type::on && e.channel == 2)
  364. {
  365. found = true;
  366. CHECK (e.sampleOffset == 10);
  367. }
  368. CHECK (found);
  369. }
  370. TEST (scheduler_off_before_on_at_same_sample)
  371. {
  372. lynx::Pattern p;
  373. lynx::Note a;
  374. a.start = 0; a.length = 240; a.channel = 0;
  375. lynx::Note b = a;
  376. b.start = 240;
  377. p.notes = { a, b };
  378. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  379. lynx::EventBuffer ev;
  380. lynx::schedulePatternLoop (p, p.effectiveLength (4), 200.0, 4000, tps, ev);
  381. CHECK (ev.size() >= 2);
  382. CHECK (ev[0].type == lynx::NoteEvent::Type::off);
  383. CHECK (ev[1].type == lynx::NoteEvent::Type::on);
  384. CHECK (ev[0].sampleOffset == ev[1].sampleOffset);
  385. }
  386. TEST (snapshot_exchange_hands_over_and_recycles)
  387. {
  388. struct Counted
  389. {
  390. int value;
  391. int* alive;
  392. Counted (int v, int* a) : value (v), alive (a) { ++*alive; }
  393. ~Counted() { --*alive; }
  394. };
  395. int alive = 0;
  396. {
  397. lynx::SnapshotExchange<Counted> x;
  398. CHECK (x.acquire() == nullptr);
  399. x.publish (std::make_unique<Counted> (1, &alive));
  400. CHECK (x.acquire()->value == 1);
  401. x.publish (std::make_unique<Counted> (2, &alive));
  402. x.publish (std::make_unique<Counted> (3, &alive)); // 2 nunca foi lido: liberado na hora
  403. CHECK (alive == 2);
  404. CHECK (x.acquire()->value == 3);
  405. CHECK (alive == 2); // o 1 foi devolvido, mas só a UI libera
  406. x.collectGarbage();
  407. CHECK (alive == 1);
  408. // sem coleta, as vagas de devolução enchem e o áudio segura o atual
  409. for (int i = 0; i < 20; ++i)
  410. {
  411. x.publish (std::make_unique<Counted> (10 + i, &alive));
  412. CHECK (x.acquire() != nullptr);
  413. }
  414. }
  415. CHECK (alive == 0);
  416. }
  417. TEST (rack_renderer_makes_sound_and_reuses_instruments)
  418. {
  419. auto song = lynx::Song::makeDefault();
  420. song.bpm = 120.0;
  421. const double sr = 48000.0;
  422. auto state = lynx::RackState::build (song, nullptr, sr);
  423. lynx::RackRenderer r;
  424. r.prepare (sr);
  425. std::vector<float> l (512), rr (512);
  426. double tick = 0.0;
  427. float peak = 0.0f;
  428. int kicks = 0;
  429. for (int block = 0; block < 93; ++block) // 47616 samples: logo antes de 1 s
  430. {
  431. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  432. for (auto& e : r.lastEvents())
  433. if (e.type == lynx::NoteEvent::Type::on && e.channel == 0)
  434. ++kicks;
  435. for (int i = 0; i < 512; ++i)
  436. {
  437. CHECK (std::isfinite (l[(std::size_t) i]));
  438. peak = std::max (peak, std::abs (l[(std::size_t) i]));
  439. }
  440. tick += 512 * lynx::ticksPerSample (song.bpm, sr);
  441. }
  442. CHECK (peak > 0.1f && peak < 4.0f);
  443. CHECK (kicks == 2); // 120 BPM: tempos em 0 e 0,5 s
  444. // editar a música preserva os instrumentos de canais que não mudaram de tipo
  445. song.channels[4].instrument = lynx::InstrumentKind::kick;
  446. auto next = lynx::RackState::build (song, state.get(), sr);
  447. CHECK (next->instruments[0] == state->instruments[0]);
  448. CHECK (next->instruments[4] != state->instruments[4]);
  449. // parar silencia o synth e não dispara notas novas
  450. r.process (next.get(), false, tick, 512, l.data(), rr.data());
  451. CHECK (r.lastEvents().size() == 0);
  452. }
  453. TEST (flp_import_maps_channels_and_rescales)
  454. {
  455. flp::Project p;
  456. p.header.ppq = 96;
  457. p.tempo = 150.0;
  458. p.channels = { { 0, flp::ChannelType::sampler, "Kick 808", "", "", 1 },
  459. { 1, flp::ChannelType::audioClip, "Vocal", "", "", 2 },
  460. { 2, flp::ChannelType::instrument, "Lead", "FLEX", "", 3 } };
  461. flp::Pattern pat;
  462. pat.index = 1;
  463. flp::Note n;
  464. n.position = 96;
  465. n.length = 0;
  466. n.channel = 2;
  467. n.key = 72;
  468. n.velocity = 64;
  469. pat.notes.push_back (n);
  470. p.patterns.push_back (pat);
  471. const auto s = lynx::importFlp (p);
  472. CHECK (s.bpm == 150.0);
  473. CHECK (s.channels.size() == 3); // canais de clip de áudio ficam no rack, como no FL
  474. CHECK (s.channels[0].instrument == lynx::InstrumentKind::kick);
  475. CHECK (s.channels[1].instrument == lynx::InstrumentKind::audioClip);
  476. CHECK (s.channels[2].instrument == lynx::InstrumentKind::synth);
  477. CHECK (s.patterns.size() == 1);
  478. CHECK (s.patterns[0].notes[0].start == lynx::ppq); // 96 @ PPQ 96 = 1 tempo
  479. CHECK (s.patterns[0].notes[0].channel == 2);
  480. CHECK (s.patterns[0].notes[0].length == lynx::ticksPerStep); // nota de step
  481. CHECK (std::abs (s.patterns[0].notes[0].velocity - 0.5f) < 1e-6f);
  482. }
  483. TEST (live_queue_is_fifo_and_bounded)
  484. {
  485. lynx::LiveEventQueue q;
  486. lynx::NoteEvent e;
  487. CHECK (! q.pop (e));
  488. for (int i = 0; i < 10; ++i)
  489. {
  490. lynx::NoteEvent in;
  491. in.key = i;
  492. CHECK (q.push (in));
  493. }
  494. for (int i = 0; i < 10; ++i)
  495. CHECK (q.pop (e) && e.key == i);
  496. int pushed = 0;
  497. while (q.push (e))
  498. ++pushed;
  499. CHECK (pushed == (int) lynx::LiveEventQueue::capacity - 1); // uma vaga fica livre para distinguir cheio de vazio
  500. }
  501. TEST (sampler_plays_pitched_one_shot)
  502. {
  503. // sample de 1000 frames com rampa: dá para medir a posição pela amplitude
  504. auto data = std::make_shared<lynx::SampleData>();
  505. data->sampleRate = 48000.0;
  506. for (int i = 0; i < 1000; ++i)
  507. data->left.push_back (1.0f);
  508. auto sampler = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  509. sampler->prepare (48000.0);
  510. std::vector<float> l (2048, 0.0f), r (2048, 0.0f);
  511. sampler->noteOn (60, 1.0f);
  512. sampler->noteOff (60); // one-shot: noteOff não corta
  513. sampler->render (l.data(), r.data(), 2048, 1.0f, 1.0f);
  514. int sounding = 0;
  515. for (auto s : l)
  516. sounding += s > 0.5f;
  517. CHECK (sounding >= 995 && sounding <= 1000); // toca o sample inteiro na altura original
  518. std::fill (l.begin(), l.end(), 0.0f);
  519. sampler->noteOn (72, 1.0f); // uma oitava acima: metade da duração
  520. sampler->render (l.data(), r.data(), 2048, 1.0f, 1.0f);
  521. sounding = 0;
  522. for (auto s : l)
  523. sounding += s > 0.5f;
  524. CHECK (sounding >= 495 && sounding <= 500);
  525. CHECK (r[10] > 0.5f); // mono vai para os dois lados
  526. auto silent = lynx::makeInstrument (lynx::InstrumentKind::sampler, nullptr);
  527. silent->prepare (48000.0);
  528. silent->noteOn (60, 1.0f);
  529. std::fill (l.begin(), l.end(), 0.0f);
  530. silent->render (l.data(), r.data(), 64, 1.0f, 1.0f);
  531. CHECK (l[0] == 0.0f);
  532. }
  533. TEST (rack_live_notes_and_sample_provider)
  534. {
  535. lynx::Song song;
  536. lynx::ChannelDef c;
  537. c.name = "Smp";
  538. c.instrument = lynx::InstrumentKind::sampler;
  539. c.samplePath = "a.wav";
  540. song.channels.push_back (c);
  541. song.patterns.emplace_back();
  542. int loads = 0;
  543. auto provider = [&] (const std::string& path) -> std::shared_ptr<const lynx::SampleData> {
  544. ++loads;
  545. CHECK (path == "a.wav");
  546. auto d = std::make_shared<lynx::SampleData>();
  547. d->left.assign (4800, 0.5f);
  548. return d;
  549. };
  550. auto state = lynx::RackState::build (song, nullptr, 48000.0, provider);
  551. CHECK (loads == 1);
  552. lynx::RackRenderer renderer;
  553. renderer.prepare (48000.0);
  554. lynx::LiveEventQueue live;
  555. lynx::NoteEvent on;
  556. on.channel = 0;
  557. on.velocity = 1.0f;
  558. live.push (on);
  559. std::vector<float> l (256), r (256);
  560. renderer.process (state.get(), false, 0.0, 256, l.data(), r.data(), &live); // parado, mas a nota ao vivo toca
  561. CHECK (l[0] > 0.1f);
  562. // mesmo sample: reaproveita; sample diferente: recarrega
  563. auto same = lynx::RackState::build (song, state.get(), 48000.0, provider);
  564. CHECK (loads == 1 && same->instruments[0] == state->instruments[0]);
  565. song.channels[0].samplePath = "b.wav";
  566. auto other = lynx::RackState::build (song, state.get(), 48000.0, [&] (const std::string&) { ++loads; return nullptr; });
  567. CHECK (loads == 2 && other->instruments[0] != state->instruments[0]);
  568. }
  569. TEST (flp_paths_resolve_and_samplers_import)
  570. {
  571. lynx::FlPathRoots roots { "C:\\FL", "C:\\FL\\Data", "D:\\User" };
  572. CHECK (lynx::resolveFlPath ("%FLStudioFactoryData%\\Data\\x.wav", roots) == "C:\\FL\\Data\\x.wav");
  573. CHECK (lynx::resolveFlPath ("%FLStudioData%\\Patches\\y.wav", roots) == "C:\\FL\\Data\\Patches\\y.wav");
  574. CHECK (lynx::resolveFlPath ("%FLStudioUserData%\\z.wav", roots) == "D:\\User\\z.wav");
  575. CHECK (lynx::resolveFlPath ("E:\\abs.wav", roots) == "E:\\abs.wav");
  576. CHECK (lynx::resolveFlPath ("%FLStudioUserData%\\z.wav", {}) == "");
  577. flp::Project p;
  578. p.channels = { { 0, flp::ChannelType::sampler, "Kick", "", "%FLStudioData%\\k.wav", 1 },
  579. { 1, flp::ChannelType::sampler, "Hat", "", "%FLStudioData%\\missing.wav", 1 } };
  580. lynx::FlpImportOptions options;
  581. options.roots = roots;
  582. options.fileExists = [] (const std::string& path) { return path == "C:\\FL\\Data\\k.wav"; };
  583. const auto s = lynx::importFlp (p, options);
  584. CHECK (s.channels[0].instrument == lynx::InstrumentKind::sampler);
  585. CHECK (s.channels[0].samplePath == "C:\\FL\\Data\\k.wav");
  586. CHECK (s.channels[1].instrument == lynx::InstrumentKind::hat); // sem arquivo: instrumento interno
  587. }
  588. TEST (soft_clip_is_transparent_below_knee_and_bounded)
  589. {
  590. float s[] = { 0.5f, -0.89f, 1.5f, -3.0f, 0.95f };
  591. lynx::softClip (s, 5);
  592. CHECK (s[0] == 0.5f && s[1] == -0.89f);
  593. CHECK (s[2] > 0.9f && s[2] <= 1.0f);
  594. CHECK (s[3] < -0.9f && s[3] >= -1.0f);
  595. CHECK (s[4] > 0.9f && s[4] < 0.95f);
  596. }
  597. TEST (song_scheduler_plays_clips_with_offset_and_cut)
  598. {
  599. lynx::Song s;
  600. s.channels.resize (1);
  601. auto& p = s.patterns.emplace_back();
  602. for (int step : { 0, 4, 8, 12 }) // uma nota por tempo
  603. p.toggleStep (0, step);
  604. // clip no compasso 2 tocando só a segunda metade da pattern (tempos 3 e 4)
  605. lynx::Clip c;
  606. c.pattern = 0;
  607. c.start = 4 * lynx::ppq;
  608. c.length = 2 * lynx::ppq;
  609. c.offset = 2 * lynx::ppq;
  610. s.playlist.push_back (c);
  611. CHECK (s.songLength() == 8 * lynx::ppq);
  612. const double sr = 48000.0;
  613. const auto tps = lynx::ticksPerSample (120.0, sr); // 1 tempo = 24000 samples
  614. lynx::EventBuffer ev;
  615. // música inteira em um bloco só (8 tempos = 192000 samples)
  616. lynx::scheduleSong (s, 0.0, 192000, tps, ev);
  617. std::vector<int> ons;
  618. for (auto& e : ev)
  619. if (e.type == lynx::NoteEvent::Type::on)
  620. ons.push_back (e.sampleOffset);
  621. CHECK (ons.size() == 2);
  622. CHECK (ons.size() == 2 && ons[0] == 4 * 24000 && ons[1] == 5 * 24000);
  623. // atravessando o loop: o compasso 1 está vazio, então nada no começo do segundo giro
  624. ev.clear();
  625. lynx::scheduleSong (s, 8.0 * lynx::ppq - 100 * tps, 200, tps, ev);
  626. CHECK (ev.size() == 0);
  627. // nota mais longa que o clip é cortada no fim do clip
  628. p.notes[3].length = 4 * lynx::ppq;
  629. ev.clear();
  630. lynx::scheduleSong (s, 0.0, 192000, tps, ev);
  631. int lastOff = -1;
  632. for (auto& e : ev)
  633. if (e.type == lynx::NoteEvent::Type::off)
  634. lastOff = std::max (lastOff, e.sampleOffset);
  635. CHECK (lastOff == 6 * 24000);
  636. }
  637. TEST (remove_pattern_fixes_clips)
  638. {
  639. lynx::Song s;
  640. s.patterns.resize (3);
  641. s.currentPattern = 2;
  642. s.playlist = { { 0, 0, 0, 100, 0 }, { 1, 0, 100, 100, 0 }, { 2, 1, 0, 100, 0 } };
  643. s.removePattern (1);
  644. CHECK (s.patterns.size() == 2);
  645. CHECK (s.playlist.size() == 2 && s.playlist[1].pattern == 1);
  646. CHECK (s.currentPattern == 1);
  647. }
  648. TEST (flp_import_3x_osc_state_and_channel_filter)
  649. {
  650. // patch novo do 3x Osc (versão 14): osc 2 mix 64 coarse -12, osc 3 mix 32 coarse -24
  651. std::vector<std::uint8_t> blob (460, 0);
  652. auto put = [&] (std::size_t off, std::int32_t v) {
  653. for (int b = 0; b < 4; ++b)
  654. blob[off + (std::size_t) b] = (std::uint8_t) ((std::uint32_t) v >> (8 * b));
  655. };
  656. put (0x00, 14);
  657. put (0x08, 3); // osc 1 serra
  658. put (0x10, 7); // osc 1 fine +7
  659. put (0x04, -32); // osc 1 pan -0,5
  660. put (0x1C, 64); // osc 2 mix
  661. put (0x28, -12); // osc 2 coarse
  662. put (0x38, 32); // osc 3 mix
  663. put (0x40, 2); // osc 3 quadrada
  664. put (0x44, -19); // osc 3 coarse: -1 oitava e -7 semitons
  665. lynx::SynthSettings s;
  666. CHECK (lynx::synthFrom3xOsc (blob, s));
  667. 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);
  668. CHECK (s.osc[0].wave == lynx::Waveform::saw && s.osc[0].detune == 7.0f && s.osc[0].pan == -0.5f);
  669. CHECK (s.osc[1].wave == lynx::Waveform::sine && s.osc[1].octave == -1 && s.osc[1].semitones == 0);
  670. CHECK (s.osc[2].wave == lynx::Waveform::square && s.osc[2].octave == -1 && s.osc[2].semitones == -7);
  671. CHECK (! lynx::synthFrom3xOsc (std::vector<std::uint8_t> (40, 0), s));
  672. // filtro do canal: padrão aberto; LP com Mod X 128 ~ 2,71 kHz; Fast LP com Mod X 128 ~ 280 Hz
  673. float hz = 0.0f, res = 1.0f;
  674. lynx::synthFilterFromChannel (256, 0, 0, hz, res);
  675. CHECK (hz >= 19999.0f && res == 0.0f);
  676. lynx::synthFilterFromChannel (128, 0, 1, hz, res);
  677. CHECK (std::abs (hz - 2710.0f) < 30.0f && res == 0.0f);
  678. lynx::synthFilterFromChannel (128, 0, 0, hz, res);
  679. CHECK (hz > 240.0f && hz < 320.0f);
  680. lynx::synthFilterFromChannel (128, 256, 1, hz, res);
  681. CHECK (res > 0.8f);
  682. lynx::synthFilterFromChannel (64, 0, 3, hz, res); // passa-altas: o synth não tem, fica aberto
  683. CHECK (hz >= 19999.0f);
  684. }
  685. TEST (sampler_channel_filter_darkens_and_bypasses_when_open)
  686. {
  687. // ruído branco no sampler: com corte em 300 Hz a energia cai muito; aberto passa igual
  688. auto data = std::make_shared<lynx::SampleData>();
  689. data->sampleRate = 48000.0;
  690. data->left.resize (48000);
  691. std::uint32_t seed = 7;
  692. for (auto& v : data->left)
  693. {
  694. seed = seed * 1664525u + 1013904223u;
  695. v = ((float) (seed >> 8) / 16777216.0f - 0.5f);
  696. }
  697. data->right = data->left;
  698. auto energy = [&] (float cutoff) {
  699. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, data);
  700. inst->prepare (48000.0);
  701. lynx::ChannelDef c;
  702. c.sampler.cutoff = cutoff;
  703. inst->configure (c, 120.0);
  704. inst->noteOn (60, 1.0f);
  705. std::vector<float> l (24000), r (24000);
  706. inst->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  707. double e = 0.0;
  708. for (auto v : l)
  709. e += (double) v * v;
  710. return e;
  711. };
  712. const auto open = energy (20000.0f), dark = energy (300.0f);
  713. CHECK (open > 100.0);
  714. CHECK (dark < open * 0.05);
  715. }
  716. TEST (synth_oscillator_pan_and_semitones)
  717. {
  718. auto render = [] (lynx::SynthSettings s, std::vector<float>& l, std::vector<float>& r) {
  719. auto synth = lynx::makeInstrument (lynx::InstrumentKind::synth);
  720. synth->prepare (48000.0);
  721. lynx::ChannelDef c;
  722. c.synth = s;
  723. synth->configure (c, 120.0);
  724. synth->noteOn (69, 1.0f);
  725. l.assign (24000, 0.0f);
  726. r.assign (24000, 0.0f);
  727. synth->render (l.data(), r.data(), 24000, 1.0f, 1.0f);
  728. };
  729. lynx::SynthSettings s;
  730. s.osc[0] = { lynx::Waveform::sine, 0, 0.0f, 1.0f, 7, 1.0f }; // quinta acima, todo à direita
  731. s.cutoff = 20000.0f;
  732. std::vector<float> l, r;
  733. render (s, l, r);
  734. float peakL = 0.0f, peakR = 0.0f;
  735. int crossings = 0;
  736. for (std::size_t i = 4800; i < 24000; ++i)
  737. {
  738. peakL = std::max (peakL, std::abs (l[i]));
  739. peakR = std::max (peakR, std::abs (r[i]));
  740. crossings += (r[i - 1] < 0.0f) != (r[i] < 0.0f);
  741. }
  742. CHECK (peakL < 1e-4f && peakR > 0.1f);
  743. // 440 * 2^(7/12) = 659,3 Hz; 0,4 s = 263,7 ciclos = ~527 cruzamentos
  744. CHECK (std::abs (crossings - 527) < 6);
  745. }
  746. TEST (flp_import_brings_playlist)
  747. {
  748. flp::Project p;
  749. p.header.ppq = 96;
  750. p.channels = { { 0, flp::ChannelType::sampler, "Kick", "", "", 1 } };
  751. flp::Pattern empty;
  752. empty.index = 1;
  753. flp::Pattern full;
  754. full.index = 2;
  755. flp::Note n;
  756. n.channel = 0;
  757. full.notes.push_back (n);
  758. p.patterns = { empty, full };
  759. flp::Arrangement a;
  760. flp::PlaylistItem item;
  761. item.kind = flp::PlaylistItem::Kind::pattern;
  762. item.index = 2;
  763. item.position = 384;
  764. item.length = 192;
  765. item.track = 3;
  766. item.patternStartTick = 96;
  767. a.items.push_back (item);
  768. item.index = 1; // pattern vazia: descartada
  769. a.items.push_back (item);
  770. item.kind = flp::PlaylistItem::Kind::channelClip; // áudio: ainda não suportado
  771. a.items.push_back (item);
  772. p.arrangements.push_back (a);
  773. const auto s = lynx::importFlp (p);
  774. CHECK (s.mode == lynx::PlayMode::song);
  775. CHECK (s.playlist.size() == 1);
  776. CHECK (s.playlist[0].pattern == 0 && s.playlist[0].track == 3);
  777. CHECK (s.playlist[0].start == 4 * lynx::ppq && s.playlist[0].length == 2 * lynx::ppq && s.playlist[0].offset == lynx::ppq);
  778. }
  779. TEST (rack_releases_notes_on_position_jump)
  780. {
  781. lynx::Song s;
  782. lynx::ChannelDef c;
  783. c.instrument = lynx::InstrumentKind::synth;
  784. s.channels.push_back (c);
  785. auto& p = s.patterns.emplace_back();
  786. lynx::Note n;
  787. n.start = 0;
  788. n.length = 4 * lynx::ppq; // nota longa
  789. p.notes.push_back (n);
  790. s.bpm = 120.0;
  791. auto state = lynx::RackState::build (s, nullptr, 48000.0);
  792. lynx::RackRenderer r;
  793. r.prepare (48000.0);
  794. std::vector<float> l (512), rr (512);
  795. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  796. double tick = 0.0;
  797. for (int i = 0; i < 20; ++i, tick += 512 * tps)
  798. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  799. // salto para o tick 2000 (no meio da nota, sem "on" novo): o synth precisa calar
  800. for (int i = 0; i < 40; ++i)
  801. r.process (state.get(), true, 2000.0 + i * 512 * tps, 512, l.data(), rr.data());
  802. float tail = 0.0f;
  803. for (auto v : l)
  804. tail = std::max (tail, std::abs (v));
  805. CHECK (tail < 0.001f);
  806. }
  807. namespace
  808. {
  809. // Dois samplers de sinal constante 0,5 em inserts diferentes; retorna o pico da saída.
  810. float juce_db (float gain)
  811. {
  812. return 20.0f * std::log10 (gain);
  813. }
  814. float renderMixerCase (const std::function<void (lynx::Song&)>& tweak, lynx::MeterBank* meters = nullptr)
  815. {
  816. lynx::Song s;
  817. s.mixer = lynx::Song::defaultMixer (4);
  818. for (int i = 0; i < 2; ++i)
  819. {
  820. lynx::ChannelDef c;
  821. c.instrument = lynx::InstrumentKind::sampler;
  822. c.samplePath = "dc";
  823. c.volume = 1.0f;
  824. c.mixerTrack = i + 1;
  825. s.channels.push_back (c);
  826. }
  827. s.patterns.emplace_back();
  828. tweak (s);
  829. auto provider = [] (const std::string&) {
  830. auto d = std::make_shared<lynx::SampleData>();
  831. d->left.assign (48000, 0.5f);
  832. return std::shared_ptr<const lynx::SampleData> (d);
  833. };
  834. auto state = lynx::RackState::build (s, nullptr, 48000.0, provider);
  835. lynx::RackRenderer r;
  836. r.prepare (48000.0, 256);
  837. lynx::LiveEventQueue live;
  838. for (int ch = 0; ch < 2; ++ch)
  839. {
  840. lynx::NoteEvent on;
  841. on.channel = ch;
  842. on.velocity = 1.0f;
  843. live.push (on);
  844. }
  845. std::vector<float> l (1000), rr (1000); // maior que o bloco do mixer: testa os pedaços
  846. r.process (state.get(), false, 0.0, 1000, l.data(), rr.data(), &live, meters);
  847. return std::max (std::abs (l[999]), std::abs (rr[999]));
  848. }
  849. } // namespace
  850. TEST (mixer_routes_mutes_solos_and_meters)
  851. {
  852. // dois canais de 0,5 somados no Master em 0 dB
  853. CHECK (std::abs (renderMixerCase ([] (lynx::Song&) {}) - 1.0f) < 1e-4f);
  854. // mute do insert 1: sobra só o canal 2
  855. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.mixer[1].muted = true; }) - 0.5f) < 1e-4f);
  856. // solo no insert 2: idem
  857. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.mixer[2].solo = true; }) - 0.5f) < 1e-4f);
  858. // curva do fader do FL: 0,8 = 0 dB, máximo ≈ +5,6 dB, metade do curso ≈ -12,7 dB
  859. CHECK (std::abs (lynx::faderGain (0.8f) - 1.0f) < 1e-5f);
  860. CHECK (std::abs (juce_db (lynx::faderGain (1.0f)) - 5.59f) < 0.05f);
  861. CHECK (lynx::faderGain (0.0f) == 0.0f);
  862. // fader do Master no máximo
  863. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.mixer[0].volume = 1.0f; }) - lynx::faderGain (1.0f)) < 1e-4f);
  864. // os dois canais no mesmo insert, insert com fader em 0,4
  865. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) {
  866. s.channels[1].mixerTrack = 1;
  867. s.mixer[1].volume = 0.4f;
  868. }) - lynx::faderGain (0.4f)) < 1e-4f);
  869. // rota fora do mixer cai no último insert existente, sem travar
  870. CHECK (renderMixerCase ([] (lynx::Song& s) { s.channels[0].mixerTrack = 100; }) > 0.9f);
  871. // sem mixer: tudo direto na saída em 0 dB
  872. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.mixer.clear(); }) - 1.0f) < 1e-4f);
  873. lynx::MeterBank meters;
  874. renderMixerCase ([] (lynx::Song&) {}, &meters);
  875. CHECK (std::abs (meters.takePeak (1, 0) - 0.5f) < 1e-4f);
  876. CHECK (std::abs (meters.takePeak (0, 1) - 1.0f) < 1e-4f);
  877. CHECK (meters.takePeak (1, 0) == 0.0f); // ler zera
  878. CHECK (meters.takePeak (3, 0) == 0.0f); // insert sem canal
  879. }
  880. TEST (next_free_insert_and_flp_mixer_import)
  881. {
  882. auto s = lynx::Song::makeDefault();
  883. CHECK (s.mixer.size() == 17 && s.mixer[0].name == "Master");
  884. CHECK (s.nextFreeInsert() == 6); // os 5 canais padrão ocupam 1..5
  885. flp::Project p;
  886. p.channels = { { 0, flp::ChannelType::sampler, "Kick", "", "", 30 } };
  887. p.mixer = { { 0, "" }, { 30, "Drums" } };
  888. const auto song = lynx::importFlp (p);
  889. CHECK (song.channels[0].mixerTrack == 30);
  890. CHECK (song.mixer.size() == 31);
  891. CHECK (song.mixer[30].name == "Drums" && song.mixer[0].name == "Master");
  892. }
  893. namespace
  894. {
  895. float runEffectOnSine (lynx::EffectKind kind, const std::function<void (lynx::EffectSlot&)>& tweak, double hz, float amp,
  896. int frames = 48000)
  897. {
  898. auto fx = lynx::makeEffect (kind);
  899. fx->prepare (48000.0);
  900. auto slot = lynx::makeEffectSlot (kind);
  901. tweak (slot);
  902. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  903. for (int i = 0; i < frames; ++i)
  904. l[(std::size_t) i] = r[(std::size_t) i] = amp * (float) std::sin (6.283185307 * hz * i / 48000.0);
  905. for (int i = 0; i < frames; i += 480)
  906. fx->process (l.data() + i, r.data() + i, std::min (480, frames - i), slot.params, 120.0);
  907. float peak = 0.0f;
  908. for (int i = frames / 2; i < frames; ++i) // segunda metade: já estabilizado
  909. {
  910. CHECK (std::isfinite (l[(std::size_t) i]));
  911. peak = std::max (peak, std::abs (l[(std::size_t) i]));
  912. }
  913. return peak;
  914. }
  915. } // namespace
  916. TEST (effects_eq_compressor_behave)
  917. {
  918. // EQ no padrão é transparente
  919. CHECK (std::abs (runEffectOnSine (lynx::EffectKind::eq, [] (auto&) {}, 1000.0, 0.5f) - 0.5f) < 0.01f);
  920. // +18 dB nos graves: 60 Hz sobe bastante, 5 kHz quase nada
  921. CHECK (runEffectOnSine (lynx::EffectKind::eq, [] (auto& s) { s.params[0] = 1.0f; }, 60.0, 0.05f) > 0.3f);
  922. CHECK (runEffectOnSine (lynx::EffectKind::eq, [] (auto& s) { s.params[0] = 1.0f; }, 5000.0, 0.05f) < 0.06f);
  923. // compressor: threshold -20 dB, ratio 20:1 achata um sinal de 0 dBFS para perto do threshold
  924. const auto squashed = runEffectOnSine (lynx::EffectKind::compressor, [] (auto& s) {
  925. s.params[0] = 40.0f / 60.0f;
  926. s.params[1] = 1.0f;
  927. }, 200.0, 1.0f);
  928. CHECK (squashed < 0.2f && squashed > 0.05f);
  929. // sinal abaixo do threshold passa intacto
  930. CHECK (std::abs (runEffectOnSine (lynx::EffectKind::compressor, [] (auto& s) { s.params[0] = 1.0f; }, 200.0, 0.3f) - 0.3f) < 0.01f);
  931. }
  932. TEST (effects_delay_echoes_on_tempo_and_reverb_has_tail)
  933. {
  934. auto delay = lynx::makeEffect (lynx::EffectKind::delay);
  935. delay->prepare (48000.0);
  936. auto slot = lynx::makeEffectSlot (lynx::EffectKind::delay);
  937. slot.params[0] = 3.5f / 8.0f; // índice 3 = 1/4 = 0,5 s a 120 BPM
  938. slot.params[1] = 0.0f; // sem feedback: um eco só
  939. slot.params[2] = 1.0f;
  940. slot.params[4] = 0.0f; // sem abafar
  941. std::vector<float> l (48000, 0.0f), r (48000, 0.0f);
  942. l[0] = r[0] = 1.0f;
  943. delay->process (l.data(), r.data(), 48000, slot.params, 120.0);
  944. CHECK (std::abs (l[24000] - 1.0f) < 1e-4f);
  945. CHECK (std::abs (l[12000]) < 1e-6f);
  946. auto reverb = lynx::makeEffect (lynx::EffectKind::reverb);
  947. reverb->prepare (48000.0);
  948. auto rs = lynx::makeEffectSlot (lynx::EffectKind::reverb);
  949. rs.params[3] = 1.0f;
  950. std::fill (l.begin(), l.end(), 0.0f);
  951. std::fill (r.begin(), r.end(), 0.0f);
  952. l[0] = r[0] = 1.0f;
  953. reverb->process (l.data(), r.data(), 48000, rs.params, 120.0);
  954. float tail = 0.0f;
  955. for (int i = 4800; i < 9600; ++i) // entre 100 e 200 ms depois do impulso
  956. tail = std::max (tail, std::abs (l[(std::size_t) i]));
  957. CHECK (tail > 1e-4f && tail < 1.0f);
  958. CHECK (lynx::formatEffectParam (lynx::EffectKind::delay, 0, slot.params[0], 120.0) == "1/4 (500 ms)");
  959. }
  960. TEST (rack_runs_insert_effects_and_reuses_them)
  961. {
  962. // insert com EQ a -inf não existe; usamos a saída do EQ em -18 dB para ver o efeito agir
  963. const auto quiet = renderMixerCase ([] (lynx::Song& s) {
  964. auto eq = lynx::makeEffectSlot (lynx::EffectKind::eq);
  965. eq.params[4] = 0.0f; // saída -18 dB
  966. s.mixer[1].effects.push_back (eq);
  967. });
  968. CHECK (quiet > 0.55f && quiet < 0.6f); // 0,5 do canal 2 + 0,5 * 0,126 do canal 1
  969. const auto bypassed = renderMixerCase ([] (lynx::Song& s) {
  970. auto eq = lynx::makeEffectSlot (lynx::EffectKind::eq);
  971. eq.params[4] = 0.0f;
  972. eq.enabled = false;
  973. s.mixer[1].effects.push_back (eq);
  974. });
  975. CHECK (std::abs (bypassed - 1.0f) < 1e-4f);
  976. auto s = lynx::Song::makeDefault();
  977. s.mixer[2].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::reverb));
  978. auto a = lynx::RackState::build (s, nullptr, 48000.0);
  979. s.mixer[2].effects[0].params[0] = 0.9f; // mexer num knob não recria o efeito
  980. auto b = lynx::RackState::build (s, a.get(), 48000.0);
  981. CHECK (b->effects[2][0] == a->effects[2][0]);
  982. s.mixer[2].effects[0] = lynx::makeEffectSlot (lynx::EffectKind::delay);
  983. auto c = lynx::RackState::build (s, b.get(), 48000.0);
  984. CHECK (c->effects[2][0] != b->effects[2][0]);
  985. }
  986. TEST (audio_clips_trigger_cut_and_resume)
  987. {
  988. lynx::Song s;
  989. s.bpm = 120.0; // 1 tempo = 0,5 s = 24000 samples a 48 kHz
  990. lynx::ChannelDef c;
  991. c.instrument = lynx::InstrumentKind::audioClip;
  992. c.samplePath = "ramp";
  993. c.volume = 1.0f;
  994. s.channels.push_back (c);
  995. s.patterns.emplace_back();
  996. lynx::Clip clip;
  997. clip.kind = lynx::ClipKind::audio;
  998. clip.channel = 0;
  999. clip.start = lynx::ppq; // começa no tempo 2
  1000. clip.length = 2 * lynx::ppq; // dura 2 tempos
  1001. clip.offset = lynx::ppq; // pula o primeiro tempo do áudio
  1002. s.playlist.push_back (clip);
  1003. s.mode = lynx::PlayMode::song;
  1004. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  1005. lynx::EventBuffer ev;
  1006. lynx::scheduleSong (s, 0.0, 4 * 24000, tps, ev);
  1007. CHECK (ev.size() == 2);
  1008. CHECK (ev[0].type == lynx::NoteEvent::Type::on && ev[0].sampleOffset == 24000 && std::abs (ev[0].startSeconds - 0.5) < 1e-9);
  1009. CHECK (ev[1].type == lynx::NoteEvent::Type::off && ev[1].sampleOffset == 3 * 24000);
  1010. // seek para o meio do clip (tempo 2,5): com resume, começa no primeiro sample do bloco
  1011. ev.clear();
  1012. lynx::scheduleSong (s, 1.5 * lynx::ppq, 256, tps, ev, true);
  1013. CHECK (ev.size() == 1 && ev[0].sampleOffset == 0 && std::abs (ev[0].startSeconds - 0.75) < 1e-9);
  1014. ev.clear();
  1015. lynx::scheduleSong (s, 1.5 * lynx::ppq, 256, tps, ev, false);
  1016. CHECK (ev.size() == 0);
  1017. // sample com valor = posição em segundos: dá para conferir de onde ele começou a tocar
  1018. auto provider = [] (const std::string&) {
  1019. auto d = std::make_shared<lynx::SampleData>();
  1020. d->sampleRate = 48000.0;
  1021. for (int i = 0; i < 48000 * 3; ++i)
  1022. d->left.push_back ((float) i / 48000.0f);
  1023. return std::shared_ptr<const lynx::SampleData> (d);
  1024. };
  1025. auto state = lynx::RackState::build (s, nullptr, 48000.0, provider);
  1026. lynx::RackRenderer r;
  1027. r.prepare (48000.0, 512);
  1028. std::vector<float> l (256), rr (256);
  1029. // primeiro bloco tocando já no meio do clip
  1030. r.process (state.get(), true, 1.5 * lynx::ppq, 256, l.data(), rr.data());
  1031. CHECK (std::abs (l[0] - 0.75f) < 0.001f);
  1032. // o clip acaba no tempo 3: depois do fade curto, silêncio (o sample ainda teria áudio)
  1033. double tick = 3.0 * lynx::ppq - 10 * tps;
  1034. r.process (state.get(), false, tick, 256, l.data(), rr.data()); // para (fade)
  1035. for (int i = 0; i < 4; ++i)
  1036. r.process (state.get(), false, tick, 256, l.data(), rr.data());
  1037. CHECK (std::abs (l[255]) < 1e-6f);
  1038. }
  1039. TEST (remove_channel_fixes_notes_and_audio_clips)
  1040. {
  1041. lynx::Song s;
  1042. s.channels.resize (3);
  1043. s.patterns.resize (1);
  1044. s.patterns[0].notes = { { 0, 240, 0, 60, 1.0f }, { 0, 240, 1, 60, 1.0f }, { 0, 240, 2, 60, 1.0f } };
  1045. lynx::Clip a;
  1046. a.kind = lynx::ClipKind::audio;
  1047. a.channel = 1;
  1048. a.length = 100;
  1049. lynx::Clip b = a;
  1050. b.channel = 2;
  1051. s.playlist = { a, b };
  1052. s.removeChannel (1);
  1053. CHECK (s.channels.size() == 2);
  1054. CHECK (s.patterns[0].notes.size() == 2 && s.patterns[0].notes[1].channel == 1);
  1055. CHECK (s.playlist.size() == 1 && s.playlist[0].channel == 1);
  1056. }
  1057. TEST (flp_import_audio_clips_with_offsets)
  1058. {
  1059. flp::Project p;
  1060. p.header.ppq = 96;
  1061. p.tempo = 120.0;
  1062. p.channels = { { 0, flp::ChannelType::audioClip, "Vocal", "", "%FLStudioData%\\v.wav", 2 },
  1063. { 1, flp::ChannelType::audioClip, "Loop", "", "%FLStudioData%\\l.wav", 3 } };
  1064. flp::Arrangement arr;
  1065. flp::PlaylistItem beats; // offset em tempos: fim - início = duração em tempos
  1066. beats.kind = flp::PlaylistItem::Kind::channelClip;
  1067. beats.index = 0;
  1068. beats.position = 192;
  1069. beats.length = 384; // 4 tempos
  1070. beats.startOffset = 2.0f;
  1071. beats.endOffset = 6.0f;
  1072. flp::PlaylistItem ms = beats; // offset em ms: 4 tempos a 120 BPM = 2000 ms
  1073. ms.index = 1;
  1074. ms.startOffset = 500.0f;
  1075. ms.endOffset = 2500.0f;
  1076. arr.items = { beats, ms };
  1077. p.arrangements.push_back (arr);
  1078. lynx::FlpImportOptions options;
  1079. options.roots = { "C:\\FL", "C:\\FL\\Data", "" };
  1080. options.fileExists = [] (const std::string&) { return true; };
  1081. const auto s = lynx::importFlp (p, options);
  1082. CHECK (s.channels.size() == 2 && s.channels[0].instrument == lynx::InstrumentKind::audioClip);
  1083. CHECK (s.channels[0].samplePath == "C:\\FL\\Data\\v.wav");
  1084. CHECK (s.playlist.size() == 2);
  1085. CHECK (s.playlist[0].kind == lynx::ClipKind::audio && s.playlist[0].start == 2 * lynx::ppq);
  1086. CHECK (s.playlist[0].offset == 2 * lynx::ppq);
  1087. CHECK (s.playlist[1].offset == lynx::ppq); // 500 ms a 120 BPM = 1 tempo
  1088. CHECK (s.mode == lynx::PlayMode::song);
  1089. }
  1090. TEST (plugin_factories_create_reuse_and_fallback)
  1091. {
  1092. lynx::Song s;
  1093. s.mixer = lynx::Song::defaultMixer (2);
  1094. lynx::ChannelDef c;
  1095. c.instrument = lynx::InstrumentKind::plugin;
  1096. c.plugin.id = "VST3-Synth-123";
  1097. c.mixerTrack = 1;
  1098. s.channels.push_back (c);
  1099. lynx::ChannelDef missing = c;
  1100. missing.plugin.id = "VST3-Ausente-0";
  1101. s.channels.push_back (missing);
  1102. lynx::EffectSlot fx;
  1103. fx.kind = lynx::EffectKind::plugin;
  1104. fx.plugin.id = "VST3-Reverb-9";
  1105. s.mixer[1].effects.push_back (fx);
  1106. s.patterns.emplace_back();
  1107. int instrumentsMade = 0, effectsMade = 0;
  1108. lynx::RackState::Factories f;
  1109. f.pluginInstruments = [&] (const lynx::PluginRef& ref, double) -> std::shared_ptr<lynx::Instrument> {
  1110. if (ref.id != "VST3-Synth-123")
  1111. return nullptr;
  1112. ++instrumentsMade;
  1113. auto synth = lynx::makeInstrument (lynx::InstrumentKind::synth);
  1114. synth->prepare (48000.0);
  1115. return synth;
  1116. };
  1117. f.pluginEffects = [&] (const lynx::PluginRef&, double) -> std::shared_ptr<lynx::Effect> {
  1118. ++effectsMade;
  1119. auto eq = lynx::makeEffect (lynx::EffectKind::eq);
  1120. eq->prepare (48000.0);
  1121. return eq;
  1122. };
  1123. auto a = lynx::RackState::build (s, nullptr, 48000.0, f);
  1124. CHECK (instrumentsMade == 1 && effectsMade == 1);
  1125. CHECK (a->instruments.size() == 2 && a->instruments[1] != nullptr); // ausente: mudo, mas existe
  1126. // mudar o estado salvo não recria; trocar o plugin recria
  1127. s.channels[0].plugin.state = "abc";
  1128. auto b = lynx::RackState::build (s, a.get(), 48000.0, f);
  1129. CHECK (instrumentsMade == 1 && b->instruments[0] == a->instruments[0] && b->effects[1][0] == a->effects[1][0]);
  1130. s.mixer[1].effects[0].plugin.id = "VST3-Outro-1";
  1131. auto c2 = lynx::RackState::build (s, b.get(), 48000.0, f);
  1132. CHECK (effectsMade == 2);
  1133. // renderizar com plugin ausente e slot de plugin não quebra nada
  1134. lynx::RackRenderer r;
  1135. r.prepare (48000.0, 256);
  1136. lynx::LiveEventQueue live;
  1137. lynx::NoteEvent on;
  1138. on.channel = 0;
  1139. on.velocity = 1.0f;
  1140. live.push (on);
  1141. on.channel = 1;
  1142. live.push (on);
  1143. std::vector<float> l (256), rr (256);
  1144. r.process (c2.get(), false, 0.0, 256, l.data(), rr.data(), &live);
  1145. float peak = 0.0f;
  1146. for (auto v : l)
  1147. {
  1148. CHECK (std::isfinite (v));
  1149. peak = std::max (peak, std::abs (v));
  1150. }
  1151. CHECK (peak > 0.0f);
  1152. }
  1153. TEST (export_song_adds_silent_tail_and_never_restarts)
  1154. {
  1155. auto s = lynx::Song::makeDefault();
  1156. s.playlist.clear();
  1157. std::int64_t length = 0;
  1158. auto pat = lynx::makeExportSong (s, true, lynx::ppq * 8, length); // Playlist vazia: usa a pattern
  1159. CHECK (length == lynx::ppq * 4);
  1160. CHECK (pat.mode == lynx::PlayMode::song && pat.playlist.size() == 2);
  1161. CHECK (pat.songLength() >= length + lynx::ppq * 8);
  1162. // nenhuma nota nova depois do fim da música, só silêncio até o fim da cauda
  1163. lynx::EventBuffer events;
  1164. const auto tps = lynx::ticksPerSample (pat.bpm, 48000.0);
  1165. int onsAfterEnd = 0, onsBefore = 0;
  1166. for (double tick = 0.0; tick < (double) (length + lynx::ppq * 8); tick += 512 * tps)
  1167. {
  1168. events.clear();
  1169. lynx::scheduleSong (pat, tick, 512, tps, events);
  1170. for (const auto& e : events)
  1171. if (e.type == lynx::NoteEvent::Type::on)
  1172. (tick + e.sampleOffset * tps >= (double) length ? onsAfterEnd : onsBefore)++;
  1173. }
  1174. CHECK (onsBefore == (int) s.patterns[0].notes.size());
  1175. CHECK (onsAfterEnd == 0);
  1176. // com Playlist: o fim é o do último clip, sem arredondar
  1177. s.playlist.push_back ({ 0, 0, lynx::ppq * 2, lynx::ppq * 3, 0 });
  1178. auto song = lynx::makeExportSong (s, true, 0, length);
  1179. CHECK (length == lynx::ppq * 5 && song.playlist.size() == 1);
  1180. song = lynx::makeExportSong (s, false, 0, length);
  1181. CHECK (length == lynx::ppq * 4 && song.playlist[0].start == 0);
  1182. }
  1183. TEST (note_edit_selection_operations)
  1184. {
  1185. namespace ne = lynx::noteedit;
  1186. lynx::Pattern p;
  1187. p.notes = { { 0, 240, 0, 60 }, { 480, 240, 0, 64 }, { 960, 480, 1, 67 } };
  1188. // ordenar acompanha os índices
  1189. p.notes[0].start = 1200;
  1190. std::vector<int> tracked { 0, 2 };
  1191. ne::sortTracking (p, tracked);
  1192. CHECK (p.notes[2].start == 1200 && p.notes[(std::size_t) tracked[0]].start == 1200);
  1193. CHECK (p.notes[(std::size_t) tracked[1]].key == 67);
  1194. // mover em grupo respeita os limites
  1195. std::int64_t dt = -5000;
  1196. int dk = 100;
  1197. ne::move (p, { 0, 1 }, dt, dk);
  1198. CHECK (dt == -480 && dk == 127 - 67 && p.notes[0].start == 0 && p.notes[1].key == 127);
  1199. // duplicar: logo depois do trecho, arredondado à grade
  1200. lynx::Pattern q;
  1201. q.notes = { { 0, 240, 0, 60 }, { 240, 300, 0, 62 } }; // trecho de 540 ticks
  1202. const auto added = ne::duplicate (q, { 0, 1 }, 960);
  1203. CHECK (added.size() == 2 && q.notes[(std::size_t) added[0]].start == 960 && q.notes[(std::size_t) added[1]].start == 1200);
  1204. // colar em outro canal com deslocamento
  1205. const auto pasted = ne::paste (q, ne::copy (q, { 1 }), 100, 3);
  1206. CHECK (pasted.size() == 1 && q.notes.back().channel == 3 && q.notes.back().start == 340);
  1207. // quantizar arredonda para o mais próximo
  1208. q.notes[0].start = 130;
  1209. q.notes[1].start = 100;
  1210. ne::quantize (q, { 0, 1 }, 240);
  1211. CHECK (q.notes[0].start == 240 && q.notes[1].start == 0);
  1212. // remover vários (ordem e repetidos não importam)
  1213. const auto before = q.notes.size();
  1214. ne::remove (q, { 1, 0, 1 });
  1215. CHECK (q.notes.size() == before - 2);
  1216. }
  1217. TEST (recorder_builds_notes_in_pattern_and_song_mode)
  1218. {
  1219. auto song = lynx::Song::makeDefault();
  1220. const auto loop = song.patterns[0].effectiveLength (4); // 1 compasso = 3840
  1221. lynx::NoteRecorder r;
  1222. r.add (song, { 100.0, 4, 60, 0.5f, true }); // sem tomada: ignorado
  1223. CHECK (r.takeFinished().empty());
  1224. r.begin (loop);
  1225. r.add (song, { 4000.0, 4, 60, 0.5f, true }); // segunda volta do loop
  1226. r.add (song, { 4480.0, 4, 60, 0.0f, false });
  1227. r.add (song, { 5000.0, 4, 64, 0.9f, true }); // presa até parar
  1228. r.end (song, 5240.0);
  1229. const auto notes = r.takeFinished();
  1230. CHECK (notes.size() == 2);
  1231. CHECK (notes[0].start == 4000 - 3840 && notes[0].length == 480 && notes[0].velocity == 0.5f && notes[0].channel == 4);
  1232. CHECK (notes[1].key == 64 && notes[1].start == 5000 - 3840 && notes[1].length == 240);
  1233. // modo song: posição dentro do clip da pattern atual (com offset)
  1234. song.mode = lynx::PlayMode::song;
  1235. song.playlist = { { 0, 0, 7680, 3840, 960 } };
  1236. CHECK (lynx::patternPositionForTick (song, 7680.0 + 100.0, loop) == 1060);
  1237. CHECK (lynx::patternPositionForTick (song, 100.0, loop) == 100); // fora do clip: como loop
  1238. }
  1239. TEST (automation_curve_and_playback)
  1240. {
  1241. lynx::Automation a;
  1242. a.points = { { 0, 0.0f }, { 960, 1.0f }, { 1920, 0.5f, 0.0f } };
  1243. CHECK (a.valueAt (-10.0) == 0.0f && a.valueAt (480.0) == 0.5f && a.valueAt (5000.0) == 0.5f);
  1244. CHECK (a.length() == 1920);
  1245. a.points[0].tension = 1.0f; // curva: começa devagar
  1246. CHECK (a.valueAt (480.0) < 0.2f && a.valueAt (480.0) > 0.0f);
  1247. // Master automatizado: silêncio no primeiro compasso, som no segundo, e o último valor
  1248. // fica valendo depois do fim do clip de automação
  1249. auto song = lynx::Song::makeDefault();
  1250. song.bpm = 120.0;
  1251. song.mode = lynx::PlayMode::song;
  1252. const auto bar = (std::int64_t) lynx::ppq * 4;
  1253. for (int b = 0; b < 3; ++b)
  1254. song.playlist.push_back ({ 0, 0, bar * b, bar, 0 });
  1255. lynx::Automation master;
  1256. master.target = { lynx::AutomationTargetKind::mixerVolume, 0 };
  1257. master.points = { { 0, 0.0f }, { bar - 1, 0.0f }, { bar, 0.8f } };
  1258. song.automations.push_back (master);
  1259. lynx::Clip ac;
  1260. ac.kind = lynx::ClipKind::automation;
  1261. ac.automation = 0;
  1262. ac.track = 1;
  1263. ac.length = bar + bar / 2;
  1264. song.playlist.push_back (ac);
  1265. const double sr = 48000.0;
  1266. auto state = lynx::RackState::build (song, nullptr, sr);
  1267. CHECK (state->hasAutomation && state->mixerVolumeAuto[0] == 0 && state->automationClips[0].size() == 1);
  1268. lynx::RackRenderer r;
  1269. r.prepare (sr, 512);
  1270. std::vector<float> l (512), rr (512);
  1271. const auto tps = lynx::ticksPerSample (song.bpm, sr);
  1272. float peakBar1 = 0.0f, peakBar2 = 0.0f, peakBar3 = 0.0f;
  1273. for (double tick = 0.0; tick < (double) (bar * 3); tick += 512 * tps)
  1274. {
  1275. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  1276. auto& peak = tick < (double) bar - 512 * tps ? peakBar1 : tick < (double) bar * 2 ? peakBar2 : peakBar3;
  1277. for (auto v : l)
  1278. peak = std::max (peak, std::abs (v));
  1279. }
  1280. CHECK (peakBar1 < 1.0e-6f);
  1281. CHECK (peakBar2 > 0.05f);
  1282. CHECK (peakBar3 > 0.05f); // depois do clip: segue no último valor
  1283. // alvo removido: automação some das tabelas
  1284. song.removeChannel (0);
  1285. song.automations[0].target = { lynx::AutomationTargetKind::channelVolume, 0 };
  1286. song.removeChannel (0);
  1287. CHECK (song.automations[0].target.kind == lynx::AutomationTargetKind::none);
  1288. song.removeAutomation (0);
  1289. CHECK (song.automations.empty() && song.playlist.size() == 3);
  1290. }
  1291. TEST (mixer_sends_between_inserts)
  1292. {
  1293. // insert 1 vai só para o 3; o 3 vai ao Master: soma igual (0,5 + 0,5)
  1294. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.setRoute (1, 3, true); s.setRoute (1, 0, false); }) - 1.0f) < 1e-4f);
  1295. // envio a 50% e destino mudo
  1296. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.setRoute (1, 3, true, 0.5f); s.setRoute (1, 0, false); }) - 0.75f) < 1e-4f);
  1297. 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);
  1298. // indo ao Master e ao 3: o sinal dobra
  1299. CHECK (std::abs (renderMixerCase ([] (lynx::Song& s) { s.setRoute (1, 3, true); }) - 1.5f) < 1e-4f);
  1300. // solo no 3 deixa soar quem chega nele (insert 1), mas não o 2
  1301. 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);
  1302. // solo no 1 deixa soar o caminho até o Master (o 3)
  1303. 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);
  1304. // ordem e ciclos
  1305. auto song = lynx::Song::makeDefault();
  1306. song.setRoute (4, 2, true);
  1307. song.setRoute (2, 1, true);
  1308. CHECK (! song.canRoute (1, 4) && ! song.canRoute (1, 2) && song.canRoute (1, 5));
  1309. song.setRoute (1, 4, true); // ignorado: criaria ciclo
  1310. CHECK (! song.routes (1, 4));
  1311. const auto order = song.mixerOrder();
  1312. const auto pos = [&] (int t) { return std::find (order.begin(), order.end(), t) - order.begin(); };
  1313. CHECK ((int) order.size() == (int) song.mixer.size() - 1);
  1314. CHECK (pos (4) < pos (2) && pos (2) < pos (1));
  1315. song.setRoute (4, 2, false);
  1316. CHECK (! song.routes (4, 2) && song.routes (4, 0));
  1317. }
  1318. namespace
  1319. {
  1320. // Efeito de teste: atrasa o sinal em `latency` samples e informa essa latência (como um plugin com lookahead).
  1321. class LatentEffect final : public lynx::Effect
  1322. {
  1323. public:
  1324. explicit LatentEffect (int samples) : latency (samples), line (samples) {}
  1325. void prepare (double) noexcept override {}
  1326. void reset() noexcept override {}
  1327. void process (float* l, float* r, int n, const lynx::EffectParams&, double) noexcept override { line.process (l, r, n); }
  1328. int latencySamples() const noexcept override { return latency; }
  1329. private:
  1330. int latency;
  1331. lynx::DelayLine line;
  1332. };
  1333. } // namespace
  1334. TEST (delay_line_mix_into_matches_process_and_drains_tail)
  1335. {
  1336. // mixInto = process sobre source*level, somado no destino; em trechos que cruzam o anel
  1337. lynx::DelayLine a (37), b (37);
  1338. std::vector<float> sl (300), sr (300), dl (300, 0.5f), dr (300, -0.5f), xl (300), xr (300);
  1339. for (int i = 0; i < 300; ++i)
  1340. {
  1341. sl[(std::size_t) i] = (float) std::sin (i * 0.1);
  1342. sr[(std::size_t) i] = (float) std::cos (i * 0.07);
  1343. }
  1344. for (int start = 0; start < 300; start += 100)
  1345. {
  1346. b.mixInto (sl.data() + start, sr.data() + start, 0.25f, dl.data() + start, dr.data() + start, 100);
  1347. for (int i = start; i < start + 100; ++i)
  1348. {
  1349. xl[(std::size_t) i] = sl[(std::size_t) i] * 0.25f;
  1350. xr[(std::size_t) i] = sr[(std::size_t) i] * 0.25f;
  1351. }
  1352. a.process (xl.data() + start, xr.data() + start, 100);
  1353. }
  1354. float worst = 0.0f;
  1355. for (int i = 0; i < 300; ++i)
  1356. worst = std::max ({ worst, std::abs (dl[(std::size_t) i] - 0.5f - xl[(std::size_t) i]),
  1357. std::abs (dr[(std::size_t) i] + 0.5f - xr[(std::size_t) i]) });
  1358. CHECK (worst < 1e-6f);
  1359. // fonte calada: a cauda que estava na linha ainda sai, depois não sobra nada
  1360. std::vector<float> tl (64, 0.0f), tr (64, 0.0f);
  1361. b.mixInto (nullptr, nullptr, 1.0f, tl.data(), tr.data(), 64);
  1362. CHECK (std::abs (tl[0] - sl[263] * 0.25f) < 1e-6f);
  1363. std::vector<float> zl (64, 0.0f), zr (64, 0.0f);
  1364. b.mixInto (nullptr, nullptr, 1.0f, zl.data(), zr.data(), 64);
  1365. CHECK (*std::max_element (zl.begin(), zl.end()) == 0.0f && *std::min_element (zl.begin(), zl.end()) == 0.0f);
  1366. }
  1367. TEST (limiter_lookahead_holds_ceiling_on_bursts)
  1368. {
  1369. // rajadas curtas sobre um fundo baixo: o máximo deslizante precisa ver cada pico antes de sair
  1370. auto fx = lynx::makeEffect (lynx::EffectKind::limiter);
  1371. fx->prepare (48000.0);
  1372. auto slot = lynx::makeEffectSlot (lynx::EffectKind::limiter);
  1373. slot.params[2] = 0.0f; // release de 10 ms
  1374. std::vector<float> l (48000), r (48000);
  1375. std::uint32_t seed = 1;
  1376. for (int i = 0; i < 48000; ++i)
  1377. {
  1378. seed = seed * 1664525u + 1013904223u;
  1379. const auto noise = ((float) (seed >> 8) / 16777216.0f - 0.5f) * 0.1f;
  1380. l[(std::size_t) i] = noise + ((i % 9973) < 3 ? 3.0f : 0.0f);
  1381. r[(std::size_t) i] = -noise;
  1382. }
  1383. for (int i = 0; i < 48000; i += 333)
  1384. fx->process (l.data() + i, r.data() + i, std::min (333, 48000 - i), slot.params, 120.0);
  1385. float peak = 0.0f, quiet = 0.0f;
  1386. for (int i = 0; i < 48000; ++i)
  1387. peak = std::max (peak, std::abs (l[(std::size_t) i]));
  1388. for (int i = 9973 * 2 + 2000; i < 9973 * 2 + 2400; ++i) // 40 ms depois da rajada o ganho já voltou
  1389. quiet = std::max (quiet, std::abs (r[(std::size_t) i]));
  1390. const auto ceiling = 1.0f; // o teto padrão fica em 0 dBFS ou abaixo
  1391. CHECK (peak <= ceiling + 1e-5f);
  1392. CHECK (quiet > 0.03f);
  1393. }
  1394. TEST (pdc_aligns_paths_through_latent_effects)
  1395. {
  1396. // plano: canal 0 -> insert 1 (efeito de 100) -> insert 3; canal 1 -> insert 2 -> Master
  1397. lynx::Song s;
  1398. s.mixer = lynx::Song::defaultMixer (4);
  1399. s.channels.resize (3);
  1400. s.channels[0].mixerTrack = 1;
  1401. s.channels[1].mixerTrack = 2;
  1402. s.channels[2].mixerTrack = 3;
  1403. s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::eq));
  1404. s.setRoute (1, 3, true);
  1405. s.setRoute (1, 0, false);
  1406. auto plan = lynx::computePdc (s, { 0, 0, 30 }, { {}, { 100 } });
  1407. CHECK (plan.inAlign[1] == 0 && plan.outLat[1] == 100);
  1408. CHECK (plan.inAlign[3] == 100 && plan.channelDelay[2] == 70); // instrumento de 30 no insert 3
  1409. CHECK (plan.sendDelay[1][1] == 0); // o caminho mais lento não atrasa
  1410. CHECK (plan.sendDelay[2][0] == 100 && plan.sendDelay[3][0] == 0 && plan.total == 100);
  1411. // bypass zera a latência do slot
  1412. s.mixer[1].effects[0].enabled = false;
  1413. CHECK (lynx::computePdc (s, { 0, 0, 30 }, { {}, { 100 } }).total == 30);
  1414. // renderizado: dois impulsos tocados juntos saem juntos
  1415. lynx::Song r;
  1416. r.mixer = lynx::Song::defaultMixer (2);
  1417. for (int i = 0; i < 2; ++i)
  1418. {
  1419. lynx::ChannelDef c;
  1420. c.instrument = lynx::InstrumentKind::sampler;
  1421. c.samplePath = "impulso";
  1422. c.volume = 1.0f;
  1423. c.mixerTrack = i + 1;
  1424. r.channels.push_back (c);
  1425. }
  1426. r.patterns.emplace_back();
  1427. lynx::EffectSlot fx;
  1428. fx.kind = lynx::EffectKind::plugin;
  1429. fx.plugin.id = "latente";
  1430. r.mixer[1].effects.push_back (fx);
  1431. lynx::RackState::Factories f;
  1432. f.samples = [] (const std::string&) {
  1433. auto d = std::make_shared<lynx::SampleData>();
  1434. d->left.assign (64, 0.0f);
  1435. d->left[0] = 1.0f;
  1436. return std::shared_ptr<const lynx::SampleData> (d);
  1437. };
  1438. f.pluginEffects = [] (const lynx::PluginRef&, double) -> std::shared_ptr<lynx::Effect> { return std::make_shared<LatentEffect> (100); };
  1439. auto state = lynx::RackState::build (r, nullptr, 48000.0, f);
  1440. CHECK (state->pdc.total == 100 && state->sendDelays[2][0] != nullptr && state->sendDelays[2][0]->length() == 100);
  1441. lynx::RackRenderer renderer;
  1442. renderer.prepare (48000.0, 256);
  1443. lynx::LiveEventQueue live;
  1444. for (int ch = 0; ch < 2; ++ch)
  1445. {
  1446. lynx::NoteEvent on;
  1447. on.channel = ch;
  1448. on.key = 60;
  1449. on.velocity = 1.0f;
  1450. live.push (on);
  1451. }
  1452. std::vector<float> l (256), rr (256);
  1453. renderer.process (state.get(), false, 0.0, 256, l.data(), rr.data(), &live);
  1454. int first = -1;
  1455. for (int i = 0; i < 256 && first < 0; ++i)
  1456. if (std::abs (l[(std::size_t) i]) > 0.01f)
  1457. first = i;
  1458. CHECK (first == 100 && std::abs (l[100] - 2.0f) < 1e-3f); // os dois impulsos chegam juntos, somados
  1459. // editar sem mudar as latências reaproveita as linhas
  1460. r.channels[0].volume = 0.5f;
  1461. auto next = lynx::RackState::build (r, state.get(), 48000.0, f);
  1462. CHECK (next->sendDelays[2][0] == state->sendDelays[2][0]);
  1463. }
  1464. TEST (mixer_mute_fades_instead_of_clicking)
  1465. {
  1466. lynx::Song s;
  1467. s.mixer = lynx::Song::defaultMixer (2);
  1468. lynx::ChannelDef c;
  1469. c.instrument = lynx::InstrumentKind::sampler;
  1470. c.samplePath = "dc";
  1471. c.volume = 1.0f;
  1472. c.mixerTrack = 1;
  1473. s.channels.push_back (c);
  1474. s.patterns.emplace_back();
  1475. auto provider = [] (const std::string&) {
  1476. auto d = std::make_shared<lynx::SampleData>();
  1477. d->left.assign (48000, 0.5f);
  1478. return std::shared_ptr<const lynx::SampleData> (d);
  1479. };
  1480. auto on = lynx::RackState::build (s, nullptr, 48000.0, provider);
  1481. s.mixer[1].muted = true;
  1482. auto off = lynx::RackState::build (s, on.get(), 48000.0, provider);
  1483. lynx::RackRenderer r;
  1484. r.prepare (48000.0, 256);
  1485. lynx::LiveEventQueue live;
  1486. lynx::NoteEvent note;
  1487. note.velocity = 1.0f;
  1488. live.push (note);
  1489. std::vector<float> l (256), rr (256);
  1490. r.process (on.get(), false, 0.0, 256, l.data(), rr.data(), &live);
  1491. CHECK (std::abs (l[255] - 0.5f) < 1e-3f);
  1492. r.process (off.get(), false, 0.0, 256, l.data(), rr.data());
  1493. CHECK (l[0] > 0.45f && l[128] > 0.2f && l[128] < 0.3f && std::abs (l[255]) < 1e-6f); // rampa até zero
  1494. r.process (off.get(), false, 0.0, 256, l.data(), rr.data());
  1495. CHECK (std::abs (l[0]) < 1e-9f);
  1496. }
  1497. TEST (dither_quantizes_to_lsb_grid_with_small_error)
  1498. {
  1499. lynx::Dither d (16);
  1500. std::vector<float> x (4800);
  1501. for (std::size_t i = 0; i < x.size(); ++i)
  1502. x[i] = 0.25f * std::sin ((float) i * 0.05f);
  1503. auto y = x;
  1504. d.process (y.data(), (int) y.size(), 0);
  1505. double errorSum = 0.0;
  1506. bool onGrid = true;
  1507. for (std::size_t i = 0; i < x.size(); ++i)
  1508. {
  1509. const auto steps = y[i] * 32768.0f;
  1510. onGrid = onGrid && std::abs (steps - std::round (steps)) < 1e-3f;
  1511. errorSum += std::abs (y[i] - x[i]);
  1512. }
  1513. CHECK (onGrid);
  1514. CHECK (errorSum / (double) x.size() < 4.0 / 32768.0); // poucos LSB de ruído em média
  1515. }
  1516. TEST (parallel_rendering_matches_sequential)
  1517. {
  1518. // 32 canais (vale a pena paralelizar), inserts com envios em cadeia
  1519. auto song = lynx::Song::makeDefault();
  1520. song.mixer = lynx::Song::defaultMixer (16);
  1521. for (int i = 5; i < 32; ++i)
  1522. {
  1523. lynx::ChannelDef c;
  1524. c.instrument = i % 2 ? lynx::InstrumentKind::synth : lynx::InstrumentKind::hat;
  1525. c.mixerTrack = 1 + i % 12;
  1526. c.volume = 0.3f;
  1527. song.channels.push_back (c);
  1528. for (int step = i % 4; step < 16; step += 3)
  1529. song.patterns[0].notes.push_back ({ (std::int64_t) step * lynx::ticksPerStep, 200, i, 48 + i, 0.7f });
  1530. }
  1531. song.patterns[0].sortNotes();
  1532. song.setRoute (3, 7, true, 0.6f);
  1533. song.setRoute (7, 9, true, 0.5f);
  1534. song.setRoute (2, 9, true);
  1535. song.mixer[9].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::reverb));
  1536. auto seqState = lynx::RackState::build (song, nullptr, 48000.0);
  1537. auto parState = lynx::RackState::build (song, nullptr, 48000.0);
  1538. CHECK (parState->parallel && parState->mixerLayers.size() == 3);
  1539. lynx::WorkerPool pool (3);
  1540. lynx::RackRenderer seq, par;
  1541. seq.prepare (48000.0, 512);
  1542. par.prepare (48000.0, 512);
  1543. par.setWorkerPool (&pool);
  1544. std::vector<float> l1 (512), r1 (512), l2 (512), r2 (512);
  1545. const auto tps = lynx::ticksPerSample (song.bpm, 48000.0);
  1546. bool same = true;
  1547. float peak = 0.0f;
  1548. for (int block = 0; block < 200; ++block)
  1549. {
  1550. seq.process (seqState.get(), true, block * 512 * tps, 512, l1.data(), r1.data());
  1551. par.process (parState.get(), true, block * 512 * tps, 512, l2.data(), r2.data());
  1552. same = same && l1 == l2 && r1 == r2;
  1553. for (auto v : l1)
  1554. peak = std::max (peak, std::abs (v));
  1555. }
  1556. CHECK (same);
  1557. CHECK (peak > 0.05f);
  1558. // o pool aguenta muitas rodadas pequenas seguidas
  1559. std::atomic<int> sum { 0 };
  1560. auto add = [&sum] (int i) { sum.fetch_add (i + 1); };
  1561. for (int round = 0; round < 2000; ++round)
  1562. pool.parallelFor (5, add);
  1563. CHECK (sum.load() == 2000 * 15);
  1564. }
  1565. TEST (arrangements_switch_and_keep_clip_indices)
  1566. {
  1567. auto s = lynx::Song::makeDefault();
  1568. s.patterns.emplace_back().name = "B";
  1569. s.playlist = { { 1, 0, 0, 960, 0 } };
  1570. s.loopEnd = 960;
  1571. CHECK (s.arrangements.size() == 1 && s.currentArrangement == 0);
  1572. const auto second = s.addArrangement ("Versão curta", true);
  1573. CHECK (second == 1 && s.currentArrangement == 1 && s.playlist.size() == 1 && s.loopEnd == 960);
  1574. s.playlist.push_back ({ 0, 1, 960, 960, 0 });
  1575. s.loopEnd = 0;
  1576. s.selectArrangement (0);
  1577. CHECK (s.playlist.size() == 1 && s.loopEnd == 960 && s.arrangements[1].clips.size() == 2);
  1578. // remover a pattern 0 conserta os clips guardados no outro arrangement
  1579. s.removePattern (0);
  1580. CHECK (s.playlist.size() == 1 && s.playlist[0].pattern == 0);
  1581. CHECK (s.arrangements[1].clips.size() == 1 && s.arrangements[1].clips[0].pattern == 0);
  1582. s.removeArrangement (0);
  1583. CHECK (s.arrangements.size() == 1 && s.currentArrangement == 0 && s.playlist.size() == 1 && s.loopEnd == 0);
  1584. }
  1585. namespace
  1586. {
  1587. // Efeito de teste que inverte o sinal e conta quantas vezes processou.
  1588. class CountingInverter final : public lynx::Effect
  1589. {
  1590. public:
  1591. void prepare (double) noexcept override {}
  1592. void reset() noexcept override {}
  1593. void process (float* l, float* r, int n, const lynx::EffectParams&, double) noexcept override
  1594. {
  1595. ++calls;
  1596. for (int i = 0; i < n; ++i)
  1597. {
  1598. l[i] = -l[i];
  1599. r[i] = -r[i];
  1600. }
  1601. }
  1602. int calls = 0;
  1603. };
  1604. } // namespace
  1605. TEST (effect_slot_dry_wet_and_smart_disable)
  1606. {
  1607. lynx::Song s;
  1608. s.mixer = lynx::Song::defaultMixer (1);
  1609. lynx::ChannelDef c;
  1610. c.instrument = lynx::InstrumentKind::sampler;
  1611. c.samplePath = "dc";
  1612. c.volume = 1.0f;
  1613. c.mixerTrack = 1;
  1614. s.channels.push_back (c);
  1615. s.patterns.emplace_back();
  1616. lynx::EffectSlot fx;
  1617. fx.kind = lynx::EffectKind::plugin;
  1618. fx.plugin.id = "inversor";
  1619. fx.mix = 0.25f; // 75% seco (+0,5) e 25% molhado (-0,5) = +0,25
  1620. s.mixer[1].effects.push_back (fx);
  1621. auto inverter = std::make_shared<CountingInverter>();
  1622. lynx::RackState::Factories f;
  1623. f.samples = [] (const std::string&) {
  1624. auto d = std::make_shared<lynx::SampleData>();
  1625. d->left.assign (4800, 0.5f);
  1626. return std::shared_ptr<const lynx::SampleData> (d);
  1627. };
  1628. f.pluginEffects = [inverter] (const lynx::PluginRef&, double) -> std::shared_ptr<lynx::Effect> { return inverter; };
  1629. auto state = lynx::RackState::build (s, nullptr, 48000.0, f);
  1630. lynx::RackRenderer r;
  1631. r.prepare (48000.0, 512);
  1632. lynx::LiveEventQueue live;
  1633. lynx::NoteEvent on;
  1634. on.velocity = 1.0f;
  1635. live.push (on);
  1636. std::vector<float> l (480), rr (480);
  1637. r.process (state.get(), false, 0.0, 480, l.data(), rr.data(), &live);
  1638. CHECK (std::abs (l[100] - 0.25f) < 1e-4f);
  1639. // depois que o sample acaba: 4 s de silêncio e o plugin deixa de ser chamado
  1640. for (int i = 0; i < 100 * 6; ++i) // 6 s
  1641. r.process (state.get(), false, 0.0, 480, l.data(), rr.data());
  1642. const auto callsAfterSilence = inverter->calls;
  1643. for (int i = 0; i < 100; ++i)
  1644. r.process (state.get(), false, 0.0, 480, l.data(), rr.data());
  1645. CHECK (inverter->calls == callsAfterSilence);
  1646. CHECK (callsAfterSilence < 100 * 6);
  1647. // som de novo: volta a processar no mesmo bloco
  1648. live.push (on);
  1649. r.process (state.get(), false, 0.0, 480, l.data(), rr.data(), &live);
  1650. CHECK (inverter->calls == callsAfterSilence + 1 && std::abs (l[100] - 0.25f) < 1e-4f);
  1651. }
  1652. TEST (swing_delays_offbeat_sixteenths)
  1653. {
  1654. CHECK (lynx::swingDelay (0, 1.0f) == 0);
  1655. CHECK (lynx::swingDelay (lynx::ticksPerStep, 1.0f) == lynx::ticksPerStep / 2);
  1656. CHECK (lynx::swingDelay (lynx::ticksPerStep * 2, 1.0f) == 0);
  1657. CHECK (lynx::swingDelay (lynx::ticksPerStep + 10, 1.0f) == (lynx::ticksPerStep - 20) / 2); // fora da grade: peso triangular (FL)
  1658. CHECK (lynx::swingDelay (lynx::ticksPerStep, 1.0f, 0.5f) == lynx::ticksPerStep / 4); // mix do canal
  1659. CHECK (lynx::swingDelay (lynx::ticksPerStep * 3, 0.5f) == lynx::ticksPerStep / 4);
  1660. lynx::Pattern p;
  1661. p.notes = { { 0, 100, 0, 60 }, { lynx::ticksPerStep, 100, 0, 62 } };
  1662. lynx::EventBuffer ev;
  1663. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  1664. lynx::schedulePatternLoop (p, p.effectiveLength (4), 0.0, 12000, tps, ev, 1.0f);
  1665. int onOffset = -1;
  1666. for (auto& e : ev)
  1667. if (e.type == lynx::NoteEvent::Type::on && e.key == 62)
  1668. onOffset = e.sampleOffset;
  1669. CHECK (onOffset == (int) std::floor ((lynx::ticksPerStep * 1.5) / tps));
  1670. }
  1671. TEST (sampler_settings_pitch_reverse_envelope_cut)
  1672. {
  1673. auto ramp = std::make_shared<lynx::SampleData>();
  1674. for (int i = 0; i < 48000; ++i)
  1675. ramp->left.push_back ((float) i / 48000.0f); // rampa: o valor diz onde a leitura está
  1676. ramp->sampleRate = 48000.0;
  1677. auto play = [&] (const lynx::SamplerSettings& s, int key, int frames, bool releaseAfterHalf) {
  1678. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  1679. inst->prepare (48000.0);
  1680. lynx::ChannelDef c;
  1681. c.sampler = s;
  1682. inst->configure (c, 120.0);
  1683. inst->noteOn (key, 1.0f);
  1684. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  1685. inst->render (l.data(), r.data(), frames / 2, 1.0f, 1.0f);
  1686. if (releaseAfterHalf)
  1687. inst->noteOff (key);
  1688. inst->render (l.data() + frames / 2, r.data() + frames / 2, frames - frames / 2, 1.0f, 1.0f);
  1689. return l;
  1690. };
  1691. // +12 semitons: lê o dobro
  1692. lynx::SamplerSettings up;
  1693. up.pitch = 12.0f;
  1694. CHECK (std::abs (play (up, 60, 1000, false)[999] - 2.0f * 999.0f / 48000.0f) < 1e-3f);
  1695. // ao contrário: começa do fim
  1696. lynx::SamplerSettings back;
  1697. back.reverse = true;
  1698. CHECK (play (back, 60, 100, false)[10] > 0.99f);
  1699. // ataque de 10 ms: começa em silêncio e chega ao nível cheio
  1700. lynx::SamplerSettings slow;
  1701. slow.attack = 0.01f;
  1702. const auto a = play (slow, 60, 2000, false);
  1703. CHECK (a[10] < 0.2f * (10.0f / 48000.0f) + 1e-6f && std::abs (a[1500] - 1500.0f / 48000.0f) < 1e-4f);
  1704. // release de 5 ms: some logo depois de soltar; sem release toca inteiro
  1705. lynx::SamplerSettings rel;
  1706. rel.release = 0.005f;
  1707. CHECK (play (rel, 60, 2000, true)[1999] == 0.0f);
  1708. CHECK (play (lynx::SamplerSettings {}, 60, 2000, true)[1999] > 0.0f);
  1709. // cut itself: a segunda nota corta a primeira (sobra uma voz)
  1710. lynx::SamplerSettings cut;
  1711. cut.cut = true;
  1712. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  1713. inst->prepare (48000.0);
  1714. lynx::ChannelDef cutChannel;
  1715. cutChannel.sampler = cut;
  1716. inst->configure (cutChannel, 120.0);
  1717. inst->noteOn (60, 1.0f);
  1718. std::vector<float> l (2000), r (2000);
  1719. inst->render (l.data(), r.data(), 1000, 1.0f, 1.0f);
  1720. inst->noteOn (60, 1.0f);
  1721. std::fill (l.begin(), l.end(), 0.0f);
  1722. inst->render (l.data(), r.data(), 2000, 1.0f, 1.0f);
  1723. CHECK (std::abs (l[1999] - 1999.0f / 48000.0f) < 1e-4f); // só a nota nova
  1724. }
  1725. TEST (playlist_split_and_track_mute)
  1726. {
  1727. lynx::Clip c { 0, 3, 960, 3840, 480 };
  1728. const auto rest = lynx::splitClip (c, 2000);
  1729. CHECK (c.start == 960 && c.length == 1040 && c.offset == 480);
  1730. CHECK (rest.start == 2000 && rest.length == 2800 && rest.offset == 480 + 1040 && rest.track == 3);
  1731. auto s = lynx::Song::makeDefault();
  1732. s.mode = lynx::PlayMode::song;
  1733. s.playlist = { { 0, 0, 0, 3840, 0 } };
  1734. lynx::EventBuffer ev;
  1735. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  1736. lynx::scheduleSong (s, 0.0, 48000, tps, ev);
  1737. CHECK (ev.size() > 0);
  1738. s.playlistTracks.resize (1);
  1739. s.playlistTracks[0].muted = true;
  1740. ev.clear();
  1741. lynx::scheduleSong (s, 0.0, 48000, tps, ev);
  1742. CHECK (ev.size() == 0);
  1743. }
  1744. TEST (note_pan_pitch_and_mute)
  1745. {
  1746. lynx::Pattern p;
  1747. lynx::Note a { 0, 240, 0, 60 };
  1748. a.pan = -1.0f;
  1749. a.finePitch = 50.0f;
  1750. lynx::Note b { 240, 240, 0, 62 };
  1751. b.muted = true;
  1752. p.notes = { a, b };
  1753. lynx::EventBuffer ev;
  1754. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  1755. lynx::schedulePatternLoop (p, p.effectiveLength (4), 0.0, 48000, tps, ev);
  1756. int ons = 0;
  1757. for (auto& e : ev)
  1758. if (e.type == lynx::NoteEvent::Type::on)
  1759. {
  1760. ++ons;
  1761. CHECK (e.key == 60 && e.pan == -1.0f && e.cents == 50.0f);
  1762. }
  1763. CHECK (ons == 1); // a mutada não toca
  1764. // pan da nota no sampler: tudo à esquerda
  1765. auto dc = std::make_shared<lynx::SampleData>();
  1766. dc->left.assign (4800, 0.5f);
  1767. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, dc);
  1768. inst->prepare (48000.0);
  1769. inst->setNextNoteExpression (-1.0f, 0.0f);
  1770. inst->noteOn (60, 1.0f);
  1771. std::vector<float> l (100), r (100);
  1772. inst->render (l.data(), r.data(), 100, 1.0f, 1.0f);
  1773. CHECK (l[50] > 0.6f && std::abs (r[50]) < 1e-6f);
  1774. }
  1775. TEST (tempo_automation_changes_speed_and_duration)
  1776. {
  1777. auto song = lynx::Song::makeDefault();
  1778. song.bpm = 120.0;
  1779. song.mode = lynx::PlayMode::song;
  1780. const auto bar = (std::int64_t) lynx::ppq * 4;
  1781. song.playlist = { { 0, 0, 0, bar, 0 }, { 0, 0, bar, bar, 0 } };
  1782. lynx::Automation tempo;
  1783. tempo.target = { lynx::AutomationTargetKind::tempo, 0 };
  1784. const auto v120 = lynx::valueFromTempo (120.0), v240 = lynx::valueFromTempo (240.0);
  1785. tempo.points = { { 0, v120 }, { bar - 1, v120 }, { bar, v240 } }; // degrau: 120 -> 240 no 2º compasso
  1786. song.automations.push_back (tempo);
  1787. lynx::Clip clip;
  1788. clip.kind = lynx::ClipKind::automation;
  1789. clip.automation = 0;
  1790. clip.track = 1;
  1791. clip.length = bar * 2;
  1792. song.playlist.push_back (clip);
  1793. CHECK (std::abs (song.tempoAt (100.0) - 120.0) < 0.01 && std::abs (song.tempoAt ((double) bar + 100.0) - 240.0) < 0.01);
  1794. // 1 compasso a 120 (2 s) + 1 a 240 (1 s)
  1795. CHECK (std::abs (song.secondsForTicks (bar * 2) - 3.0) < 0.01);
  1796. auto state = lynx::RackState::build (song, nullptr, 48000.0);
  1797. CHECK (state->tempoAutomation == 0);
  1798. lynx::RackRenderer r;
  1799. r.prepare (48000.0, 512);
  1800. std::vector<float> l (512), rr (512);
  1801. r.process (state.get(), true, 10.0, 512, l.data(), rr.data());
  1802. CHECK (std::abs (r.currentBpm() - 120.0) < 0.01);
  1803. r.process (state.get(), true, (double) bar + 10.0, 512, l.data(), rr.data());
  1804. CHECK (std::abs (r.currentBpm() - 240.0) < 0.01);
  1805. }
  1806. TEST (bounce_insert_song_and_apply)
  1807. {
  1808. auto s = lynx::Song::makeDefault();
  1809. s.setRoute (3, 7, true, 0.5f);
  1810. s.mixer[0].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::reverb));
  1811. s.mixer[2].solo = true;
  1812. const auto b = lynx::makeBounceSong (s, 3);
  1813. CHECK (b.mixer[3].solo && ! b.mixer[2].solo && b.mixer[3].toMaster && b.mixer[3].sends.empty());
  1814. CHECK (b.mixer[0].effects.empty() && b.mode == lynx::PlayMode::song);
  1815. const auto audible = b.soloAudible();
  1816. CHECK (audible[3] && ! audible[1] && ! audible[7]);
  1817. const auto channels = s.channels.size();
  1818. const auto inserts = s.mixer.size();
  1819. const auto created = lynx::applyBounce (s, 3, "C:/x.wav", 3840);
  1820. CHECK (created == (int) inserts && s.mixer.size() == inserts + 1 && s.mixer[3].muted);
  1821. CHECK (s.mixer[(std::size_t) created].sends.size() == 1 && s.mixer[(std::size_t) created].sends[0].target == 7);
  1822. CHECK (s.channels.size() == channels + 1 && s.channels.back().mixerTrack == created);
  1823. CHECK (s.playlist.back().kind == lynx::ClipKind::audio && s.playlist.back().length == 3840);
  1824. }
  1825. TEST (mixer_stereo_separation_phase_swap)
  1826. {
  1827. lynx::MixerTrack t;
  1828. std::vector<float> l { 1.0f }, r { 0.0f };
  1829. t.stereo = 1.0f; // mono
  1830. lynx::RackRenderer::applyStereoForTest (t, l.data(), r.data(), 1);
  1831. CHECK (std::abs (l[0] - 0.5f) < 1e-6f && std::abs (r[0] - 0.5f) < 1e-6f);
  1832. l = { 1.0f };
  1833. r = { 0.0f };
  1834. t.stereo = -1.0f; // lado dobrado: 1,5 L - 0,5 R
  1835. lynx::RackRenderer::applyStereoForTest (t, l.data(), r.data(), 1);
  1836. CHECK (std::abs (l[0] - 1.5f) < 1e-6f && std::abs (r[0] + 0.5f) < 1e-6f);
  1837. l = { 1.0f };
  1838. r = { 0.25f };
  1839. t.stereo = 0.0f;
  1840. t.swapChannels = true;
  1841. t.invertPhase = true;
  1842. lynx::RackRenderer::applyStereoForTest (t, l.data(), r.data(), 1);
  1843. CHECK (l[0] == -0.25f && r[0] == -1.0f);
  1844. }
  1845. TEST (effects_limiter_filter_distortion_chorus)
  1846. {
  1847. const double sr = 48000.0;
  1848. auto sine = [] (float hz, float amp, int n) {
  1849. std::vector<float> v ((std::size_t) n);
  1850. for (int i = 0; i < n; ++i)
  1851. v[(std::size_t) i] = amp * std::sin (2.0f * 3.14159265f * hz * (float) i / 48000.0f);
  1852. return v;
  1853. };
  1854. auto peak = [] (const std::vector<float>& v, int from) {
  1855. float p = 0.0f;
  1856. for (std::size_t i = (std::size_t) from; i < v.size(); ++i)
  1857. p = std::max (p, std::abs (v[i]));
  1858. return p;
  1859. };
  1860. // limiter: +12 dB num seno de 0,9 nunca passa do teto (-1 dB) e informa a latência
  1861. auto lim = lynx::makeEffect (lynx::EffectKind::limiter);
  1862. lim->prepare (sr);
  1863. auto slot = lynx::makeEffectSlot (lynx::EffectKind::limiter);
  1864. slot.params[0] = 11.0f / 12.0f; // -1 dB
  1865. slot.params[1] = 0.5f; // +12 dB
  1866. auto l = sine (100.0f, 0.9f, 48000), r = l;
  1867. lim->process (l.data(), r.data(), 48000, slot.params, 120.0);
  1868. CHECK (peak (l, 0) <= std::pow (10.0f, -1.0f / 20.0f) + 1e-4f);
  1869. CHECK (peak (l, 4800) > 0.8f);
  1870. CHECK (lim->latencySamples() == 72);
  1871. // filtro passa-baixas em 500 Hz derruba um seno de 8 kHz
  1872. auto lp = lynx::makeEffect (lynx::EffectKind::filter);
  1873. lp->prepare (sr);
  1874. auto fs = lynx::makeEffectSlot (lynx::EffectKind::filter);
  1875. fs.params[1] = std::log (500.0f / 20.0f) / std::log (1000.0f);
  1876. l = sine (8000.0f, 1.0f, 9600);
  1877. r = l;
  1878. lp->process (l.data(), r.data(), 9600, fs.params, 120.0);
  1879. CHECK (peak (l, 4800) < 0.05f);
  1880. // distorção e chorus: saída finita e com som
  1881. for (auto kind : { lynx::EffectKind::distortion, lynx::EffectKind::chorus })
  1882. {
  1883. auto fx = lynx::makeEffect (kind);
  1884. fx->prepare (sr);
  1885. auto ps = lynx::makeEffectSlot (kind);
  1886. l = sine (220.0f, 0.5f, 9600);
  1887. r = l;
  1888. fx->process (l.data(), r.data(), 9600, ps.params, 120.0);
  1889. bool finite = true;
  1890. for (auto v : l)
  1891. finite = finite && std::isfinite (v);
  1892. CHECK (finite && peak (l, 2400) > 0.1f && peak (l, 0) < 2.0f);
  1893. }
  1894. }
  1895. TEST (slide_notes_glide_without_retrigger)
  1896. {
  1897. // sampler com rampa: a velocidade de leitura dobra depois do slide de uma oitava
  1898. auto ramp = std::make_shared<lynx::SampleData>();
  1899. for (int i = 0; i < 96000; ++i)
  1900. ramp->left.push_back ((float) i / 96000.0f);
  1901. ramp->sampleRate = 48000.0;
  1902. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  1903. inst->prepare (48000.0);
  1904. inst->noteOn (60, 1.0f);
  1905. std::vector<float> l (2000), r (2000);
  1906. inst->render (l.data(), r.data(), 1000, 1.0f, 1.0f);
  1907. const auto stepBefore = l[999] - l[998];
  1908. inst->slideTo (72, 0.0f, 100.0f);
  1909. std::fill (l.begin(), l.end(), 0.0f);
  1910. inst->render (l.data(), r.data(), 1000, 1.0f, 1.0f);
  1911. const auto stepAfter = l[999] - l[998];
  1912. CHECK (std::abs (stepAfter / stepBefore - 2.0f) < 0.01f);
  1913. // o sequenciador manda "slide" (sem off) para a nota slide
  1914. lynx::Pattern p;
  1915. lynx::Note base { 0, 960, 0, 48 };
  1916. lynx::Note glide { 480, 240, 0, 55 };
  1917. glide.slide = true;
  1918. p.notes = { base, glide };
  1919. lynx::EventBuffer ev;
  1920. const auto tps = lynx::ticksPerSample (120.0, 48000.0);
  1921. lynx::schedulePatternLoop (p, p.effectiveLength (4), 0.0, 30000, tps, ev);
  1922. int ons = 0, offs = 0, slides = 0;
  1923. for (auto& e : ev)
  1924. {
  1925. ons += e.type == lynx::NoteEvent::Type::on;
  1926. offs += e.type == lynx::NoteEvent::Type::off;
  1927. if (e.type == lynx::NoteEvent::Type::slide)
  1928. {
  1929. ++slides;
  1930. CHECK (e.key == 55 && std::abs (e.slideSamples - 240.0f / (float) tps) < 1.0f);
  1931. }
  1932. }
  1933. CHECK (ons == 1 && offs == 1 && slides == 1);
  1934. }
  1935. TEST (synth_three_oscillators_adsr_filter)
  1936. {
  1937. auto render = [] (const lynx::SynthSettings& s, int frames, int releaseAt) {
  1938. auto inst = lynx::makeInstrument (lynx::InstrumentKind::synth);
  1939. inst->prepare (48000.0);
  1940. lynx::ChannelDef c;
  1941. c.synth = s;
  1942. inst->configure (c, 120.0);
  1943. inst->noteOn (69, 1.0f); // A4 = 440 Hz
  1944. std::vector<float> l ((std::size_t) frames), r ((std::size_t) frames);
  1945. inst->render (l.data(), r.data(), releaseAt, 1.0f, 1.0f);
  1946. inst->noteOff (69);
  1947. inst->render (l.data() + releaseAt, r.data() + releaseAt, frames - releaseAt, 1.0f, 1.0f);
  1948. return l;
  1949. };
  1950. auto peakIn = [] (const std::vector<float>& v, int from, int to) {
  1951. float p = 0.0f;
  1952. for (int i = from; i < to; ++i)
  1953. p = std::max (p, std::abs (v[(std::size_t) i]));
  1954. return p;
  1955. };
  1956. // padrão: soa e some depois do release
  1957. const lynx::SynthSettings standard;
  1958. const auto a = render (standard, 48000, 24000);
  1959. CHECK (peakIn (a, 1000, 20000) > 0.05f && peakIn (a, 40000, 48000) < 1e-3f);
  1960. // seno puro com filtro aberto: a contagem de cruzamentos por zero dá ~440 Hz
  1961. lynx::SynthSettings sine;
  1962. sine.osc[0].wave = lynx::Waveform::sine;
  1963. sine.cutoff = 20000.0f;
  1964. const auto b = render (sine, 48000, 47000);
  1965. int crossings = 0;
  1966. for (int i = 4800; i < 4800 + 48000 / 2; ++i)
  1967. crossings += (b[(std::size_t) i - 1] < 0.0f) != (b[(std::size_t) i] < 0.0f);
  1968. CHECK (std::abs (crossings - 440) < 6); // meio segundo = 220 ciclos = 440 cruzamentos
  1969. float sinePeak = 0.0f;
  1970. for (int i = 4800; i < 9600; ++i)
  1971. sinePeak = std::max (sinePeak, std::abs (b[(std::size_t) i]));
  1972. CHECK (sinePeak > 0.2f && sinePeak < 0.35f); // 0,3 de nível, seno aproximado sem estouro
  1973. // segundo oscilador uma oitava acima soma energia; sustain 0 faz a nota decair sozinha
  1974. lynx::SynthSettings two = sine;
  1975. two.osc[1] = { lynx::Waveform::sine, 1, 0.0f, 1.0f };
  1976. two.sustain = 0.0f;
  1977. two.decay = 0.1f;
  1978. const auto c = render (two, 48000, 47000);
  1979. CHECK (peakIn (c, 100, 2000) > peakIn (b, 100, 2000) && peakIn (c, 30000, 40000) < 1e-3f);
  1980. }
  1981. TEST (set_target_value_round_trips)
  1982. {
  1983. auto s = lynx::Song::makeDefault();
  1984. s.mixer[2].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay));
  1985. const lynx::AutomationTarget targets[] = {
  1986. { lynx::AutomationTargetKind::channelVolume, 1 }, { lynx::AutomationTargetKind::channelPan, 2 },
  1987. { lynx::AutomationTargetKind::mixerVolume, 3 }, { lynx::AutomationTargetKind::mixerPan, 0 },
  1988. { lynx::AutomationTargetKind::effectParam, 2, 0, 1 }, { lynx::AutomationTargetKind::tempo, 0 },
  1989. };
  1990. for (const auto& t : targets)
  1991. {
  1992. CHECK (s.setTargetValue (t, 0.25f));
  1993. CHECK (std::abs (s.targetValue (t) - 0.25f) < 1e-5f);
  1994. }
  1995. CHECK (! s.setTargetValue ({ lynx::AutomationTargetKind::channelParam, 0, 0, 3 }, 0.5f)); // mora no plugin
  1996. }
  1997. TEST (cut_groups_stretch_and_envelope_import)
  1998. {
  1999. // hat aberto (cut by 1) é cortado quando o fechado (grupo 1) toca
  2000. lynx::Song s;
  2001. s.mixer = lynx::Song::defaultMixer (2);
  2002. for (int i = 0; i < 2; ++i)
  2003. {
  2004. lynx::ChannelDef c;
  2005. c.instrument = lynx::InstrumentKind::sampler;
  2006. c.samplePath = "dc";
  2007. c.volume = 1.0f;
  2008. c.mixerTrack = i + 1;
  2009. s.channels.push_back (c);
  2010. }
  2011. s.channels[0].cutBy = 1; // aberto
  2012. s.channels[1].cutGroup = 1; // fechado
  2013. auto& p = s.patterns.emplace_back();
  2014. p.notes = { { 0, 100, 0, 60 }, { 960, 100, 1, 60 } };
  2015. auto provider = [] (const std::string&) {
  2016. auto d = std::make_shared<lynx::SampleData>();
  2017. d->left.assign (96000, 0.5f);
  2018. return std::shared_ptr<const lynx::SampleData> (d);
  2019. };
  2020. auto state = lynx::RackState::build (s, nullptr, 48000.0, provider);
  2021. CHECK (state->hasCutGroups && state->cutTargets[1].size() == 1 && state->cutTargets[1][0] == 0);
  2022. lynx::RackRenderer r;
  2023. r.prepare (48000.0, 512);
  2024. std::vector<float> l (512), rr (512);
  2025. const auto tps = lynx::ticksPerSample (s.bpm, 48000.0);
  2026. float afterCut = 0.0f;
  2027. for (double tick = 0.0; tick < 960.0 * 3; tick += 512 * tps)
  2028. {
  2029. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  2030. if (tick > 960.0 * 2) // o fechado segue; o aberto já parou
  2031. afterCut = std::max (afterCut, std::abs (l[256]));
  2032. }
  2033. CHECK (std::abs (afterCut - 0.5f * 0.78f) < 0.01f); // só o fechado (velocity padrão 0,78)
  2034. // stretch por reamostragem: 1 s de sample esticado para 4 tempos a 120 BPM = 2 s
  2035. auto ramp = std::make_shared<lynx::SampleData>();
  2036. for (int i = 0; i < 48000; ++i)
  2037. ramp->left.push_back ((float) i / 48000.0f);
  2038. ramp->sampleRate = 48000.0;
  2039. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  2040. inst->prepare (48000.0);
  2041. lynx::ChannelDef c;
  2042. c.sampler.stretchBeats = 4.0f;
  2043. inst->configure (c, 120.0);
  2044. inst->noteOn (72, 1.0f); // a altura da nota não muda a velocidade
  2045. std::vector<float> a (48000), b (48000);
  2046. inst->render (a.data(), b.data(), 48000, 1.0f, 1.0f);
  2047. CHECK (std::abs (a[47999] - 0.5f) < 0.01f); // depois de 1 s leu metade
  2048. // tempo do envelope do FL: 32950 = 2 s; < 101 = 0
  2049. CHECK (std::abs (flp::Channel::envelopeTime (32950) - 2.0) < 0.01 && flp::Channel::envelopeTime (50) == 0.0);
  2050. }
  2051. TEST (time_stretch_keeps_pitch)
  2052. {
  2053. lynx::SampleData sine;
  2054. sine.sampleRate = 48000.0;
  2055. for (int i = 0; i < 48000; ++i)
  2056. sine.left.push_back (0.5f * std::sin (2.0f * 3.14159265f * 440.0f * (float) i / 48000.0f));
  2057. auto crossingsPerSecond = [] (const lynx::SampleData& d) {
  2058. int c = 0;
  2059. const auto n = (int) d.frames();
  2060. for (int i = 4800; i < n - 4800; ++i)
  2061. c += (d.left[(std::size_t) i - 1] < 0.0f) != (d.left[(std::size_t) i] < 0.0f);
  2062. return (double) c / ((double) (n - 9600) / d.sampleRate);
  2063. };
  2064. for (double ratio : { 2.0, 0.5, 1.37 })
  2065. {
  2066. const auto out = lynx::timeStretch (sine, ratio);
  2067. CHECK (std::abs ((double) out->frames() - 48000.0 * ratio) < 2.0);
  2068. CHECK (std::abs (crossingsPerSecond (*out) - 880.0) < 15.0); // 440 Hz continua 440 Hz
  2069. float peak = 0.0f;
  2070. for (std::size_t i = 4800; i + 4800 < out->frames(); ++i)
  2071. peak = std::max (peak, std::abs (out->left[i]));
  2072. CHECK (peak > 0.4f && peak < 0.6f); // sem buracos nem estouro na sobreposição
  2073. }
  2074. }
  2075. TEST (sampler_region_start_and_end)
  2076. {
  2077. auto ramp = std::make_shared<lynx::SampleData>();
  2078. for (int i = 0; i < 10000; ++i)
  2079. ramp->left.push_back ((float) i / 10000.0f);
  2080. ramp->sampleRate = 48000.0;
  2081. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  2082. inst->prepare (48000.0);
  2083. lynx::ChannelDef c;
  2084. c.sampler.regionStart = 0.25f;
  2085. c.sampler.regionEnd = 0.5f;
  2086. inst->configure (c, 120.0);
  2087. inst->noteOn (60, 1.0f);
  2088. std::vector<float> l (6000), r (6000);
  2089. inst->render (l.data(), r.data(), 6000, 1.0f, 1.0f);
  2090. CHECK (std::abs (l[0] - 0.25f) < 0.001f); // começa no início do trecho
  2091. CHECK (l[2400] > 0.48f && l[2600] == 0.0f); // e para no fim dele
  2092. }
  2093. TEST (arpeggiator_plays_held_chord_in_steps)
  2094. {
  2095. auto song = lynx::Song::makeDefault();
  2096. song.bpm = 120.0;
  2097. song.patterns[0].notes.clear();
  2098. for (int key : { 60, 64, 67 })
  2099. song.patterns[0].notes.push_back ({ 0, lynx::ppq * 4, 4, key, 0.8f }); // acorde segurado 1 compasso
  2100. song.channels[4].arp.direction = 1; // sobe
  2101. song.channels[4].arp.stepBeats = 0.25f;
  2102. auto state = lynx::RackState::build (song, nullptr, 48000.0);
  2103. CHECK (state->arpeggiators[4] != nullptr && state->arpeggiators[0] == nullptr);
  2104. // o arpejador gera as notas; contamos o que ele entrega ao instrumento
  2105. auto& arp = *state->arpeggiators[4];
  2106. const auto tps = lynx::ticksPerSample (song.bpm, 48000.0);
  2107. std::vector<int> keys;
  2108. lynx::EventBuffer ev;
  2109. for (double tick = 0.0; tick < lynx::ppq * 2.0; tick += 512 * tps)
  2110. {
  2111. ev.clear();
  2112. lynx::schedulePatternLoop (song.patterns[0], song.patterns[0].effectiveLength (4), tick, 512, tps, ev);
  2113. int in = 0, out = 0;
  2114. for (auto& e : ev)
  2115. if (e.channel == 4)
  2116. arp.input[(std::size_t) in++] = e;
  2117. arp.process (4, arp.input.data(), in, tick, tps, 512, song.channels[4].arp, arp.output.data(), out);
  2118. for (int i = 0; i < out; ++i)
  2119. if (arp.output[(std::size_t) i].type == lynx::NoteEvent::Type::on)
  2120. keys.push_back (arp.output[(std::size_t) i].key);
  2121. }
  2122. // 2 tempos = 8 passos de semicolcheia: 60 64 67 60 64 67 60 64
  2123. CHECK (keys.size() >= 8); // o último bloco passa um pouco dos 2 tempos
  2124. const int expected[] = { 60, 64, 67, 60, 64, 67, 60, 64 };
  2125. for (std::size_t i = 0; i < keys.size() && i < 8; ++i)
  2126. CHECK (keys[i] == expected[i]);
  2127. // renderizando de verdade também soa
  2128. lynx::RackRenderer r;
  2129. r.prepare (48000.0, 512);
  2130. std::vector<float> l (512), rr (512);
  2131. float peak = 0.0f;
  2132. for (double tick = 0.0; tick < lynx::ppq; tick += 512 * tps)
  2133. {
  2134. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  2135. for (auto v : l)
  2136. peak = std::max (peak, std::abs (v));
  2137. }
  2138. CHECK (peak > 0.01f);
  2139. }
  2140. TEST (audio_clip_fades_and_gain)
  2141. {
  2142. lynx::Song s;
  2143. s.bpm = 120.0;
  2144. s.mode = lynx::PlayMode::song;
  2145. s.mixer = lynx::Song::defaultMixer (1);
  2146. lynx::ChannelDef c;
  2147. c.instrument = lynx::InstrumentKind::audioClip;
  2148. c.samplePath = "dc";
  2149. c.volume = 1.0f;
  2150. c.mixerTrack = 1;
  2151. s.channels.push_back (c);
  2152. s.patterns.emplace_back();
  2153. lynx::Clip clip;
  2154. clip.kind = lynx::ClipKind::audio;
  2155. clip.channel = 0;
  2156. clip.length = lynx::ppq * 4; // 2 s a 120 BPM
  2157. clip.fadeIn = lynx::ppq; // 0,5 s
  2158. clip.fadeOut = lynx::ppq;
  2159. clip.gain = 0.5f;
  2160. s.playlist.push_back (clip);
  2161. auto provider = [] (const std::string&) {
  2162. auto d = std::make_shared<lynx::SampleData>();
  2163. d->left.assign (48000 * 4, 1.0f);
  2164. return std::shared_ptr<const lynx::SampleData> (d);
  2165. };
  2166. auto state = lynx::RackState::build (s, nullptr, 48000.0, provider);
  2167. lynx::RackRenderer r;
  2168. r.prepare (48000.0, 512);
  2169. std::vector<float> all;
  2170. std::vector<float> l (512), rr (512);
  2171. const auto tps = lynx::ticksPerSample (s.bpm, 48000.0);
  2172. for (double tick = 0.0; tick < lynx::ppq * 4.0; tick += 512 * tps)
  2173. {
  2174. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  2175. all.insert (all.end(), l.begin(), l.end());
  2176. }
  2177. CHECK (all[100] < 0.01f); // começo do fade-in
  2178. CHECK (std::abs (all[12000] - 0.25f) < 0.02f); // meio do fade-in: metade de 0,5
  2179. CHECK (std::abs (all[48000] - 0.5f) < 0.01f); // corpo: o ganho do clip
  2180. CHECK (std::abs (all[96000 - 12000] - 0.25f) < 0.02f); // meio do fade-out
  2181. }
  2182. TEST (slicer_detects_hits_and_plays_slices_by_key)
  2183. {
  2184. // 4 batidas (ruído com decaimento) a cada 0,25 s
  2185. lynx::SampleData loop;
  2186. loop.sampleRate = 48000.0;
  2187. loop.left.assign (48000, 0.0f);
  2188. lynx::Noise noise;
  2189. for (int hit = 0; hit < 4; ++hit)
  2190. for (int i = 0; i < 6000; ++i)
  2191. loop.left[(std::size_t) (hit * 12000 + i)] = noise.next() * 0.8f * std::exp (-(float) i / 1500.0f);
  2192. const auto slices = lynx::detectSlices (loop, 0.5f);
  2193. CHECK (slices.size() == 4);
  2194. for (std::size_t i = 0; i < slices.size(); ++i)
  2195. CHECK (std::abs (slices[i] - 0.25f * (float) i) < 0.01f);
  2196. // a tecla 61 toca a segunda fatia, que começa em 0,25 e acaba antes de 0,5
  2197. auto ramp = std::make_shared<lynx::SampleData>();
  2198. for (int i = 0; i < 48000; ++i)
  2199. ramp->left.push_back ((float) i / 48000.0f);
  2200. ramp->sampleRate = 48000.0;
  2201. auto inst = lynx::makeInstrument (lynx::InstrumentKind::sampler, ramp);
  2202. inst->prepare (48000.0);
  2203. lynx::ChannelDef c;
  2204. c.sampler.slices = slices;
  2205. inst->configure (c, 120.0);
  2206. inst->noteOn (61, 1.0f);
  2207. std::vector<float> l (20000), r (20000);
  2208. inst->render (l.data(), r.data(), 20000, 1.0f, 1.0f);
  2209. CHECK (std::abs (l[0] - 0.25f) < 0.01f && l[11000] > 0.45f && l[13000] == 0.0f);
  2210. }
  2211. TEST (project_templates_render_sound)
  2212. {
  2213. const auto names = lynx::templateNames();
  2214. CHECK (names.size() == 4);
  2215. for (int t = 1; t < (int) names.size(); ++t)
  2216. {
  2217. auto song = lynx::makeTemplate (t);
  2218. auto state = lynx::RackState::build (song, nullptr, 48000.0);
  2219. lynx::RackRenderer r;
  2220. r.prepare (48000.0, 512);
  2221. std::vector<float> l (512), rr (512);
  2222. const auto tps = lynx::ticksPerSample (song.bpm, 48000.0);
  2223. float peak = 0.0f;
  2224. for (double tick = 0.0; tick < lynx::ppq * 4.0; tick += 512 * tps)
  2225. {
  2226. r.process (state.get(), true, tick, 512, l.data(), rr.data());
  2227. for (auto v : l)
  2228. peak = std::max (peak, std::abs (v));
  2229. }
  2230. CHECK (peak > 0.05f && peak < 4.0f);
  2231. }
  2232. CHECK (lynx::makeTemplate (0).patterns[0].notes.empty());
  2233. }
  2234. int main (int argc, char** argv)
  2235. {
  2236. if (argc > 1)
  2237. realFlpDir = argv[1];
  2238. for (auto& [name, fn] : registry())
  2239. {
  2240. std::printf ("%s\n", name);
  2241. fn();
  2242. }
  2243. std::printf ("\n%d verificações, %d falhas\n", checks, failures);
  2244. return failures == 0 ? 0 : 1;
  2245. }