4
0

PolySoundModel.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. // Polyphonic engine - sound model: a pitch-informed harmonic NMF (after Ewert & Mueller 2012) that gives each
  2. // note its share of the bins around its partials.
  3. #include "PolyInternal.h"
  4. namespace polyphonic
  5. {
  6. namespace detail
  7. {
  8. namespace
  9. {
  10. // Magnitude of the Hann window's transform at a fractional bin offset, 1 at the centre.
  11. inline float hannLobe(float d)
  12. {
  13. d = std::fabs(d);
  14. if (d >= 2.0f)
  15. return 0.0f;
  16. if (d < 1e-6f)
  17. return 1.0f;
  18. const float den = 1.0f - d * d;
  19. if (std::fabs(den) < 1e-5f)
  20. return 0.5f;
  21. const float x = static_cast<float>(kPi) * d;
  22. return std::fabs(std::sin(x) / x / den);
  23. }
  24. inline int roundHalfEven(float v) { return static_cast<int>(std::nearbyint(v)); }
  25. struct Entry
  26. {
  27. int t, k, note, harm, seg;
  28. float phi, kc;
  29. };
  30. } // namespace
  31. namespace
  32. {
  33. // One NMF solve over frames [lo, hi) for the notes in `idx`; masks are stored for [coreLo, coreHi).
  34. void nmfBlock(const Context& ctx, const std::vector<Candidate>& notes, const std::vector<int>& idx,
  35. int lo, int hi, int coreLo, int coreHi, Analysis& out)
  36. {
  37. const Params& p = ctx.p;
  38. const int K = ctx.numBins;
  39. const float binHz = static_cast<float>(p.sampleRate / p.fftSize);
  40. const int H = p.nmfHarmonics;
  41. const int kmax = std::min(K - 2, static_cast<int>(p.nmfMaxHz / binHz));
  42. const int segLen = std::max(1, static_cast<int>(std::lround(p.nmfSegmentSeconds * p.sampleRate / p.hop)));
  43. const int N = static_cast<int>(idx.size());
  44. const auto& pk = ctx.peaks;
  45. std::vector<Entry> entries;
  46. std::vector<int> nseg(static_cast<size_t>(N), 1), first(static_cast<size_t>(N)), last(static_cast<size_t>(N)), gOff(static_cast<size_t>(N) + 1, 0);
  47. for (int q = 0; q < N; ++q)
  48. {
  49. const auto& n = notes[static_cast<size_t>(idx[static_cast<size_t>(q)])];
  50. const int a = std::max({0, n.start - p.preFrames, lo});
  51. const int b = std::min({ctx.numFrames - 1, n.end + p.postFrames, hi - 1});
  52. first[static_cast<size_t>(q)] = a;
  53. last[static_cast<size_t>(q)] = std::max(a, b);
  54. nseg[static_cast<size_t>(q)] = 1 + (std::max(a, b) - a) / segLen;
  55. gOff[static_cast<size_t>(q) + 1] = gOff[static_cast<size_t>(q)] + (std::max(a, b) - a + 1);
  56. for (int t = a; t <= b; ++t)
  57. {
  58. const float f0 = n.f0At(t);
  59. for (int h = 1; h <= H; ++h)
  60. {
  61. const float fh = static_cast<float>(f0 * h * std::sqrt(1.0 + n.B * h * h));
  62. if (!(fh < std::min(p.nmfMaxHz, static_cast<float>(p.sampleRate / 2 - 200))))
  63. continue;
  64. float kc = fh / binHz;
  65. if (pk.begin(t) < pk.end(t))
  66. {
  67. const int j = pk.nearest(t, kc);
  68. const float tol = std::min(std::max(1.0f, 0.01f * kc), 0.35f * f0 / binHz);
  69. if (std::fabs(pk.fbin[static_cast<size_t>(j)] - kc) < tol)
  70. kc = pk.fbin[static_cast<size_t>(j)];
  71. }
  72. const int k0 = roundHalfEven(kc);
  73. for (int o = -p.nmfHalfWidth; o <= p.nmfHalfWidth; ++o)
  74. {
  75. const int kk = k0 + o;
  76. const float phi = hannLobe(static_cast<float>(kk) - kc);
  77. if (kk < 1 || kk > kmax || phi <= 1e-3f)
  78. continue;
  79. entries.push_back({t, kk, q, h - 1, (t - a) / segLen, phi, kc});
  80. }
  81. }
  82. }
  83. }
  84. if (entries.empty())
  85. return;
  86. int maxSeg = 1;
  87. for (int s : nseg)
  88. maxSeg = std::max(maxSeg, s);
  89. auto wIndex = [&](int n, int s, int h) { return (static_cast<size_t>(n) * maxSeg + static_cast<size_t>(s)) * H + static_cast<size_t>(h); };
  90. auto gIndex = [&](int n, int t) { return static_cast<size_t>(gOff[static_cast<size_t>(n)] + (t - first[static_cast<size_t>(n)])); };
  91. std::vector<double> W(static_cast<size_t>(N) * maxSeg * H, 0.0), numW(W.size()), denW(W.size());
  92. for (int q = 0; q < N; ++q)
  93. for (int s = 0; s < nseg[static_cast<size_t>(q)]; ++s)
  94. for (int h = 0; h < H; ++h)
  95. W[wIndex(q, s, h)] = 1.0 / (h + 1);
  96. std::vector<double> G(static_cast<size_t>(gOff.back()), 0.05), numG(G.size()), denG(G.size());
  97. // cells: distinct (t, k) touched by the model
  98. std::vector<size_t> flat(entries.size()), order(entries.size());
  99. for (size_t e = 0; e < entries.size(); ++e)
  100. {
  101. flat[e] = static_cast<size_t>(entries[e].t) * K + static_cast<size_t>(entries[e].k);
  102. order[e] = e;
  103. }
  104. std::sort(order.begin(), order.end(), [&](size_t a, size_t b) { return flat[a] < flat[b]; });
  105. std::vector<int> cell(entries.size());
  106. int numCells = 0;
  107. for (size_t q = 0; q < order.size(); ++q)
  108. {
  109. if (q > 0 && flat[order[q]] != flat[order[q - 1]])
  110. ++numCells;
  111. cell[order[q]] = numCells;
  112. }
  113. ++numCells;
  114. std::vector<double> Vh(static_cast<size_t>(numCells)), cellV(static_cast<size_t>(numCells)), cellNoise(static_cast<size_t>(numCells));
  115. {
  116. // magnitude and noise floor for this block only (recomputed: nothing frame-sized is kept)
  117. StftFrames frames(ctx.audio, ctx.numSamples, p);
  118. Matrix magB(hi - lo, K), noiseB(hi - lo, K);
  119. std::vector<std::complex<float>> spec(static_cast<size_t>(K));
  120. std::vector<float> scratch;
  121. for (int t = lo; t < hi; ++t)
  122. {
  123. frames.spectrum(t, spec.data());
  124. float* m = magB.row(t - lo);
  125. for (int k = 0; k < K; ++k)
  126. m[k] = std::abs(spec[static_cast<size_t>(k)]);
  127. medianRow(m, K, p.noiseMedianBins, noiseB.row(t - lo), scratch);
  128. }
  129. for (size_t e = 0; e < entries.size(); ++e)
  130. {
  131. cellV[static_cast<size_t>(cell[e])] = magB.at(entries[e].t - lo, entries[e].k);
  132. cellNoise[static_cast<size_t>(cell[e])] = noiseB.at(entries[e].t - lo, entries[e].k);
  133. }
  134. }
  135. const double eps = 1e-12;
  136. std::vector<double> contrib(entries.size());
  137. auto evaluate = [&]() {
  138. for (int c = 0; c < numCells; ++c)
  139. Vh[static_cast<size_t>(c)] = cellNoise[static_cast<size_t>(c)];
  140. for (size_t e = 0; e < entries.size(); ++e)
  141. {
  142. const auto& en = entries[e];
  143. contrib[e] = G[gIndex(en.note, en.t)] * W[wIndex(en.note, en.seg, en.harm)] * en.phi;
  144. Vh[static_cast<size_t>(cell[e])] += contrib[e];
  145. }
  146. };
  147. std::vector<double> tmp(static_cast<size_t>(maxSeg) * H);
  148. for (int it = 0; it < p.nmfIterations; ++it)
  149. {
  150. evaluate();
  151. std::fill(numW.begin(), numW.end(), 0.0);
  152. std::fill(denW.begin(), denW.end(), 0.0);
  153. for (size_t e = 0; e < entries.size(); ++e)
  154. {
  155. const auto& en = entries[e];
  156. const double r = cellV[static_cast<size_t>(cell[e])] / (Vh[static_cast<size_t>(cell[e])] + eps);
  157. const double g = G[gIndex(en.note, en.t)] * en.phi;
  158. numW[wIndex(en.note, en.seg, en.harm)] += g * r;
  159. denW[wIndex(en.note, en.seg, en.harm)] += g;
  160. }
  161. for (size_t i = 0; i < W.size(); ++i)
  162. W[i] *= numW[i] / (denW[i] + eps);
  163. for (int q = 0; q < N; ++q)
  164. {
  165. const int ns = nseg[static_cast<size_t>(q)];
  166. if (ns > 1)
  167. {
  168. for (int s = 0; s < ns; ++s)
  169. for (int h = 0; h < H; ++h)
  170. {
  171. const double l = W[wIndex(q, std::max(0, s - 1), h)], c = W[wIndex(q, s, h)], r = W[wIndex(q, std::min(ns - 1, s + 1), h)];
  172. tmp[static_cast<size_t>(s) * H + static_cast<size_t>(h)] = 0.5 * c + 0.25 * (l + r);
  173. }
  174. for (int s = 0; s < ns; ++s)
  175. for (int h = 0; h < H; ++h)
  176. W[wIndex(q, s, h)] = tmp[static_cast<size_t>(s) * H + static_cast<size_t>(h)];
  177. }
  178. double meanScale = 0.0;
  179. for (int s = 0; s < ns; ++s)
  180. {
  181. double sum = eps;
  182. for (int h = 0; h < H; ++h)
  183. sum += W[wIndex(q, s, h)];
  184. for (int h = 0; h < H; ++h)
  185. W[wIndex(q, s, h)] /= sum;
  186. meanScale += sum;
  187. }
  188. meanScale /= ns;
  189. for (int g = gOff[static_cast<size_t>(q)]; g < gOff[static_cast<size_t>(q) + 1]; ++g)
  190. G[static_cast<size_t>(g)] *= meanScale;
  191. }
  192. evaluate();
  193. std::fill(numG.begin(), numG.end(), 0.0);
  194. std::fill(denG.begin(), denG.end(), 0.0);
  195. for (size_t e = 0; e < entries.size(); ++e)
  196. {
  197. const auto& en = entries[e];
  198. const double r = cellV[static_cast<size_t>(cell[e])] / (Vh[static_cast<size_t>(cell[e])] + eps);
  199. const double w = W[wIndex(en.note, en.seg, en.harm)] * en.phi;
  200. numG[gIndex(en.note, en.t)] += w * r;
  201. denG[gIndex(en.note, en.t)] += w;
  202. }
  203. for (size_t i = 0; i < G.size(); ++i)
  204. G[i] *= numG[i] / (denG[i] + eps);
  205. }
  206. evaluate();
  207. std::vector<size_t> byKey;
  208. for (size_t e = 0; e < entries.size(); ++e)
  209. if (entries[e].t >= coreLo && entries[e].t < coreHi)
  210. byKey.push_back(e);
  211. std::sort(byKey.begin(), byKey.end(), [&](size_t a, size_t b) {
  212. const auto& x = entries[a];
  213. const auto& y = entries[b];
  214. if (x.note != y.note) return x.note < y.note;
  215. if (x.t != y.t) return x.t < y.t;
  216. if (x.harm != y.harm) return x.harm < y.harm;
  217. return x.k < y.k;
  218. });
  219. size_t q = 0;
  220. while (q < byKey.size())
  221. {
  222. const auto& e0 = entries[byKey[q]];
  223. size_t r = q;
  224. int kLo = e0.k, kHi = e0.k;
  225. while (r < byKey.size() && entries[byKey[r]].note == e0.note && entries[byKey[r]].t == e0.t && entries[byKey[r]].harm == e0.harm)
  226. {
  227. kLo = std::min(kLo, entries[byKey[r]].k);
  228. kHi = std::max(kHi, entries[byKey[r]].k);
  229. ++r;
  230. }
  231. auto& nm = out.masks[static_cast<size_t>(idx[static_cast<size_t>(e0.note)])];
  232. PartialMask pm;
  233. pm.frame = e0.t;
  234. pm.harmonic = e0.harm + 1;
  235. pm.lo = kLo;
  236. pm.count = kHi - kLo + 1;
  237. pm.weightOffset = static_cast<int>(nm.weights.size());
  238. pm.freqHz = e0.kc * binHz;
  239. pm.amplitude = static_cast<float>(G[gIndex(e0.note, e0.t)] * W[wIndex(e0.note, e0.seg, e0.harm)]);
  240. nm.weights.resize(nm.weights.size() + static_cast<size_t>(pm.count), 0.0f);
  241. for (size_t s = q; s < r; ++s)
  242. {
  243. const size_t e = byKey[s];
  244. nm.weights[static_cast<size_t>(pm.weightOffset + entries[e].k - kLo)] =
  245. static_cast<float>(contrib[e] / (Vh[static_cast<size_t>(cell[e])] + eps));
  246. }
  247. nm.partials.push_back(pm);
  248. q = r;
  249. }
  250. }
  251. } // namespace
  252. // Notes only interact where they overlap in time, so the NMF is solved in blocks of a few seconds
  253. // (with margins) to bound memory on long recordings. A recording shorter than one block is
  254. // solved in one piece.
  255. // LYNX modification (round 190lk): the block grid and one block's solve are separate functions (maskBlocks,
  256. // buildMaskBlock), so that LYNX can build the masks of the blocks an edit reaches on demand (ensureMasks) instead
  257. // of keeping every note's masks for the whole recording. buildMasks solves the same blocks in the same way.
  258. std::vector<MaskBlock> maskBlocks(const Params& p, int T)
  259. {
  260. std::vector<MaskBlock> blocks;
  261. const int core = std::max(16, static_cast<int>(std::lround(4.0 * p.sampleRate / p.hop)));
  262. const int margin = static_cast<int>(std::lround(0.5 * p.sampleRate / p.hop));
  263. for (int blockStart = 0; blockStart < T; blockStart += core)
  264. {
  265. int coreEnd = std::min(T, blockStart + core);
  266. if (T - coreEnd < margin) // fold a short tail into this block
  267. coreEnd = T;
  268. blocks.push_back({blockStart, coreEnd, std::max(0, blockStart - margin), std::min(T, coreEnd + margin)});
  269. if (coreEnd == T)
  270. break;
  271. }
  272. return blocks;
  273. }
  274. void buildMaskBlock(const Context& ctx, const std::vector<Candidate>& notes, const MaskBlock& block, Analysis& out)
  275. {
  276. const Params& p = ctx.p;
  277. std::vector<int> idx;
  278. for (int ni = 0; ni < static_cast<int>(notes.size()); ++ni)
  279. {
  280. const auto& n = notes[static_cast<size_t>(ni)];
  281. if (n.end + p.postFrames >= block.lo && n.start - p.preFrames < block.hi)
  282. idx.push_back(ni);
  283. }
  284. if (!idx.empty())
  285. nmfBlock(ctx, notes, idx, block.lo, block.hi, block.coreLo, block.coreHi, out);
  286. }
  287. void buildMasks(const Context& ctx, const std::vector<Candidate>& notes, Analysis& out)
  288. {
  289. out.masks.assign(out.notes.size(), {});
  290. for (const auto& block : maskBlocks(ctx.p, ctx.numFrames))
  291. buildMaskBlock(ctx, notes, block, out);
  292. }
  293. } // namespace detail
  294. } // namespace polyphonic