PolyInternal.h 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. #pragma once
  2. // Internal building blocks of the polyphonic engine. Not part of the public API.
  3. #include "PolyEngine.h"
  4. #include "PolyFFT.h"
  5. #include <algorithm>
  6. #include <cstddef>
  7. #include <cstdint>
  8. #include <cmath>
  9. #include <complex>
  10. #include <memory>
  11. #include <vector>
  12. namespace polyphonic
  13. {
  14. namespace detail
  15. {
  16. constexpr double kPi = 3.14159265358979323846;
  17. /**
  18. * STFT frames computed on demand (nothing frame-sized is stored for the whole signal).
  19. * Frame t is centred on sample t * hop; spectra are normalised so a sinusoid of
  20. * amplitude A peaks at ~A.
  21. */
  22. class StftFrames
  23. {
  24. public:
  25. StftFrames(const float* signal, int numSamples, const Params& p);
  26. int numFrames() const { return frames; }
  27. int numBins() const { return bins; }
  28. void spectrum(int t, std::complex<float>* out);
  29. private:
  30. const float* x;
  31. int n, frames, bins, N, H;
  32. std::vector<float> window, buffer;
  33. float norm;
  34. std::unique_ptr<RealFFT> fft;
  35. };
  36. /** Dense frames x bins float matrix. */
  37. struct Matrix
  38. {
  39. int rows = 0;
  40. int cols = 0;
  41. std::vector<float> data;
  42. Matrix() = default;
  43. Matrix(int r, int c, float v = 0.0f) : rows(r), cols(c), data(static_cast<size_t>(r) * c, v) {}
  44. float* row(int r) { return data.data() + static_cast<size_t>(r) * cols; }
  45. const float* row(int r) const { return data.data() + static_cast<size_t>(r) * cols; }
  46. float& at(int r, int c) { return data[static_cast<size_t>(r) * cols + c]; }
  47. float at(int r, int c) const { return data[static_cast<size_t>(r) * cols + c]; }
  48. };
  49. /** Spectral peaks, grouped by frame (CSR layout). */
  50. struct Peaks
  51. {
  52. std::vector<int> frameStart; // numFrames + 1 offsets
  53. std::vector<int> bin; // integer peak bin
  54. std::vector<float> fbin; // refined frequency in bins
  55. std::vector<float> amp; // sinusoid amplitude
  56. std::vector<float> tonality; // 0..1
  57. std::vector<float> wamp; // whitened amplitude
  58. int begin(int t) const { return frameStart[static_cast<size_t>(t)]; }
  59. int end(int t) const { return frameStart[static_cast<size_t>(t) + 1]; }
  60. /** Index of the peak in frame t nearest to frequency `bins`, or -1. */
  61. int nearest(int t, float bins) const;
  62. };
  63. /** A note candidate during analysis, before the note filter decides whether it is real. */
  64. struct Candidate
  65. {
  66. int start = 0;
  67. int end = 0; // inclusive
  68. std::vector<float> cents; // field index per frame
  69. std::vector<float> strength; // relevance along the crest
  70. double energy = 0.0;
  71. int hits = 1;
  72. std::vector<float> f0; // Hz per frame (after refinement)
  73. float B = 0.0f;
  74. float probability = 1.0f;
  75. int length() const { return end - start + 1; }
  76. float f0At(int t) const
  77. {
  78. const int i = std::clamp(t - start, 0, static_cast<int>(f0.size()) - 1);
  79. return f0[static_cast<size_t>(i)];
  80. }
  81. float midi() const;
  82. };
  83. struct Context
  84. {
  85. Params p;
  86. const float* audio = nullptr; // mono analysis signal (owned by the caller of analyze())
  87. int numSamples = 0;
  88. int numFrames = 0;
  89. int numBins = 0;
  90. const NoteEvidence* evidence = nullptr; // non-owning; only for neural-guided candidate search
  91. Peaks peaks;
  92. std::vector<float> r0max; // per frame: maximum of the initial relevance landscape
  93. };
  94. // ---- PolySpectral.cpp ----
  95. std::vector<float> hannPeriodic(int n);
  96. void medianRow(const float* in, int K, int width, float* out, std::vector<float>& scratch);
  97. /** One streaming pass: spectral peaks with instantaneous frequency, tonality and whitening. */
  98. void analyzeSpectra(Context& ctx, const std::atomic<bool>* cancel, int frameLo = 0, int frameHi = -1); // (LYNX: frame range)
  99. // ---- PolyExtraction.cpp ----
  100. int numCentsBins(const Params& p);
  101. float hzToField(float hz, const Params& p);
  102. float fieldToHz(float c, const Params& p);
  103. std::vector<Candidate> extractCandidates(Context& ctx, const std::atomic<bool>* cancel);
  104. void pruneCandidates(const Context& ctx, std::vector<Candidate>& cands);
  105. void refineCandidates(const Context& ctx, std::vector<Candidate>& cands);
  106. std::vector<float> harmonicEnvelope(const Context& ctx, const Candidate& n, int numHarmonics, int t0, int t1);
  107. /** envMax: the maximum of env when the caller already has it (computed otherwise). */
  108. bool isReattack(const std::vector<float>& env, int i, float ratio = 2.0f, float floorRel = 0.1f, float envMax = -1.0f);
  109. /** Amplitude of each of the first numHarmonics partials, per frame in [t0, t1]. */
  110. std::vector<std::vector<float>> partialEnvelopes(const Context& ctx, const Candidate& n, int numHarmonics, int t0, int t1);
  111. /** True when at least `minShare` of the partials present around frame i rise together there. */
  112. bool partialsRiseTogether(const std::vector<std::vector<float>>& partials, int i, float minShare);
  113. constexpr float kReattackShare = 0.6f;
  114. constexpr float kReattackDip = 0.7f;
  115. constexpr float kReattackStandOut = 2.5f; // rise over the note's typical frame-to-frame change
  116. /** Split candidates where their own partials are struck again (repeated notes at one pitch). */
  117. std::vector<Candidate> splitReattacks(const Context& ctx, const std::vector<Candidate>& cands);
  118. /** One note per stroke from overlapping or touching notes of one pitch (see PolyExtraction.cpp). */
  119. std::vector<Candidate> mergeFragments(const Context& ctx, std::vector<Candidate> notes, bool overlapsOnly = false);
  120. void refineOnsets(const Context& ctx, std::vector<Candidate>& notes);
  121. // LYNX modification (round 190lo): split active notes at slow re-attacks (Params::slowReattacks)
  122. std::vector<Candidate> splitSlowReattacks(const Context& ctx, const std::vector<Candidate>& notes);
  123. // ---- PolyPurifier.cpp ----
  124. void scoreCandidates(const Context& ctx, std::vector<Candidate>& cands, const NoteEvidence* evidence,
  125. std::vector<CandidateFeatures>* exportTo = nullptr);
  126. // ---- PolySoundModel.cpp ----
  127. void buildMasks(const Context& ctx, const std::vector<Candidate>& notes, Analysis& out);
  128. // LYNX modification (round 190lk): the masks in blocks, on demand. The block grid of buildMasks: block b covers core
  129. // frames [first, last) and is solved over [lo, hi) (its margins).
  130. struct MaskBlock { int coreLo, coreHi, lo, hi; };
  131. std::vector<MaskBlock> maskBlocks(const Params& p, int numFrames);
  132. void buildMaskBlock(const Context& ctx, const std::vector<Candidate>& notes, const MaskBlock& block, Analysis& out);
  133. } // namespace detail
  134. } // namespace polyphonic