4
0

PolySpectral.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. // Polyphonic engine - STFT frames, instantaneous frequency, spectral peaks with tonality and whitening.
  2. // Everything here streams over frames: memory does not grow with the length of the recording
  3. // beyond the (sparse) peak list.
  4. #include "PolyInternal.h"
  5. #include <numeric>
  6. namespace polyphonic
  7. {
  8. namespace detail
  9. {
  10. std::vector<float> hannPeriodic(int n)
  11. {
  12. std::vector<float> w(static_cast<size_t>(n));
  13. for (int i = 0; i < n; ++i)
  14. w[static_cast<size_t>(i)] = static_cast<float>(0.5 - 0.5 * std::cos(2.0 * kPi * i / n));
  15. return w;
  16. }
  17. StftFrames::StftFrames(const float* signal, int numSamples, const Params& p)
  18. : x(signal), n(numSamples), N(p.fftSize), H(p.hop)
  19. {
  20. frames = 1 + (numSamples + H - 1) / H;
  21. bins = N / 2 + 1;
  22. window = hannPeriodic(N);
  23. buffer.resize(static_cast<size_t>(N));
  24. norm = 2.0f / std::accumulate(window.begin(), window.end(), 0.0f);
  25. fft = std::make_unique<RealFFT>(N);
  26. }
  27. void StftFrames::spectrum(int t, std::complex<float>* out)
  28. {
  29. const int first = t * H - N / 2;
  30. for (int i = 0; i < N; ++i)
  31. {
  32. const int s = first + i;
  33. buffer[static_cast<size_t>(i)] = (s >= 0 && s < n) ? x[s] * window[static_cast<size_t>(i)] : 0.0f;
  34. }
  35. fft->forward(buffer.data(), out);
  36. for (int k = 0; k < bins; ++k)
  37. out[k] *= norm;
  38. }
  39. static inline float princarg(float a)
  40. {
  41. const float twoPi = static_cast<float>(2.0 * kPi);
  42. a = std::fmod(a + static_cast<float>(kPi), twoPi);
  43. if (a < 0)
  44. a += twoPi;
  45. return a - static_cast<float>(kPi);
  46. }
  47. // Exact running median over `width` bins (edges replicated).
  48. void medianRow(const float* in, int K, int width, float* out, std::vector<float>& sorted)
  49. {
  50. const int half = width / 2;
  51. auto value = [&](int k) { return in[std::clamp(k, 0, K - 1)]; };
  52. sorted.clear();
  53. for (int k = -half; k <= half; ++k)
  54. sorted.push_back(value(k));
  55. std::sort(sorted.begin(), sorted.end());
  56. for (int k = 0; k < K; ++k)
  57. {
  58. out[k] = sorted[static_cast<size_t>(half)];
  59. if (k + 1 == K)
  60. break;
  61. const float leaving = value(k - half);
  62. const float entering = value(k + half + 1);
  63. sorted.erase(std::lower_bound(sorted.begin(), sorted.end(), leaving));
  64. sorted.insert(std::upper_bound(sorted.begin(), sorted.end(), entering), entering);
  65. }
  66. }
  67. int Peaks::nearest(int t, float bins) const
  68. {
  69. // peaks of a frame are sorted by bin: binary search, then compare the two neighbours
  70. const int b = begin(t), e = end(t);
  71. if (b == e)
  72. return -1;
  73. const auto first = fbin.begin() + b, last = fbin.begin() + e;
  74. const auto it = std::lower_bound(first, last, bins);
  75. int j = static_cast<int>(it - fbin.begin());
  76. if (j >= e)
  77. return e - 1;
  78. if (j > b && std::fabs(fbin[static_cast<size_t>(j - 1)] - bins) <= std::fabs(fbin[static_cast<size_t>(j)] - bins))
  79. return j - 1;
  80. return j;
  81. }
  82. namespace
  83. {
  84. struct Band
  85. {
  86. int k0;
  87. std::vector<float> w;
  88. float sum;
  89. };
  90. // Klapuri (2006) whitening bands: centres 229 (10^((b+1)/21.4) - 1) Hz with triangular responses.
  91. std::vector<double> whiteningCentres(const Params& p)
  92. {
  93. std::vector<double> cb;
  94. for (int b = 0; b < 32; ++b)
  95. {
  96. const double c = 229.0 * (std::pow(10.0, (b + 1) / 21.4) - 1.0);
  97. if (c < p.sampleRate / 2)
  98. cb.push_back(c);
  99. }
  100. return cb;
  101. }
  102. std::vector<Band> whiteningBands(const std::vector<double>& cb, const Params& p, int K)
  103. {
  104. const double binHz = p.sampleRate / p.fftSize;
  105. std::vector<Band> bands;
  106. for (size_t b = 0; b < cb.size(); ++b)
  107. {
  108. const double lo = b > 0 ? cb[b - 1] : 0.0;
  109. const double hi = b + 1 < cb.size() ? cb[b + 1] : p.sampleRate / 2;
  110. Band band{std::max(0, static_cast<int>(std::floor(lo / binHz))), {}, 0.0f};
  111. const int k1 = std::min(K - 1, static_cast<int>(std::ceil(hi / binHz)));
  112. for (int k = band.k0; k <= k1; ++k)
  113. {
  114. const double f = k * binHz;
  115. const double v = std::max(0.0, std::min((f - lo) / std::max(cb[b] - lo, 1e-9), (hi - f) / std::max(hi - cb[b], 1e-9)));
  116. band.w.push_back(static_cast<float>(v));
  117. band.sum += static_cast<float>(v);
  118. }
  119. bands.push_back(std::move(band));
  120. }
  121. return bands;
  122. }
  123. } // namespace
  124. void analyzeSpectra(Context& ctx, const std::atomic<bool>* cancel, int frameLo, int frameHi)
  125. {
  126. const Params& p = ctx.p;
  127. StftFrames frames(ctx.audio, ctx.numSamples, p);
  128. const int T = frames.numFrames(), K = frames.numBins();
  129. ctx.numFrames = T;
  130. ctx.numBins = K;
  131. const double binHz = p.sampleRate / p.fftSize;
  132. const auto cb = whiteningCentres(p);
  133. const auto bands = whiteningBands(cb, p, K);
  134. std::vector<float> gamma(cb.size()), gains(static_cast<size_t>(K));
  135. std::vector<std::complex<float>> cur(static_cast<size_t>(K)), nxt(static_cast<size_t>(K)), prev(static_cast<size_t>(K));
  136. std::vector<float> mag(static_cast<size_t>(K)), noise(static_cast<size_t>(K)), IF(static_cast<size_t>(K)), scratch;
  137. Peaks& pk = ctx.peaks;
  138. pk = Peaks{};
  139. pk.frameStart.assign(static_cast<size_t>(T) + 1, 0);
  140. const float absThr = std::pow(10.0f, p.peakAbsDb / 20.0f);
  141. const float relFactor = std::pow(10.0f, p.peakRelDb / 20.0f);
  142. const float overNoise = std::pow(10.0f, p.peakOverNoiseDb / 20.0f);
  143. const float ifScale = static_cast<float>(p.fftSize / (2.0 * kPi * p.hop));
  144. // LYNX modification (round 190lk): peaks for frames [frameLo, frameHi) only (the others stay empty), so the
  145. // masks of a few NMF blocks can be built on demand without a pass over the whole recording. Each frame's peaks
  146. // depend only on that frame and its neighbours, so they are the same as in a whole pass.
  147. const int tLo = std::clamp(frameLo, 0, T);
  148. const int tHi = frameHi < 0 ? T : std::clamp(frameHi, tLo, T);
  149. for (int t = 0; t <= tLo && t <= T; ++t)
  150. pk.frameStart[static_cast<size_t>(t)] = 0;
  151. if (tLo > 0 && tLo < T)
  152. {
  153. frames.spectrum(tLo - 1, prev.data());
  154. frames.spectrum(tLo, cur.data());
  155. if (tLo + 1 < T)
  156. frames.spectrum(tLo + 1, nxt.data());
  157. }
  158. else
  159. {
  160. frames.spectrum(0, cur.data());
  161. if (T > 1)
  162. frames.spectrum(1, nxt.data());
  163. }
  164. for (int t = tLo; t < tHi; ++t)
  165. {
  166. if (cancel && cancel->load())
  167. return;
  168. if (t > tLo)
  169. {
  170. prev.swap(cur);
  171. cur.swap(nxt);
  172. if (t + 1 < T)
  173. frames.spectrum(t + 1, nxt.data());
  174. }
  175. // instantaneous frequency from the phase advance (frame 0 uses frames 0 -> 1)
  176. const auto& a = (t == 0) ? cur : prev;
  177. const auto& b = (t == 0) ? (T > 1 ? nxt : cur) : cur;
  178. for (int k = 0; k < K; ++k)
  179. {
  180. mag[static_cast<size_t>(k)] = std::abs(cur[static_cast<size_t>(k)]);
  181. const float expected = static_cast<float>(2.0 * kPi * k * p.hop / p.fftSize);
  182. const float dphi = (t == 0 && T <= 1) ? 0.0f : std::arg(b[static_cast<size_t>(k)]) - std::arg(a[static_cast<size_t>(k)]);
  183. IF[static_cast<size_t>(k)] = static_cast<float>(k) + princarg(dphi - expected) * ifScale;
  184. }
  185. medianRow(mag.data(), K, p.noiseMedianBins, noise.data(), scratch);
  186. // whitening gains
  187. if (p.whitenNu < 1.0f)
  188. {
  189. for (size_t q = 0; q < bands.size(); ++q)
  190. {
  191. double s = 0.0;
  192. for (size_t j = 0; j < bands[q].w.size(); ++j)
  193. {
  194. const float m = mag[static_cast<size_t>(bands[q].k0) + j];
  195. s += bands[q].w[j] * static_cast<double>(m) * m;
  196. }
  197. const double sigma = std::sqrt(s / std::max(1e-9, static_cast<double>(bands[q].sum)));
  198. gamma[q] = static_cast<float>(std::pow(sigma + 1e-7, p.whitenNu - 1.0));
  199. }
  200. size_t q = 0;
  201. for (int k = 0; k < K; ++k)
  202. {
  203. const double f = k * binHz;
  204. if (f <= cb.front()) { gains[static_cast<size_t>(k)] = gamma.front(); continue; }
  205. if (f >= cb.back()) { gains[static_cast<size_t>(k)] = gamma.back(); continue; }
  206. while (q + 1 < cb.size() && cb[q + 1] < f)
  207. ++q;
  208. const double u = (f - cb[q]) / (cb[q + 1] - cb[q]);
  209. gains[static_cast<size_t>(k)] = static_cast<float>(gamma[q] * (1.0 - u) + gamma[q + 1] * u);
  210. }
  211. }
  212. else
  213. {
  214. std::fill(gains.begin(), gains.end(), 1.0f);
  215. }
  216. // peaks
  217. pk.frameStart[static_cast<size_t>(t)] = static_cast<int>(pk.bin.size());
  218. float frameMax = 0.0f;
  219. for (int k = 0; k < K; ++k)
  220. frameMax = std::max(frameMax, mag[static_cast<size_t>(k)]);
  221. const float thr = std::max(absThr, frameMax * relFactor);
  222. for (int k = 2; k < K - 2; ++k)
  223. {
  224. const float v = mag[static_cast<size_t>(k)];
  225. if (!(v > mag[static_cast<size_t>(k - 1)] && v >= mag[static_cast<size_t>(k + 1)] && v > mag[static_cast<size_t>(k - 2)] && v >= mag[static_cast<size_t>(k + 2)]))
  226. continue;
  227. if (!(v > thr) || !(v > noise[static_cast<size_t>(k)] * overNoise))
  228. continue;
  229. const float la = std::log(mag[static_cast<size_t>(k - 1)] + 1e-12f), lb = std::log(v + 1e-12f), lc = std::log(mag[static_cast<size_t>(k + 1)] + 1e-12f);
  230. const float den = la - 2.0f * lb + lc;
  231. float d = std::fabs(den) > 1e-12f ? 0.5f * (la - lc) / den : 0.0f;
  232. d = std::clamp(d, -0.5f, 0.5f);
  233. const float amp = std::exp(lb - 0.25f * (la - lc) * d);
  234. const float fif = IF[static_cast<size_t>(k)];
  235. const float fbin = std::fabs(fif - k) <= 1.0f ? fif : k + d;
  236. const float dev = std::max(std::fabs(IF[static_cast<size_t>(k - 1)] - fif), std::fabs(IF[static_cast<size_t>(k + 1)] - fif));
  237. const float ton = std::exp(-(dev / p.tonalDevBins) * (dev / p.tonalDevBins));
  238. pk.bin.push_back(k);
  239. pk.fbin.push_back(fbin);
  240. pk.amp.push_back(amp);
  241. pk.tonality.push_back(ton);
  242. pk.wamp.push_back(amp * gains[static_cast<size_t>(k)]);
  243. }
  244. // keep each frame's peaks sorted by refined frequency for binary search
  245. {
  246. const int b0 = pk.frameStart[static_cast<size_t>(t)], b1 = static_cast<int>(pk.bin.size());
  247. bool sorted = true;
  248. for (int j = b0 + 1; j < b1 && sorted; ++j)
  249. sorted = pk.fbin[static_cast<size_t>(j - 1)] <= pk.fbin[static_cast<size_t>(j)];
  250. if (!sorted)
  251. {
  252. std::vector<int> o(static_cast<size_t>(b1 - b0));
  253. for (int j = 0; j < b1 - b0; ++j)
  254. o[static_cast<size_t>(j)] = b0 + j;
  255. std::stable_sort(o.begin(), o.end(), [&](int x, int y) { return pk.fbin[static_cast<size_t>(x)] < pk.fbin[static_cast<size_t>(y)]; });
  256. auto permute = [&](auto& v) {
  257. auto copy = v;
  258. for (int j = 0; j < b1 - b0; ++j)
  259. v[static_cast<size_t>(b0 + j)] = copy[static_cast<size_t>(o[static_cast<size_t>(j)])];
  260. };
  261. permute(pk.bin); permute(pk.fbin); permute(pk.amp); permute(pk.tonality); permute(pk.wamp);
  262. }
  263. }
  264. }
  265. for (int t = tHi; t <= T; ++t)
  266. pk.frameStart[static_cast<size_t>(t)] = static_cast<int>(pk.bin.size());
  267. }
  268. } // namespace detail
  269. } // namespace polyphonic