PolyExtraction.cpp 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343
  1. // Polyphonic engine - cents field, harmonic-sum salience, iterative estimation and cancellation of note
  2. // candidates, candidate pruning, f0/inharmonicity refinement, repeated-note splitting and fragment
  3. // merging. Everything here works on pitched (harmonic) energy only.
  4. #include "PolyInternal.h"
  5. #include <limits>
  6. #include <numeric>
  7. namespace polyphonic
  8. {
  9. namespace detail
  10. {
  11. namespace
  12. {
  13. template <typename T>
  14. float medianOf(std::vector<T> v)
  15. {
  16. if (v.empty())
  17. return 0.0f;
  18. const size_t n = v.size();
  19. std::nth_element(v.begin(), v.begin() + static_cast<std::ptrdiff_t>(n / 2), v.end());
  20. const float hi = static_cast<float>(v[n / 2]);
  21. if (n % 2)
  22. return hi;
  23. const float lo = static_cast<float>(*std::max_element(v.begin(), v.begin() + static_cast<std::ptrdiff_t>(n / 2)));
  24. return 0.5f * (lo + hi);
  25. }
  26. // Fill the entries without a value by linear interpolation between known neighbours (held flat
  27. // past the ends). An explicit mask rather than NaN sentinels: pitchnet_core builds with
  28. // -ffast-math, under which NaN checks may be optimised away.
  29. void fillGaps(std::vector<float>& v, const std::vector<uint8_t>& known)
  30. {
  31. const int n = static_cast<int>(v.size());
  32. int prev = -1;
  33. for (int i = 0; i < n; ++i)
  34. {
  35. if (!known[static_cast<size_t>(i)])
  36. continue;
  37. if (prev < 0)
  38. for (int j = 0; j < i; ++j)
  39. v[static_cast<size_t>(j)] = v[static_cast<size_t>(i)];
  40. else
  41. for (int j = prev + 1; j < i; ++j)
  42. {
  43. const float u = static_cast<float>(j - prev) / static_cast<float>(i - prev);
  44. v[static_cast<size_t>(j)] = v[static_cast<size_t>(prev)] * (1 - u) + v[static_cast<size_t>(i)] * u;
  45. }
  46. prev = i;
  47. }
  48. if (prev >= 0)
  49. for (int j = prev + 1; j < n; ++j)
  50. v[static_cast<size_t>(j)] = v[static_cast<size_t>(prev)];
  51. }
  52. std::vector<float> medianFilter3(const std::vector<float>& v)
  53. {
  54. const int n = static_cast<int>(v.size());
  55. std::vector<float> out(v);
  56. for (int i = 0; i < n; ++i)
  57. {
  58. float a = v[static_cast<size_t>(std::max(0, i - 1))], b = v[static_cast<size_t>(i)], c = v[static_cast<size_t>(std::min(n - 1, i + 1))];
  59. out[static_cast<size_t>(i)] = std::max(std::min(a, b), std::min(std::max(a, b), c));
  60. }
  61. return out;
  62. }
  63. } // namespace
  64. float Candidate::midi() const
  65. {
  66. if (f0.empty())
  67. return 0.0f;
  68. return 69.0f + 12.0f * std::log2(medianOf(f0) / 440.0f);
  69. }
  70. int numCentsBins(const Params& p)
  71. {
  72. return static_cast<int>(std::ceil(1200.0 * std::log2(p.fTop / p.fRef) / p.centsStep)) + 1;
  73. }
  74. float hzToField(float hz, const Params& p)
  75. {
  76. return static_cast<float>(1200.0 * std::log2(std::max(hz, 1e-6f) / p.fRef) / p.centsStep);
  77. }
  78. float fieldToHz(float c, const Params& p)
  79. {
  80. return static_cast<float>(p.fRef * std::pow(2.0, c * p.centsStep / 1200.0));
  81. }
  82. namespace
  83. {
  84. // F(t, f, E) for frames [t0, t1): tonality-weighted, whitened peak amplitudes deposited at their
  85. // instantaneous frequency on a cents grid with a half-tone-wide Hann window, smoothed over time.
  86. Matrix buildField(const Context& ctx, int t0, int t1)
  87. {
  88. const Params& p = ctx.p;
  89. const int C = numCentsBins(p);
  90. const int a = std::max(0, t0 - 1), b = std::min(ctx.numFrames, t1 + 1);
  91. Matrix E(b - a, C);
  92. const double binHz = p.sampleRate / p.fftSize;
  93. const float s = p.spreadCents / p.centsStep;
  94. const int r = static_cast<int>(std::ceil(s));
  95. const auto& pk = ctx.peaks;
  96. for (int t = a; t < b; ++t)
  97. {
  98. float* row = E.row(t - a);
  99. for (int j = pk.begin(t); j < pk.end(t); ++j)
  100. {
  101. const float f = static_cast<float>(pk.fbin[static_cast<size_t>(j)] * binHz);
  102. if (!(f > p.fRef && f < p.fTop))
  103. continue;
  104. const float c = hzToField(f, p);
  105. const float val = pk.wamp[static_cast<size_t>(j)] * pk.tonality[static_cast<size_t>(j)];
  106. const int base = static_cast<int>(std::floor(c));
  107. for (int o = -r; o <= r + 1; ++o)
  108. {
  109. const int ci = base + o;
  110. const float d = std::fabs(static_cast<float>(ci) - c);
  111. if (ci < 0 || ci >= C || d >= s)
  112. continue;
  113. row[ci] += val * (0.5f + 0.5f * std::cos(static_cast<float>(kPi) * d / s));
  114. }
  115. }
  116. }
  117. Matrix out(t1 - t0, C);
  118. for (int t = t0; t < t1; ++t)
  119. {
  120. const bool smooth = t > 0 && t < ctx.numFrames - 1;
  121. for (int c = 0; c < C; ++c)
  122. out.at(t - t0, c) = smooth ? 0.25f * E.at(t - 1 - a, c) + 0.5f * E.at(t - a, c) + 0.25f * E.at(t + 1 - a, c)
  123. : E.at(t - a, c);
  124. }
  125. return out;
  126. }
  127. } // namespace
  128. namespace
  129. {
  130. struct RelevanceTable
  131. {
  132. int c0Lo = 0, c0Hi = 0, C = 0;
  133. std::vector<int> offsets; // per harmonic
  134. std::vector<std::vector<float>> w; // [harmonic][column]
  135. };
  136. RelevanceTable makeRelevanceTable(const Params& p)
  137. {
  138. RelevanceTable rt;
  139. rt.C = numCentsBins(p);
  140. rt.c0Lo = static_cast<int>(std::floor(hzToField(p.f0Min, p)));
  141. rt.c0Hi = static_cast<int>(std::ceil(hzToField(p.f0Max, p)));
  142. const int cols = rt.c0Hi - rt.c0Lo + 1;
  143. for (int h = 1; h <= p.numHarmonicsRelevance; ++h)
  144. {
  145. rt.offsets.push_back(static_cast<int>(std::lround(1200.0 * std::log2(h) / p.centsStep)));
  146. std::vector<float> w(static_cast<size_t>(cols));
  147. for (int j = 0; j < cols; ++j)
  148. {
  149. const float f0 = fieldToHz(static_cast<float>(rt.c0Lo + j), p);
  150. w[static_cast<size_t>(j)] = (f0 + p.alpha) / (h * f0 + p.beta);
  151. }
  152. rt.w.push_back(std::move(w));
  153. }
  154. return rt;
  155. }
  156. void relevanceRows(const RelevanceTable& rt, const Matrix& E, int t0, int t1, Matrix& R)
  157. {
  158. const int cols = rt.c0Hi - rt.c0Lo + 1;
  159. for (int t = t0; t < t1; ++t)
  160. {
  161. float* out = R.row(t);
  162. std::fill(out, out + cols, 0.0f);
  163. const float* e = E.row(t);
  164. for (size_t h = 0; h < rt.offsets.size(); ++h)
  165. {
  166. const int off = rt.offsets[h];
  167. const float* w = rt.w[h].data();
  168. const int jMax = std::min(cols, rt.C - rt.c0Lo - off);
  169. for (int j = 0; j < jMax; ++j)
  170. out[j] += w[j] * e[rt.c0Lo + j + off];
  171. }
  172. }
  173. }
  174. } // namespace
  175. namespace
  176. {
  177. struct Crest
  178. {
  179. std::vector<int> t;
  180. std::vector<int> c; // relevance column
  181. };
  182. Crest trackCrest(const Matrix& R, int t0, int c0, const Params& p)
  183. {
  184. const float peak = R.at(t0, c0);
  185. const int jump = static_cast<int>(std::lround(p.crestJumpCents / p.centsStep));
  186. std::vector<std::pair<int, int>> fwd, bwd;
  187. for (int dir : {1, -1})
  188. {
  189. int c = c0, t = t0 + dir;
  190. while (t >= 0 && t < R.rows)
  191. {
  192. const int lo = std::max(0, c - jump), hi = std::min(R.cols, c + jump + 1);
  193. const float* row = R.row(t);
  194. int cn = lo;
  195. for (int j = lo + 1; j < hi; ++j)
  196. if (row[j] > row[cn])
  197. cn = j;
  198. if (row[cn] < p.crestRelative * peak)
  199. break;
  200. (dir > 0 ? fwd : bwd).push_back({t, cn});
  201. c = cn;
  202. t += dir;
  203. }
  204. }
  205. Crest cr;
  206. for (auto it = bwd.rbegin(); it != bwd.rend(); ++it)
  207. {
  208. cr.t.push_back(it->first);
  209. cr.c.push_back(it->second);
  210. }
  211. cr.t.push_back(t0);
  212. cr.c.push_back(c0);
  213. for (auto& e : fwd)
  214. {
  215. cr.t.push_back(e.first);
  216. cr.c.push_back(e.second);
  217. }
  218. return cr;
  219. }
  220. // Withdraw a fraction G of the note's energy at the fundamental and its harmonics, bounded for
  221. // h >= 2 by a robust spectral-smoothness envelope (median over +-3 harmonics) so that energy of
  222. // coinciding partials of other notes survives. The fundamental is always reduced by G.
  223. double withdraw(Matrix& E, const std::vector<int>& ts, const std::vector<int>& cField, const Params& p)
  224. {
  225. const int C = E.cols;
  226. const float s = p.spreadCents / p.centsStep;
  227. const int rad = static_cast<int>(std::ceil(s));
  228. const int H = p.numHarmonicsSubtract;
  229. std::vector<int> offs(static_cast<size_t>(H));
  230. for (int h = 1; h <= H; ++h)
  231. offs[static_cast<size_t>(h - 1)] = static_cast<int>(std::lround(1200.0 * std::log2(h) / p.centsStep));
  232. std::vector<float> kern;
  233. for (int o = -rad; o <= rad; ++o)
  234. kern.push_back(std::fabs(static_cast<float>(o)) < s ? 0.5f + 0.5f * std::cos(static_cast<float>(kPi) * o / s) : 0.0f);
  235. const size_t n = ts.size();
  236. std::vector<int> ip(n * static_cast<size_t>(H));
  237. std::vector<float> amt(n * static_cast<size_t>(H));
  238. std::vector<uint8_t> valid(n * static_cast<size_t>(H));
  239. std::vector<float> a(static_cast<size_t>(H)), padded(static_cast<size_t>(H) + 6), win(7);
  240. for (size_t i = 0; i < n; ++i)
  241. {
  242. const float* row = E.row(ts[i]);
  243. for (int h = 0; h < H; ++h)
  244. {
  245. const int pos = cField[i] + offs[static_cast<size_t>(h)];
  246. const bool ok = (pos + rad + 4 < C) && (pos - rad - 4 >= 0);
  247. const int pc = std::clamp(pos, 3, C - 4);
  248. int best = pc - 3;
  249. for (int o = -2; o <= 3; ++o)
  250. if (row[pc + o] > row[best])
  251. best = pc + o;
  252. const size_t idx = i * static_cast<size_t>(H) + static_cast<size_t>(h);
  253. ip[idx] = best;
  254. valid[idx] = ok ? 1 : 0;
  255. a[static_cast<size_t>(h)] = ok ? row[best] : 0.0f;
  256. }
  257. for (int h = 0; h < H + 6; ++h)
  258. padded[static_cast<size_t>(h)] = a[static_cast<size_t>(std::clamp(h - 3, 0, H - 1))];
  259. for (int h = 0; h < H; ++h)
  260. {
  261. for (int j = 0; j < 7; ++j)
  262. win[static_cast<size_t>(j)] = padded[static_cast<size_t>(h + j)];
  263. std::nth_element(win.begin(), win.begin() + 3, win.end());
  264. const float env = win[3];
  265. const float av = a[static_cast<size_t>(h)];
  266. amt[i * static_cast<size_t>(H) + static_cast<size_t>(h)] = p.subtractFraction * (h == 0 ? av : std::min(av, env));
  267. }
  268. }
  269. double total = 0.0;
  270. std::vector<float> takes(n * static_cast<size_t>(H));
  271. for (int o = -rad; o <= rad; ++o)
  272. {
  273. const float k = kern[static_cast<size_t>(o + rad)];
  274. if (k <= 0.0f)
  275. continue;
  276. for (size_t i = 0; i < n; ++i)
  277. {
  278. const float* row = E.row(ts[i]);
  279. for (int h = 0; h < H; ++h)
  280. {
  281. const size_t idx = i * static_cast<size_t>(H) + static_cast<size_t>(h);
  282. const int ci = std::clamp(ip[idx] + o, 0, C - 1);
  283. takes[idx] = valid[idx] ? std::min(row[ci], amt[idx] * k) : 0.0f;
  284. }
  285. }
  286. for (size_t i = 0; i < n; ++i)
  287. {
  288. float* row = E.row(ts[i]);
  289. for (int h = 0; h < H; ++h)
  290. {
  291. const size_t idx = i * static_cast<size_t>(H) + static_cast<size_t>(h);
  292. if (takes[idx] <= 0.0f)
  293. continue;
  294. const int ci = std::clamp(ip[idx] + o, 0, C - 1);
  295. row[ci] -= takes[idx];
  296. total += takes[idx];
  297. }
  298. }
  299. }
  300. for (size_t i = 0; i < n; ++i)
  301. {
  302. float* row = E.row(ts[i]);
  303. for (int c = 0; c < C; ++c)
  304. row[c] = std::max(row[c], 0.0f);
  305. }
  306. return total;
  307. }
  308. void mergeOrAdd(std::vector<Candidate>& notes, const std::vector<int>& ts, const std::vector<int>& cs,
  309. const std::vector<float>& strength, double energy, const Params& p)
  310. {
  311. const float jump = p.crestJumpCents / p.centsStep;
  312. const int a = ts.front(), b = ts.back();
  313. for (auto& n : notes)
  314. {
  315. if (a > n.end + p.mergeGapFrames || b < n.start - p.mergeGapFrames)
  316. continue;
  317. const int ovLo = std::max(a, n.start), ovHi = std::min(b, n.end);
  318. float d;
  319. if (ovLo <= ovHi)
  320. {
  321. std::vector<float> diffs;
  322. for (size_t i = 0; i < ts.size(); ++i)
  323. if (ts[i] >= ovLo && ts[i] <= ovHi)
  324. diffs.push_back(std::fabs(static_cast<float>(cs[i]) - n.cents[static_cast<size_t>(ts[i] - n.start)]));
  325. d = medianOf(diffs);
  326. }
  327. else if (a > n.end)
  328. d = std::fabs(static_cast<float>(cs.front()) - n.cents.back());
  329. else
  330. d = std::fabs(static_cast<float>(cs.back()) - n.cents.front());
  331. if (d > jump)
  332. continue;
  333. const int lo = std::min(n.start, a), hi = std::max(n.end, b);
  334. std::vector<float> cents(static_cast<size_t>(hi - lo + 1), 0.0f);
  335. std::vector<uint8_t> known(cents.size(), 0);
  336. std::vector<float> stren(static_cast<size_t>(hi - lo + 1), 0.0f);
  337. for (int t = n.start; t <= n.end; ++t)
  338. {
  339. cents[static_cast<size_t>(t - lo)] = n.cents[static_cast<size_t>(t - n.start)];
  340. known[static_cast<size_t>(t - lo)] = 1;
  341. stren[static_cast<size_t>(t - lo)] = n.strength[static_cast<size_t>(t - n.start)];
  342. }
  343. for (size_t i = 0; i < ts.size(); ++i)
  344. {
  345. const size_t k = static_cast<size_t>(ts[i] - lo);
  346. if (!known[k] || strength[i] > stren[k])
  347. cents[k] = static_cast<float>(cs[i]);
  348. known[k] = 1;
  349. stren[k] += strength[i];
  350. }
  351. fillGaps(cents, known);
  352. n.start = lo;
  353. n.end = hi;
  354. n.cents = std::move(cents);
  355. n.strength = std::move(stren);
  356. n.energy += energy;
  357. n.hits += 1;
  358. return;
  359. }
  360. Candidate c;
  361. c.start = a;
  362. c.end = b;
  363. for (int v : cs)
  364. c.cents.push_back(static_cast<float>(v));
  365. c.strength = strength;
  366. c.energy = energy;
  367. notes.push_back(std::move(c));
  368. }
  369. } // namespace
  370. namespace
  371. {
  372. // Iterative estimation and cancellation over frames [lo, hi). Crests whose maximum lies in the core
  373. // [coreLo, coreHi) become (or merge into) note candidates; crests found in the margins are only
  374. // withdrawn - the neighbouring block owns them.
  375. void extractBlock(Context& ctx, int lo, int hi, int coreLo, int coreHi, std::vector<Candidate>& notes,
  376. const std::atomic<bool>* cancel)
  377. {
  378. const Params& p = ctx.p;
  379. Matrix E = buildField(ctx, lo, hi);
  380. const auto rt = makeRelevanceTable(p);
  381. const int T = E.rows, cols = rt.c0Hi - rt.c0Lo + 1;
  382. Matrix R(T, cols);
  383. relevanceRows(rt, E, 0, T, R);
  384. // Guide all pitch hypotheses before explaining away shared harmonic energy.
  385. // Keep unweighted strengths/r0max in the learned feature schema.
  386. const bool guided = ctx.evidence != nullptr && !ctx.evidence->empty();
  387. Matrix guide(guided ? T : 0, guided ? cols : 0, 1.0f);
  388. constexpr double guideStrength = 0.75;
  389. if (guided)
  390. {
  391. const auto& ev = *ctx.evidence;
  392. for (int t = 0; t < T; ++t)
  393. {
  394. const float sec = static_cast<float>((lo + t) * p.hop / p.sampleRate);
  395. auto it = std::lower_bound(ev.frameTimes.begin(), ev.frameTimes.end(), sec);
  396. const int ef = static_cast<int>(std::min<std::ptrdiff_t>(it - ev.frameTimes.begin(), ev.frameTimes.size() - 1));
  397. for (int c = 0; c < cols; ++c)
  398. {
  399. const float m = 69.0f + 12.0f * std::log2(fieldToHz(static_cast<float>(rt.c0Lo + c), p) / 440.0f) - 21.0f;
  400. if (m < 0.0f || m > 87.0f)
  401. continue;
  402. const int a = static_cast<int>(m), b = std::min(87, a + 1);
  403. const float u = m - a;
  404. const float q = ev.note[static_cast<size_t>(ef) * 88 + a] * (1 - u) + ev.note[static_cast<size_t>(ef) * 88 + b] * u;
  405. guide.at(t, c) = static_cast<float>((1 - guideStrength) + guideStrength * std::sqrt(std::max(0.0f, q)));
  406. }
  407. }
  408. }
  409. auto applyGuide = [&](int a, int b) {
  410. if (!guided)
  411. return;
  412. for (int t = a; t < b; ++t)
  413. for (int c = 0; c < cols; ++c)
  414. R.at(t, c) *= guide.at(t, c);
  415. };
  416. for (int t = 0; t < T; ++t)
  417. if (guided && lo + t >= coreLo && lo + t < coreHi)
  418. ctx.r0max[static_cast<size_t>(lo + t)] = *std::max_element(R.row(t), R.row(t) + cols);
  419. applyGuide(0, T);
  420. std::vector<uint8_t> supp(static_cast<size_t>(T) * cols, 0);
  421. std::vector<float> rowMax(static_cast<size_t>(T));
  422. std::vector<int> rowArg(static_cast<size_t>(T));
  423. auto updateRow = [&](int t) {
  424. const float* r = R.row(t);
  425. int best = 0;
  426. for (int j = 1; j < cols; ++j)
  427. if (r[j] > r[best])
  428. best = j;
  429. rowMax[static_cast<size_t>(t)] = r[best];
  430. rowArg[static_cast<size_t>(t)] = best;
  431. };
  432. for (int t = 0; t < T; ++t)
  433. {
  434. updateRow(t);
  435. if (!guided && lo + t >= coreLo && lo + t < coreHi)
  436. ctx.r0max[static_cast<size_t>(lo + t)] = rowMax[static_cast<size_t>(t)];
  437. }
  438. double eTotal = 0.0;
  439. for (float v : E.data)
  440. eTotal += v;
  441. const double e0 = eTotal;
  442. float first = -1.0f;
  443. for (int it = 0; it < p.maxIterations; ++it)
  444. {
  445. if (cancel && cancel->load())
  446. return;
  447. const int t0 = static_cast<int>(std::max_element(rowMax.begin(), rowMax.end()) - rowMax.begin());
  448. const int c0 = rowArg[static_cast<size_t>(t0)];
  449. const float peak = R.at(t0, c0);
  450. if (first < 0.0f)
  451. first = peak;
  452. if (peak <= 0.0f || peak < p.stopRelativePeak * first || eTotal < p.stopEnergy * e0)
  453. break;
  454. const Crest cr = trackCrest(R, t0, c0, p);
  455. std::vector<int> cField(cr.c.size());
  456. std::vector<float> strength(cr.c.size());
  457. for (size_t i = 0; i < cr.c.size(); ++i)
  458. {
  459. cField[i] = cr.c[i] + rt.c0Lo;
  460. strength[i] = guided ? R.at(cr.t[i], cr.c[i]) / guide.at(cr.t[i], cr.c[i]) : R.at(cr.t[i], cr.c[i]);
  461. }
  462. const double took = withdraw(E, cr.t, cField, p);
  463. eTotal -= took;
  464. const int a = std::max(0, cr.t.front() - 1), b = std::min(T, cr.t.back() + 2);
  465. relevanceRows(rt, E, a, b, R);
  466. applyGuide(a, b);
  467. if (R.at(t0, c0) > 0.9f * peak)
  468. for (size_t i = 0; i < cr.t.size(); ++i)
  469. for (int d = -1; d <= 1; ++d)
  470. supp[static_cast<size_t>(cr.t[i]) * cols + static_cast<size_t>(std::clamp(cr.c[i] + d, 0, cols - 1))] = 1;
  471. for (int t = a; t < b; ++t)
  472. {
  473. float* r = R.row(t);
  474. const uint8_t* sp = supp.data() + static_cast<size_t>(t) * cols;
  475. for (int j = 0; j < cols; ++j)
  476. if (sp[j])
  477. r[j] = 0.0f;
  478. updateRow(t);
  479. }
  480. if (lo + t0 < coreLo || lo + t0 >= coreHi)
  481. continue;
  482. std::vector<int> tg(cr.t);
  483. for (auto& t : tg)
  484. t += lo;
  485. mergeOrAdd(notes, tg, cField, strength, took, p);
  486. }
  487. }
  488. } // namespace
  489. // Long recordings are processed in overlapping blocks so that memory stays bounded; a recording
  490. // shorter than one block is processed in one piece (a single global iteration).
  491. std::vector<Candidate> extractCandidates(Context& ctx, const std::atomic<bool>* cancel)
  492. {
  493. const Params& p = ctx.p;
  494. const int T = ctx.numFrames;
  495. ctx.r0max.assign(static_cast<size_t>(T), 0.0f);
  496. const int core = std::max(64, static_cast<int>(std::lround(15.0 * p.sampleRate / p.hop)));
  497. const int margin = static_cast<int>(std::lround(2.5 * p.sampleRate / p.hop));
  498. std::vector<Candidate> notes;
  499. for (int start = 0; start < T; start += core)
  500. {
  501. int end = std::min(T, start + core);
  502. if (T - end < margin)
  503. end = T;
  504. extractBlock(ctx, std::max(0, start - margin), std::min(T, end + margin), start, end, notes, cancel);
  505. if (end == T || (cancel && cancel->load()))
  506. break;
  507. }
  508. return notes;
  509. }
  510. void pruneCandidates(const Context& ctx, std::vector<Candidate>& cands)
  511. {
  512. const Params& p = ctx.p;
  513. const int minLen = static_cast<int>(std::lround(p.minNoteSeconds * p.sampleRate / p.hop));
  514. const auto& r0max = ctx.r0max;
  515. std::vector<Candidate> keep;
  516. for (auto& n : cands)
  517. {
  518. if (n.length() < minLen)
  519. continue;
  520. float ref = 0.0f;
  521. for (int t = n.start; t <= n.end; ++t)
  522. ref = std::max(ref, r0max[static_cast<size_t>(t)]);
  523. const float smax = *std::max_element(n.strength.begin(), n.strength.end());
  524. if (smax < p.minRelativeStrength * ref)
  525. continue;
  526. keep.push_back(std::move(n));
  527. }
  528. std::stable_sort(keep.begin(), keep.end(), [](const Candidate& x, const Candidate& y) {
  529. if (x.start != y.start)
  530. return x.start < y.start;
  531. return medianOf(x.cents) < medianOf(y.cents);
  532. });
  533. cands = std::move(keep);
  534. }
  535. void refineCandidates(const Context& ctx, std::vector<Candidate>& cands)
  536. {
  537. const Params& p = ctx.p;
  538. const auto& pk = ctx.peaks;
  539. const float binHz = static_cast<float>(p.sampleRate / p.fftSize);
  540. for (auto& n : cands)
  541. {
  542. const int T = n.length();
  543. std::vector<float> f0c(static_cast<size_t>(T));
  544. for (int i = 0; i < T; ++i)
  545. f0c[static_cast<size_t>(i)] = fieldToHz(n.cents[static_cast<size_t>(i)], p);
  546. if (T >= 5)
  547. {
  548. std::vector<float> lg(static_cast<size_t>(T));
  549. for (int i = 0; i < T; ++i)
  550. lg[static_cast<size_t>(i)] = std::log(f0c[static_cast<size_t>(i)]);
  551. for (int i = 0; i < T; ++i)
  552. {
  553. float s = 0.0f;
  554. for (int d = -2; d <= 2; ++d)
  555. s += lg[static_cast<size_t>(std::clamp(i + d, 0, T - 1))];
  556. f0c[static_cast<size_t>(i)] = std::exp(s / 5.0f);
  557. }
  558. }
  559. std::vector<float> f0r(f0c);
  560. std::vector<int> hh, tt;
  561. std::vector<float> rr, ww;
  562. std::vector<float> ests, wts;
  563. for (int i = 0; i < T; ++i)
  564. {
  565. const int t = n.start + i;
  566. if (pk.begin(t) == pk.end(t))
  567. continue;
  568. ests.clear();
  569. wts.clear();
  570. for (int h = 1; h <= 12; ++h)
  571. {
  572. const float fh = h * f0c[static_cast<size_t>(i)];
  573. if (fh > p.sampleRate / 2 - 200)
  574. break;
  575. const float tol = h <= 6 ? std::max(0.035f * fh, 1.5f * binHz) : 0.05f * fh;
  576. const int j = pk.nearest(t, fh / binHz);
  577. const float fp = pk.fbin[static_cast<size_t>(j)] * binHz;
  578. if (std::fabs(fp - fh) < tol)
  579. {
  580. hh.push_back(h);
  581. rr.push_back(fp / h);
  582. ww.push_back(pk.amp[static_cast<size_t>(j)]);
  583. tt.push_back(i);
  584. if (h <= 6)
  585. {
  586. ests.push_back(fp / h);
  587. wts.push_back(pk.amp[static_cast<size_t>(j)] * pk.tonality[static_cast<size_t>(j)]);
  588. }
  589. }
  590. }
  591. if (!ests.empty())
  592. {
  593. const float med = medianOf(ests);
  594. double sw = 0.0, s = 0.0;
  595. for (size_t q = 0; q < ests.size(); ++q)
  596. if (std::fabs(ests[q] - med) < 0.01f * med)
  597. {
  598. s += ests[q] * wts[q];
  599. sw += wts[q];
  600. }
  601. if (sw > 0.0)
  602. f0r[static_cast<size_t>(i)] = static_cast<float>(s / sw);
  603. }
  604. }
  605. float B = 0.0f;
  606. if (hh.size() > 10)
  607. {
  608. double num = 0.0, den = 0.0;
  609. int count = 0;
  610. for (size_t q = 0; q < hh.size(); ++q)
  611. {
  612. if (hh[q] < 2)
  613. continue;
  614. const double ratio = rr[q] / f0r[static_cast<size_t>(tt[q])];
  615. const double y = ratio * ratio - 1.0, x = static_cast<double>(hh[q]) * hh[q];
  616. num += ww[q] * x * y;
  617. den += ww[q] * x * x;
  618. ++count;
  619. }
  620. if (count > 5 && den > 0.0)
  621. B = static_cast<float>(std::clamp(num / den, 0.0, 0.002));
  622. }
  623. if (T >= 3)
  624. f0r = medianFilter3(f0r);
  625. n.f0 = std::move(f0r);
  626. n.B = B;
  627. }
  628. }
  629. std::vector<float> harmonicEnvelope(const Context& ctx, const Candidate& n, int numHarmonics, int t0, int t1)
  630. {
  631. const Params& p = ctx.p;
  632. const auto& pk = ctx.peaks;
  633. const float binHz = static_cast<float>(p.sampleRate / p.fftSize);
  634. std::vector<float> env(static_cast<size_t>(std::max(0, t1 - t0 + 1)), 0.0f);
  635. for (int t = std::max(0, t0); t <= std::min(ctx.numFrames - 1, t1); ++t)
  636. {
  637. if (pk.begin(t) == pk.end(t))
  638. continue;
  639. const float f0 = n.f0At(t);
  640. double s = 0.0;
  641. for (int h = 1; h <= numHarmonics; ++h)
  642. {
  643. const float fh = static_cast<float>(f0 * h * std::sqrt(1.0 + n.B * h * h));
  644. const float tol = std::min(std::max(1.2f * binHz, 0.012f * fh), 0.4f * f0);
  645. const int j = pk.nearest(t, fh / binHz);
  646. if (std::fabs(pk.fbin[static_cast<size_t>(j)] * binHz - fh) < tol)
  647. s += static_cast<double>(pk.amp[static_cast<size_t>(j)]) * pk.amp[static_cast<size_t>(j)];
  648. }
  649. env[static_cast<size_t>(t - t0)] = static_cast<float>(std::sqrt(s));
  650. }
  651. return env;
  652. }
  653. bool isReattack(const std::vector<float>& env, int i, float ratio, float floorRel, float envMax)
  654. {
  655. const int n = static_cast<int>(env.size());
  656. if (i < 2 || i + 1 >= n)
  657. return false;
  658. float before = 1e30f, after = 0.0f, mx = 0.0f;
  659. double meanBefore = 0.0, meanAfter = 0.0;
  660. int nb = 0, na = 0;
  661. for (int j = std::max(0, i - 4); j < i; ++j)
  662. before = std::min(before, env[static_cast<size_t>(j)]);
  663. for (int j = i; j < std::min(n, i + 3); ++j)
  664. after = std::max(after, env[static_cast<size_t>(j)]);
  665. for (int j = std::max(0, i - 6); j < i; ++j, ++nb)
  666. meanBefore += env[static_cast<size_t>(j)];
  667. for (int j = i; j < std::min(n, i + 4); ++j, ++na)
  668. meanAfter += env[static_cast<size_t>(j)];
  669. meanBefore /= std::max(1, nb);
  670. meanAfter /= std::max(1, na);
  671. if (envMax >= 0.0f)
  672. mx = envMax;
  673. else
  674. for (float v : env)
  675. mx = std::max(mx, v);
  676. // a real attack lifts the level for several frames, not just one amplitude-modulation peak
  677. return after >= ratio * before + 1e-12f && meanAfter >= 0.75 * ratio * meanBefore && after >= floorRel * mx;
  678. }
  679. // Amplitude of each of the first `numHarmonics` partials of a candidate, per frame in [t0, t1]
  680. // (0 where no spectral peak lies close enough to the partial).
  681. std::vector<std::vector<float>> partialEnvelopes(const Context& ctx, const Candidate& n, int numHarmonics, int t0, int t1)
  682. {
  683. const Params& p = ctx.p;
  684. const auto& pk = ctx.peaks;
  685. const float binHz = static_cast<float>(p.sampleRate / p.fftSize);
  686. std::vector<std::vector<float>> env(static_cast<size_t>(numHarmonics), std::vector<float>(static_cast<size_t>(std::max(0, t1 - t0 + 1)), 0.0f));
  687. for (int t = std::max(0, t0); t <= std::min(ctx.numFrames - 1, t1); ++t)
  688. {
  689. if (pk.begin(t) == pk.end(t))
  690. continue;
  691. const float f0 = n.f0At(t);
  692. for (int h = 1; h <= numHarmonics; ++h)
  693. {
  694. const float fh = static_cast<float>(f0 * h * std::sqrt(1.0 + n.B * h * h));
  695. const float tol = std::min(std::max(1.2f * binHz, 0.012f * fh), 0.4f * f0);
  696. const int j = pk.nearest(t, fh / binHz);
  697. if (std::fabs(pk.fbin[static_cast<size_t>(j)] * binHz - fh) < tol)
  698. env[static_cast<size_t>(h - 1)][static_cast<size_t>(t - t0)] = pk.amp[static_cast<size_t>(j)];
  699. }
  700. }
  701. return env;
  702. }
  703. bool partialsRiseTogether(const std::vector<std::vector<float>>& partials, int i, float minShare)
  704. {
  705. if (partials.empty())
  706. return false;
  707. const int n = static_cast<int>(partials.front().size());
  708. std::vector<double> before(partials.size(), 0.0), after(partials.size(), 0.0);
  709. double strongest = 0.0;
  710. for (size_t h = 0; h < partials.size(); ++h)
  711. {
  712. int nb = 0, na = 0;
  713. for (int j = std::max(0, i - 6); j < i; ++j, ++nb)
  714. before[h] += partials[h][static_cast<size_t>(j)];
  715. for (int j = i; j < std::min(n, i + 4); ++j, ++na)
  716. after[h] += partials[h][static_cast<size_t>(j)];
  717. before[h] /= std::max(1, nb);
  718. after[h] /= std::max(1, na);
  719. strongest = std::max(strongest, after[h]);
  720. }
  721. int present = 0, rising = 0;
  722. for (size_t h = 0; h < partials.size(); ++h)
  723. {
  724. if (!(after[h] > 0.06 * strongest)) // within ~24 dB of the strongest partial
  725. continue;
  726. ++present;
  727. rising += after[h] >= 1.5 * before[h] ? 1 : 0;
  728. }
  729. return present > 0 && rising >= minShare * present;
  730. }
  731. namespace
  732. {
  733. // Repeated-note evidence along a candidate, from its own partials only. A repeated note shows up as
  734. // their energy rising again, all of them together, by much more than the note's own amplitude
  735. // modulation (beating, vibrato, bow pressure) moves it, and staying up. Another note entering on
  736. // one shared partial lifts only some of the partials.
  737. // LYNX modification (round 190lo): slow re-attacks (see splitReattacks)
  738. constexpr double kSlowDip = 0.3; // the dip: at most 30 % of the level the note had reached (-10.5 dB)
  739. constexpr double kSlowRise = 3.0; // then back up by 3x (+9.5 dB) within 0.5 s
  740. constexpr double kSlowBack = 0.35; // to at least 35 % of the earlier level
  741. constexpr double kSlowShare = 0.6; // with 60 % of its present partials rising 2x or more
  742. constexpr double kSlowDeepDip = 0.15; // deeper than this (-16.5 dB) needs no other note starting or ending there
  743. struct ReattackTest
  744. {
  745. std::vector<float> env, rise, peakSoFar;
  746. std::vector<uint8_t> valid;
  747. std::vector<std::vector<float>> partials;
  748. float envMax = 0.0f;
  749. int len = 0;
  750. ReattackTest(const Context& ctx, const Candidate& n)
  751. : env(harmonicEnvelope(ctx, n, 8, n.start, n.end)), partials(partialEnvelopes(ctx, n, 8, n.start, n.end))
  752. {
  753. len = static_cast<int>(env.size());
  754. // local rise: level of the next 4 frames over the previous 6, in log units
  755. rise.assign(static_cast<size_t>(len), 0.0f);
  756. valid.assign(static_cast<size_t>(len), 0);
  757. for (int i = 3; i + 3 <= len; ++i)
  758. {
  759. rise[static_cast<size_t>(i)] = static_cast<float>(std::log((meanOf(i, i + 3) + 1e-12) / (meanOf(i - 6, i - 1) + 1e-12)));
  760. valid[static_cast<size_t>(i)] = 1;
  761. }
  762. // running maximum, for "the note had been louder before it dipped"
  763. peakSoFar.assign(static_cast<size_t>(len), 0.0f);
  764. for (int i = 0; i < len; ++i)
  765. peakSoFar[static_cast<size_t>(i)] = std::max(i > 0 ? peakSoFar[static_cast<size_t>(i - 1)] : 0.0f, env[static_cast<size_t>(i)]);
  766. envMax = len > 0 ? peakSoFar.back() : 0.0f;
  767. }
  768. double meanOf(int a, int b) const // mean of env over [a, b] clipped to the candidate
  769. {
  770. a = std::max(a, 0);
  771. b = std::min(b, len - 1);
  772. double s = 0.0;
  773. for (int j = a; j <= b; ++j)
  774. s += env[static_cast<size_t>(j)];
  775. return b >= a ? s / (b - a + 1) : 0.0;
  776. }
  777. bool standsOut(int i) const
  778. {
  779. std::vector<float> around;
  780. for (int j = i - 18; j <= i + 18; ++j)
  781. if (std::abs(j - i) > 6 && j >= 0 && j < len && valid[static_cast<size_t>(j)])
  782. around.push_back(std::fabs(rise[static_cast<size_t>(j)]));
  783. float typical = 0.0f;
  784. if (!around.empty())
  785. {
  786. std::nth_element(around.begin(), around.begin() + static_cast<std::ptrdiff_t>(around.size() / 2), around.end());
  787. typical = around[around.size() / 2];
  788. }
  789. return rise[static_cast<size_t>(i)] >= kReattackStandOut * typical;
  790. }
  791. bool dipped(int i) const { return i >= 4 && meanOf(i - 6, i - 1) <= kReattackDip * peakSoFar[static_cast<size_t>(i - 4)]; }
  792. // the level rises after a dip and stays up
  793. bool risesAndStays(int i) const
  794. {
  795. return isReattack(env, i, 2.0f, 0.1f, envMax) && dipped(i) && meanOf(i + 1, i + 12) >= 1.5 * meanOf(i - 12, i - 1);
  796. }
  797. // ... and by more than the note's own modulation, with its partials together: a repeated note
  798. bool qualifies(int i) const { return risesAndStays(i) && standsOut(i) && partialsRiseTogether(partials, i, kReattackShare); }
  799. };
  800. } // namespace
  801. std::vector<Candidate> splitReattacks(const Context& ctx, const std::vector<Candidate>& cands)
  802. {
  803. std::vector<Candidate> out;
  804. for (const auto& n : cands)
  805. {
  806. const ReattackTest test(ctx, n);
  807. const int len = test.len;
  808. std::vector<int> cuts;
  809. for (int i = 4; i <= len - 5;)
  810. {
  811. if (!test.qualifies(i))
  812. {
  813. ++i;
  814. continue;
  815. }
  816. // within a run of frames that qualify, cut where the level steps up most (the next 4
  817. // frames over the previous 6, which peaks at the onset); cuts stay 6 frames (~70 ms) apart
  818. int best = i, j = i;
  819. for (; j <= len - 5 && test.qualifies(j); ++j)
  820. if (test.rise[static_cast<size_t>(j)] > test.rise[static_cast<size_t>(best)])
  821. best = j;
  822. if (cuts.empty() || n.start + best - cuts.back() >= 6)
  823. cuts.push_back(n.start + best);
  824. i = j + 1;
  825. }
  826. if (cuts.empty())
  827. {
  828. out.push_back(n);
  829. continue;
  830. }
  831. std::vector<int> bounds{n.start};
  832. bounds.insert(bounds.end(), cuts.begin(), cuts.end());
  833. bounds.push_back(n.end + 1);
  834. for (size_t q = 0; q + 1 < bounds.size(); ++q)
  835. {
  836. const int i0 = bounds[q] - n.start, i1 = bounds[q + 1] - n.start;
  837. Candidate m;
  838. m.start = bounds[q];
  839. m.end = bounds[q + 1] - 1;
  840. m.cents.assign(n.cents.begin() + i0, n.cents.begin() + i1);
  841. m.strength.assign(n.strength.begin() + i0, n.strength.begin() + i1);
  842. m.f0.assign(n.f0.begin() + i0, n.f0.begin() + i1);
  843. m.energy = n.energy * (i1 - i0) / static_cast<double>(n.cents.size());
  844. m.hits = n.hits;
  845. m.B = n.B;
  846. out.push_back(std::move(m));
  847. }
  848. }
  849. const int minLen = static_cast<int>(std::lround(ctx.p.minNoteSeconds * ctx.p.sampleRate / ctx.p.hop));
  850. out.erase(std::remove_if(out.begin(), out.end(), [&](const Candidate& c) { return c.length() < minLen; }), out.end());
  851. return out;
  852. }
  853. // LYNX modification (round 190lo): slow re-attacks. A note played again with a slow attack (a pad, strings, a swell)
  854. // never rises by 2x within splitReattacks()'s 4-frame window, so two chords that hold the same pitch became one note.
  855. // Here: the level dips well below what it had been, then comes back within ~0.5 s with most of the note's partials
  856. // rising together (where the dip is not very deep, other notes must begin or end there too: a chord change); the cut
  857. // goes at the bottom of the dip. Run on the active notes after the note filter (the pieces
  858. // keep the note's probability), so that it never changes which candidates are notes.
  859. std::vector<Candidate> splitSlowReattacks(const Context& ctx, const std::vector<Candidate>& notes)
  860. {
  861. std::vector<Candidate> out;
  862. for (const auto& n : notes)
  863. {
  864. const ReattackTest test(ctx, n);
  865. const int len = test.len;
  866. std::vector<int> cuts;
  867. if (len > 80)
  868. {
  869. const int span = static_cast<int>(std::lround(0.5 * ctx.p.sampleRate / ctx.p.hop));
  870. const int gap = static_cast<int>(std::lround(0.3 * ctx.p.sampleRate / ctx.p.hop));
  871. for (int i = gap; i <= len - gap; ++i)
  872. {
  873. const double trough = test.meanOf(i - 2, i + 2);
  874. bool lowest = true;
  875. for (int j = i - gap / 2; j <= i + gap / 2 && lowest; ++j)
  876. lowest = j == i || j < 2 || j > len - 3 || test.meanOf(j - 2, j + 2) >= trough;
  877. if (!lowest)
  878. continue;
  879. const double before = test.peakSoFar[static_cast<size_t>(i - 6)];
  880. double after = 0.0;
  881. int afterAt = i;
  882. for (int j = i + 6; j <= std::min(len - 4, i + span); ++j)
  883. if (test.meanOf(j - 3, j + 3) > after)
  884. after = test.meanOf(j - 3, j + 3), afterAt = j;
  885. if (!(trough <= kSlowDip * before && after >= kSlowRise * trough && after >= kSlowBack * before))
  886. continue;
  887. // a dip that is not very deep counts where other notes begin or end too (a chord change), not inside
  888. // a held chord (where beating detuned voices dip as well)
  889. if (trough > kSlowDeepDip * before)
  890. {
  891. const int at0 = n.start + i, near = static_cast<int>(std::lround(0.2 * ctx.p.sampleRate / ctx.p.hop));
  892. bool chordChange = false;
  893. for (const auto& o : notes)
  894. chordChange = chordChange || (&o != &n && (std::abs(o.start - at0) <= near || std::abs(o.end - at0) <= near));
  895. if (!chordChange)
  896. continue;
  897. }
  898. // most present partials rise together from the dip to the new peak
  899. int present = 0, rising = 0;
  900. double strongest = 0.0;
  901. std::vector<double> lo(test.partials.size()), hi(test.partials.size());
  902. for (size_t h = 0; h < test.partials.size(); ++h)
  903. {
  904. const auto& e = test.partials[h];
  905. for (int j = i - 2; j <= i + 2; ++j)
  906. lo[h] += e[static_cast<size_t>(std::clamp(j, 0, len - 1))] / 5.0;
  907. for (int j = afterAt - 3; j <= afterAt + 3; ++j)
  908. hi[h] += e[static_cast<size_t>(std::clamp(j, 0, len - 1))] / 7.0;
  909. strongest = std::max(strongest, hi[h]);
  910. }
  911. for (size_t h = 0; h < test.partials.size(); ++h)
  912. if (hi[h] > 0.06 * strongest)
  913. ++present, rising += hi[h] >= 2.0 * lo[h] ? 1 : 0;
  914. if (present == 0 || rising < kSlowShare * present)
  915. continue;
  916. const int at = n.start + i;
  917. const bool clear = std::all_of(cuts.begin(), cuts.end(), [&](int c) { return std::abs(c - at) >= gap; });
  918. if (clear)
  919. cuts.push_back(at);
  920. }
  921. std::sort(cuts.begin(), cuts.end());
  922. }
  923. if (cuts.empty())
  924. {
  925. out.push_back(n);
  926. continue;
  927. }
  928. std::vector<int> bounds{n.start};
  929. bounds.insert(bounds.end(), cuts.begin(), cuts.end());
  930. bounds.push_back(n.end + 1);
  931. for (size_t q = 0; q + 1 < bounds.size(); ++q)
  932. {
  933. const int i0 = bounds[q] - n.start, i1 = bounds[q + 1] - n.start;
  934. Candidate m = n;
  935. m.start = bounds[q];
  936. m.end = bounds[q + 1] - 1;
  937. m.cents.assign(n.cents.begin() + i0, n.cents.begin() + i1);
  938. m.strength.assign(n.strength.begin() + i0, n.strength.begin() + i1);
  939. m.f0.assign(n.f0.begin() + i0, n.f0.begin() + i1);
  940. m.energy = n.energy * (i1 - i0) / static_cast<double>(n.cents.size());
  941. out.push_back(std::move(m));
  942. }
  943. }
  944. return out;
  945. }
  946. // A note whose pitch coincides with a partial of an earlier note tends to be tracked back into that
  947. // partial. Move its start to where its own (unshared) partials actually begin to rise, when that is at
  948. // least one analysis window later: closer than that, the frames still see the note's own attack.
  949. void refineOnsets(const Context& ctx, std::vector<Candidate>& notes)
  950. {
  951. const Params& p = ctx.p;
  952. const int maxLook = static_cast<int>(std::lround(0.6 * p.sampleRate / p.hop));
  953. const int minLen = static_cast<int>(std::lround(p.minNoteSeconds * p.sampleRate / p.hop));
  954. const auto& pk = ctx.peaks;
  955. const float binHz = static_cast<float>(p.sampleRate / p.fftSize);
  956. for (size_t ni = 0; ni < notes.size(); ++ni)
  957. {
  958. auto& n = notes[ni];
  959. const int t1 = std::min(n.end - minLen, n.start + maxLook);
  960. if (t1 <= n.start + 2)
  961. continue;
  962. // harmonics of n that coincide with a partial of another note sounding in this window
  963. std::vector<int> unique;
  964. for (int h = 1; h <= 8; ++h)
  965. {
  966. bool shared = false;
  967. for (size_t mi = 0; mi < notes.size() && !shared; ++mi)
  968. {
  969. const auto& m = notes[mi];
  970. if (mi == ni || m.end < n.start || m.start > t1)
  971. continue;
  972. const float fh = h * n.f0At(n.start + 2);
  973. const float fm = m.f0At(std::max(m.start, n.start));
  974. for (int k = 1; k <= 24 && !shared; ++k)
  975. shared = std::fabs(fh - k * fm * std::sqrt(1.0f + m.B * k * k)) < 0.015f * fh;
  976. }
  977. if (!shared)
  978. unique.push_back(h);
  979. }
  980. if (unique.empty())
  981. continue;
  982. // level of the given partials of n at frame t
  983. auto partialsLevel = [&](int t, const std::vector<int>& harmonics) {
  984. if (t >= ctx.numFrames || pk.begin(t) == pk.end(t))
  985. return 0.0f;
  986. double s = 0.0;
  987. for (int h : harmonics)
  988. {
  989. const float fh = static_cast<float>(n.f0At(t) * h * std::sqrt(1.0 + n.B * h * h));
  990. const int j = pk.nearest(t, fh / binHz);
  991. if (std::fabs(pk.fbin[static_cast<size_t>(j)] * binHz - fh) < std::max(1.2f * binHz, 0.012f * fh))
  992. s += static_cast<double>(pk.amp[static_cast<size_t>(j)]) * pk.amp[static_cast<size_t>(j)];
  993. }
  994. return static_cast<float>(std::sqrt(s));
  995. };
  996. std::vector<float> env(static_cast<size_t>(t1 - n.start + 4), 0.0f);
  997. for (int t = n.start; t < n.start + static_cast<int>(env.size()); ++t)
  998. env[static_cast<size_t>(t - n.start)] = partialsLevel(t, unique);
  999. // steepest rise of the unshared partials (works for closely spaced onsets too)
  1000. int bestI = -1;
  1001. double bestRise = 0.0;
  1002. float envMax = 0.0f;
  1003. for (float v : env)
  1004. envMax = std::max(envMax, v);
  1005. for (int i = 3; i <= t1 - n.start; ++i)
  1006. {
  1007. double before = 0.0, after = 0.0;
  1008. int nb = 0, na = 0;
  1009. for (int j = std::max(0, i - 6); j < i; ++j, ++nb)
  1010. before += env[static_cast<size_t>(j)];
  1011. for (int j = i; j < std::min(static_cast<int>(env.size()), i + 4); ++j, ++na)
  1012. after += env[static_cast<size_t>(j)];
  1013. before /= std::max(1, nb);
  1014. after /= std::max(1, na);
  1015. if (after >= 3.0 * before && after >= 0.25 * envMax && after - before > bestRise)
  1016. {
  1017. bestRise = after - before;
  1018. bestI = i;
  1019. }
  1020. }
  1021. if (bestI > 0)
  1022. {
  1023. // everything before the rise must be quiet compared with the note itself
  1024. double pre = 0.0;
  1025. for (int j = 0; j < bestI; ++j)
  1026. pre += env[static_cast<size_t>(j)];
  1027. pre /= bestI;
  1028. if (pre < 0.3 * bestRise)
  1029. {
  1030. // the onset is where the rise begins, not its steepest point (soft attacks ramp up)
  1031. const double level = bestRise;
  1032. while (bestI > 0 && env[static_cast<size_t>(bestI - 1)] < env[static_cast<size_t>(bestI)] &&
  1033. env[static_cast<size_t>(bestI - 1)] > 0.1 * level)
  1034. --bestI;
  1035. }
  1036. // A rise within one analysis window of the start is that window still sliding over the
  1037. // note's own attack, not an onset further on.
  1038. const int window = std::max(3, p.fftSize / p.hop);
  1039. bool move = pre < 0.3 * bestRise && bestI >= window;
  1040. std::vector<float> whole; // the note's whole level (its first eight partials), when needed
  1041. auto wholeLevel = [&]() -> const std::vector<float>& {
  1042. static const std::vector<int> all{ 1, 2, 3, 4, 5, 6, 7, 8 };
  1043. if (whole.empty())
  1044. for (int j = 0; j < static_cast<int>(env.size()); ++j)
  1045. whole.push_back(partialsLevel(n.start + j, all));
  1046. return whole;
  1047. };
  1048. // with its lower partials all shared, the rise is seen only in weak upper ones, where noise and
  1049. // other notes can fake it: then the note's whole level must rise there too
  1050. if (move && unique.front() > 4)
  1051. {
  1052. const auto& w = wholeLevel();
  1053. const int to = std::min(static_cast<int>(w.size()), bestI + 4);
  1054. double before = 0.0, after = 0.0;
  1055. for (int j = 0; j < bestI; ++j)
  1056. before += w[static_cast<size_t>(j)];
  1057. for (int j = bestI; j < to; ++j)
  1058. after += w[static_cast<size_t>(j)];
  1059. move = after / std::max(1, to - bestI) >= 1.5 * before / bestI;
  1060. }
  1061. // if nothing sounds at the note's partials before the rise, no other note's partial held its
  1062. // start back: that is a slow attack, unless the rise comes well over a window later
  1063. if (move && bestI < window + window / 4)
  1064. {
  1065. const auto& w = wholeLevel();
  1066. double before = 0.0, peak = 0.0;
  1067. for (int j = 0; j < static_cast<int>(w.size()); ++j)
  1068. {
  1069. if (j < bestI)
  1070. before += w[static_cast<size_t>(j)];
  1071. peak = std::max(peak, static_cast<double>(w[static_cast<size_t>(j)]));
  1072. }
  1073. move = before / bestI >= 0.05 * peak;
  1074. }
  1075. if (move)
  1076. {
  1077. n.start += bestI;
  1078. n.cents.erase(n.cents.begin(), n.cents.begin() + bestI);
  1079. n.strength.erase(n.strength.begin(), n.strength.begin() + bestI);
  1080. n.f0.erase(n.f0.begin(), n.f0.begin() + bestI);
  1081. }
  1082. }
  1083. }
  1084. }
  1085. // Notes of one pitch that overlap or nearly touch form a lane, which becomes one note per stroke.
  1086. // A note starting where the lane's sound so far ends starts a new note if its level rises again
  1087. // there. One starting inside the lane's sound starts a new note only if its level rises and stays
  1088. // up (as a repeated note's does, unlike a swell from beating or vibrato); if its level only rises
  1089. // but it goes on past the lane's sound so far, it begins where that sound ends. Otherwise it is the
  1090. // same note found twice and is merged in. A resulting note follows the member it starts with where
  1091. // that member's pitch stays within 25 cents of the lane's (the member nearest the lane's typical
  1092. // pitch at each frame), and is that member as it was if it matches it. With `overlapsOnly`, notes
  1093. // that do not overlap are left apart.
  1094. std::vector<Candidate> mergeFragments(const Context& ctx, std::vector<Candidate> notes, bool overlapsOnly)
  1095. {
  1096. const int maxGap = 4;
  1097. const float maxCents = 40.0f;
  1098. const int minApart = 12; // a start inside a note within ~140 ms of the last one is that same attack
  1099. const int minLen = static_cast<int>(std::lround(ctx.p.minNoteSeconds * ctx.p.sampleRate / ctx.p.hop));
  1100. std::stable_sort(notes.begin(), notes.end(), [](const Candidate& a, const Candidate& b) { return a.start < b.start; });
  1101. struct Lane
  1102. {
  1103. std::vector<size_t> members; // by start
  1104. int start = 0, end = 0;
  1105. };
  1106. std::vector<Lane> lanes;
  1107. for (size_t i = 0; i < notes.size(); ++i)
  1108. {
  1109. const auto& c = notes[i];
  1110. const float hz = medianOf(c.f0);
  1111. // the lane it overlaps most, among those with a member of its pitch that it touches
  1112. int best = -1, bestOverlap = std::numeric_limits<int>::min();
  1113. for (size_t l = 0; l < lanes.size(); ++l)
  1114. {
  1115. const auto& lane = lanes[l];
  1116. if (c.start > lane.end + maxGap || c.end < lane.start - maxGap)
  1117. continue;
  1118. const bool near = std::any_of(lane.members.begin(), lane.members.end(), [&](size_t k) {
  1119. const auto& m = notes[k];
  1120. return c.start <= m.end + maxGap && c.end >= m.start - maxGap &&
  1121. std::fabs(1200.0f * std::log2(hz / medianOf(m.f0))) <= maxCents;
  1122. });
  1123. const int overlap = std::min(c.end, lane.end) - std::max(c.start, lane.start);
  1124. if (near && overlap > bestOverlap)
  1125. {
  1126. bestOverlap = overlap;
  1127. best = static_cast<int>(l);
  1128. }
  1129. }
  1130. if (best < 0)
  1131. {
  1132. lanes.push_back({ { i }, c.start, c.end });
  1133. continue;
  1134. }
  1135. auto& lane = lanes[static_cast<size_t>(best)];
  1136. lane.members.push_back(i);
  1137. lane.end = std::max(lane.end, c.end);
  1138. }
  1139. std::vector<Candidate> out;
  1140. for (const auto& lane : lanes)
  1141. {
  1142. if (lane.members.size() == 1)
  1143. {
  1144. out.push_back(std::move(notes[lane.members.front()]));
  1145. continue;
  1146. }
  1147. // the lane as one candidate: at each frame the pitch of the member nearest the lane's typical
  1148. // pitch there (a member can wander onto a neighbouring note's partials)
  1149. std::vector<float> pooled;
  1150. for (size_t k : lane.members)
  1151. for (float hz : notes[k].f0)
  1152. pooled.push_back(hz);
  1153. const float typical = medianOf(pooled);
  1154. Candidate whole;
  1155. whole.start = lane.start;
  1156. whole.end = lane.end;
  1157. whole.f0.assign(static_cast<size_t>(lane.end - lane.start + 1), 0.0f);
  1158. std::vector<float> off(whole.f0.size(), std::numeric_limits<float>::max());
  1159. std::vector<uint8_t> known(whole.f0.size(), 0);
  1160. for (size_t k : lane.members)
  1161. {
  1162. const auto& m = notes[k];
  1163. for (int t = m.start; t <= m.end; ++t)
  1164. {
  1165. const size_t q = static_cast<size_t>(t - lane.start);
  1166. const float hz = m.f0[static_cast<size_t>(t - m.start)];
  1167. const float d = std::fabs(std::log2(hz / typical));
  1168. if (d < off[q])
  1169. {
  1170. off[q] = d;
  1171. whole.f0[q] = hz;
  1172. known[q] = 1;
  1173. }
  1174. }
  1175. whole.B = std::max(whole.B, m.B);
  1176. }
  1177. fillGaps(whole.f0, known);
  1178. std::unique_ptr<ReattackTest> test;
  1179. std::vector<int> bounds{ lane.start };
  1180. int cover = notes[lane.members.front()].end;
  1181. for (size_t k = 1; k < lane.members.size(); ++k)
  1182. {
  1183. const auto& c = notes[lane.members[k]];
  1184. bool split = false;
  1185. if (c.start >= cover - maxGap)
  1186. {
  1187. if (overlapsOnly)
  1188. split = c.start > bounds.back();
  1189. else if (c.start > bounds.back() + 3)
  1190. {
  1191. const auto env = harmonicEnvelope(ctx, c, 8, c.start - 6, c.start + 3);
  1192. split = isReattack(env, 6);
  1193. }
  1194. }
  1195. else if (c.start - bounds.back() >= minApart)
  1196. {
  1197. const auto env = harmonicEnvelope(ctx, c, 8, c.start - 6, c.start + 3);
  1198. if (isReattack(env, 6))
  1199. {
  1200. if (!test)
  1201. test = std::make_unique<ReattackTest>(ctx, whole);
  1202. for (int i = c.start - 3 - lane.start; i <= c.start + 3 - lane.start && !split; ++i)
  1203. split = i >= 4 && i <= test->len - 5 && test->risesAndStays(i);
  1204. if (!split && c.end > cover + maxGap && cover + 1 - bounds.back() >= minApart)
  1205. {
  1206. // it goes on past the lane's sound so far and started like a new note: it begins where that sound ends
  1207. bounds.push_back(cover + 1);
  1208. cover = std::max(cover, c.end);
  1209. continue;
  1210. }
  1211. }
  1212. }
  1213. if (split)
  1214. bounds.push_back(c.start);
  1215. cover = std::max(cover, c.end);
  1216. }
  1217. // no note shorter than a note can be
  1218. for (size_t q = 1; q < bounds.size();)
  1219. {
  1220. const int next = q + 1 < bounds.size() ? bounds[q + 1] : lane.end + 1;
  1221. if (next - bounds[q] < minLen || bounds[q] - bounds[q - 1] < minLen)
  1222. bounds.erase(bounds.begin() + static_cast<std::ptrdiff_t>(q));
  1223. else
  1224. ++q;
  1225. }
  1226. bounds.push_back(lane.end + 1);
  1227. for (size_t q = 0; q + 1 < bounds.size(); ++q)
  1228. {
  1229. const int from = bounds[q];
  1230. int to = bounds[q + 1] - 1;
  1231. // up to where its members reach (a note left apart keeps its own end)
  1232. int reach = from;
  1233. for (size_t k : lane.members)
  1234. if (notes[k].start <= to && notes[k].end >= from)
  1235. reach = std::max(reach, notes[k].end);
  1236. to = std::min(to, reach);
  1237. // its own member: the one starting there (else the one covering most of it)
  1238. int own = -1, ownScore = -1;
  1239. for (size_t k : lane.members)
  1240. {
  1241. const auto& m = notes[k];
  1242. const int overlap = std::min(m.end, to) - std::max(m.start, from) + 1;
  1243. if (overlap <= 0)
  1244. continue;
  1245. const int score = (m.start == from ? 1 << 20 : 0) + overlap;
  1246. if (score > ownScore)
  1247. {
  1248. ownScore = score;
  1249. own = static_cast<int>(k);
  1250. }
  1251. }
  1252. if (own < 0)
  1253. continue;
  1254. const auto& self = notes[static_cast<size_t>(own)];
  1255. // its own member's pitch where that agrees with the lane's, the lane's elsewhere
  1256. Candidate note;
  1257. note.start = from;
  1258. note.end = to;
  1259. note.f0.resize(static_cast<size_t>(to - from + 1));
  1260. bool agrees = true;
  1261. for (int t = from; t <= to; ++t)
  1262. {
  1263. float hz = whole.f0[static_cast<size_t>(t - lane.start)];
  1264. if (t >= self.start && t <= self.end)
  1265. {
  1266. const float ownHz = self.f0[static_cast<size_t>(t - self.start)];
  1267. if (std::fabs(1200.0f * std::log2(ownHz / hz)) <= 25.0f)
  1268. hz = ownHz;
  1269. else
  1270. agrees = false;
  1271. }
  1272. note.f0[static_cast<size_t>(t - from)] = hz;
  1273. }
  1274. if (agrees && self.start == from && self.end == to)
  1275. {
  1276. out.push_back(self); // a member as it was, the rest merged into it
  1277. continue;
  1278. }
  1279. note.cents.resize(note.f0.size());
  1280. for (size_t i = 0; i < note.f0.size(); ++i)
  1281. note.cents[i] = hzToField(note.f0[i], ctx.p);
  1282. note.strength.assign(note.cents.size(), 1.0f);
  1283. note.B = whole.B;
  1284. note.probability = 0.0f;
  1285. for (size_t k : lane.members)
  1286. {
  1287. const auto& m = notes[k];
  1288. const int overlap = std::min(m.end, note.end) - std::max(m.start, note.start) + 1;
  1289. if (overlap <= 0)
  1290. continue;
  1291. note.energy += m.energy * overlap / std::max(1, m.length());
  1292. note.probability = std::max(note.probability, m.probability);
  1293. note.hits = std::max(note.hits, m.hits);
  1294. }
  1295. out.push_back(std::move(note));
  1296. }
  1297. }
  1298. std::stable_sort(out.begin(), out.end(), [](const Candidate& a, const Candidate& b) { return a.start < b.start; });
  1299. return out;
  1300. }
  1301. } // namespace detail
  1302. } // namespace polyphonic