SimpleNext190dsTests.inc 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  1. // --- Round 190ds: the Simple layout's next block — the keyboard's Scale keys / Chord pad / Lock to key (core/ScaleKeys.h),
  2. // loops that follow the project key (core/KeyFollow.h, ProjectKey retune), and a pattern for every new Instrument track
  3. // (core/SimpleTracks.h). The last test measures the key move's quality on the real render path (pitch in cents, the
  4. // length kept, artefacts against an ideal transposition and LYNX's stretch modes, CPU); LYNX_190DS_REPORT=1 prints the
  5. // tables.
  6. #include <chrono>
  7. #include <cmath>
  8. #include <complex>
  9. #include <cstdlib>
  10. #include <memory>
  11. #include "core/AudioEditTools.h"
  12. #include "core/KeyFollow.h"
  13. #include "core/RackRenderer.h"
  14. #include "core/ScaleKeys.h"
  15. #include "core/Scheduler.h"
  16. #include "core/SimpleTracks.h"
  17. #include "core/TimeStretch.h"
  18. namespace simple190ds
  19. {
  20. using namespace lynx;
  21. inline int scaleIndex (const char* name)
  22. {
  23. const auto& list = notetools::flReferenceScales();
  24. for (int i = 0; i < (int) list.size(); ++i)
  25. if (std::string (list[(std::size_t) i].name) == name)
  26. return i;
  27. return -1;
  28. }
  29. inline projectkey::Key key (int root, const char* scale) { return { root, scaleIndex (scale) }; }
  30. inline Song songIn (std::optional<projectkey::Key> k)
  31. {
  32. Song s;
  33. projectkey::set (s, k);
  34. return s;
  35. }
  36. // a loop: chords of harmonic tones (each note with six partials), two bars at 120 BPM, 48 kHz, mono
  37. inline std::shared_ptr<SampleData> chordLoop (const std::vector<std::vector<int>>& chords, double seconds = 4.0, double rate = 48000.0)
  38. {
  39. auto d = std::make_shared<SampleData>();
  40. d->sampleRate = rate;
  41. const auto frames = (std::size_t) (seconds * rate);
  42. d->left.assign (frames, 0.0f);
  43. for (std::size_t i = 0; i < frames; ++i)
  44. {
  45. const auto& chord = chords[i * chords.size() / frames];
  46. const auto t = (double) i / rate;
  47. const auto beat = std::fmod (t, 0.5);
  48. double v = 0.0;
  49. for (const auto k : chord)
  50. {
  51. const auto f = 440.0 * std::pow (2.0, (k - 69) / 12.0);
  52. for (int h = 1; h <= 6; ++h)
  53. v += std::sin (2.0 * 3.141592653589793 * f * h * t) / (h * h);
  54. }
  55. d->left[i] = (float) (0.08 * v * (1.0 - std::exp (-beat * 60.0)));
  56. }
  57. return d;
  58. }
  59. inline std::shared_ptr<SampleData> tone (double f0, double seconds = 4.0, double rate = 48000.0)
  60. {
  61. auto d = std::make_shared<SampleData>();
  62. d->sampleRate = rate;
  63. d->left.resize ((std::size_t) (seconds * rate));
  64. for (std::size_t i = 0; i < d->left.size(); ++i)
  65. {
  66. const auto t = (double) i / rate;
  67. double v = 0.0;
  68. for (int h = 1; h <= 6; ++h)
  69. v += std::sin (2.0 * 3.141592653589793 * f0 * h * t) / h;
  70. d->left[i] = (float) (0.25 * v * std::min (1.0, t * 200.0));
  71. }
  72. return d;
  73. }
  74. // The song a dropped loop becomes: one audio clip of `beats` beats on track 0, through insert 1. `stretched`: the loop
  75. // keeps time (its channel stretched to the beats, pitch kept, round 190p), with the stretch method `method`.
  76. struct Render
  77. {
  78. std::vector<float> out;
  79. double nsPerSample = 0.0;
  80. };
  81. inline Render renderClip (std::shared_ptr<SampleData> data, float clipPitch, bool stretched, StretchMethod method = StretchMethod::general,
  82. float channelPitch = 0.0f, bool keepPitch = false, double seconds = 4.0)
  83. {
  84. constexpr double rate = 48000.0;
  85. Song s;
  86. s.bpm = 120.0;
  87. s.mixer.resize (2);
  88. ChannelDef c;
  89. c.instrument = InstrumentKind::audioClip;
  90. c.samplePath = "loop.wav";
  91. c.mixerTrack = 1;
  92. c.sampler.pitch = channelPitch;
  93. c.sampler.keepPitch = keepPitch || stretched;
  94. c.sampler.stretchMethod = method;
  95. if (stretched)
  96. c.sampler.stretchBeats = (float) (data->frames() / data->sampleRate * 2.0); // (its own length at 120 BPM)
  97. s.channels.push_back (c);
  98. s.patterns.emplace_back();
  99. Clip clip;
  100. clip.kind = ClipKind::audio;
  101. clip.channel = 0;
  102. clip.track = 0;
  103. clip.start = 0;
  104. clip.length = (std::int64_t) std::llround (seconds * 2.0 * ppq);
  105. clip.pitch = clipPitch;
  106. s.playlist.push_back (clip);
  107. s.mode = PlayMode::song;
  108. RackState::Factories f;
  109. f.samples = [data] (const std::string&) { return std::shared_ptr<const SampleData> (data); };
  110. f.stretchedSamples = [data] (const std::string&, double ratio, StretchMethod m, double semis, const StretchMap&, const lynx::StretchOptions&) {
  111. return std::shared_ptr<const SampleData> (timeStretch (*data, ratio, m, semis));
  112. };
  113. auto state = RackState::build (s, nullptr, rate, f);
  114. RackRenderer renderer;
  115. constexpr int block = 512;
  116. renderer.prepare (rate, block);
  117. const auto tps = ticksPerSample (s.bpm, rate);
  118. Render r;
  119. std::vector<float> l (block), rr (block);
  120. double tick = 0.0;
  121. std::int64_t ns = 0;
  122. const auto blocks = (int) ((seconds + 0.5) * rate / block);
  123. for (int b = 0; b < blocks; ++b, tick += block * tps)
  124. {
  125. const auto t0 = std::chrono::steady_clock::now();
  126. renderer.process (state.get(), true, tick, block, l.data(), rr.data());
  127. ns += std::chrono::duration_cast<std::chrono::nanoseconds> (std::chrono::steady_clock::now() - t0).count();
  128. r.out.insert (r.out.end(), l.begin(), l.end());
  129. }
  130. r.nsPerSample = (double) ns / (double) (blocks * block);
  131. return r;
  132. }
  133. // magnitude spectrum (Hann, n = power of two) of x[from, from + n)
  134. inline std::vector<double> spectrum (const std::vector<float>& x, std::size_t from, int n)
  135. {
  136. std::vector<double> re ((std::size_t) n), im ((std::size_t) n);
  137. for (int i = 0; i < n; ++i)
  138. {
  139. const auto w = 0.5 - 0.5 * std::cos (2.0 * 3.141592653589793 * i / (n - 1));
  140. re[(std::size_t) i] = from + (std::size_t) i < x.size() ? (double) x[from + (std::size_t) i] * w : 0.0;
  141. }
  142. audioedit::fftInPlace (re, im, false);
  143. std::vector<double> m ((std::size_t) n / 2);
  144. for (int k = 0; k < n / 2; ++k)
  145. m[(std::size_t) k] = std::hypot (re[(std::size_t) k], im[(std::size_t) k]);
  146. return m;
  147. }
  148. // the frequency of the strongest peak near `expected` Hz (±8 %), parabolic interpolation on the log magnitude
  149. inline double peakNear (const std::vector<double>& m, double expected, double rate, int n)
  150. {
  151. const auto lo = (int) (expected * 0.92 * n / rate), hi = (int) (expected * 1.08 * n / rate);
  152. int best = lo;
  153. for (int k = lo; k <= hi; ++k)
  154. if (m[(std::size_t) k] > m[(std::size_t) best])
  155. best = k;
  156. const auto a = std::log (m[(std::size_t) best - 1] + 1e-30), b = std::log (m[(std::size_t) best] + 1e-30), c = std::log (m[(std::size_t) best + 1] + 1e-30);
  157. const auto d = 0.5 * (a - c) / (a - 2.0 * b + c);
  158. return ((double) best + d) * rate / n;
  159. }
  160. // energy outside ±4 bins of the harmonics of `f0` (80 Hz – 8 kHz) against the energy on them, dB: what a transposition
  161. // adds that isn't the tone (lower is better)
  162. inline double offHarmonicDb (const std::vector<double>& m, double f0, double rate, int n)
  163. {
  164. double on = 0.0, off = 0.0;
  165. const auto lo = (int) (80.0 * n / rate), hi = (int) (8000.0 * n / rate);
  166. for (int k = lo; k <= hi; ++k)
  167. {
  168. const auto f = k * rate / n;
  169. const auto h = std::round (f / f0);
  170. const auto near = h >= 1.0 && std::abs (f - h * f0) <= 4.0 * rate / n;
  171. (near ? on : off) += m[(std::size_t) k] * m[(std::size_t) k];
  172. }
  173. return 10.0 * std::log10 ((off + 1e-30) / (on + 1e-30));
  174. }
  175. // spectral difference (dB, RMS over 100 Hz – 6 kHz of the log magnitudes, floor −80 dB below the peak) between two
  176. // signals over the same span: how far a key move is from the ideal transposition
  177. inline double spectralDistanceDb (const std::vector<double>& a, const std::vector<double>& b, double rate, int n)
  178. {
  179. double peak = 1e-30;
  180. for (std::size_t k = 0; k < a.size(); ++k)
  181. peak = std::max ({ peak, a[k], b[k] });
  182. const auto floor = peak * 1e-4;
  183. double sum = 0.0;
  184. int count = 0;
  185. for (int k = (int) (100.0 * n / rate); k <= (int) (6000.0 * n / rate); ++k)
  186. {
  187. const auto x = 20.0 * std::log10 (std::max (a[(std::size_t) k], floor) / std::max (b[(std::size_t) k], floor));
  188. sum += x * x;
  189. ++count;
  190. }
  191. return std::sqrt (sum / std::max (1, count));
  192. }
  193. // energy away (beyond ±4 bins) from the partials of `keys` (MIDI keys, harmonics 1…6) against the energy on them, dB,
  194. // 100 Hz – 6 kHz: how much of a chord is not the notes it should play (lower is better)
  195. inline double offPartialsDb (const std::vector<double>& m, const std::vector<double>& keys, double rate, int n)
  196. {
  197. std::vector<double> partials;
  198. for (const auto k : keys)
  199. for (int h = 1; h <= 6; ++h)
  200. partials.push_back (440.0 * std::pow (2.0, (k - 69.0) / 12.0) * h);
  201. double on = 0.0, off = 0.0;
  202. for (int b = (int) (100.0 * n / rate); b <= (int) (6000.0 * n / rate); ++b)
  203. {
  204. const auto f = b * rate / n;
  205. bool near = false;
  206. for (const auto p : partials)
  207. near = near || std::abs (f - p) <= 4.0 * rate / n;
  208. (near ? on : off) += m[(std::size_t) b] * m[(std::size_t) b];
  209. }
  210. return 10.0 * std::log10 ((off + 1e-30) / (on + 1e-30));
  211. }
  212. inline double rms (const std::vector<float>& x, std::size_t from, std::size_t to)
  213. {
  214. double s = 0.0;
  215. to = std::min (to, x.size());
  216. for (std::size_t i = from; i < to; ++i)
  217. s += (double) x[i] * x[i];
  218. return std::sqrt (s / (double) std::max<std::size_t> (1, to - from));
  219. }
  220. inline bool report() { return std::getenv ("LYNX_190DS_REPORT") != nullptr; }
  221. } // namespace simple190ds
  222. TEST (simple190ds_scale_keys_every_scale)
  223. {
  224. using namespace lynx;
  225. const auto& scales = notetools::flReferenceScales();
  226. for (int sc = 0; sc < (int) scales.size(); ++sc)
  227. for (int root = 0; root < 12; ++root)
  228. {
  229. const projectkey::Key k { root, sc };
  230. const auto n = scalekeys::degreeCount (k);
  231. if (n == 0)
  232. continue;
  233. const auto base = scalekeys::rootAtOrAbove (k, 48);
  234. CHECK (base >= 48 && base < 60 && scalekeys::wrap12 (base) == root);
  235. int last = base - 1;
  236. for (int i = -n; i <= 2 * n; ++i)
  237. {
  238. const auto note = scalekeys::scaleNote (k, i, base);
  239. CHECK (projectkey::contains (k, note)); // every scale key is in the key
  240. if (i >= 0)
  241. {
  242. CHECK (note > last); // rising
  243. last = note;
  244. }
  245. }
  246. CHECK (scalekeys::scaleNote (k, n, base) == base + 12); // one octave of degrees
  247. CHECK (scalekeys::scaleNote (k, -n, base) == base - 12);
  248. }
  249. }
  250. TEST (simple190ds_diatonic_chords_and_numerals)
  251. {
  252. using namespace lynx;
  253. using simple190ds::key;
  254. const auto cMajor = key (0, "Major (Ionian)");
  255. CHECK (cMajor.flScale >= 0);
  256. const char* names[] { "I", "ii", "iii", "IV", "V", "vi", "vii\xc2\xb0" };
  257. const std::vector<int> triads[] { { 48, 52, 55 }, { 50, 53, 57 }, { 52, 55, 59 }, { 53, 57, 60 }, { 55, 59, 62 }, { 57, 60, 64 }, { 59, 62, 65 } };
  258. for (int d = 0; d < 7; ++d)
  259. {
  260. const auto notes = scalekeys::diatonicChord (cMajor, d, 48, scalekeys::Complexity::triad, scalekeys::Spread::close);
  261. CHECK (notes == triads[d]);
  262. CHECK (scalekeys::numeral (d, notes) == names[d]);
  263. }
  264. CHECK (chordread::nameKeys (scalekeys::diatonicChord (cMajor, 5, 48, scalekeys::Complexity::triad, scalekeys::Spread::close)).text.rfind ("Am", 0) == 0);
  265. // richer chords
  266. CHECK ((scalekeys::diatonicChord (cMajor, 4, 48, scalekeys::Complexity::seventh, scalekeys::Spread::close) == std::vector<int> { 55, 59, 62, 65 })); // G7
  267. CHECK ((scalekeys::diatonicChord (cMajor, 0, 48, scalekeys::Complexity::ninth, scalekeys::Spread::close) == std::vector<int> { 48, 52, 55, 59, 62 }));
  268. CHECK ((scalekeys::diatonicChord (cMajor, 1, 48, scalekeys::Complexity::sus4, scalekeys::Spread::close) == std::vector<int> { 50, 55, 57 }));
  269. CHECK ((scalekeys::diatonicChord (cMajor, 0, 48, scalekeys::Complexity::add9, scalekeys::Spread::close) == std::vector<int> { 48, 52, 55, 62 }));
  270. // spread: open moves the third up an octave; wide also doubles the root below
  271. CHECK ((scalekeys::diatonicChord (cMajor, 0, 48, scalekeys::Complexity::triad, scalekeys::Spread::open) == std::vector<int> { 48, 55, 64 }));
  272. CHECK ((scalekeys::diatonicChord (cMajor, 0, 48, scalekeys::Complexity::triad, scalekeys::Spread::wide) == std::vector<int> { 36, 48, 55, 64 }));
  273. // A minor: i ii° III iv v VI VII; a pentatonic key uses its parent
  274. const auto aMinor = key (9, "Minor Natural (Aeolian)");
  275. CHECK (scalekeys::numeral (1, scalekeys::diatonicChord (aMinor, 1, 48, scalekeys::Complexity::triad, scalekeys::Spread::close)) == "ii\xc2\xb0");
  276. CHECK (scalekeys::numeral (0, scalekeys::diatonicChord (aMinor, 0, 48, scalekeys::Complexity::triad, scalekeys::Spread::close)) == "i");
  277. const auto aPenta = key (9, "Minor Pentatonic");
  278. CHECK (aPenta.flScale >= 0);
  279. CHECK (scalekeys::diatonicChord (aPenta, 0, 48, scalekeys::Complexity::triad, scalekeys::Spread::close)
  280. == scalekeys::diatonicChord (aMinor, 0, 48, scalekeys::Complexity::triad, scalekeys::Spread::close));
  281. // the key's diatonic set: C Dm Em F G Am B° (qualities as FL Studio Mobile's default set)
  282. const auto set = scalekeys::diatonicSet (cMajor);
  283. CHECK (set.size() == 7);
  284. const int qualities[] { 0, 1, 1, 0, 0, 1, 3 };
  285. for (int d = 0; d < 7 && d < (int) set.size(); ++d)
  286. CHECK (set[(std::size_t) d].quality == qualities[d] && set[(std::size_t) d].root == triads[d][0] % 12);
  287. // every chord stays inside MIDI
  288. for (int d = 0; d < 14; ++d)
  289. for (const auto n : scalekeys::diatonicChord (cMajor, d, 120, scalekeys::Complexity::ninth, scalekeys::Spread::wide))
  290. CHECK (n >= 0 && n <= 127);
  291. }
  292. TEST (simple190ds_strum_and_chord_sets)
  293. {
  294. using namespace lynx;
  295. scalekeys::Settings s;
  296. s.strumMs = 60;
  297. const auto up = scalekeys::strummed ({ 64, 60, 67 }, s);
  298. CHECK (up.size() == 3 && up[0] == std::make_pair (60, 0) && up[1] == std::make_pair (64, 30) && up[2] == std::make_pair (67, 60));
  299. s.strumDown = true;
  300. const auto down = scalekeys::strummed ({ 64, 60, 67 }, s);
  301. CHECK (down[0].first == 67 && down[2].first == 60 && down[2].second == 60);
  302. s.strumMs = 500; // clamped
  303. CHECK (scalekeys::strummed ({ 60, 64 }, s).back().second == scalekeys::maxStrumMs);
  304. // FL Studio Mobile's KEYB (the text of a real file's default set) and LYNX's chords from it
  305. const std::string keyb = "{\n \"chords\": [\n {\n \"baseNote\": 0,\n \"extensions\": [],\n \"octave\": 3,\n"
  306. " \"quality\": 0\n },\n {\n \"baseNote\": 2,\n \"extensions\": [],\n"
  307. " \"octave\": 3,\n \"quality\": 1\n },\n {\n \"baseNote\": 11,\n"
  308. " \"extensions\": [ 3 ],\n \"octave\": 3,\n \"quality\": 3\n },\n {\n"
  309. " \"baseNote\": 0,\n \"extensions\": [],\n \"octave\": 4,\n \"quality\": 0\n }\n ],\n"
  310. " \"rootNote\": 0\n}";
  311. int dropped = -1;
  312. const auto set = scalekeys::parseFlmChordSet (keyb, &dropped);
  313. CHECK (set.size() == 4);
  314. CHECK (dropped == 0);
  315. if (set.size() == 4)
  316. {
  317. CHECK (set[0].root == 0 && set[0].quality == 0 && set[0].octave == 3);
  318. CHECK (set[1].root == 2 && set[1].quality == 1);
  319. CHECK (set[2].root == 11 && set[2].quality == 3 && set[2].extensions == std::vector<int> { 3 });
  320. CHECK (set[3].octave == 4);
  321. CHECK ((scalekeys::setChord (set, 0, 48, scalekeys::Spread::close) == std::vector<int> { 48, 52, 55 }));
  322. CHECK ((scalekeys::setChord (set, 2, 48, scalekeys::Spread::close) == std::vector<int> { 59, 62, 65 })); // B°
  323. CHECK ((scalekeys::setChord (set, 3, 48, scalekeys::Spread::close) == std::vector<int> { 60, 64, 67 })); // C, an octave up
  324. }
  325. // KEYB extensions are semitones (REA 190ds: 10 = "7", 14 = "9"); power chords; out-of-range values are counted
  326. const auto rich = scalekeys::parseFlmChordSet ("{\"chords\":[{\"baseNote\":7,\"extensions\":[10,14],\"octave\":3,\"quality\":0},"
  327. "{\"baseNote\":4,\"extensions\":[],\"octave\":3,\"quality\":6},{\"baseNote\":0,\"extensions\":[99],\"octave\":3,\"quality\":0}]}",
  328. &dropped);
  329. CHECK (rich.size() == 3 && dropped == 1);
  330. if (rich.size() == 3)
  331. {
  332. CHECK ((scalekeys::setChord (rich, 0, 48, scalekeys::Spread::close) == std::vector<int> { 55, 59, 62, 65, 69 })); // G9
  333. CHECK ((scalekeys::setChord (rich, 1, 48, scalekeys::Spread::close) == std::vector<int> { 52, 59 })); // E5
  334. }
  335. CHECK (scalekeys::parseFlmChordSet ("not json").empty());
  336. CHECK (scalekeys::parseFlmChordSet ("{\"chords\": []}").empty());
  337. // a project chord set replaces the diatonic pads when chosen
  338. Song song;
  339. song.keyboardChords = set;
  340. scalekeys::Settings pads;
  341. pads.projectChords = true;
  342. CHECK (scalekeys::padCount (song, pads) == 4);
  343. pads.projectChords = false;
  344. CHECK (scalekeys::padCount (song, pads) == 7);
  345. CHECK (scalekeys::padNotes (song, pads, 0, 48).empty()); // (no key: the diatonic pads have nothing to play)
  346. // extensions are semitones over the root (LYNX's own edits)
  347. std::vector<KeyboardChord> own { { 7, 0, 4, { 10 } } };
  348. CHECK ((scalekeys::setChord (own, 0, 48, scalekeys::Spread::close) == std::vector<int> { 55, 59, 62, 65 })); // G7
  349. }
  350. TEST (simple190ds_flm_key_locker)
  351. {
  352. using namespace lynx;
  353. // FLM's HEAD root + scale index (REA 190ds), as the files on disk hold them
  354. auto named = [] (std::uint32_t root, std::uint32_t scale) {
  355. const auto k = scalekeys::flmKeyLocker (root, scale);
  356. return k ? projectkey::name (*k) : std::string ("none");
  357. };
  358. CHECK (named (0, 0) == "none"); // Chromatic: no lock
  359. CHECK (named (2, 30) == "D Other Phrygian"); // "Permich - Arabic"
  360. CHECK (named (7, 10) == "G Minor Natural (Aeolian)");
  361. CHECK (named (10, 1) == "A# Major (Ionian)");
  362. CHECK (named (2, 4) == "D Major Pentatonic");
  363. CHECK (named (9, 12) == "A Minor Pentatonic");
  364. CHECK (named (0, 99) == "none" && named (12, 1) == "none");
  365. // every FLM scale that maps lands on FL's scale with the same degrees
  366. int mapped = 0;
  367. for (std::uint32_t sc = 1; sc < 33; ++sc)
  368. if (const auto k = scalekeys::flmKeyLocker (0, sc))
  369. {
  370. ++mapped;
  371. CHECK (projectkey::contains (*k, 0));
  372. }
  373. if (simple190ds::report())
  374. std::printf (" FLM key locker scales FL's list has: %d of 32\n", mapped);
  375. CHECK (mapped >= 12);
  376. }
  377. TEST (simple190ds_typing_keys_follow_the_mode)
  378. {
  379. using namespace lynx;
  380. const auto aMinor = simple190ds::songIn (simple190ds::key (9, "Minor Natural (Aeolian)"));
  381. scalekeys::Settings s;
  382. // Keys mode: as typed; Lock to key: out of key plays nothing
  383. CHECK ((scalekeys::typedNotes (aMinor, s, 61, 60) == std::vector<int> { 61 }));
  384. s.lockToKey = true;
  385. CHECK (scalekeys::typedNotes (aMinor, s, 61, 60).empty());
  386. CHECK ((scalekeys::typedNotes (aMinor, s, 60, 60) == std::vector<int> { 60 }));
  387. // Scale keys: Z X C V B N M (C D E F G A B) = the degrees from the root at or above the typing C; black keys silent
  388. s = {};
  389. s.mode = scalekeys::Mode::scaleKeys;
  390. const int typed[] { 60, 62, 64, 65, 67, 69, 71, 72, 74 };
  391. const int expect[] { 69, 71, 72, 74, 76, 77, 79, 81, 83 };
  392. for (int i = 0; i < 9; ++i)
  393. CHECK ((scalekeys::typedNotes (aMinor, s, typed[i], 60) == std::vector<int> { expect[i] }));
  394. CHECK (scalekeys::typedNotes (aMinor, s, 63, 60).empty());
  395. // an octave lower on the keyboard: an octave lower
  396. CHECK ((scalekeys::typedNotes (aMinor, s, 48, 60) == std::vector<int> { 57 }));
  397. // Chord pad: the degrees' chords; the 8th white key starts the pads again an octave up
  398. s.mode = scalekeys::Mode::chordPad;
  399. CHECK ((scalekeys::typedNotes (aMinor, s, 60, 60) == std::vector<int> { 69, 72, 76 }));
  400. CHECK ((scalekeys::typedNotes (aMinor, s, 65, 60) == std::vector<int> { 74, 77, 81 }));
  401. CHECK ((scalekeys::typedNotes (aMinor, s, 72, 60) == std::vector<int> { 81, 84, 88 }));
  402. // no project key: every mode plays what is typed
  403. const Song none;
  404. for (const auto mode : { scalekeys::Mode::keys, scalekeys::Mode::scaleKeys, scalekeys::Mode::chordPad })
  405. {
  406. s.mode = mode;
  407. s.lockToKey = true;
  408. CHECK ((scalekeys::typedNotes (none, s, 61, 60) == std::vector<int> { 61 }));
  409. }
  410. // pentatonic: five degrees per octave on seven white keys
  411. const auto penta = simple190ds::songIn (simple190ds::key (9, "Minor Pentatonic"));
  412. s = {};
  413. s.mode = scalekeys::Mode::scaleKeys;
  414. CHECK ((scalekeys::typedNotes (penta, s, 69, 60) == std::vector<int> { 81 })); // A = the 6th white key = the octave's root
  415. CHECK (scalekeys::typingLabel (0) == std::string ("Z") && scalekeys::typingLabel (7) == std::string ("Q"));
  416. }
  417. TEST (simple190ds_key_in_the_file_name)
  418. {
  419. using namespace lynx;
  420. using keyfollow::LoopKey;
  421. const std::pair<const char*, std::optional<LoopKey>> cases[] {
  422. { "Night Pad 120 Gm.wav", LoopKey { 7, true } },
  423. { "DL_102_Dm_Stack.wav", LoopKey { 2, true } },
  424. { "Pluck_120_D_minor.wav", LoopKey { 2, true } },
  425. { "Guitar Loop - F# Major - 95 BPM.wav", LoopKey { 6, false } },
  426. { "Keys_Ebmaj_128.wav", LoopKey { 3, false } },
  427. { "bass_c#min_140.wav", LoopKey { 1, true } },
  428. { "Lead 140bpm Bbm.wav", LoopKey { 10, true } },
  429. { "120Am_vox.wav", LoopKey { 9, true } },
  430. { "Synth Loop 128 C.wav", LoopKey { 0, false } },
  431. { "Brass Csharp minor.aif", LoopKey { 1, true } },
  432. { "Strings A minor.wav", LoopKey { 9, true } },
  433. // no key
  434. { "Kick 01.wav", std::nullopt },
  435. { "Drum Loop 120.wav", std::nullopt },
  436. { "I am here.wav", std::nullopt },
  437. { "Bass Groove 98.wav", std::nullopt },
  438. { "Ambient Texture.wav", std::nullopt },
  439. { "Piano C.wav", std::nullopt }, // a bare note needs a tempo beside it
  440. { "Cmaj7 stab 120.wav", std::nullopt }, // a chord name, not a key
  441. { "Vocal take 3.wav", std::nullopt },
  442. };
  443. for (const auto& [name, expected] : cases)
  444. {
  445. const auto got = keyfollow::keyInName (name);
  446. CHECK (got == expected);
  447. if (got != expected)
  448. std::printf (" key in name \"%s\": %s\n", name, got ? keyfollow::keyName (*got).c_str() : "none");
  449. }
  450. }
  451. TEST (simple190ds_key_detected_from_the_audio)
  452. {
  453. using namespace lynx;
  454. // progressions in a key (i VI VII i / I IV V I and friends); the move needs the right notes, so the relative major
  455. // root must be right; the key itself (major or minor) too for these clear cadences
  456. struct Case
  457. {
  458. int root;
  459. bool minor;
  460. std::vector<std::vector<int>> chords;
  461. };
  462. const Case cases[] {
  463. { 7, true, { { 55, 58, 62 }, { 51, 55, 58 }, { 53, 57, 60 }, { 55, 58, 62 } } }, // G minor
  464. { 4, true, { { 52, 55, 59, 64 }, { 48, 52, 55, 60 }, { 50, 54, 57, 62 }, { 52, 55, 59, 64 } } }, // E minor
  465. { 0, false, { { 48, 52, 55 }, { 53, 57, 60 }, { 55, 59, 62 }, { 48, 52, 55 } } }, // C major
  466. { 2, false, { { 50, 54, 57 }, { 55, 59, 62 }, { 57, 61, 64 }, { 50, 54, 57 } } }, // D major
  467. { 9, true, { { 57, 60, 64 }, { 53, 57, 60 }, { 52, 56, 59 }, { 57, 60, 64 } } }, // A minor (harmonic V)
  468. { 3, false, { { 51, 55, 58 }, { 56, 60, 63 }, { 58, 62, 65 }, { 51, 55, 58 } } }, // Eb major
  469. };
  470. int exact = 0;
  471. for (const auto& c : cases)
  472. {
  473. const auto d = keyfollow::detectKey (*simple190ds::chordLoop (c.chords));
  474. const auto relative = [] (const keyfollow::LoopKey& k) { return (k.root + (k.minor ? 3 : 0)) % 12; };
  475. CHECK (d.key.has_value());
  476. if (! d.key)
  477. continue;
  478. CHECK (relative (*d.key) == relative ({ c.root, c.minor }));
  479. exact += d.key->root == c.root && d.key->minor == c.minor ? 1 : 0;
  480. if (simple190ds::report())
  481. std::printf (" detect %s: %s (r %.3f, margin %.3f)\n", keyfollow::keyName ({ c.root, c.minor }).c_str(), keyfollow::keyName (*d.key).c_str(),
  482. d.correlation, d.margin);
  483. }
  484. CHECK (exact >= 5);
  485. // no key: noise, a drum loop, a single pure tone, silence, a file too short
  486. auto noise = std::make_shared<SampleData>();
  487. noise->sampleRate = 48000.0;
  488. noise->left.resize (192000);
  489. std::uint32_t seed = 190;
  490. for (auto& v : noise->left)
  491. v = (float) ((seed = seed * 1664525u + 1013904223u) >> 8 & 0xffff) / 65536.0f - 0.5f;
  492. CHECK (! keyfollow::detectKey (*noise).key);
  493. auto drums = std::make_shared<SampleData>();
  494. drums->sampleRate = 48000.0;
  495. drums->left.resize (192000);
  496. for (std::size_t i = 0; i < drums->left.size(); ++i)
  497. {
  498. const auto t = (double) (i % 24000) / 48000.0;
  499. const auto w = (float) ((seed = seed * 1664525u + 1013904223u) >> 8 & 0xffff) / 65536.0f - 0.5f;
  500. drums->left[i] = (float) (std::sin (2.0 * 3.141592653589793 * (50.0 * t + 1.5 * (1.0 - std::exp (-t * 40.0)))) * std::exp (-t * 9.0)
  501. + (i / 24000 % 2 == 1 ? w * std::exp (-t * 20.0) : 0.0));
  502. }
  503. CHECK (! keyfollow::detectKey (*drums).key);
  504. CHECK (! keyfollow::detectKey (*simple190ds::tone (440.0)).key);
  505. auto silence = std::make_shared<SampleData>();
  506. silence->left.assign (96000, 0.0f);
  507. CHECK (! keyfollow::detectKey (*silence).key);
  508. auto shortOne = std::make_shared<SampleData>();
  509. shortOne->left.assign (1000, 0.1f);
  510. CHECK (! keyfollow::detectKey (*shortOne).key);
  511. }
  512. TEST (simple190ds_loops_follow_the_project_key)
  513. {
  514. using namespace lynx;
  515. using simple190ds::key;
  516. // the move between relative-major roots, −6 … +5
  517. const auto gMinor = key (7, "Minor Natural (Aeolian)"), cMajor = key (0, "Major (Ionian)");
  518. CHECK (projectkey::loopShift (2, true, gMinor) == 5); // D minor → G minor
  519. CHECK (projectkey::loopShift (9, true, cMajor) == 0); // A minor in C major: the same notes
  520. CHECK (projectkey::loopShift (7, false, cMajor) == 5); // G → C: +5 (not −7)
  521. CHECK (projectkey::loopShift (6, false, cMajor) == -6); // the tritone goes down
  522. for (int from = 0; from < 12; ++from)
  523. for (int to = 0; to < 12; ++to)
  524. {
  525. const auto s = projectkey::loopShift (from, false, projectkey::Key { to, cMajor.flScale });
  526. CHECK (s >= -6 && s <= 5 && ((from + s) % 12 + 12) % 12 == to);
  527. }
  528. // a song with two loop clips (one following) and the user's own pitch on one
  529. Song s;
  530. s.channels.resize (2);
  531. for (auto& c : s.channels)
  532. c.instrument = InstrumentKind::audioClip;
  533. keyfollow::setLoopKey (s, 0, keyfollow::LoopKey { 2, true }, 1); // D minor
  534. keyfollow::setLoopKey (s, 1, keyfollow::LoopKey { 7, true }, 2); // G minor
  535. Clip a, b, pat;
  536. a.kind = b.kind = ClipKind::audio;
  537. a.channel = 0;
  538. b.channel = 1;
  539. b.pitch = 1.0f; // the user's own pitch
  540. pat.kind = ClipKind::pattern;
  541. s.playlist = { a, b, pat };
  542. // nothing follows yet: nothing moves when the key is set
  543. projectkey::set (s, gMinor);
  544. CHECK (s.playlist[0].pitch == 0.0f && s.playlist[1].pitch == 1.0f);
  545. keyfollow::setFollow (s, { 0, 1, 2 }, true);
  546. CHECK (s.playlist[0].followKey && s.playlist[1].followKey && ! s.playlist[2].followKey); // (a pattern clip: no)
  547. CHECK (s.playlist[0].keyShift == 5 && s.playlist[0].pitch == 5.0f);
  548. CHECK (s.playlist[1].keyShift == 0 && s.playlist[1].pitch == 1.0f);
  549. CHECK (keyfollow::shiftOf (s, s.playlist[0]) == 5);
  550. // the key moves: every follower moves, the user's pitch stays on top
  551. projectkey::set (s, key (9, "Minor Natural (Aeolian)"));
  552. CHECK (s.playlist[0].keyShift == -5 && s.playlist[0].pitch == -5.0f);
  553. CHECK (s.playlist[1].keyShift == 2 && s.playlist[1].pitch == 3.0f);
  554. // no key: back to their own keys
  555. projectkey::set (s, std::nullopt);
  556. CHECK (s.playlist[0].keyShift == 0 && s.playlist[0].pitch == 0.0f && s.playlist[1].pitch == 1.0f);
  557. projectkey::set (s, key (9, "Minor Natural (Aeolian)"));
  558. // switched off: its own key again; the loop's key corrected by hand: it moves from there
  559. keyfollow::setFollow (s, { 1 }, false);
  560. CHECK (s.playlist[1].keyShift == 0 && s.playlist[1].pitch == 1.0f && ! s.playlist[1].followKey);
  561. keyfollow::setLoopKey (s, 0, keyfollow::LoopKey { 4, true }, 3); // E minor (the user's)
  562. CHECK (s.playlist[0].keyShift == 5 && s.channels[0].sampler.loopKeySource == 3);
  563. keyfollow::setLoopKey (s, 0, std::nullopt, 0); // not known: it stays where it is in its own key
  564. CHECK (s.playlist[0].keyShift == 0 && s.playlist[0].pitch == 0.0f && s.playlist[0].followKey);
  565. // the clip pitch's ±12 limit: the user's +10 and a +5 move stop at +12; switching off gives back exactly +10
  566. keyfollow::setLoopKey (s, 0, keyfollow::LoopKey { 4, true }, 3);
  567. s.playlist[0].pitch = 10.0f + s.playlist[0].keyShift;
  568. projectkey::set (s, key (9, "Minor Natural (Aeolian)"));
  569. projectkey::set (s, gMinor); // E minor → G minor: +3
  570. CHECK (s.playlist[0].pitch == 12.0f && s.playlist[0].keyShift == 2);
  571. keyfollow::setFollow (s, { 0 }, false);
  572. CHECK (s.playlist[0].pitch == 10.0f);
  573. // the other clip lists move too (arrangements, the clip grid)
  574. Song g;
  575. g.channels.resize (1);
  576. keyfollow::setLoopKey (g, 0, keyfollow::LoopKey { 2, true }, 1);
  577. Clip gridClip;
  578. gridClip.kind = ClipKind::audio;
  579. gridClip.channel = 0;
  580. gridClip.followKey = true;
  581. g.clipGrid.emplace();
  582. g.clipGrid->clips.push_back (gridClip);
  583. projectkey::set (g, gMinor);
  584. CHECK (g.clipGrid->clips[0].keyShift == 5);
  585. // old projects: nothing follows, a key change moves nothing (the same sound)
  586. Song old;
  587. old.channels.resize (1);
  588. Clip plain;
  589. plain.kind = ClipKind::audio;
  590. plain.channel = 0;
  591. plain.pitch = 2.0f;
  592. old.playlist = { plain };
  593. const auto before = old.playlist;
  594. projectkey::set (old, gMinor);
  595. CHECK (old.playlist == before);
  596. // the Clip keeps its size (the two fields sit in its padding)
  597. CHECK (sizeof (Clip) == 144 || sizeof (void*) != 8);
  598. }
  599. TEST (simple190ds_simple_tracks_patterns_and_keyed_loops)
  600. {
  601. using namespace lynx;
  602. namespace st = simpletracks;
  603. Song s = Song::makeDefault();
  604. s.playlist.clear();
  605. st::Request q;
  606. q.kind = st::Kind::instrument;
  607. ChannelDef synth;
  608. synth.instrument = InstrumentKind::synth;
  609. q.channel = synth;
  610. q.emptyBars = 4;
  611. const auto r = st::addTrack (s, q);
  612. CHECK (r.ok() && r.pattern >= 0);
  613. if (! r.ok() || r.pattern < 0)
  614. return;
  615. CHECK (s.patterns[(std::size_t) r.pattern].notes.empty());
  616. CHECK (s.patterns[(std::size_t) r.pattern].effectiveLength (s.meter()) == 4 * s.beatsPerBar * ppq);
  617. CHECK (st::patternOf (s, r.track) == r.pattern);
  618. bool made = true;
  619. CHECK (st::ensurePattern (s, r.track, 4, &made) == r.pattern && ! made); // (it has one)
  620. // a track without a pattern gets one; a second call gives the same
  621. q.emptyBars = 0;
  622. const auto r2 = st::addTrack (s, q);
  623. CHECK (r2.ok() && r2.pattern < 0 && st::patternOf (s, r2.track) < 0);
  624. const auto p = st::ensurePattern (s, r2.track, 4, &made);
  625. CHECK (p >= 0 && made && st::patternOf (s, r2.track) == p && st::ensurePattern (s, r2.track) == p);
  626. // an audio track has none
  627. st::Request voice;
  628. voice.kind = st::Kind::voice;
  629. const auto r3 = st::addTrack (s, voice);
  630. CHECK (r3.ok() && st::ensurePattern (s, r3.track) == -1);
  631. // a keyed loop: its key on the channel, the clip following and moved to the project key in the same edit
  632. projectkey::set (s, simple190ds::key (7, "Minor Natural (Aeolian)"));
  633. st::Request loop;
  634. loop.kind = st::Kind::audio;
  635. loop.audioFile = "/loops/Pluck_120_D_minor.wav";
  636. loop.audioLength = 8 * ppq;
  637. loop.audioBeats = 8.0f;
  638. loop.audioKeyRoot = 2;
  639. loop.audioKeyMinor = true;
  640. loop.audioKeySource = 1;
  641. loop.followKey = true;
  642. const auto r4 = st::addTrack (s, loop);
  643. CHECK (r4.ok() && ! r4.channels.empty());
  644. if (r4.ok() && ! r4.channels.empty())
  645. {
  646. const auto& c = s.playlist.back();
  647. CHECK (c.followKey && c.keyShift == 5 && c.pitch == 5.0f);
  648. CHECK (s.channels[(std::size_t) r4.channels[0]].sampler.loopKeyRoot == 2 && s.channels[(std::size_t) r4.channels[0]].sampler.loopKeySource == 1);
  649. CHECK (s.channels[(std::size_t) r4.channels[0]].sampler.keepPitch); // (a loop: stretched to the tempo, pitch kept)
  650. }
  651. // the project key for a loop key: its root, Major or Minor
  652. const auto k = keyfollow::projectKeyFor ({ 2, true });
  653. CHECK (k.root == 2 && projectkey::isMinor (k) && notetools::flReferenceScales()[(std::size_t) k.flScale].name == std::string ("Minor Natural (Aeolian)"));
  654. }
  655. TEST (simple190ds_key_move_quality)
  656. {
  657. // The key move is the clip's pitch on LYNX's own voice pitch shifter (core/TimeStretch VoicePitchShifter): measured
  658. // on the real render path for every move a loop can get (−6 … +5), and against LYNX's stretch modes.
  659. using namespace simple190ds;
  660. using lynx::StretchMethod;
  661. constexpr double rate = 48000.0;
  662. constexpr int n = 65536;
  663. const std::size_t from = (std::size_t) (0.6 * rate); // (past the start)
  664. const auto source = tone (220.0);
  665. double worstCents = 0.0, worstLength = 0.0, worstOffDb = -200.0, shiftedNs = 0.0;
  666. const auto plain = renderClip (source, 0.0f, false);
  667. const auto plainOff = offHarmonicDb (spectrum (plain.out, from, n), 220.0, rate, n);
  668. if (report())
  669. std::printf (" key move on a 220 Hz harmonic tone (clip pitch, length kept): shift, measured f0 error (cents), level 3.4..3.9 s "
  670. "vs unshifted (dB), off-harmonic energy (dB), ns/sample\n plain: off-harmonic %.1f dB, %.0f ns/sample\n",
  671. plainOff, plain.nsPerSample);
  672. for (int shift = -6; shift <= 5; ++shift)
  673. {
  674. if (shift == 0)
  675. continue;
  676. const auto r = renderClip (source, (float) shift, false);
  677. const auto expected = 220.0 * std::pow (2.0, shift / 12.0);
  678. const auto m = spectrum (r.out, from, n);
  679. const auto f = peakNear (m, expected, rate, n);
  680. const auto cents = 1200.0 * std::log2 (f / expected);
  681. // the length stays: the end of the clip (3.4 … 3.9 s) as loud as without the move, silence after it
  682. const auto endLevel = 20.0 * std::log10 (rms (r.out, (std::size_t) (3.4 * rate), (std::size_t) (3.9 * rate))
  683. / std::max (1e-12, rms (plain.out, (std::size_t) (3.4 * rate), (std::size_t) (3.9 * rate))));
  684. // (after the clip the song loops back to its start: the same as without the move)
  685. const auto after = rms (r.out, (std::size_t) (4.1 * rate), (std::size_t) (4.4 * rate));
  686. const auto off = offHarmonicDb (m, expected, rate, n);
  687. worstCents = std::max (worstCents, std::abs (cents));
  688. worstLength = std::max (worstLength, std::abs (endLevel));
  689. worstOffDb = std::max (worstOffDb, off);
  690. shiftedNs = std::max (shiftedNs, r.nsPerSample);
  691. if (report())
  692. std::printf (" %+d: %+.2f cents, end %+.2f dB, off-harmonic %.1f dB, %.0f ns/sample, after the end %.6f (plain %.6f)\n", shift, cents, endLevel, off,
  693. r.nsPerSample, after, rms (plain.out, (std::size_t) (4.1 * rate), (std::size_t) (4.4 * rate)));
  694. }
  695. CHECK (worstCents < 3.0); // pitch-exact within 3 cents for every move
  696. CHECK (worstLength < 1.5); // the clip plays to its end, at its level
  697. CHECK (worstOffDb < -25.0); // artefacts at least 25 dB under the tone
  698. if (report())
  699. std::printf (" worst: %.2f cents, %.2f dB at the end, off-harmonic %.1f dB, CPU %.0f ns/sample (plain %.0f)\n", worstCents, worstLength, worstOffDb,
  700. shiftedNs, plain.nsPerSample);
  701. // a chord loop (G minor: Gm Eb F Gm) moved +3 / −5: how much of its first chord (0.12 … 0.46 s, 16384 points) is not
  702. // the moved chord's partials — for the ideal transposition (the loop resampled by the channel: the same pitches, no
  703. // stretch), the clip's pitch on a loop that keeps time (a dropped loop) in each of LYNX's stretch modes, the clip's
  704. // pitch on a loop at its own speed, and the loop not moved at all
  705. const auto loop = chordLoop ({ { 55, 58, 62 }, { 51, 55, 58 }, { 53, 57, 60 }, { 55, 58, 62 } });
  706. const struct
  707. {
  708. StretchMethod method;
  709. const char* name;
  710. } modes[] { { StretchMethod::general, "general (default)" }, { StretchMethod::transients, "transients" }, { StretchMethod::mono, "mono" },
  711. { StretchMethod::tones, "tones" }, { StretchMethod::texture, "texture" }, { StretchMethod::complex, "complex" } };
  712. constexpr int cn = 16384;
  713. const auto at = (std::size_t) (0.12 * rate);
  714. for (const int shift : { 3, -5 })
  715. {
  716. const std::vector<double> moved { 55.0 + shift, 58.0 + shift, 62.0 + shift };
  717. const auto ideal = offPartialsDb (spectrum (renderClip (loop, 0.0f, false, StretchMethod::general, (float) shift, false).out, at, cn), moved, rate, cn);
  718. const auto unmoved = offPartialsDb (spectrum (renderClip (loop, 0.0f, false).out, at, cn), moved, rate, cn);
  719. double general = 0.0, best = 1e9;
  720. const char* bestName = "";
  721. for (const auto& mode : modes)
  722. {
  723. const auto r = renderClip (loop, (float) shift, true, mode.method);
  724. const auto d = offPartialsDb (spectrum (r.out, at, cn), moved, rate, cn);
  725. if (mode.method == StretchMethod::general)
  726. general = d;
  727. if (d < best)
  728. best = d, bestName = mode.name;
  729. if (report())
  730. std::printf (" chord loop %+d, kept in time, %s: off the chord's partials %.1f dB, %.0f ns/sample\n", shift, mode.name, d, r.nsPerSample);
  731. }
  732. const auto own = offPartialsDb (spectrum (renderClip (loop, (float) shift, false).out, at, cn), moved, rate, cn);
  733. if (report())
  734. std::printf (" chord loop %+d: ideal (resampled) %.1f dB, at its own speed (clip pitch only) %.1f dB, not moved %.1f dB; best mode: %s\n", shift,
  735. ideal, own, unmoved, bestName);
  736. CHECK (general < unmoved - 15.0); // the moved loop plays the moved chord
  737. CHECK (own < unmoved - 15.0);
  738. CHECK (general < -20.0); // the rest at least 20 dB under the chord (measured: -42.8 dB at +3, -27.5 dB at -5)
  739. }
  740. }