WaveAnalysis.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. #include "core/WaveAnalysis.h"
  2. #include <algorithm>
  3. #include <cmath>
  4. #include <cstring>
  5. namespace lynx::wave
  6. {
  7. namespace
  8. {
  9. // 2nd-order Butterworth section (RBJ cookbook, Q = 1/sqrt 2), transposed direct form II, mono
  10. struct Section
  11. {
  12. double b0 = 1, b1 = 0, b2 = 0, a1 = 0, a2 = 0, z1 = 0, z2 = 0;
  13. static Section make (double hz, double rate, bool highPass) noexcept
  14. {
  15. const auto w = 2.0 * 3.14159265358979323846 * std::min (hz, rate * 0.45) / rate;
  16. const auto cw = std::cos (w), alpha = std::sin (w) / (2.0 * 0.70710678118654752);
  17. const auto a0 = 1.0 + alpha;
  18. Section s;
  19. if (highPass)
  20. {
  21. s.b0 = (1.0 + cw) / 2.0 / a0;
  22. s.b1 = -(1.0 + cw) / a0;
  23. }
  24. else
  25. {
  26. s.b0 = (1.0 - cw) / 2.0 / a0;
  27. s.b1 = (1.0 - cw) / a0;
  28. }
  29. s.b2 = s.b0;
  30. s.a1 = -2.0 * cw / a0;
  31. s.a2 = (1.0 - alpha) / a0;
  32. return s;
  33. }
  34. double process (double x) noexcept
  35. {
  36. const auto y = b0 * x + z1;
  37. z1 = b1 * x - a1 * y + z2;
  38. z2 = b2 * x - a2 * y;
  39. return y;
  40. }
  41. };
  42. std::int16_t quantiseSigned (float v, float scale) noexcept
  43. {
  44. return (std::int16_t) std::lround (std::clamp (v / scale, -1.0f, 1.0f) * 32767.0f);
  45. }
  46. std::uint16_t quantiseUnsigned (double v, float scale) noexcept
  47. {
  48. return (std::uint16_t) std::lround (std::clamp (v / (double) scale, 0.0, 1.0) * 65535.0);
  49. }
  50. float rms16 (double sumOfSquares, std::size_t n) noexcept
  51. {
  52. return n == 0 ? 0.0f : (float) std::sqrt (sumOfSquares / (double) n);
  53. }
  54. // merges `count` columns into one (min of mins, max of maxes, RMS of RMS values)
  55. Column merge (const Column* c, std::size_t count) noexcept
  56. {
  57. Column out;
  58. for (int ch = 0; ch < 2; ++ch)
  59. {
  60. out.lo[ch] = c[0].lo[ch];
  61. out.hi[ch] = c[0].hi[ch];
  62. }
  63. double rms[2] {}, band[3] {};
  64. for (std::size_t i = 0; i < count; ++i)
  65. {
  66. for (int ch = 0; ch < 2; ++ch)
  67. {
  68. out.lo[ch] = std::min (out.lo[ch], c[i].lo[ch]);
  69. out.hi[ch] = std::max (out.hi[ch], c[i].hi[ch]);
  70. rms[ch] += (double) c[i].rms[ch] * c[i].rms[ch];
  71. }
  72. for (int b = 0; b < 3; ++b)
  73. band[b] += (double) c[i].band[b] * c[i].band[b];
  74. }
  75. for (int ch = 0; ch < 2; ++ch)
  76. out.rms[ch] = (std::uint16_t) std::lround (std::min (65535.0, std::sqrt (rms[ch] / (double) count)));
  77. for (int b = 0; b < 3; ++b)
  78. out.band[b] = (std::uint16_t) std::lround (std::min (65535.0, std::sqrt (band[b] / (double) count)));
  79. return out;
  80. }
  81. template <typename T>
  82. void put (std::vector<std::uint8_t>& out, T v)
  83. {
  84. const auto at = out.size();
  85. out.resize (at + sizeof (T));
  86. std::memcpy (out.data() + at, &v, sizeof (T));
  87. }
  88. template <typename T>
  89. bool get (const std::uint8_t*& p, const std::uint8_t* end, T& v)
  90. {
  91. if ((std::size_t) (end - p) < sizeof (T))
  92. return false;
  93. std::memcpy (&v, p, sizeof (T));
  94. p += sizeof (T);
  95. return true;
  96. }
  97. constexpr std::uint32_t magic = 0x5657594c; // "LYWV"
  98. static_assert (sizeof (Column) == 18, "Column is written raw to the disk cache");
  99. } // namespace
  100. std::size_t Summary::bucketOf (std::size_t level) const noexcept
  101. {
  102. auto b = bucket;
  103. for (std::size_t i = 0; i < level; ++i)
  104. b *= levelFactor;
  105. return b;
  106. }
  107. std::size_t Summary::memoryBytes() const noexcept
  108. {
  109. std::size_t total = sizeof (Summary);
  110. for (const auto& l : levels)
  111. total += l.size() * sizeof (Column);
  112. return total;
  113. }
  114. Point Summary::query (double fromFrame, double toFrame, int channel) const noexcept
  115. {
  116. Point p;
  117. if (levels.empty() || levels[0].empty() || fromFrame >= (double) frames || toFrame <= 0.0)
  118. return p;
  119. fromFrame = std::max (0.0, fromFrame);
  120. toFrame = std::min ((double) frames, std::max (toFrame, fromFrame));
  121. const auto span = toFrame - fromFrame;
  122. const auto sampleScale = scale / 32767.0f, levelScale = scale / 65535.0f;
  123. const auto right = channels > 1 ? 1 : 0;
  124. auto read = [&] (const Column& c, float& lo, float& hi, float& rms) {
  125. if (channel < 0)
  126. {
  127. lo = (float) std::min (c.lo[0], c.lo[right]) * sampleScale;
  128. hi = (float) std::max (c.hi[0], c.hi[right]) * sampleScale;
  129. const auto r0 = (float) c.rms[0], r1 = (float) c.rms[right];
  130. rms = std::sqrt ((r0 * r0 + r1 * r1) * 0.5f) * levelScale;
  131. }
  132. else
  133. {
  134. const auto ch = channel > 0 ? right : 0;
  135. lo = (float) c.lo[ch] * sampleScale;
  136. hi = (float) c.hi[ch] * sampleScale;
  137. rms = (float) c.rms[ch] * levelScale;
  138. }
  139. };
  140. if (span < (double) bucket)
  141. {
  142. // closer than one column per pixel: interpolate between neighbouring column centres
  143. const auto& base = levels[0];
  144. const auto pos = std::max (0.0, (fromFrame + toFrame) * 0.5 / (double) bucket - 0.5);
  145. const auto i0 = std::min ((std::size_t) pos, base.size() - 1);
  146. const auto i1 = std::min (i0 + 1, base.size() - 1);
  147. const auto t = (float) std::clamp (pos - (double) i0, 0.0, 1.0);
  148. float lo0, hi0, r0, lo1, hi1, r1;
  149. read (base[i0], lo0, hi0, r0);
  150. read (base[i1], lo1, hi1, r1);
  151. p.lo = lo0 + (lo1 - lo0) * t;
  152. p.hi = hi0 + (hi1 - hi0) * t;
  153. p.rms = r0 + (r1 - r0) * t;
  154. p.low = ((float) base[i0].band[0] + ((float) base[i1].band[0] - (float) base[i0].band[0]) * t) * levelScale;
  155. p.mid = ((float) base[i0].band[1] + ((float) base[i1].band[1] - (float) base[i0].band[1]) * t) * levelScale;
  156. p.high = ((float) base[i0].band[2] + ((float) base[i1].band[2] - (float) base[i0].band[2]) * t) * levelScale;
  157. p.valid = true;
  158. return p;
  159. }
  160. // the coarsest level whose columns are still no wider than the range: a few columns per pixel
  161. std::size_t level = 0;
  162. while (level + 1 < levels.size() && (double) bucketOf (level + 1) <= span)
  163. ++level;
  164. const auto& columns = levels[level];
  165. const auto b = (double) bucketOf (level);
  166. const auto first = std::min ((std::size_t) (fromFrame / b), columns.size() - 1);
  167. const auto last = std::clamp ((std::size_t) std::ceil (toFrame / b), first + 1, columns.size());
  168. float lo = 0.0f, hi = 0.0f;
  169. double sumRms = 0.0, sumBand[3] {};
  170. for (auto i = first; i < last; ++i)
  171. {
  172. float cLo, cHi, cRms;
  173. read (columns[i], cLo, cHi, cRms);
  174. lo = i == first ? cLo : std::min (lo, cLo);
  175. hi = i == first ? cHi : std::max (hi, cHi);
  176. sumRms += (double) cRms * cRms;
  177. for (int k = 0; k < 3; ++k)
  178. sumBand[k] += (double) columns[i].band[k] * columns[i].band[k];
  179. }
  180. const auto n = (double) (last - first);
  181. p.lo = lo;
  182. p.hi = hi;
  183. p.rms = (float) std::sqrt (sumRms / n);
  184. p.low = (float) std::sqrt (sumBand[0] / n) * levelScale;
  185. p.mid = (float) std::sqrt (sumBand[1] / n) * levelScale;
  186. p.high = (float) std::sqrt (sumBand[2] / n) * levelScale;
  187. p.valid = true;
  188. return p;
  189. }
  190. Summary analyse (const float* left, const float* right, std::size_t frames, double sampleRate, const std::atomic<bool>* cancel)
  191. {
  192. Summary s;
  193. s.sampleRate = sampleRate > 0.0 ? sampleRate : 44100.0;
  194. s.frames = frames;
  195. s.channels = right != nullptr && right != left ? 2 : 1;
  196. if (left == nullptr || frames == 0)
  197. {
  198. s.frames = 0;
  199. return s;
  200. }
  201. if (s.channels == 1)
  202. right = left;
  203. while (frames / s.bucket > maxBaseColumns)
  204. s.bucket *= 2;
  205. float peak = 0.0f;
  206. for (std::size_t i = 0; i < frames; ++i)
  207. peak = std::max ({ peak, std::abs (left[i]), std::abs (right[i]) });
  208. s.peak = peak;
  209. s.scale = std::max (1.0f, peak);
  210. // crossovers: low = LP 250 x2, mid = HP 250 x2 + LP 4k x2, high = HP 4k x2
  211. Section lowLp[2] = { Section::make (lowCrossoverHz, s.sampleRate, false), Section::make (lowCrossoverHz, s.sampleRate, false) };
  212. Section midHp[2] = { Section::make (lowCrossoverHz, s.sampleRate, true), Section::make (lowCrossoverHz, s.sampleRate, true) };
  213. Section midLp[2] = { Section::make (highCrossoverHz, s.sampleRate, false), Section::make (highCrossoverHz, s.sampleRate, false) };
  214. Section highHp[2] = { Section::make (highCrossoverHz, s.sampleRate, true), Section::make (highCrossoverHz, s.sampleRate, true) };
  215. auto& base = s.levels.emplace_back();
  216. base.resize ((frames + s.bucket - 1) / s.bucket);
  217. for (std::size_t c = 0; c < base.size(); ++c)
  218. {
  219. if (cancel != nullptr && (c & 255) == 0 && cancel->load (std::memory_order_relaxed))
  220. return {};
  221. const auto from = c * s.bucket, to = std::min (frames, from + s.bucket);
  222. float lo[2] = { left[from], right[from] }, hi[2] = { left[from], right[from] };
  223. double sq[2] {}, band[3] {};
  224. for (auto i = from; i < to; ++i)
  225. {
  226. const auto l = left[i], r = right[i];
  227. lo[0] = std::min (lo[0], l);
  228. hi[0] = std::max (hi[0], l);
  229. lo[1] = std::min (lo[1], r);
  230. hi[1] = std::max (hi[1], r);
  231. sq[0] += (double) l * l;
  232. sq[1] += (double) r * r;
  233. const auto mono = 0.5 * ((double) l + (double) r);
  234. const auto lowBand = lowLp[1].process (lowLp[0].process (mono));
  235. const auto midBand = midLp[1].process (midLp[0].process (midHp[1].process (midHp[0].process (mono))));
  236. const auto highBand = highHp[1].process (highHp[0].process (mono));
  237. band[0] += lowBand * lowBand;
  238. band[1] += midBand * midBand;
  239. band[2] += highBand * highBand;
  240. }
  241. const auto n = to - from;
  242. auto& col = base[c];
  243. for (int ch = 0; ch < 2; ++ch)
  244. {
  245. col.lo[ch] = quantiseSigned (lo[ch], s.scale);
  246. col.hi[ch] = quantiseSigned (hi[ch], s.scale);
  247. col.rms[ch] = quantiseUnsigned (rms16 (sq[ch], n), s.scale);
  248. }
  249. for (int k = 0; k < 3; ++k)
  250. col.band[k] = quantiseUnsigned (rms16 (band[k], n), s.scale);
  251. }
  252. // coarser levels until one column covers everything
  253. while (s.levels.back().size() > 1)
  254. {
  255. const auto& below = s.levels.back();
  256. std::vector<Column> next ((below.size() + levelFactor - 1) / levelFactor);
  257. for (std::size_t i = 0; i < next.size(); ++i)
  258. {
  259. const auto from = i * levelFactor;
  260. next[i] = merge (below.data() + from, std::min (levelFactor, below.size() - from));
  261. }
  262. s.levels.push_back (std::move (next));
  263. }
  264. return s;
  265. }
  266. std::vector<std::uint8_t> serialise (const Summary& s)
  267. {
  268. std::vector<std::uint8_t> out;
  269. out.reserve (64 + s.memoryBytes());
  270. put (out, magic);
  271. put (out, formatVersion);
  272. put (out, (std::uint64_t) s.frames);
  273. put (out, s.sampleRate);
  274. put (out, (std::uint32_t) s.channels);
  275. put (out, (std::uint64_t) s.bucket);
  276. put (out, s.scale);
  277. put (out, s.peak);
  278. put (out, (std::uint32_t) s.levels.size());
  279. for (const auto& level : s.levels)
  280. {
  281. put (out, (std::uint64_t) level.size());
  282. const auto at = out.size();
  283. out.resize (at + level.size() * sizeof (Column));
  284. if (! level.empty())
  285. std::memcpy (out.data() + at, level.data(), level.size() * sizeof (Column));
  286. }
  287. return out;
  288. }
  289. bool deserialise (const std::uint8_t* data, std::size_t size, Summary& out)
  290. {
  291. const auto* p = data;
  292. const auto* end = data + size;
  293. std::uint32_t m = 0, version = 0, channels = 0, levelCount = 0;
  294. std::uint64_t frames = 0, bucket = 0;
  295. Summary s;
  296. if (data == nullptr || ! get (p, end, m) || m != magic || ! get (p, end, version) || version != formatVersion)
  297. return false;
  298. if (! get (p, end, frames) || ! get (p, end, s.sampleRate) || ! get (p, end, channels) || ! get (p, end, bucket)
  299. || ! get (p, end, s.scale) || ! get (p, end, s.peak) || ! get (p, end, levelCount))
  300. return false;
  301. if (frames == 0 || (channels != 1 && channels != 2) || bucket < minBucket || (bucket & (bucket - 1)) != 0 || levelCount == 0
  302. || levelCount > 64 || ! (s.sampleRate > 0.0 && s.sampleRate < 1.0e7) || ! (s.scale >= 1.0f) || ! std::isfinite (s.peak))
  303. return false;
  304. s.frames = (std::size_t) frames;
  305. s.channels = (int) channels;
  306. s.bucket = (std::size_t) bucket;
  307. auto expected = (s.frames + s.bucket - 1) / s.bucket;
  308. for (std::uint32_t l = 0; l < levelCount; ++l)
  309. {
  310. std::uint64_t count = 0;
  311. if (! get (p, end, count) || count != expected || (std::size_t) (end - p) / sizeof (Column) < count)
  312. return false;
  313. auto& level = s.levels.emplace_back ((std::size_t) count);
  314. std::memcpy (level.data(), p, (std::size_t) count * sizeof (Column));
  315. p += count * sizeof (Column);
  316. expected = (expected + levelFactor - 1) / levelFactor;
  317. }
  318. if (p != end || s.levels.back().size() != 1)
  319. return false;
  320. out = std::move (s);
  321. return true;
  322. }
  323. BandMix bandMix (float low, float mid, float high) noexcept
  324. {
  325. // weighted amplitudes, then a gentle contrast (power 1.5) so a dominant band reads clearly
  326. const auto l = std::pow (std::max (0.0f, low), 1.5f);
  327. const auto m = std::pow (std::max (0.0f, mid) * 1.6f, 1.5f);
  328. const auto h = std::pow (std::max (0.0f, high) * 3.2f, 1.5f);
  329. const auto sum = l + m + h;
  330. if (! (sum > 1.0e-12f))
  331. return { 0.0f, 1.0f, 0.0f }; // silence: neutral
  332. return { l / sum, m / sum, h / sum };
  333. }
  334. Rgb spectralColour (const BandMix& mix) noexcept
  335. {
  336. Rgb c { lowColour.r * mix.low + midColour.r * mix.mid + highColour.r * mix.high,
  337. lowColour.g * mix.low + midColour.g * mix.mid + highColour.g * mix.high,
  338. lowColour.b * mix.low + midColour.b * mix.mid + highColour.b * mix.high };
  339. // blends of opposite anchors drift to grey: push saturation back up and keep the colour bright
  340. const auto grey = (c.r + c.g + c.b) / 3.0f;
  341. c.r = grey + (c.r - grey) * 1.3f;
  342. c.g = grey + (c.g - grey) * 1.3f;
  343. c.b = grey + (c.b - grey) * 1.3f;
  344. const auto top = std::max ({ c.r, c.g, c.b });
  345. if (top > 0.0f && top < 0.9f)
  346. {
  347. const auto k = 0.9f / top;
  348. c.r *= k;
  349. c.g *= k;
  350. c.b *= k;
  351. }
  352. c.r = std::clamp (c.r, 0.0f, 1.0f);
  353. c.g = std::clamp (c.g, 0.0f, 1.0f);
  354. c.b = std::clamp (c.b, 0.0f, 1.0f);
  355. return c;
  356. }
  357. } // namespace lynx::wave