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.

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