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.

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