PolyRenderer.cpp 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143
  1. // Polyphonic engine - resynthesis with per-note edits, streaming frame by frame.
  2. //
  3. // The output spectrum of a frame starts as the input spectrum. Every edited note first removes its
  4. // own share (its masks) and then adds that share back transformed:
  5. // pitch each partial's bin region moves by round((r - 1) f / binHz) bins and is rotated by an
  6. // accumulated phase psi += 2 pi (r - 1) f hop / fs (Laroche & Dolson 1999), which keeps
  7. // the partial phase-coherent from frame to frame without any time stretching. Phases are
  8. // those at the frame centre: frames start N/2 before it, so bin k carries (-1)^k and a
  9. // region moved by an odd number of bins is flipped back (vibrato changes the shift).
  10. // A scalar compensates Hann overlap-add attenuation at fractional-bin offsets;
  11. // formant optional: partial amplitudes follow the note's smoothed spectral envelope;
  12. // gain a scalar; mute removes the share;
  13. // time whole hops plus a fractional linear-phase delay;
  14. // stretch lengthened: the note's first Params::stretchAttackSeconds play as recorded; after that,
  15. // output frame u plays source time tau(u) (StretchMap). Each partial's region is taken
  16. // from frame floor(tau), its level interpolated towards the next frame, and the whole
  17. // region rotated so that its peak continues the phase the partial had in the previous
  18. // output frame (phase propagation with identity phase locking, Laroche & Dolson 1999),
  19. // also at the frame centre, since the peak changes bin as the partial wanders.
  20. // Shortened: the note plays as recorded up to its new end, fading out over the
  21. // Params::cutFadeSeconds before it (raised cosine, not into the attack), and nothing
  22. // of it after.
  23. // Only a note's own share moves. Unpitched sound (a hammer, a pick, breath) is not assigned to
  24. // notes and stays where it was in the remainder of the recording. (The experimental
  25. // NoteEdit::takeBackground gives an edited note a part of everything no note owns; see
  26. // BackgroundShares.)
  27. // Notes without edits are never touched, so an unedited render is the analysis/resynthesis
  28. // identity (perfect reconstruction of the weighted overlap-add); frames no edit reaches skip the
  29. // transforms and add their windowed input directly. Memory is O(fftSize) per channel.
  30. #include "PolyInternal.h"
  31. #include <functional>
  32. #include <limits>
  33. #include <map>
  34. #include <numeric>
  35. #include <tuple>
  36. namespace polyphonic
  37. {
  38. float Note::medianMidi() const
  39. {
  40. if (f0.empty())
  41. return 0.0f;
  42. std::vector<float> v(f0);
  43. std::nth_element(v.begin(), v.begin() + static_cast<std::ptrdiff_t>(v.size() / 2), v.end());
  44. float m = v[v.size() / 2];
  45. if (v.size() % 2 == 0)
  46. m = 0.5f * (m + *std::max_element(v.begin(), v.begin() + static_cast<std::ptrdiff_t>(v.size() / 2)));
  47. return 69.0f + 12.0f * std::log2(m / 440.0f);
  48. }
  49. float Note::f0At(int frame) const
  50. {
  51. if (f0.empty())
  52. return 0.0f;
  53. const int i = std::clamp(frame - startFrame, 0, static_cast<int>(f0.size()) - 1);
  54. return f0[static_cast<size_t>(i)];
  55. }
  56. namespace
  57. {
  58. using detail::kPi;
  59. using detail::StftFrames;
  60. using Complex = std::complex<float>;
  61. /** Smoothed log-amplitude envelope over log-frequency from a note's partial amplitudes. */
  62. struct Envelope
  63. {
  64. std::vector<double> f, a;
  65. bool valid() const { return f.size() >= 2; }
  66. double at(double logF) const
  67. {
  68. if (logF <= f.front()) return a.front();
  69. if (logF >= f.back()) return a.back();
  70. const size_t j = static_cast<size_t>(std::upper_bound(f.begin(), f.end(), logF) - f.begin());
  71. const double u = (logF - f[j - 1]) / (f[j] - f[j - 1]);
  72. return a[j - 1] * (1 - u) + a[j] * u;
  73. }
  74. };
  75. // Third-octave bins, then a +-1 bin moving average: a gentle envelope, not one that follows the
  76. // odd/even pattern of individual partials (which is not a formant).
  77. Envelope noteEnvelope(const NoteMasks& nm, double sampleRate)
  78. {
  79. const double lo = std::log(40.0), hi = std::log(sampleRate / 2);
  80. const int nb = std::max(2, static_cast<int>(std::ceil((hi - lo) / (std::log(2.0) / 3.0))));
  81. std::vector<double> acc(static_cast<size_t>(nb), 0.0), cnt(static_cast<size_t>(nb), 0.0);
  82. for (const auto& pm : nm.partials)
  83. {
  84. const double lf = std::log(std::max(1.0f, pm.freqHz));
  85. const int i = std::clamp(static_cast<int>(std::floor((lf - lo) / (hi - lo) * nb)), 0, nb - 1);
  86. acc[static_cast<size_t>(i)] += std::log(pm.amplitude + 1e-12);
  87. cnt[static_cast<size_t>(i)] += 1.0;
  88. }
  89. Envelope e;
  90. for (int i = 0; i < nb; ++i)
  91. if (cnt[static_cast<size_t>(i)] > 0)
  92. {
  93. e.f.push_back(lo + (hi - lo) * (i + 0.5) / nb);
  94. e.a.push_back(acc[static_cast<size_t>(i)] / cnt[static_cast<size_t>(i)]);
  95. }
  96. if (e.a.size() >= 3)
  97. {
  98. std::vector<double> s(e.a.size());
  99. for (size_t i = 0; i < e.a.size(); ++i)
  100. s[i] = (e.a[i == 0 ? 0 : i - 1] + e.a[i] + e.a[std::min(e.a.size() - 1, i + 1)]) / 3.0;
  101. e.a = std::move(s);
  102. }
  103. return e;
  104. }
  105. /** Range of a note's partial masks at frame t. */
  106. std::pair<size_t, size_t> partialsAt(const NoteMasks& nm, int t)
  107. {
  108. auto lo = std::lower_bound(nm.partials.begin(), nm.partials.end(), t, [](const PartialMask& pm, int f) { return pm.frame < f; });
  109. auto hi = std::upper_bound(lo, nm.partials.end(), t, [](int f, const PartialMask& pm) { return f < pm.frame; });
  110. return {static_cast<size_t>(lo - nm.partials.begin()), static_cast<size_t>(hi - nm.partials.begin())};
  111. }
  112. /** Input spectra with a small cache (moved notes read frames other than the one being written). */
  113. class SourceFrames
  114. {
  115. public:
  116. SourceFrames(const std::vector<std::vector<float>>& channels, const Params& p)
  117. {
  118. for (const auto& ch : channels)
  119. src.push_back(std::make_unique<StftFrames>(ch.data(), static_cast<int>(ch.size()), p));
  120. bins = src.empty() ? 0 : src[0]->numBins();
  121. }
  122. const Complex* get(int c, int t)
  123. {
  124. for (auto& e : cache)
  125. if (e.channel == c && e.frame == t)
  126. return e.data.data();
  127. Entry& e = cache[next++ % cache.size()];
  128. e.channel = c;
  129. e.frame = t;
  130. e.data.resize(static_cast<size_t>(bins));
  131. src[static_cast<size_t>(c)]->spectrum(t, e.data.data());
  132. return e.data.data();
  133. }
  134. private:
  135. struct Entry { int channel = -1, frame = -1; std::vector<Complex> data; };
  136. std::vector<std::unique_ptr<StftFrames>> src;
  137. std::vector<Entry> cache = std::vector<Entry>(24);
  138. size_t next = 0;
  139. int bins = 0;
  140. };
  141. struct EditState
  142. {
  143. int note = 0;
  144. const NoteEdit* edit = nullptr;
  145. float gain = 1.0f;
  146. int D = 0; // whole-hop move
  147. double delta = 0.0; // remaining fractional move, samples
  148. Envelope env;
  149. std::map<int, std::pair<int, double>> psi; // harmonic -> (last source frame, phase)
  150. bool shifts = false;
  151. bool moves = false;
  152. int touchLo = 0; // output frames this edit can change (inclusive, conservative)
  153. int touchHi = -1;
  154. // stretching (lengthened) or cutting (shortened)
  155. StretchMap map;
  156. bool stretches = false;
  157. bool cuts = false;
  158. double fadeFrames = 1.0;
  159. int maskHi = -1; // last frame of the note's masks
  160. struct Track { int frame = -1; double phase = 0.0; };
  161. std::map<std::pair<int, int>, Track> track; // (harmonic, channel) -> output frame and peak phase
  162. // NoteEdit::takeBackground: frames of its claim on what no note owns (none when bgHi < bgLo)
  163. int bgLo = 0, bgHi = -1;
  164. };
  165. /** Index of the strongest bin of a partial's share in one frame. */
  166. int peakBin(const NoteMasks& nm, const PartialMask& pm, const std::complex<float>* x)
  167. {
  168. int best = 0;
  169. float bestValue = -1.0f;
  170. for (int k = 0; k < pm.count; ++k)
  171. {
  172. const float v = nm.weights[static_cast<size_t>(pm.weightOffset + k)] * std::abs(x[pm.lo + k]);
  173. if (v > bestValue)
  174. {
  175. bestValue = v;
  176. best = k;
  177. }
  178. }
  179. return best;
  180. }
  181. /**
  182. * Frames start N/2 samples before their centre, so a sinusoid's phase at the centre is arg X[k] +
  183. * pi k: moving a region by an odd number of bins flips its sign unless it is flipped back.
  184. */
  185. inline float binShiftSign(int shift) { return (shift & 1) != 0 ? -1.0f : 1.0f; }
  186. /**
  187. * Integer bin relocation plus continuous phase advance puts a stationary partial at the exact
  188. * target frequency, but the residual fractional-bin offset attenuates its carrier in Hann
  189. * analysis/synthesis overlap-add. The normalized Fourier transform of the centred Hann squared
  190. * window is G(a) = 4 sinc(a) / ((1-a*a)(4-a*a)); compensate its gain for |a| <= 0.5.
  191. * This is exact for a complete stationary partial away from edges and approximate for masked
  192. * or changing partials. Regions narrower than a full Hann main lobe are left alone. Keeping
  193. * the original bin region avoids interpolation truncation spurs.
  194. */
  195. float fractionalShiftGain(double bins, int count)
  196. {
  197. if (count < 3)
  198. return 1.0f;
  199. const double a = bins - std::nearbyint(bins);
  200. if (std::fabs(a) < 1e-8)
  201. return 1.0f;
  202. const double a2 = a * a;
  203. return static_cast<float>((kPi * a / std::sin(kPi * a)) * (1.0 - a2) * (1.0 - 0.25 * a2));
  204. }
  205. /** Frame range [lo, hi] of a note's masks (empty when hi < lo). */
  206. std::pair<int, int> noteFrameRange(const Analysis& A, int note)
  207. {
  208. const auto& nm = A.masks[static_cast<size_t>(note)];
  209. const int lo = nm.partials.empty() ? 0 : nm.partials.front().frame;
  210. const int hi = nm.partials.empty() ? -1 : nm.partials.back().frame;
  211. return {lo, hi};
  212. }
  213. constexpr double kClaimLeadSeconds = 0.05; // a claim on what no note owns fades in before the onset
  214. constexpr double kClaimTailSeconds = 2.0; // and lasts this long after the last frame (fading over the second half)
  215. /** Frames [lo, hi] in which `note` may have a claim on what no note owns (empty when hi < lo). */
  216. std::pair<int, int> claimSpan(const Analysis& A, int note, int numFrames)
  217. {
  218. if (note < 0 || note >= static_cast<int>(std::min(A.notes.size(), A.masks.size())))
  219. return {0, -1};
  220. const auto& nm = A.masks[static_cast<size_t>(note)];
  221. if (nm.partials.empty())
  222. return {0, -1};
  223. const Params& p = A.params;
  224. const double framesPerSecond = p.sampleRate / p.hop;
  225. const int lead = std::max(1, static_cast<int>(std::lround(kClaimLeadSeconds * framesPerSecond)));
  226. const int tail = std::max(2, static_cast<int>(std::lround(kClaimTailSeconds * framesPerSecond)));
  227. const int leadEnd = std::min(nm.partials.front().frame, A.notes[static_cast<size_t>(note)].startFrame - p.preFrames);
  228. return {std::max(0, leadEnd - lead), std::min(numFrames - 1, nm.partials.back().frame + tail)};
  229. }
  230. /**
  231. * Experimental (NoteEdit::takeBackground): what no note owns, the input minus every note's share,
  232. * split among the notes sounding in a frame so that an edited note can take its part along.
  233. *
  234. * A note's claim on a bin is its level in that frame times the shape of its spectrum: its partials
  235. * widened to fill the gaps between them, normalised to 1 at the strongest, with a small floor
  236. * elsewhere (so that what lies far from every note is shared by level). In its attack a note also
  237. * takes what is new: the part of each bin by which the input has grown since just before the note
  238. * (its onset noise, its first partials), while what was sounding already stays with the notes that
  239. * own it. Notes starting together share what is new in proportion to their own spectra in that
  240. * frame (each partial's amplitude over a few bins, plus a floor in proportion to the note's
  241. * level), so a note keeps the onset sound around its partials even beside a louder note, and what
  242. * lies far from every partial is shared by level. After its last frame the claim keeps that
  243. * frame's shape and decays; it fades in over a short lead-in before the onset and out over the
  244. * second half of the tail. Frames must be prepared in increasing order.
  245. */
  246. class BackgroundShares
  247. {
  248. public:
  249. using Spectrum = std::function<const Complex*(int channel, int frame)>;
  250. BackgroundShares(const Analysis& A, int numFrames, int numChannels, Spectrum spectrumOf)
  251. : analysis(A), K(A.params.fftSize / 2 + 1), binHz(A.params.sampleRate / A.params.fftSize),
  252. channels(numChannels), spectrum(std::move(spectrumOf))
  253. {
  254. const Params& p = A.params;
  255. const double framesPerSecond = p.sampleRate / p.hop;
  256. const int attack = static_cast<int>(std::lround(p.stretchAttackSeconds * framesPerSecond));
  257. const int tail = std::max(2, static_cast<int>(std::lround(kClaimTailSeconds * framesPerSecond)));
  258. decayFrames = kTailDecaySeconds * framesPerSecond;
  259. ownerOf.assign(A.notes.size(), -1);
  260. for (int n = 0; n < static_cast<int>(std::min(A.notes.size(), A.masks.size())); ++n)
  261. {
  262. const auto& nm = A.masks[static_cast<size_t>(n)];
  263. if (nm.partials.empty())
  264. continue;
  265. Owner o;
  266. o.note = n;
  267. o.maskLo = nm.partials.front().frame;
  268. o.maskHi = nm.partials.back().frame;
  269. o.leadEnd = std::min(o.maskLo, A.notes[static_cast<size_t>(n)].startFrame - p.preFrames);
  270. std::tie(o.lo, o.hi) = claimSpan(A, n, numFrames);
  271. o.attackHi = A.notes[static_cast<size_t>(n)].startFrame + attack;
  272. o.fadeLo = o.maskHi + tail / 2;
  273. int frame = nm.partials.front().frame;
  274. double level = 0.0;
  275. for (const auto& pm : nm.partials)
  276. {
  277. if (pm.frame != frame)
  278. {
  279. o.peak = std::max(o.peak, level);
  280. frame = pm.frame;
  281. level = 0.0;
  282. }
  283. level += pm.amplitude;
  284. }
  285. o.peak = std::max(o.peak, level);
  286. o.last = level;
  287. if (o.hi < o.lo || o.peak <= 0.0)
  288. continue;
  289. ownerOf[static_cast<size_t>(n)] = static_cast<int>(owners.size());
  290. owners.push_back(o);
  291. }
  292. byStart.resize(owners.size());
  293. std::iota(byStart.begin(), byStart.end(), 0);
  294. std::sort(byStart.begin(), byStart.end(), [&](int a, int b) { return owners[static_cast<size_t>(a)].lo < owners[static_cast<size_t>(b)].lo; });
  295. for (auto* v : { &rest, &total, &shape, &onset, &current, &fresh, &freshTotal, &scratch })
  296. v->resize(static_cast<size_t>(K));
  297. }
  298. /** Frames [lo, hi] in which `note` has a claim (empty when hi < lo). */
  299. std::pair<int, int> span(int note) const
  300. {
  301. const int o = note >= 0 && note < static_cast<int>(ownerOf.size()) ? ownerOf[static_cast<size_t>(note)] : -1;
  302. return o < 0 ? std::pair<int, int>{0, -1} : std::pair<int, int>{owners[static_cast<size_t>(o)].lo, owners[static_cast<size_t>(o)].hi};
  303. }
  304. /**
  305. * `note`'s part of what no note owns at frame u of `channel`, written to out[0..K); false (and
  306. * out untouched) when it has none there.
  307. */
  308. bool part(int note, int u, int channel, Complex* out)
  309. {
  310. const int o = note >= 0 && note < static_cast<int>(ownerOf.size()) ? ownerOf[static_cast<size_t>(note)] : -1;
  311. if (o < 0)
  312. return false;
  313. prepare(u);
  314. const auto it = std::find(present.begin(), present.end(), o);
  315. if (it == present.end())
  316. return false;
  317. const Complex* x = spectrum(channel, u); // after prepare(), which reads other frames
  318. const size_t j = static_cast<size_t>(it - present.begin());
  319. const auto& c = claims[j];
  320. const auto& n = newClaims[j];
  321. for (int k = 0; k < K; ++k)
  322. {
  323. const size_t q = static_cast<size_t>(k);
  324. float share = total[q] > 0.0f ? (1.0f - fresh[q]) * c[q] / total[q] : 0.0f;
  325. if (!n.empty() && freshTotal[q] > 0.0f)
  326. share += fresh[q] * n[q] / freshTotal[q];
  327. out[k] = (coverage * rest[q] * share) * x[k];
  328. }
  329. return true;
  330. }
  331. private:
  332. static constexpr double kTailDecaySeconds = 0.3; // decay of the claim's level in the tail
  333. static constexpr float kFloor = 0.05f; // claim far from the note's partials
  334. static constexpr double kMinWidthBins = 2.0; // narrowest widening of a partial
  335. static constexpr double kFillWidth = 0.5; // claim: partials widened by this much of their spacing
  336. static constexpr double kOnsetWidth = 0.05; // onset: partials widened by this much of their spacing
  337. static constexpr double kOnsetFloor = 0.1; // onset: claim far from the partials, relative to the level
  338. static constexpr int kSmoothBins = 2; // magnitudes compared over +-2 bins
  339. struct Owner
  340. {
  341. int note = 0;
  342. int lo = 0, hi = -1; // frames with a claim
  343. int maskLo = 0, maskHi = -1;
  344. int leadEnd = 0; // the claim is complete from here on
  345. int attackHi = 0; // last frame of the attack (claims what is new)
  346. int fadeLo = 0; // the claim fades out after this frame
  347. double peak = 0.0; // largest frame level (sum of partial amplitudes)
  348. double last = 0.0; // level at the last mask frame
  349. std::vector<float> before; // input magnitude just before the claim starts (while in the attack)
  350. };
  351. /** dst: the input magnitude at frame t, summed over channels and smoothed over +-kSmoothBins. */
  352. void magnitude(int t, std::vector<float>& dst)
  353. {
  354. std::fill(scratch.begin(), scratch.end(), 0.0f);
  355. if (t >= 0)
  356. for (int c = 0; c < channels; ++c)
  357. {
  358. const Complex* x = spectrum(c, t);
  359. for (int k = 0; k < K; ++k)
  360. scratch[static_cast<size_t>(k)] += std::abs(x[k]);
  361. }
  362. dst.assign(static_cast<size_t>(K), 0.0f);
  363. double run = 0.0;
  364. int count = 0;
  365. for (int k = -kSmoothBins; k < K; ++k)
  366. {
  367. if (k + kSmoothBins < K)
  368. {
  369. run += scratch[static_cast<size_t>(k + kSmoothBins)];
  370. ++count;
  371. }
  372. if (k - kSmoothBins - 1 >= 0)
  373. {
  374. run -= scratch[static_cast<size_t>(k - kSmoothBins - 1)];
  375. --count;
  376. }
  377. if (k >= 0)
  378. dst[static_cast<size_t>(k)] = static_cast<float>(run / std::max(1, count));
  379. }
  380. }
  381. void prepare(int u)
  382. {
  383. if (u == preparedFrame)
  384. return;
  385. preparedFrame = u;
  386. while (nextStart < byStart.size() && owners[static_cast<size_t>(byStart[nextStart])].lo <= u)
  387. present.push_back(byStart[nextStart++]);
  388. present.erase(std::remove_if(present.begin(), present.end(), [&](int o) { return owners[static_cast<size_t>(o)].hi < u; }),
  389. present.end());
  390. claims.resize(present.size());
  391. newClaims.resize(present.size());
  392. std::fill(rest.begin(), rest.end(), 1.0f);
  393. std::fill(total.begin(), total.end(), 0.0f);
  394. std::fill(fresh.begin(), fresh.end(), 0.0f);
  395. std::fill(freshTotal.begin(), freshTotal.end(), 0.0f);
  396. coverage = 0.0f;
  397. bool haveCurrent = false;
  398. for (size_t j = 0; j < present.size(); ++j)
  399. {
  400. Owner& o = owners[static_cast<size_t>(present[j])];
  401. const auto& nm = analysis.masks[static_cast<size_t>(o.note)];
  402. if (u >= o.maskLo && u <= o.maskHi)
  403. {
  404. const auto [b, e] = partialsAt(nm, u);
  405. for (size_t q = b; q < e; ++q)
  406. {
  407. const auto& pm = nm.partials[q];
  408. for (int k = 0; k < pm.count; ++k)
  409. rest[static_cast<size_t>(pm.lo + k)] -= nm.weights[static_cast<size_t>(pm.weightOffset + k)];
  410. }
  411. }
  412. // the claim fades in over the lead-in and out at the end of the tail; where the strongest
  413. // claim is faded, part of what no note owns stays (coverage), so the edges are not gated
  414. double fade = 1.0;
  415. if (u < o.leadEnd)
  416. fade = (u - o.lo + 1.0) / (o.leadEnd - o.lo + 1.0);
  417. if (u > o.fadeLo)
  418. fade *= std::max(0.0, 1.0 - (u - o.fadeLo) / static_cast<double>(o.hi - o.fadeLo + 1));
  419. coverage = std::max(coverage, static_cast<float>(fade));
  420. // its share of what was sounding: level times the shape of its spectrum
  421. const int at = std::clamp(u, o.maskLo, o.maskHi);
  422. double atLevel = 0.0; // level at `at` (before the mask starts: its first frame)
  423. {
  424. const auto [b, e] = partialsAt(nm, at);
  425. for (size_t q = b; q < e; ++q)
  426. atLevel += nm.partials[q].amplitude;
  427. }
  428. double level = u >= o.maskLo ? atLevel : 0.0;
  429. if (u > o.maskHi)
  430. level = o.last * std::exp(-(u - o.maskHi) / decayFrames);
  431. level = fade * std::max(level, 1e-3 * o.peak);
  432. spectrumShape(nm, u >= o.maskLo ? at : -1);
  433. auto& c = claims[j];
  434. c.resize(static_cast<size_t>(K));
  435. for (int k = 0; k < K; ++k)
  436. {
  437. c[static_cast<size_t>(k)] = static_cast<float>(level) * shape[static_cast<size_t>(k)];
  438. total[static_cast<size_t>(k)] += c[static_cast<size_t>(k)];
  439. }
  440. // in its attack, what is new since just before the note, in proportion to the note's own
  441. // spectrum in this frame (its partials over a few bins, plus a floor in proportion to its
  442. // level), so notes starting together each keep the onset sound around their partials
  443. auto& n = newClaims[j];
  444. if (u > o.attackHi)
  445. {
  446. n.clear();
  447. o.before.clear();
  448. o.before.shrink_to_fit();
  449. continue;
  450. }
  451. if (o.before.empty())
  452. magnitude(o.lo - 1, o.before);
  453. if (!haveCurrent)
  454. {
  455. magnitude(u, current);
  456. haveCurrent = true;
  457. }
  458. partialSpectrum(nm, at, kOnsetWidth, onset);
  459. const double onsetFloor = kOnsetFloor * std::max(atLevel, 1e-3 * o.peak);
  460. n.resize(static_cast<size_t>(K));
  461. for (int k = 0; k < K; ++k)
  462. {
  463. const size_t q = static_cast<size_t>(k);
  464. const float grown = current[q] > 0.0f ? std::clamp(1.0f - o.before[q] / current[q], 0.0f, 1.0f) : 0.0f;
  465. n[q] = static_cast<float>(fade * (onset[q] + onsetFloor)) * grown;
  466. fresh[q] = std::max(fresh[q], static_cast<float>(fade) * grown);
  467. freshTotal[q] += n[q];
  468. }
  469. }
  470. for (auto& r : rest)
  471. r = std::clamp(r, 0.0f, 1.0f);
  472. }
  473. /**
  474. * out: the note's partials at frame t (none when t < 0), each its amplitude times a Gaussian
  475. * over max(kMinWidthBins, widthFraction x the spacing of its harmonics) bins.
  476. */
  477. void partialSpectrum(const NoteMasks& nm, int t, double widthFraction, std::vector<float>& out) const
  478. {
  479. std::fill(out.begin(), out.end(), 0.0f);
  480. if (t < 0)
  481. return;
  482. const auto [b, e] = partialsAt(nm, t);
  483. for (size_t q = b; q < e; ++q)
  484. {
  485. const auto& pm = nm.partials[q];
  486. const double kc = pm.freqHz / binHz;
  487. const double width = std::max(kMinWidthBins, widthFraction * pm.freqHz / std::max(1, pm.harmonic) / binHz);
  488. const int k0 = std::max(1, static_cast<int>(std::floor(kc - 3.0 * width)));
  489. const int k1 = std::min(K - 2, static_cast<int>(std::ceil(kc + 3.0 * width)));
  490. for (int k = k0; k <= k1; ++k)
  491. {
  492. const double d = (k - kc) / width;
  493. out[static_cast<size_t>(k)] += static_cast<float>(pm.amplitude * std::exp(-0.5 * d * d));
  494. }
  495. }
  496. }
  497. /** shape: the note's partials at frame t widened to fill the gaps between them, peak 1, floor kFloor. */
  498. void spectrumShape(const NoteMasks& nm, int t)
  499. {
  500. partialSpectrum(nm, t, kFillWidth, shape);
  501. const float peak = *std::max_element(shape.begin(), shape.end());
  502. for (auto& s : shape)
  503. s = std::max(kFloor, peak > 0.0f ? s / peak : 0.0f);
  504. }
  505. const Analysis& analysis;
  506. const int K;
  507. const double binHz;
  508. const int channels;
  509. Spectrum spectrum;
  510. double decayFrames = 1.0;
  511. std::vector<Owner> owners;
  512. std::vector<int> ownerOf; // note -> owner index (-1: no masks)
  513. std::vector<int> byStart; // owners by first claimed frame
  514. size_t nextStart = 0;
  515. std::vector<int> present; // owners with a claim at the prepared frame
  516. int preparedFrame = std::numeric_limits<int>::min();
  517. std::vector<std::vector<float>> claims, newClaims;
  518. std::vector<float> rest, total, shape, onset, current, fresh, freshTotal, scratch;
  519. float coverage = 0.0f; // the strongest (least faded) claim at the prepared frame
  520. };
  521. /**
  522. * Core synthesis. With a non-empty `solo` the output is those notes only: each as its edit in
  523. * `edits` makes it (transformed exactly as in a full render), or its separated signal when it has
  524. * no edit. Edits of notes outside `solo` are ignored.
  525. *
  526. * Frames that no edit can reach are not transformed at all: their windowed input goes straight
  527. * into the overlap-add, which is exactly what the FFT round trip would give. Rendering a few
  528. * edits therefore costs time in proportion to the edited notes, not to the recording.
  529. *
  530. * The output covers samples [fromSample, toSample) (toSample < 0: to the end). Only the frames
  531. * that overlap that range are processed, and they are processed in order, so the samples in it
  532. * are exactly those of a whole render.
  533. */
  534. std::vector<std::vector<float>> synthesize(const Analysis& A, const std::vector<std::vector<float>>& channels,
  535. const std::map<int, NoteEdit>& edits, const std::vector<int>& solo,
  536. const std::atomic<bool>* cancel, int fromSample = 0, int toSample = -1,
  537. bool soloBackground = false)
  538. {
  539. const Params& p = A.params;
  540. const int numCh = static_cast<int>(channels.size());
  541. if (numCh == 0)
  542. return {};
  543. const int numSamples = static_cast<int>(channels[0].size());
  544. const int N = p.fftSize, H = p.hop, pad = N / 2;
  545. const int T = 1 + (numSamples + H - 1) / H;
  546. const int from = std::clamp(fromSample, 0, numSamples);
  547. const int to = toSample < 0 ? numSamples : std::clamp(toSample, from, numSamples);
  548. // frame u overlaps samples [u H - pad, u H - pad + N)
  549. const auto floorDiv = [](int a, int b) { return a >= 0 ? a / b : -((-a + b - 1) / b); };
  550. const int uFirst = std::max(0, floorDiv(from + pad - N, H) + 1);
  551. const int uLast = std::min(T - 1, floorDiv(to + pad - 1, H));
  552. const int K = N / 2 + 1;
  553. const double binHz = p.sampleRate / p.fftSize;
  554. SourceFrames source(channels, p);
  555. const auto window = detail::hannPeriodic(N);
  556. const float scale = std::accumulate(window.begin(), window.end(), 0.0f) / 2.0f;
  557. RealFFT fft(N);
  558. // what no note owns, split among the notes (NoteEdit::takeBackground): one splitter per offset
  559. // between the output frame and the frame a note's part is taken from (a moved note's copy comes
  560. // from D frames earlier), since each splitter goes through its frames in increasing order
  561. std::map<int, std::unique_ptr<BackgroundShares>> background;
  562. auto backgroundAt = [&](int offset) -> BackgroundShares& {
  563. auto& b = background[offset];
  564. if (b == nullptr)
  565. b = std::make_unique<BackgroundShares>(A, T, numCh, [&source](int c, int t) { return source.get(c, t); });
  566. return *b;
  567. };
  568. std::vector<Complex> part(static_cast<size_t>(K));
  569. std::vector<EditState> states;
  570. for (const auto& [ni, ed] : edits)
  571. {
  572. if (ni < 0 || ni >= static_cast<int>(A.notes.size()) || ni >= static_cast<int>(A.masks.size()) || ed.isIdentity())
  573. continue;
  574. EditState s;
  575. s.note = ni;
  576. s.edit = &ed;
  577. s.gain = std::pow(10.0f, ed.gainDb / 20.0f);
  578. s.shifts = ed.semitones != 0.0f;
  579. for (float v : ed.pitchCurve)
  580. s.shifts = s.shifts || v != 0.0f;
  581. if (ed.preserveFormants && s.shifts)
  582. s.env = noteEnvelope(A.masks[static_cast<size_t>(ni)], p.sampleRate);
  583. const double offset = ed.timeOffsetSeconds * p.sampleRate;
  584. s.D = static_cast<int>(std::lround(offset / H));
  585. s.delta = offset - static_cast<double>(s.D) * H;
  586. s.moves = offset != 0.0;
  587. s.map = stretchMap(A, ni, ed);
  588. s.stretches = s.map.ratio > 1.0;
  589. s.cuts = s.map.cuts();
  590. // the fade ends at the cut and never reaches into the attack
  591. s.fadeFrames = std::max(1.0, std::min(static_cast<double>(p.cutFadeSeconds) * p.sampleRate / H, s.map.end - s.map.anchor));
  592. // removal touches the note's own frames; the transformed copy lands D frames later (and,
  593. // when stretched, ends where the time map puts the note's last frame)
  594. const auto [lo, hi] = noteFrameRange(A, ni);
  595. s.maskHi = hi;
  596. s.touchLo = lo;
  597. s.touchHi = hi;
  598. if (!ed.mute && hi >= lo)
  599. {
  600. const int outHi = s.stretches ? static_cast<int>(std::ceil(s.map.outputFrame(hi))) : hi;
  601. s.touchLo = std::min(lo, lo + s.D);
  602. s.touchHi = std::max(hi, outHi + s.D);
  603. }
  604. // with its background, the note's part of what no note owns goes too: removed over its
  605. // claim and, unless muted, added back D frames later (up to its new end when shortened; not
  606. // for a lengthened note)
  607. if (ed.takeBackground && (ed.mute || !s.stretches))
  608. {
  609. const auto [blo, bhi] = backgroundAt(0).span(ni);
  610. if (bhi >= blo)
  611. {
  612. s.bgLo = blo;
  613. s.bgHi = bhi;
  614. s.touchLo = std::min({s.touchLo, blo, ed.mute ? blo : blo + s.D});
  615. s.touchHi = std::max({s.touchHi, bhi, ed.mute ? bhi : bhi + s.D});
  616. }
  617. }
  618. states.push_back(std::move(s));
  619. }
  620. std::vector<int> soloNotes;
  621. for (int ni : solo)
  622. if (ni >= 0 && ni < static_cast<int>(A.masks.size()))
  623. soloNotes.push_back(ni);
  624. const bool soloMode = !solo.empty();
  625. // On their own, only the listed notes' edits apply: an edited note contributes its transformed
  626. // copy (and nothing is removed), an unedited one its separated share, everything else silence.
  627. std::vector<char> soloEdited(A.masks.size(), 0);
  628. std::vector<std::pair<int, int>> soloClaims(soloNotes.size(), {0, -1}); // unedited notes taking their background
  629. if (soloMode)
  630. {
  631. states.erase(std::remove_if(states.begin(), states.end(),
  632. [&](const EditState& s) {
  633. return std::find(soloNotes.begin(), soloNotes.end(), s.note) == soloNotes.end();
  634. }),
  635. states.end());
  636. for (const auto& s : states)
  637. soloEdited[static_cast<size_t>(s.note)] = 1;
  638. for (size_t j = 0; j < soloNotes.size(); ++j)
  639. {
  640. const auto entry = edits.find(soloNotes[j]);
  641. if (!soloEdited[static_cast<size_t>(soloNotes[j])] && (soloBackground || (entry != edits.end() && entry->second.takeBackground)))
  642. soloClaims[j] = backgroundAt(0).span(soloNotes[j]);
  643. }
  644. }
  645. auto untouched = [&](int u) {
  646. for (const auto& st : states)
  647. if (u >= st.touchLo && u <= st.touchHi)
  648. return false;
  649. return true;
  650. };
  651. std::vector<std::vector<Complex>> Y(static_cast<size_t>(numCh), std::vector<Complex>(static_cast<size_t>(K)));
  652. std::vector<std::vector<double>> acc(static_cast<size_t>(numCh), std::vector<double>(static_cast<size_t>(N), 0.0));
  653. std::vector<double> nrm(static_cast<size_t>(N), 0.0);
  654. std::vector<std::vector<float>> out(static_cast<size_t>(numCh), std::vector<float>(static_cast<size_t>(to - from), 0.0f));
  655. std::vector<float> frame(static_cast<size_t>(N));
  656. std::vector<Complex> spec(static_cast<size_t>(K));
  657. // LYNX modification (round 190lo): overlap-aware moves (Params::overlapAwareMoves). A moved note's copy comes
  658. // from another frame; in bins the note shares with other notes that copy carries their sound too, from that
  659. // other frame, and its complex sum with what stays here partly cancels (the two frames' phases differ): the
  660. // shared partials of a sustained chord lose level. The copy is collected on its own and joined with what stays
  661. // with the phase of their complex sum (as before, continuous from frame to frame) and the level of their power
  662. // sum (what two independent parts add up to).
  663. std::vector<std::vector<Complex>> moved(static_cast<size_t>(numCh), std::vector<Complex>(static_cast<size_t>(K)));
  664. bool movedPending = false;
  665. auto joinMoved = [&]() {
  666. if (!movedPending)
  667. return;
  668. movedPending = false;
  669. for (int c = 0; c < numCh; ++c)
  670. {
  671. auto& y = Y[static_cast<size_t>(c)];
  672. auto& m = moved[static_cast<size_t>(c)];
  673. for (int k = 0; k < K; ++k)
  674. {
  675. const Complex mv = m[static_cast<size_t>(k)];
  676. if (mv == Complex{})
  677. continue;
  678. m[static_cast<size_t>(k)] = Complex{};
  679. const Complex r = y[static_cast<size_t>(k)];
  680. const Complex sum = r + mv;
  681. const float level = std::sqrt(std::norm(r) + std::norm(mv)), as = std::abs(sum);
  682. y[static_cast<size_t>(k)] = as > 1e-20f ? sum * (level / as) : sum;
  683. }
  684. }
  685. };
  686. auto fracDelay = [&](double delta, int k) {
  687. return delta == 0.0 ? Complex(1.0f, 0.0f) : std::polar(1.0f, static_cast<float>(-2.0 * kPi * k * delta / N));
  688. };
  689. auto finalize = [&](std::ptrdiff_t q0, std::ptrdiff_t q1) { // padded sample range [q0, q1) is complete
  690. for (std::ptrdiff_t q = q0; q < q1; ++q)
  691. {
  692. const size_t r = static_cast<size_t>(q % N);
  693. const std::ptrdiff_t i = q - pad;
  694. if (i >= from && i < to)
  695. for (int c = 0; c < numCh; ++c)
  696. out[static_cast<size_t>(c)][static_cast<size_t>(i - from)] =
  697. static_cast<float>(acc[static_cast<size_t>(c)][r] / std::max(nrm[r], 1e-8));
  698. for (int c = 0; c < numCh; ++c)
  699. acc[static_cast<size_t>(c)][r] = 0.0;
  700. nrm[r] = 0.0;
  701. }
  702. };
  703. std::vector<double> window2(static_cast<size_t>(N));
  704. for (int i = 0; i < N; ++i)
  705. window2[static_cast<size_t>(i)] = static_cast<double>(window[static_cast<size_t>(i)]) * window[static_cast<size_t>(i)];
  706. for (int u = uFirst; u <= uLast; ++u)
  707. {
  708. if (cancel && cancel->load())
  709. return {};
  710. bool transform = true;
  711. if (soloMode)
  712. {
  713. transform = false;
  714. for (auto& y : Y)
  715. std::fill(y.begin(), y.end(), Complex{});
  716. for (const auto& st : states)
  717. transform = transform || (u >= st.touchLo && u <= st.touchHi);
  718. for (size_t j = 0; j < soloNotes.size(); ++j)
  719. {
  720. const int ni = soloNotes[j];
  721. if (soloEdited[static_cast<size_t>(ni)])
  722. continue; // added below as its edited copy
  723. // its part of what no note owns, when it takes its background
  724. if (u >= soloClaims[j].first && u <= soloClaims[j].second)
  725. {
  726. transform = true;
  727. for (int c = 0; c < numCh; ++c)
  728. if (backgroundAt(0).part(ni, u, c, part.data()))
  729. {
  730. auto& y = Y[static_cast<size_t>(c)];
  731. for (int k = 0; k < K; ++k)
  732. y[static_cast<size_t>(k)] += part[static_cast<size_t>(k)];
  733. }
  734. }
  735. const auto& nm = A.masks[static_cast<size_t>(ni)];
  736. const auto [b, e] = partialsAt(nm, u);
  737. if (b == e)
  738. continue;
  739. transform = true;
  740. for (int c = 0; c < numCh; ++c)
  741. {
  742. const Complex* x = source.get(c, u);
  743. auto& y = Y[static_cast<size_t>(c)];
  744. for (size_t q = b; q < e; ++q)
  745. {
  746. const auto& pm = nm.partials[q];
  747. for (int k = 0; k < pm.count; ++k)
  748. y[static_cast<size_t>(pm.lo + k)] += nm.weights[static_cast<size_t>(pm.weightOffset + k)] * x[pm.lo + k];
  749. }
  750. }
  751. }
  752. }
  753. else if (untouched(u))
  754. {
  755. // identity frame: the windowed input itself (what IFFT(FFT(x w)) w would return)
  756. transform = false;
  757. const std::ptrdiff_t first = static_cast<std::ptrdiff_t>(u) * H - pad;
  758. for (int c = 0; c < numCh; ++c)
  759. {
  760. const auto& x = channels[static_cast<size_t>(c)];
  761. auto& a = acc[static_cast<size_t>(c)];
  762. for (int i = 0; i < N; ++i)
  763. {
  764. const std::ptrdiff_t si = first + i;
  765. if (si >= 0 && si < numSamples)
  766. a[static_cast<size_t>((static_cast<std::ptrdiff_t>(u) * H + i) % N)] +=
  767. static_cast<double>(x[static_cast<size_t>(si)]) * window2[static_cast<size_t>(i)];
  768. }
  769. }
  770. }
  771. else
  772. {
  773. for (int c = 0; c < numCh; ++c)
  774. std::copy(source.get(c, u), source.get(c, u) + K, Y[static_cast<size_t>(c)].begin());
  775. }
  776. const size_t editsHere = transform ? states.size() : 0;
  777. for (size_t sIndex = 0; sIndex < editsHere; ++sIndex)
  778. {
  779. joinMoved();
  780. auto& st = states[sIndex];
  781. const Note& n = A.notes[static_cast<size_t>(st.note)];
  782. const NoteMasks& nm = A.masks[static_cast<size_t>(st.note)];
  783. const NoteEdit& ed = *st.edit;
  784. // 1) remove the note's own share at this frame (on its own there is nothing to remove)
  785. if (!soloMode)
  786. {
  787. const auto [b, e] = partialsAt(nm, u);
  788. for (int c = 0; c < numCh; ++c)
  789. {
  790. const Complex* x = source.get(c, u);
  791. auto& y = Y[static_cast<size_t>(c)];
  792. for (size_t q = b; q < e; ++q)
  793. {
  794. const auto& pm = nm.partials[q];
  795. for (int k = 0; k < pm.count; ++k)
  796. y[static_cast<size_t>(pm.lo + k)] -= nm.weights[static_cast<size_t>(pm.weightOffset + k)] * x[pm.lo + k];
  797. }
  798. }
  799. }
  800. // and its part of what no note owns, when it takes its background
  801. if (!soloMode && st.bgHi >= st.bgLo && u >= st.bgLo && u <= st.bgHi)
  802. for (int c = 0; c < numCh; ++c)
  803. if (backgroundAt(0).part(st.note, u, c, part.data()))
  804. {
  805. auto& y = Y[static_cast<size_t>(c)];
  806. for (int k = 0; k < K; ++k)
  807. y[static_cast<size_t>(k)] -= part[static_cast<size_t>(k)];
  808. }
  809. if (ed.mute)
  810. continue;
  811. const int uo = u - st.D; // output frame before the move
  812. if (st.stretches && uo > st.map.anchor)
  813. {
  814. // 2b) stretched part: source time tau, partial regions from frame floor(tau)
  815. const double tau = st.map.sourceFrame(uo);
  816. if (tau > st.maskHi || tau < 0.0)
  817. continue;
  818. const int a = static_cast<int>(std::floor(tau));
  819. const double mu = tau - a;
  820. const int bFrame = std::min(a + 1, st.maskHi);
  821. const auto [ba, ea] = partialsAt(nm, a);
  822. const auto [bb, eb] = partialsAt(nm, bFrame);
  823. for (size_t q = ba; q < ea; ++q)
  824. {
  825. const auto& pa = nm.partials[q];
  826. const PartialMask* pb = nullptr;
  827. for (size_t j = bb; j < eb && pb == nullptr; ++j)
  828. if (nm.partials[j].harmonic == pa.harmonic)
  829. pb = &nm.partials[j];
  830. double semis = ed.semitones;
  831. if (!ed.pitchCurve.empty())
  832. semis += ed.pitchCurve[static_cast<size_t>(std::clamp(static_cast<int>(std::lround(tau)) - n.startFrame, 0,
  833. static_cast<int>(ed.pitchCurve.size()) - 1))];
  834. const double r = std::pow(2.0, semis / 12.0);
  835. const double f = pb != nullptr ? (1.0 - mu) * pa.freqHz + mu * pb->freqHz : pa.freqHz;
  836. // level between this frame and the next (a partial that ends fades out)
  837. double level = 1.0 - mu;
  838. if (pb != nullptr)
  839. level += mu * (pa.amplitude > 0.0f ? std::clamp(static_cast<double>(pb->amplitude / pa.amplitude), 0.0, 4.0) : 1.0);
  840. const int shift = r != 1.0 ? static_cast<int>(std::nearbyint((r - 1.0) * f / binHz)) : 0;
  841. float g = st.gain * static_cast<float>(level) * fractionalShiftGain((r - 1.0) * f / binHz, pa.count);
  842. if (r != 1.0 && st.env.valid())
  843. {
  844. const double l0 = std::log(std::max(1.0, f)), l1 = std::log(std::max(1.0, f * r));
  845. g *= static_cast<float>(std::exp(std::clamp(st.env.at(l1) - st.env.at(l0), -2.3, 2.3)));
  846. }
  847. const double advance = 2.0 * kPi * r * f * H / p.sampleRate;
  848. for (int c = 0; c < numCh; ++c)
  849. {
  850. const Complex* x = source.get(c, a);
  851. // phases at the frame centre (frames start N/2 before it, so bin k carries an
  852. // extra (-1)^k); the peak may sit in another bin from one frame to the next
  853. const int kp = pa.lo + peakBin(nm, pa, x);
  854. const double srcPhase = std::arg(x[kp]) + kPi * kp;
  855. auto& tr = st.track[{pa.harmonic, c}];
  856. const double target = tr.frame == u - 1 ? tr.phase + advance : srcPhase;
  857. tr.frame = u;
  858. tr.phase = std::remainder(target, 2.0 * kPi);
  859. const Complex rot = std::polar(1.0f, static_cast<float>(target - srcPhase)) * binShiftSign(shift);
  860. auto& y = Y[static_cast<size_t>(c)];
  861. for (int k = 0; k < pa.count; ++k)
  862. {
  863. const int kk = pa.lo + k + shift;
  864. if (kk < 1 || kk > K - 2)
  865. continue;
  866. y[static_cast<size_t>(kk)] += g * nm.weights[static_cast<size_t>(pa.weightOffset + k)] * x[pa.lo + k] * rot * fracDelay(st.delta, kk);
  867. }
  868. }
  869. }
  870. continue;
  871. }
  872. // 2) add it back, transformed, from source frame s = u - D
  873. const int s = uo;
  874. if (s < 0 || s >= T)
  875. continue;
  876. // a shortened note fades out before its new end, and nothing of it plays after that
  877. float cutGain = 1.0f;
  878. if (st.cuts)
  879. {
  880. const double left = st.map.end - s;
  881. if (left <= 0.0)
  882. continue;
  883. if (left < st.fadeFrames)
  884. cutGain = static_cast<float>(std::pow(std::sin(0.5 * kPi * left / st.fadeFrames), 2.0));
  885. }
  886. const auto [b, e] = partialsAt(nm, s);
  887. for (size_t q = b; q < e; ++q)
  888. {
  889. const auto& pm = nm.partials[q];
  890. double semis = ed.semitones;
  891. if (!ed.pitchCurve.empty())
  892. semis += ed.pitchCurve[static_cast<size_t>(std::clamp(s - n.startFrame, 0, static_cast<int>(ed.pitchCurve.size()) - 1))];
  893. const double r = std::pow(2.0, semis / 12.0);
  894. double phase = 0.0;
  895. int shift = 0;
  896. float g = st.gain * cutGain;
  897. if (st.shifts)
  898. {
  899. // A curve returning to zero keeps the phase accumulated by its earlier
  900. // pitch changes. Update the frame even at zero so a later change does not
  901. // apply its frequency offset across the intervening unshifted frames.
  902. const double dfh = (r - 1.0) * pm.freqHz;
  903. auto it = st.psi.find(pm.harmonic);
  904. const int tLast = it == st.psi.end() ? s - 1 : it->second.first;
  905. const double phLast = it == st.psi.end() ? 0.0 : it->second.second;
  906. phase = phLast + (s - tLast) * 2.0 * kPi * dfh * H / p.sampleRate;
  907. st.psi[pm.harmonic] = {s, phase};
  908. shift = static_cast<int>(std::nearbyint(dfh / binHz));
  909. g *= fractionalShiftGain(dfh / binHz, pm.count);
  910. if (r != 1.0 && st.env.valid())
  911. {
  912. const double l0 = std::log(std::max(1.0f, pm.freqHz)), l1 = std::log(std::max(1.0, pm.freqHz * r));
  913. g *= static_cast<float>(std::exp(std::clamp(st.env.at(l1) - st.env.at(l0), -2.3, 2.3)));
  914. }
  915. }
  916. const Complex rot = std::polar(1.0f, static_cast<float>(phase)) * binShiftSign(shift);
  917. // (LYNX, round 190lo: a pure move's copy is joined by joinMoved())
  918. const bool apart = p.overlapAwareMoves && !soloMode && st.moves && !st.shifts && !st.stretches;
  919. movedPending = movedPending || apart;
  920. for (int c = 0; c < numCh; ++c)
  921. {
  922. const Complex* x = source.get(c, s);
  923. if (st.stretches)
  924. {
  925. // where this partial's phase stands at the frame centre, for the stretched part
  926. // to continue from
  927. const int kp = pm.lo + peakBin(nm, pm, x);
  928. auto& tr = st.track[{pm.harmonic, c}];
  929. tr.frame = u;
  930. tr.phase = std::remainder(std::arg(x[kp]) + kPi * kp + phase, 2.0 * kPi);
  931. }
  932. auto& y = apart ? moved[static_cast<size_t>(c)] : Y[static_cast<size_t>(c)];
  933. for (int k = 0; k < pm.count; ++k)
  934. {
  935. const int kk = pm.lo + k + shift;
  936. if (kk < 1 || kk > K - 2)
  937. continue;
  938. y[static_cast<size_t>(kk)] += g * nm.weights[static_cast<size_t>(pm.weightOffset + k)] * x[pm.lo + k] * rot * fracDelay(st.delta, kk);
  939. }
  940. }
  941. }
  942. // its part of what no note owns, moved with it; with a pitch change, each partial's band
  943. // (half way to its neighbours) moves with that partial, with its phase
  944. if (st.bgHi >= st.bgLo && s >= st.bgLo && s <= st.bgHi)
  945. {
  946. std::vector<int> bandShift(static_cast<size_t>(K), 0);
  947. std::vector<Complex> bandRot(static_cast<size_t>(K), Complex(1.0f, 0.0f));
  948. const int maskLo = nm.partials.front().frame;
  949. const auto [bq, eq] = partialsAt(nm, std::clamp(s, maskLo, st.maskHi));
  950. for (size_t q = bq; st.shifts && q < eq; ++q)
  951. {
  952. const auto& pm = nm.partials[q];
  953. double semis = ed.semitones;
  954. if (!ed.pitchCurve.empty())
  955. semis += ed.pitchCurve[static_cast<size_t>(std::clamp(s - n.startFrame, 0, static_cast<int>(ed.pitchCurve.size()) - 1))];
  956. const double dfh = (std::pow(2.0, semis / 12.0) - 1.0) * pm.freqHz;
  957. const double step = 2.0 * kPi * dfh * H / p.sampleRate;
  958. // the partial's own phase at frame s (continued past its last frame)
  959. const auto it = st.psi.find(pm.harmonic);
  960. const double phase = it != st.psi.end() ? it->second.second + (s - it->second.first) * step : (s - (maskLo - 1)) * step;
  961. const int shift = static_cast<int>(std::nearbyint(dfh / binHz));
  962. const double kc = pm.freqHz / binHz;
  963. const double kPrev = q > bq ? nm.partials[q - 1].freqHz / binHz : -1.0;
  964. const double kNext = q + 1 < eq ? nm.partials[q + 1].freqHz / binHz : -1.0;
  965. const double halfGap = kNext > 0.0 ? 0.5 * (kNext - kc) : (kPrev > 0.0 ? 0.5 * (kc - kPrev) : 0.5 * kc);
  966. const double edgeLo = kPrev > 0.0 ? 0.5 * (kPrev + kc) : kc - halfGap;
  967. const double edgeHi = kNext > 0.0 ? 0.5 * (kc + kNext) : kc + (kPrev > 0.0 ? 0.5 * (kc - kPrev) : halfGap);
  968. const Complex rot = std::polar(1.0f, static_cast<float>(phase)) * binShiftSign(shift);
  969. for (int k = std::max(1, static_cast<int>(std::ceil(edgeLo))); k <= std::min(K - 2, static_cast<int>(std::floor(edgeHi))); ++k)
  970. {
  971. bandShift[static_cast<size_t>(k)] = shift;
  972. bandRot[static_cast<size_t>(k)] = rot;
  973. }
  974. }
  975. for (int c = 0; c < numCh; ++c)
  976. {
  977. if (!backgroundAt(st.D).part(st.note, s, c, part.data()))
  978. continue;
  979. const bool apart = p.overlapAwareMoves && !soloMode && st.moves && !st.shifts && !st.stretches;
  980. movedPending = movedPending || apart;
  981. auto& y = apart ? moved[static_cast<size_t>(c)] : Y[static_cast<size_t>(c)];
  982. for (int k = 1; k < K - 1; ++k)
  983. {
  984. const int kk = k + bandShift[static_cast<size_t>(k)];
  985. if (kk < 1 || kk > K - 2)
  986. continue;
  987. y[static_cast<size_t>(kk)] += st.gain * cutGain * part[static_cast<size_t>(k)] * bandRot[static_cast<size_t>(k)] * fracDelay(st.delta, kk);
  988. }
  989. }
  990. }
  991. }
  992. joinMoved();
  993. // inverse transform and weighted overlap-add
  994. for (int c = 0; transform && c < numCh; ++c)
  995. {
  996. auto& y = Y[static_cast<size_t>(c)];
  997. for (int k = 0; k < K; ++k)
  998. spec[static_cast<size_t>(k)] = y[static_cast<size_t>(k)] * scale;
  999. spec[0] = {spec[0].real(), 0.0f};
  1000. spec[static_cast<size_t>(K - 1)] = {spec[static_cast<size_t>(K - 1)].real(), 0.0f};
  1001. fft.inverse(spec.data(), frame.data());
  1002. auto& a = acc[static_cast<size_t>(c)];
  1003. for (int i = 0; i < N; ++i)
  1004. a[static_cast<size_t>((static_cast<std::ptrdiff_t>(u) * H + i) % N)] += static_cast<double>(frame[static_cast<size_t>(i)]) * window[static_cast<size_t>(i)];
  1005. }
  1006. for (int i = 0; i < N; ++i)
  1007. nrm[static_cast<size_t>((static_cast<std::ptrdiff_t>(u) * H + i) % N)] += window2[static_cast<size_t>(i)];
  1008. finalize(static_cast<std::ptrdiff_t>(u) * H, static_cast<std::ptrdiff_t>(u + 1) * H);
  1009. }
  1010. finalize(static_cast<std::ptrdiff_t>(uLast + 1) * H, static_cast<std::ptrdiff_t>(uLast) * H + N);
  1011. return out;
  1012. }
  1013. } // namespace
  1014. StretchMap stretchMap(const Analysis& A, int note, const NoteEdit& edit)
  1015. {
  1016. StretchMap m;
  1017. if (note < 0 || note >= static_cast<int>(A.notes.size()))
  1018. return m;
  1019. const Params& p = A.params;
  1020. const double hopSeconds = p.hop / p.sampleRate;
  1021. const Note& n = A.notes[static_cast<size_t>(note)];
  1022. m.anchor = n.startFrame + std::max(0.0, std::round(p.stretchAttackSeconds / hopSeconds));
  1023. m.ratio = std::clamp(static_cast<double>(edit.stretch), 0.0, 4.0);
  1024. // shortened, the note keeps that share of its length: nothing is sped up, so the cut may fall
  1025. // anywhere, inside the attack too
  1026. m.end = n.startFrame + std::max(0, n.endFrame - n.startFrame) * std::min(1.0, m.ratio);
  1027. return m;
  1028. }
  1029. std::vector<std::vector<float>> render(const Analysis& A, const std::vector<std::vector<float>>& channels,
  1030. const std::map<int, NoteEdit>& edits, const std::atomic<bool>* cancel)
  1031. {
  1032. return synthesize(A, channels, edits, {}, cancel);
  1033. }
  1034. std::vector<std::vector<float>> extractNotes(const Analysis& A, const std::vector<std::vector<float>>& channels,
  1035. const std::vector<int>& noteIndices, const std::atomic<bool>* cancel,
  1036. bool takeBackground)
  1037. {
  1038. if (noteIndices.empty())
  1039. return std::vector<std::vector<float>>(channels.size(), std::vector<float>(channels.empty() ? 0 : channels[0].size(), 0.0f));
  1040. return synthesize(A, channels, {}, noteIndices, cancel, 0, -1, takeBackground);
  1041. }
  1042. AudioSpan renderNotes(const Analysis& A, const std::vector<std::vector<float>>& channels,
  1043. const std::vector<int>& noteIndices, const std::map<int, NoteEdit>& edits,
  1044. const std::atomic<bool>* cancel)
  1045. {
  1046. AudioSpan span;
  1047. span.channels.resize(channels.size());
  1048. if (channels.empty() || channels[0].empty())
  1049. return span;
  1050. const Params& p = A.params;
  1051. const int H = p.hop, pad = p.fftSize / 2;
  1052. // the frames these notes reach: their own (with their claim on what no note owns when they take
  1053. // their background), or where an edit puts their transformed copy
  1054. const int numFrames = 1 + (static_cast<int>(channels[0].size()) + H - 1) / H;
  1055. int lo = std::numeric_limits<int>::max(), hi = std::numeric_limits<int>::min();
  1056. for (int ni : noteIndices)
  1057. {
  1058. if (ni < 0 || ni >= static_cast<int>(A.notes.size()) || ni >= static_cast<int>(A.masks.size()))
  1059. continue;
  1060. auto [a, b] = noteFrameRange(A, ni);
  1061. if (b < a)
  1062. continue;
  1063. const auto it = edits.find(ni);
  1064. const auto map = it != edits.end() ? stretchMap(A, ni, it->second) : StretchMap{};
  1065. if (it != edits.end() && it->second.takeBackground && (it->second.mute || map.ratio <= 1.0))
  1066. {
  1067. const auto [ca, cb] = claimSpan(A, ni, numFrames);
  1068. a = std::min(a, ca);
  1069. b = std::max(b, cb);
  1070. }
  1071. if (it != edits.end() && !it->second.isIdentity())
  1072. {
  1073. const NoteEdit& ed = it->second;
  1074. if (ed.mute)
  1075. continue;
  1076. if (map.ratio != 1.0)
  1077. b = static_cast<int>(std::ceil(map.outputFrame(b)));
  1078. const int D = static_cast<int>(std::lround(ed.timeOffsetSeconds * p.sampleRate / H));
  1079. a += D;
  1080. b += D;
  1081. }
  1082. lo = std::min(lo, a);
  1083. hi = std::max(hi, b);
  1084. }
  1085. if (hi < lo)
  1086. return span;
  1087. const int numSamples = static_cast<int>(channels[0].size());
  1088. const int from = std::clamp(lo * H - pad, 0, numSamples);
  1089. const int to = std::clamp(hi * H - pad + p.fftSize, from, numSamples);
  1090. if (to <= from)
  1091. return span;
  1092. span.start = from;
  1093. span.channels = synthesize(A, channels, edits, noteIndices, cancel, from, to);
  1094. return span;
  1095. }
  1096. std::vector<float> extractNote(const Analysis& A, const std::vector<float>& channel, int noteIndex)
  1097. {
  1098. auto out = synthesize(A, {channel}, {}, {std::max(0, noteIndex)}, nullptr);
  1099. return out.empty() ? std::vector<float>{} : std::move(out[0]);
  1100. }
  1101. } // namespace polyphonic