Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

621 lines
18KB

  1. /*
  2. ZynAddSubFX - a software synthesizer
  3. SUBnote.cpp - The "subtractive" synthesizer
  4. Copyright (C) 2002-2005 Nasca Octavian Paul
  5. Author: Nasca Octavian Paul
  6. This program is free software; you can redistribute it and/or
  7. modify it under the terms of the GNU General Public License
  8. as published by the Free Software Foundation; either version 2
  9. of the License, or (at your option) any later version.
  10. */
  11. #include <cmath>
  12. #include <cstdlib>
  13. #include <cstdio>
  14. #include <cassert>
  15. #include <iostream>
  16. #include "../globals.h"
  17. #include "SUBnote.h"
  18. #include "Envelope.h"
  19. #include "ModFilter.h"
  20. #include "../Containers/ScratchString.h"
  21. #include "../Params/Controller.h"
  22. #include "../Params/SUBnoteParameters.h"
  23. #include "../Params/FilterParams.h"
  24. #include "../Misc/Time.h"
  25. #include "../Misc/Util.h"
  26. #include "../Misc/Allocator.h"
  27. #ifndef M_PI
  28. # define M_PI 3.14159265358979323846 /* pi */
  29. #endif
  30. SUBnote::SUBnote(const SUBnoteParameters *parameters, SynthParams &spars)
  31. :SynthNote(spars), pars(*parameters),
  32. AmpEnvelope(nullptr),
  33. FreqEnvelope(nullptr),
  34. BandWidthEnvelope(nullptr),
  35. GlobalFilter(nullptr),
  36. GlobalFilterEnvelope(nullptr),
  37. NoteEnabled(true),
  38. lfilter(nullptr), rfilter(nullptr),
  39. wm(nullptr)
  40. {
  41. setup(spars.frequency, spars.velocity, spars.portamento, spars.note);
  42. }
  43. float SUBnote::setupFilters(int *pos, bool automation)
  44. {
  45. //how much the amplitude is normalised (because the harmonics)
  46. float reduceamp = 0.0f;
  47. for(int n = 0; n < numharmonics; ++n) {
  48. const float freq = basefreq * pars.POvertoneFreqMult[pos[n]];
  49. overtone_freq[n] = freq;
  50. overtone_rolloff[n] = computerolloff(freq);
  51. //the bandwidth is not absolute(Hz); it is relative to frequency
  52. const float bw = SUBnoteParameters::convertBandwidth(pars.Pbandwidth,
  53. numstages, freq, pars.Pbwscale, pars.Phrelbw[pos[n]]);
  54. //try to keep same amplitude on all freqs and bw. (empirically)
  55. const float hgain = SUBnoteParameters::convertHarmonicMag(pars.Phmag[pos[n]],
  56. pars.Phmagtype);
  57. const float gain = hgain * sqrt(1500.0f / (bw * freq));
  58. reduceamp += hgain;
  59. for(int nph = 0; nph < numstages; ++nph) {
  60. float amp = 1.0f;
  61. if(nph == 0)
  62. amp = gain;
  63. initfilter(lfilter[nph + n * numstages], freq + OffsetHz, bw,
  64. amp, hgain, automation);
  65. if(stereo)
  66. initfilter(rfilter[nph + n * numstages], freq + OffsetHz, bw,
  67. amp, hgain, automation);
  68. }
  69. }
  70. if(reduceamp < 0.001f)
  71. reduceamp = 1.0f;
  72. return reduceamp;
  73. }
  74. void SUBnote::setup(float freq,
  75. float velocity,
  76. int portamento_,
  77. int midinote,
  78. bool legato)
  79. {
  80. this->velocity = velocity;
  81. portamento = portamento_;
  82. NoteEnabled = ON;
  83. volume = powf(0.1f, 3.0f * (1.0f - pars.PVolume / 96.0f)); //-60 dB .. 0 dB
  84. volume *= VelF(velocity, pars.PAmpVelocityScaleFunction);
  85. if(pars.PPanning != 0)
  86. panning = pars.PPanning / 127.0f;
  87. else
  88. panning = RND;
  89. if(!legato) { //normal note
  90. numstages = pars.Pnumstages;
  91. stereo = pars.Pstereo;
  92. start = pars.Pstart;
  93. firsttick = 1;
  94. }
  95. if(pars.Pfixedfreq == 0)
  96. basefreq = freq;
  97. else {
  98. basefreq = 440.0f;
  99. int fixedfreqET = pars.PfixedfreqET;
  100. if(fixedfreqET) { //if the frequency varies according the keyboard note
  101. float tmp = (midinote - 69.0f) / 12.0f
  102. * (powf(2.0f, (fixedfreqET - 1) / 63.0f) - 1.0f);
  103. if(fixedfreqET <= 64)
  104. basefreq *= powf(2.0f, tmp);
  105. else
  106. basefreq *= powf(3.0f, tmp);
  107. }
  108. }
  109. int BendAdj = pars.PBendAdjust - 64;
  110. if (BendAdj % 24 == 0)
  111. BendAdjust = BendAdj / 24;
  112. else
  113. BendAdjust = BendAdj / 24.0f;
  114. float offset_val = (pars.POffsetHz - 64)/64.0f;
  115. OffsetHz = 15.0f*(offset_val * sqrtf(fabsf(offset_val)));
  116. float detune = getdetune(pars.PDetuneType,
  117. pars.PCoarseDetune,
  118. pars.PDetune);
  119. basefreq *= powf(2.0f, detune / 1200.0f); //detune
  120. // basefreq*=ctl.pitchwheel.relfreq;//pitch wheel
  121. int pos[MAX_SUB_HARMONICS];
  122. int harmonics;
  123. pars.activeHarmonics(pos, harmonics);
  124. if(!legato) //normal note
  125. firstnumharmonics = numharmonics = harmonics;
  126. else {
  127. if(harmonics > firstnumharmonics)
  128. numharmonics = firstnumharmonics;
  129. else
  130. numharmonics = harmonics;
  131. }
  132. if(numharmonics == 0) {
  133. NoteEnabled = false;
  134. return;
  135. }
  136. if(!legato) { //normal note
  137. lfilter = memory.valloc<bpfilter>(numstages * numharmonics);
  138. if(stereo)
  139. rfilter = memory.valloc<bpfilter>(numstages * numharmonics);
  140. }
  141. //how much the amplitude is normalised (because the harmonics)
  142. float reduceamp = setupFilters(pos, false);
  143. oldreduceamp = reduceamp;
  144. volume /= reduceamp;
  145. oldpitchwheel = 0;
  146. oldbandwidth = 64;
  147. if(!legato) { //normal note
  148. if(pars.Pfixedfreq == 0)
  149. initparameters(basefreq, wm);
  150. else
  151. initparameters(basefreq / 440.0f * freq, wm);
  152. }
  153. else {
  154. if(pars.Pfixedfreq == 0)
  155. freq = basefreq;
  156. else
  157. freq *= basefreq / 440.0f;
  158. if(GlobalFilter)
  159. GlobalFilter->updateNoteFreq(basefreq);
  160. }
  161. oldamplitude = newamplitude;
  162. }
  163. SynthNote *SUBnote::cloneLegato(void)
  164. {
  165. SynthParams sp{memory, ctl, synth, time, legato.param.freq, velocity,
  166. portamento, legato.param.midinote, true};
  167. return memory.alloc<SUBnote>(&pars, sp);
  168. }
  169. void SUBnote::legatonote(LegatoParams pars)
  170. {
  171. // Manage legato stuff
  172. if(legato.update(pars))
  173. return;
  174. try {
  175. setup(pars.frequency, pars.velocity, pars.portamento, pars.midinote,
  176. true);
  177. } catch (std::bad_alloc &ba) {
  178. std::cerr << "failed to set legato note parameter in SUBnote: " << ba.what() << std::endl;
  179. }
  180. }
  181. SUBnote::~SUBnote()
  182. {
  183. if(NoteEnabled)
  184. KillNote();
  185. }
  186. /*
  187. * Kill the note
  188. */
  189. void SUBnote::KillNote()
  190. {
  191. if(NoteEnabled) {
  192. memory.devalloc(numstages * numharmonics, lfilter);
  193. if(stereo)
  194. memory.devalloc(numstages * numharmonics, rfilter);
  195. memory.dealloc(AmpEnvelope);
  196. memory.dealloc(FreqEnvelope);
  197. memory.dealloc(BandWidthEnvelope);
  198. memory.dealloc(GlobalFilter);
  199. memory.dealloc(GlobalFilterEnvelope);
  200. NoteEnabled = false;
  201. }
  202. }
  203. /*
  204. * Compute the filters coefficients
  205. */
  206. void SUBnote::computefiltercoefs(bpfilter &filter,
  207. float freq,
  208. float bw,
  209. float gain)
  210. {
  211. if(freq > synth.samplerate_f / 2.0f - 200.0f)
  212. freq = synth.samplerate_f / 2.0f - 200.0f;
  213. float omega = 2.0f * PI * freq / synth.samplerate_f;
  214. float sn = sinf(omega);
  215. float cs = cosf(omega);
  216. float alpha = sn * sinh(LOG_2 / 2.0f * bw * omega / sn);
  217. if(alpha > 1)
  218. alpha = 1;
  219. if(alpha > bw)
  220. alpha = bw;
  221. filter.b0 = alpha / (1.0f + alpha) * filter.amp * gain;
  222. filter.b2 = -alpha / (1.0f + alpha) * filter.amp * gain;
  223. filter.a1 = -2.0f * cs / (1.0f + alpha);
  224. filter.a2 = (1.0f - alpha) / (1.0f + alpha);
  225. }
  226. /*
  227. * Initialise the filters
  228. */
  229. void SUBnote::initfilter(bpfilter &filter,
  230. float freq,
  231. float bw,
  232. float amp,
  233. float mag,
  234. bool automation)
  235. {
  236. if(!automation) {
  237. filter.xn1 = 0.0f;
  238. filter.xn2 = 0.0f;
  239. if(start == 0) {
  240. filter.yn1 = 0.0f;
  241. filter.yn2 = 0.0f;
  242. }
  243. else {
  244. float a = 0.1f * mag; //empirically
  245. float p = RND * 2.0f * PI;
  246. if(start == 1)
  247. a *= RND;
  248. filter.yn1 = a * cosf(p);
  249. filter.yn2 = a * cosf(p + freq * 2.0f * PI / synth.samplerate_f);
  250. //correct the error of computation the start amplitude
  251. //at very high frequencies
  252. if(freq > synth.samplerate_f * 0.96f) {
  253. filter.yn1 = 0.0f;
  254. filter.yn2 = 0.0f;
  255. }
  256. }
  257. }
  258. filter.amp = amp;
  259. filter.freq = freq;
  260. filter.bw = bw;
  261. computefiltercoefs(filter, freq, bw, 1.0f);
  262. }
  263. /*
  264. * Do the filtering
  265. */
  266. inline void SubFilterA(const float coeff[4], float &src, float work[4])
  267. {
  268. work[3] = src*coeff[0]+work[1]*coeff[1]+work[2]*coeff[2]+work[3]*coeff[3];
  269. work[1] = src;
  270. src = work[3];
  271. }
  272. inline void SubFilterB(const float coeff[4], float &src, float work[4])
  273. {
  274. work[2] = src*coeff[0]+work[0]*coeff[1]+work[3]*coeff[2]+work[2]*coeff[3];
  275. work[0] = src;
  276. src = work[2];
  277. }
  278. //This dance is designed to minimize unneeded memory operations which can result
  279. //in quite a bit of wasted time
  280. void SUBnote::filter(bpfilter &filter, float *smps)
  281. {
  282. assert(synth.buffersize % 8 == 0);
  283. float coeff[4] = {filter.b0, filter.b2, -filter.a1, -filter.a2};
  284. float work[4] = {filter.xn1, filter.xn2, filter.yn1, filter.yn2};
  285. for(int i = 0; i < synth.buffersize; i += 8) {
  286. SubFilterA(coeff, smps[i + 0], work);
  287. SubFilterB(coeff, smps[i + 1], work);
  288. SubFilterA(coeff, smps[i + 2], work);
  289. SubFilterB(coeff, smps[i + 3], work);
  290. SubFilterA(coeff, smps[i + 4], work);
  291. SubFilterB(coeff, smps[i + 5], work);
  292. SubFilterA(coeff, smps[i + 6], work);
  293. SubFilterB(coeff, smps[i + 7], work);
  294. }
  295. filter.xn1 = work[0];
  296. filter.xn2 = work[1];
  297. filter.yn1 = work[2];
  298. filter.yn2 = work[3];
  299. }
  300. /*
  301. * Init Parameters
  302. */
  303. void SUBnote::initparameters(float freq, WatchManager *wm)
  304. {
  305. //TODO populate this base string
  306. ScratchString pre;
  307. AmpEnvelope = memory.alloc<Envelope>(*pars.AmpEnvelope, freq,
  308. synth.dt(), wm, (pre+"AmpEnvelope/").c_str);
  309. if(pars.PFreqEnvelopeEnabled)
  310. FreqEnvelope = memory.alloc<Envelope>(*pars.FreqEnvelope, freq,
  311. synth.dt(), wm, (pre+"FreqEnvelope/").c_str);
  312. if(pars.PBandWidthEnvelopeEnabled)
  313. BandWidthEnvelope = memory.alloc<Envelope>(*pars.BandWidthEnvelope,
  314. freq, synth.dt(), wm, (pre+"BandWidthEnvelope/").c_str);
  315. if(pars.PGlobalFilterEnabled) {
  316. GlobalFilterEnvelope =
  317. memory.alloc<Envelope>(*pars.GlobalFilterEnvelope, freq,
  318. synth.dt(), wm, (pre+"GlobalFilterEnvelope/").c_str);
  319. GlobalFilter = memory.alloc<ModFilter>(*pars.GlobalFilter, synth, time, memory, stereo, freq);
  320. GlobalFilter->updateSense(velocity, pars.PGlobalFilterVelocityScale,
  321. pars.PGlobalFilterVelocityScaleFunction);
  322. GlobalFilter->addMod(*GlobalFilterEnvelope);
  323. }
  324. computecurrentparameters();
  325. }
  326. /*
  327. * Compute how much to reduce amplitude near nyquist or subaudible frequencies.
  328. */
  329. float SUBnote::computerolloff(float freq)
  330. {
  331. const float lower_limit = 10.0f;
  332. const float lower_width = 10.0f;
  333. const float upper_width = 200.0f;
  334. float upper_limit = synth.samplerate / 2.0f;
  335. if (freq > lower_limit + lower_width &&
  336. freq < upper_limit - upper_width)
  337. return 1.0f;
  338. if (freq <= lower_limit || freq >= upper_limit)
  339. return 0.0f;
  340. if (freq <= lower_limit + lower_width)
  341. return (1.0f - cosf(M_PI * (freq - lower_limit) / lower_width)) / 2.0f;
  342. return (1.0f - cosf(M_PI * (freq - upper_limit) / upper_width)) / 2.0f;
  343. }
  344. /*
  345. * Compute Parameters of SUBnote for each tick
  346. */
  347. void SUBnote::computecurrentparameters()
  348. {
  349. //Recompute parameters for realtime automation
  350. if(pars.time && pars.last_update_timestamp == pars.time->time()) {
  351. //A little bit of copy/paste for now
  352. int pos[MAX_SUB_HARMONICS];
  353. int harmonics;
  354. pars.activeHarmonics(pos, harmonics);
  355. bool delta_harmonics = (harmonics != numharmonics);
  356. if(delta_harmonics) {
  357. memory.devalloc(lfilter);
  358. memory.devalloc(rfilter);
  359. firstnumharmonics = numharmonics = harmonics;
  360. lfilter = memory.valloc<bpfilter>(numstages * numharmonics);
  361. if(stereo)
  362. rfilter = memory.valloc<bpfilter>(numstages * numharmonics);
  363. }
  364. float reduceamp = setupFilters(pos, !delta_harmonics);
  365. volume = volume*oldreduceamp/reduceamp;
  366. oldreduceamp = reduceamp;
  367. }
  368. if(FreqEnvelope || BandWidthEnvelope
  369. || (oldpitchwheel != ctl.pitchwheel.data)
  370. || (oldbandwidth != ctl.bandwidth.data)
  371. || portamento) {
  372. float envfreq = 1.0f;
  373. float envbw = 1.0f;
  374. if(FreqEnvelope) {
  375. envfreq = FreqEnvelope->envout() / 1200;
  376. envfreq = powf(2.0f, envfreq);
  377. }
  378. envfreq *=
  379. powf(ctl.pitchwheel.relfreq, BendAdjust); //pitch wheel
  380. //Update frequency while portamento is converging
  381. if(portamento) {
  382. envfreq *= ctl.portamento.freqrap;
  383. if(!ctl.portamento.used) //the portamento has finished
  384. portamento = false;
  385. }
  386. if(BandWidthEnvelope) {
  387. envbw = BandWidthEnvelope->envout();
  388. envbw = powf(2, envbw);
  389. }
  390. envbw *= ctl.bandwidth.relbw; //bandwidth controller
  391. //Recompute High Frequency Dampening Terms
  392. for(int n = 0; n < numharmonics; ++n)
  393. overtone_rolloff[n] = computerolloff(overtone_freq[n] * envfreq);
  394. //Recompute Filter Coefficients
  395. float tmpgain = 1.0f / sqrt(envbw * envfreq);
  396. computeallfiltercoefs(lfilter, envfreq, envbw, tmpgain);
  397. if(stereo)
  398. computeallfiltercoefs(rfilter, envfreq, envbw, tmpgain);
  399. oldbandwidth = ctl.bandwidth.data;
  400. oldpitchwheel = ctl.pitchwheel.data;
  401. }
  402. newamplitude = volume * AmpEnvelope->envout_dB() * 2.0f;
  403. //Filter
  404. if(GlobalFilter)
  405. GlobalFilter->update(ctl.filtercutoff.relfreq,
  406. ctl.filterq.relq);
  407. }
  408. void SUBnote::computeallfiltercoefs(bpfilter *filters, float envfreq,
  409. float envbw, float gain)
  410. {
  411. for(int n = 0; n < numharmonics; ++n)
  412. for(int nph = 0; nph < numstages; ++nph)
  413. computefiltercoefs(filters[nph + n * numstages],
  414. filters[nph + n * numstages].freq * envfreq,
  415. filters[nph + n * numstages].bw * envbw,
  416. nph == 0 ? gain : 1.0);
  417. }
  418. void SUBnote::chanOutput(float *out, bpfilter *bp, int buffer_size)
  419. {
  420. float tmprnd[buffer_size];
  421. float tmpsmp[buffer_size];
  422. //Initialize Random Input
  423. for(int i = 0; i < buffer_size; ++i)
  424. tmprnd[i] = RND * 2.0f - 1.0f;
  425. //For each harmonic apply the filter on the random input stream
  426. //Sum the filter outputs to obtain the output signal
  427. for(int n = 0; n < numharmonics; ++n) {
  428. float rolloff = overtone_rolloff[n];
  429. memcpy(tmpsmp, tmprnd, synth.bufferbytes);
  430. for(int nph = 0; nph < numstages; ++nph)
  431. filter(bp[nph + n * numstages], tmpsmp);
  432. for(int i = 0; i < synth.buffersize; ++i)
  433. out[i] += tmpsmp[i] * rolloff;
  434. }
  435. }
  436. /*
  437. * Note Output
  438. */
  439. int SUBnote::noteout(float *outl, float *outr)
  440. {
  441. memcpy(outl, synth.denormalkillbuf, synth.bufferbytes);
  442. memcpy(outr, synth.denormalkillbuf, synth.bufferbytes);
  443. if(!NoteEnabled)
  444. return 0;
  445. if(stereo) {
  446. chanOutput(outl, lfilter, synth.buffersize);
  447. chanOutput(outr, rfilter, synth.buffersize);
  448. if(GlobalFilter)
  449. GlobalFilter->filter(outl, outr);
  450. } else {
  451. chanOutput(outl, lfilter, synth.buffersize);
  452. if(GlobalFilter)
  453. GlobalFilter->filter(outl, 0);
  454. memcpy(outr, outl, synth.bufferbytes);
  455. }
  456. if(firsttick) {
  457. int n = 10;
  458. if(n > synth.buffersize)
  459. n = synth.buffersize;
  460. for(int i = 0; i < n; ++i) {
  461. float ampfadein = 0.5f - 0.5f * cosf(
  462. (float) i / (float) n * PI);
  463. outl[i] *= ampfadein;
  464. outr[i] *= ampfadein;
  465. }
  466. firsttick = false;
  467. }
  468. if(ABOVE_AMPLITUDE_THRESHOLD(oldamplitude, newamplitude))
  469. // Amplitude interpolation
  470. for(int i = 0; i < synth.buffersize; ++i) {
  471. float tmpvol = INTERPOLATE_AMPLITUDE(oldamplitude,
  472. newamplitude,
  473. i,
  474. synth.buffersize);
  475. outl[i] *= tmpvol * panning;
  476. outr[i] *= tmpvol * (1.0f - panning);
  477. }
  478. else
  479. for(int i = 0; i < synth.buffersize; ++i) {
  480. outl[i] *= newamplitude * panning;
  481. outr[i] *= newamplitude * (1.0f - panning);
  482. }
  483. oldamplitude = newamplitude;
  484. computecurrentparameters();
  485. // Apply legato-specific sound signal modifications
  486. legato.apply(*this, outl, outr);
  487. // Check if the note needs to be computed more
  488. if(AmpEnvelope->finished() != 0) {
  489. for(int i = 0; i < synth.buffersize; ++i) { //fade-out
  490. float tmp = 1.0f - (float)i / synth.buffersize_f;
  491. outl[i] *= tmp;
  492. outr[i] *= tmp;
  493. }
  494. KillNote();
  495. }
  496. return 1;
  497. }
  498. /*
  499. * Release Key (Note Off)
  500. */
  501. void SUBnote::releasekey()
  502. {
  503. AmpEnvelope->releasekey();
  504. if(FreqEnvelope)
  505. FreqEnvelope->releasekey();
  506. if(BandWidthEnvelope)
  507. BandWidthEnvelope->releasekey();
  508. if(GlobalFilterEnvelope)
  509. GlobalFilterEnvelope->releasekey();
  510. }
  511. /*
  512. * Check if the note is finished
  513. */
  514. bool SUBnote::finished() const
  515. {
  516. return !NoteEnabled;
  517. }
  518. void SUBnote::entomb(void)
  519. {
  520. AmpEnvelope->forceFinish();
  521. }