PolyEngine.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. #pragma once
  2. #include <algorithm>
  3. #include <atomic>
  4. #include <complex>
  5. #include <cstdint>
  6. #include <functional>
  7. #include <map>
  8. #include <vector>
  9. /**
  10. * Polyphonic engine - note analysis and per-note resynthesis of polyphonic audio.
  11. *
  12. * Built from the multi-pitch estimation and source-separation literature:
  13. *
  14. * analysis STFT -> instantaneous frequency per bin -> spectral peaks weighted
  15. * by tonality -> log-frequency (cents) field -> harmonic-sum
  16. * salience (Klapuri 2006 weights) -> iterative estimation and
  17. * cancellation (cf. Klapuri 2003): take the strongest pitch, follow
  18. * it in time, cancel part of its harmonic energy (bounded by a
  19. * spectral-smoothness envelope), repeat; merge rediscovered notes
  20. * notes per-candidate f0 tracks and inharmonicity; a candidate whose own
  21. * harmonic energy decays and rises again is split (a repeated note)
  22. * filter candidates are scored as real notes or harmonic ghosts by
  23. * gradient-boosted trees over harmonic-relationship, energy and
  24. * (optionally) Basic Pitch note-posterior features
  25. * (PolyPurifierModel.h); rejected candidates stay available as
  26. * inactive note candidates
  27. * model a pitch-informed harmonic NMF (cf. Ewert & Mueller 2012) gives each
  28. * note its share of the bins around its partials
  29. * render an edited note's share is moved in frequency with phase-coherent
  30. * accumulation (Laroche & Dolson 1999), re-gained, muted or moved in
  31. * time; everything else passes through untouched, so an unedited
  32. * render reproduces the input.
  33. *
  34. * Only pitched notes are modelled. Transients and other unpitched sound are never
  35. * detected as objects of their own. Unless an edit sets NoteEdit::takeBackground
  36. * (experimental; the Polyphonic Lab always does), they are not attached to notes
  37. * either and stay in the recording where they are.
  38. *
  39. * Self-contained C++17 without JUCE. Analysis and rendering are offline
  40. * operations for a worker thread, not the audio thread. See docs/polyphonic-editing.md.
  41. */
  42. namespace polyphonic
  43. {
  44. /** Candidate search strategy. NeuralGuided is experimental and needs neural evidence. */
  45. enum class DetectionMode { Harmonic, NeuralGuided };
  46. struct Params
  47. {
  48. // ---- framing (scaled with the sample rate by Params::forSampleRate) ----
  49. double sampleRate = 44100.0;
  50. int fftSize = 4096;
  51. int hop = 512;
  52. // ---- spectral peaks ----
  53. float peakAbsDb = -90.0f; // absolute floor (sinusoid amplitude, dBFS)
  54. float peakRelDb = -75.0f; // relative to the loudest peak of the frame
  55. float peakOverNoiseDb = 4.0f; // above the median-filtered noise floor
  56. int noiseMedianBins = 41;
  57. float tonalDevBins = 0.35f; // IF disagreement scale for tonality
  58. // ---- cents field ----
  59. float fRef = 27.5f;
  60. float centsStep = 10.0f;
  61. float fTop = 11000.0f;
  62. float spreadCents = 50.0f; // deposit half width (about a half tone)
  63. float whitenNu = 0.33f; // Klapuri spectral whitening exponent
  64. // ---- relevance landscape ----
  65. float f0Min = 30.0f;
  66. float f0Max = 2200.0f;
  67. int numHarmonicsRelevance = 16;
  68. float alpha = 27.0f;
  69. float beta = 320.0f;
  70. // ---- iterative estimation and cancellation ----
  71. float subtractFraction = 0.5f; // G: share of the energy withdrawn per pass
  72. float stopEnergy = 0.10f; // stop when this share of the field energy remains
  73. float stopRelativePeak = 0.04f; // ... or when the best maximum falls this low
  74. float crestRelative = 0.10f; // abandon a crest below 10 % of its peak
  75. float crestJumpCents = 50.0f; // ... or on a pitch jump above 50 cents
  76. int maxIterations = 4000;
  77. int numHarmonicsSubtract = 40;
  78. // ---- candidate notes ----
  79. float minNoteSeconds = 0.07f;
  80. float minRelativeStrength = 0.02f;
  81. int mergeGapFrames = 3;
  82. float activationThreshold = 0.5f; // purifier probability for an active note (harmonic detector)
  83. // The guided detector has its own classifier; validation F1 is flat from 0.60 to 0.80
  84. // and 0.60 separates best (docs/testing/polyphonic-detector-research.md, threshold tuning).
  85. float guidedActivationThreshold = 0.6f;
  86. float activationThresholdFor(DetectionMode mode) const
  87. {
  88. return mode == DetectionMode::NeuralGuided ? guidedActivationThreshold : activationThreshold;
  89. }
  90. // ---- sound model / masks ----
  91. int nmfIterations = 40;
  92. int nmfHarmonics = 40;
  93. int nmfHalfWidth = 3;
  94. float nmfSegmentSeconds = 0.5f;
  95. float nmfMaxHz = 12000.0f;
  96. int preFrames = 3; // masks start this many frames before a note begins
  97. int postFrames = 3;
  98. // ---- rendering ----
  99. float stretchAttackSeconds = 0.08f; // a stretched note's first part keeps its speed
  100. float cutFadeSeconds = 0.15f; // a shortened note fades out over this long before its new end
  101. // ---- diagnostics ----
  102. bool exportFeatures = false; // fill Analysis::candidateFeatures (purifier training)
  103. // Opt-in research detector; without evidence it uses the original DSP-only path.
  104. DetectionMode detectionMode = DetectionMode::Harmonic;
  105. // LYNX modification (round 190lk): analyze() leaves the masks out (Analysis::masks stays empty per note); the
  106. // blocks an edit needs are built later by ensureMasks(). Memory then follows the edited spans, not the length
  107. // of the recording (the masks were ~0.6 MB per second of dense chords).
  108. bool deferMasks = false;
  109. // LYNX modification (round 190lo): also split notes at slow re-attacks (a pad or strings playing the same pitch in
  110. // the next chord after a dip; splitReattacks()). Off = PitchNet's behaviour.
  111. bool slowReattacks = false;
  112. // LYNX modification (round 190lo): overlap-aware moves in render() (a moved note's copy joined with what stays by
  113. // the phase of their complex sum and the level of their power sum; see PolyRenderer.cpp). Off = PitchNet's sum.
  114. bool overlapAwareMoves = false;
  115. /** Framing that keeps ~93 ms windows and 8x overlap at any sample rate. */
  116. static Params forSampleRate(double rate)
  117. {
  118. Params p;
  119. p.sampleRate = rate;
  120. p.fftSize = rate > 64000.0 ? 8192 : 4096;
  121. p.hop = p.fftSize / 8;
  122. return p;
  123. }
  124. };
  125. /** One note. Frames are analysis hops. */
  126. struct Note
  127. {
  128. int id = 0;
  129. int startFrame = 0;
  130. int endFrame = 0; // inclusive
  131. std::vector<float> f0; // Hz, one value per frame startFrame..endFrame
  132. float inharmonicity = 0.0f; // B in f_h = h f0 sqrt(1 + B h^2)
  133. double energy = 0.0; // energy withdrawn during extraction
  134. float probability = 1.0f; // purifier score
  135. bool active = true; // false: candidate only (kept for "note assignment")
  136. int parent = -1; // for inactive overtone candidates: the note they belong to
  137. float medianMidi() const;
  138. int numFrames() const { return endFrame - startFrame + 1; }
  139. float f0At(int frame) const; // clamped to the note's own range
  140. };
  141. /** A note's claim on one partial in one frame: weights for bins lo..lo+weights.size()-1. */
  142. struct PartialMask
  143. {
  144. int frame = 0;
  145. int harmonic = 0;
  146. int lo = 0;
  147. int count = 0;
  148. int weightOffset = 0; // into NoteMasks::weights
  149. float freqHz = 0.0f; // measured partial frequency
  150. float amplitude = 0.0f; // model amplitude (for formant handling)
  151. };
  152. struct NoteMasks
  153. {
  154. std::vector<PartialMask> partials; // sorted by frame, then harmonic
  155. std::vector<float> weights;
  156. };
  157. /** Purifier input for one candidate (before fragment merging), for training and diagnostics. */
  158. struct CandidateFeatures
  159. {
  160. int startFrame = 0;
  161. int endFrame = 0;
  162. float midi = 0.0f;
  163. float probability = 0.0f;
  164. std::vector<float> x; // feature vector in the order of PolyPurifierModel.h
  165. };
  166. struct Analysis
  167. {
  168. Params params;
  169. int numSamples = 0;
  170. int numFrames = 0;
  171. int numBins = 0;
  172. std::vector<Note> notes; // active notes followed by inactive candidates
  173. std::vector<NoteMasks> masks; // one entry per note in `notes` (inactive: empty)
  174. std::vector<CandidateFeatures> candidateFeatures; // only with Params::exportFeatures
  175. // LYNX modification (round 190lk): which NMF blocks' masks are built (Params::deferMasks / ensureMasks); empty
  176. // after a full analyze() (all built)
  177. std::vector<unsigned char> maskBlocksBuilt;
  178. double frameToSeconds(double frame) const { return frame * params.hop / params.sampleRate; }
  179. };
  180. /**
  181. * Optional neural note evidence on a semitone grid (MIDI 21..108): how likely each
  182. * semitone is sounding in each frame, e.g. the note posteriorgram of Spotify's
  183. * Basic Pitch model. Frame times are in seconds. When absent, the purifier uses
  184. * its DSP-only weights.
  185. */
  186. struct NoteEvidence
  187. {
  188. std::vector<float> frameTimes; // seconds, ascending
  189. std::vector<float> note; // [frames x 88]
  190. bool empty() const { return frameTimes.empty(); }
  191. };
  192. /** Per-note edit. Pitch offsets are in semitones relative to the analysed pitch. */
  193. struct NoteEdit
  194. {
  195. float semitones = 0.0f;
  196. std::vector<float> pitchCurve; // optional per-frame offset (semitones), added to `semitones`
  197. float gainDb = 0.0f;
  198. bool mute = false;
  199. bool preserveFormants = false; // instrument partial patterns are not formants; see docs
  200. double timeOffsetSeconds = 0.0; // move the note
  201. // Length ratio, 0..4. Longer (> 1): the part after the attack is that many times as long and
  202. // slows down; the attack keeps its speed. Shorter (< 1): the note keeps that share of its length;
  203. // it plays as recorded and is cut, fading out just before its new end.
  204. float stretch = 1.0f;
  205. // Experimental: the note also owns a part of what no note owns (the background around its
  206. // harmonics, the noise at its start, its decay for up to 2 s; see render()). A mute removes that
  207. // part too, and a move, pitch or gain change takes it along; a shortened note cuts it with the note
  208. // (a lengthened one leaves it in place).
  209. bool takeBackground = false;
  210. bool isIdentity() const
  211. {
  212. return !mute && semitones == 0.0f && pitchCurve.empty() && gainDb == 0.0f && timeOffsetSeconds == 0.0 && stretch == 1.0f;
  213. }
  214. };
  215. /**
  216. * Where a stretched note's frames go, in analysis frames before any move. Lengthened (ratio > 1):
  217. * frames up to `anchor` (the attack) keep their speed, later frames are spaced `ratio` times as far
  218. * apart. Shortened (ratio < 1): every frame keeps its place and the note ends at `end`, `ratio` of
  219. * the way from its first frame to its last; later frames are cut.
  220. */
  221. struct StretchMap
  222. {
  223. double anchor = 0.0;
  224. double ratio = 1.0;
  225. double end = 0.0; // last frame played when shortened
  226. bool cuts() const { return ratio < 1.0; }
  227. double outputFrame(double sourceFrame) const
  228. {
  229. if (cuts())
  230. return std::min(sourceFrame, end);
  231. return sourceFrame <= anchor ? sourceFrame : anchor + (sourceFrame - anchor) * ratio;
  232. }
  233. double sourceFrame(double outputFrame) const
  234. {
  235. if (cuts())
  236. return outputFrame;
  237. return outputFrame <= anchor ? outputFrame : anchor + (outputFrame - anchor) / ratio;
  238. }
  239. };
  240. /** The time map render() uses for `note` under `edit` (ratio 1 when the note is not stretched). */
  241. StretchMap stretchMap(const Analysis& analysis, int note, const NoteEdit& edit);
  242. using Progress = std::function<void(float)>;
  243. /** Analyse mono audio. Returns notes, candidates, masks. */
  244. Analysis analyze(const float* mono, int numSamples, const Params& params,
  245. const NoteEvidence* evidence = nullptr,
  246. const std::atomic<bool>* cancel = nullptr,
  247. const Progress& progress = {});
  248. /**
  249. * Render the edited result for each input channel (the channels the analysis
  250. * was made from, e.g. left/right; the masks come from their mono mix).
  251. * Notes without an entry in `edits` pass through untouched, and frames no edit
  252. * reaches are copied rather than transformed, so the cost follows the edited
  253. * notes rather than the length of the recording.
  254. *
  255. * A note's share of a bin is its model over the total model including the noise
  256. * floor, so an edit leaves the noise floor's share of its bins, and everything no note
  257. * owns, in place.
  258. * Experimental (NoteEdit::takeBackground): what no note owns is split among the notes
  259. * sounding in each frame (by level and spectral shape; at an onset what is new goes to
  260. * the notes starting there, in proportion to each one's own spectrum; a claim fades out
  261. * over 2 s after a note ends). A muted note
  262. * removes its part, and a moved, re-pitched or re-gained note takes it along, each
  263. * partial's band moving with that partial. Muting every note then silences the frames
  264. * their claims cover.
  265. */
  266. std::vector<std::vector<float>> render(const Analysis& analysis,
  267. const std::vector<std::vector<float>>& channels,
  268. const std::map<int, NoteEdit>& edits,
  269. const std::atomic<bool>* cancel = nullptr);
  270. /**
  271. * The separated signal of a set of notes (no edits) for each input channel, for
  272. * auditioning a selection on its own. Empty `noteIndices` gives silence. With
  273. * `takeBackground` each note also brings its part of what no note owns (exactly what a
  274. * NoteEdit::takeBackground mute removes).
  275. */
  276. std::vector<std::vector<float>> extractNotes(const Analysis& analysis,
  277. const std::vector<std::vector<float>>& channels,
  278. const std::vector<int>& noteIndices,
  279. const std::atomic<bool>* cancel = nullptr,
  280. bool takeBackground = false);
  281. /** Part of a recording: `channels` hold the samples from `start` on. */
  282. struct AudioSpan
  283. {
  284. int start = 0;
  285. std::vector<std::vector<float>> channels;
  286. };
  287. /**
  288. * A set of notes on their own with their entries in `edits` applied (pitch, gain, mute, move,
  289. * stretch), for hearing an edit while it is being made. It is the same synthesis as render(): the
  290. * listed notes sound exactly as they will in the full render, minus everything else. Notes
  291. * without an edit come out as their separated signal (with their part of the background when
  292. * their entry sets NoteEdit::takeBackground, even if it changes nothing else); edits of notes not
  293. * listed are ignored.
  294. * Only the samples the notes reach are rendered and returned, so the cost follows the notes,
  295. * not the recording (an empty span when nothing sounds, e.g. a muted note).
  296. */
  297. AudioSpan renderNotes(const Analysis& analysis,
  298. const std::vector<std::vector<float>>& channels,
  299. const std::vector<int>& noteIndices,
  300. const std::map<int, NoteEdit>& edits,
  301. const std::atomic<bool>* cancel = nullptr);
  302. /** One note's separated signal (no edits), for auditioning/solo. */
  303. std::vector<float> extractNote(const Analysis& analysis, const std::vector<float>& channel, int noteIndex);
  304. // ---- LYNX modification (round 190lk): masks on demand (PolyLazy.cpp) ----
  305. /**
  306. * The frames whose masks render() / renderNotes() read for these edits: each edited note's span with its
  307. * pre/post frames and its claim tail (NoteEdit::takeBackground), widened to the whole span of every active note
  308. * that overlaps it, as sorted, disjoint inclusive ranges (empty when there is no edit).
  309. */
  310. std::vector<std::pair<int, int>> framesForEdits(const Analysis& analysis, const std::map<int, NoteEdit>& edits);
  311. /**
  312. * Builds the masks of every NMF block that overlaps frames [frameLo, frameHi] and is not built yet (from `mono`,
  313. * the signal the analysis was made from). The masks of a block are exactly those analyze() builds without
  314. * Params::deferMasks. False when cancelled (the masks then stay as they were).
  315. */
  316. bool ensureMasks(Analysis& analysis, const float* mono, int numSamples, int frameLo, int frameHi,
  317. const std::atomic<bool>* cancel = nullptr);
  318. /** Frees every mask (they are built again on demand). */
  319. void releaseMasks(Analysis& analysis);
  320. /** Bytes the masks take now. */
  321. size_t maskBytes(const Analysis& analysis);
  322. } // namespace polyphonic