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.

Synthesiser.cpp 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2016 ROLI Ltd.
  5. Copyright (C) 2018 Filipe Coelho <falktx@falktx.com>
  6. Permission is granted to use this software under the terms of the ISC license
  7. http://www.isc.org/downloads/software-support-policy/isc-license/
  8. Permission to use, copy, modify, and/or distribute this software for any
  9. purpose with or without fee is hereby granted, provided that the above
  10. copyright notice and this permission notice appear in all copies.
  11. THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH REGARD
  12. TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  13. FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT,
  14. OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
  15. USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  16. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
  17. OF THIS SOFTWARE.
  18. ==============================================================================
  19. */
  20. #include "Synthesiser.h"
  21. #include "../buffers/AudioSampleBuffer.h"
  22. #include "../containers/Array.h"
  23. #include "../midi/MidiBuffer.h"
  24. #include "../midi/MidiMessage.h"
  25. namespace water {
  26. SynthesiserSound::SynthesiserSound() {}
  27. SynthesiserSound::~SynthesiserSound() {}
  28. //==============================================================================
  29. SynthesiserVoice::SynthesiserVoice()
  30. : currentSampleRate (44100.0),
  31. currentlyPlayingNote (-1),
  32. currentPlayingMidiChannel (0),
  33. noteOnTime (0),
  34. keyIsDown (false),
  35. sustainPedalDown (false),
  36. sostenutoPedalDown (false)
  37. {
  38. }
  39. SynthesiserVoice::~SynthesiserVoice()
  40. {
  41. }
  42. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  43. {
  44. return currentPlayingMidiChannel == midiChannel;
  45. }
  46. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  47. {
  48. currentSampleRate = newRate;
  49. }
  50. bool SynthesiserVoice::isVoiceActive() const
  51. {
  52. return getCurrentlyPlayingNote() >= 0;
  53. }
  54. void SynthesiserVoice::clearCurrentNote()
  55. {
  56. currentlyPlayingNote = -1;
  57. currentlyPlayingSound = nullptr;
  58. currentPlayingMidiChannel = 0;
  59. }
  60. void SynthesiserVoice::aftertouchChanged (int) {}
  61. void SynthesiserVoice::channelPressureChanged (int) {}
  62. bool SynthesiserVoice::wasStartedBefore (const SynthesiserVoice& other) const noexcept
  63. {
  64. return noteOnTime < other.noteOnTime;
  65. }
  66. //==============================================================================
  67. Synthesiser::Synthesiser()
  68. : sampleRate (0),
  69. lastNoteOnCounter (0),
  70. minimumSubBlockSize (32),
  71. subBlockSubdivisionIsStrict (false),
  72. shouldStealNotes (true)
  73. {
  74. for (size_t i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  75. lastPitchWheelValues[i] = 0x2000;
  76. zerostruct(sustainPedalsDown);
  77. }
  78. Synthesiser::~Synthesiser()
  79. {
  80. }
  81. //==============================================================================
  82. SynthesiserVoice* Synthesiser::getVoice (const int index) const
  83. {
  84. return voices [index];
  85. }
  86. void Synthesiser::clearVoices()
  87. {
  88. voices.clear();
  89. }
  90. SynthesiserVoice* Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  91. {
  92. newVoice->setCurrentPlaybackSampleRate (sampleRate);
  93. return voices.add (newVoice);
  94. }
  95. void Synthesiser::removeVoice (const int index)
  96. {
  97. voices.remove (index);
  98. }
  99. void Synthesiser::clearSounds()
  100. {
  101. sounds.clear();
  102. }
  103. SynthesiserSound* Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  104. {
  105. return sounds.add (newSound);
  106. }
  107. void Synthesiser::removeSound (const int index)
  108. {
  109. sounds.remove (index);
  110. }
  111. void Synthesiser::setNoteStealingEnabled (const bool shouldSteal)
  112. {
  113. shouldStealNotes = shouldSteal;
  114. }
  115. void Synthesiser::setMinimumRenderingSubdivisionSize (int numSamples, bool shouldBeStrict) noexcept
  116. {
  117. wassert (numSamples > 0); // it wouldn't make much sense for this to be less than 1
  118. minimumSubBlockSize = numSamples;
  119. subBlockSubdivisionIsStrict = shouldBeStrict;
  120. }
  121. //==============================================================================
  122. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  123. {
  124. if (sampleRate != newRate)
  125. {
  126. allNotesOff (0, false);
  127. sampleRate = newRate;
  128. for (int i = voices.size(); --i >= 0;)
  129. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  130. }
  131. }
  132. void Synthesiser::processNextBlock (AudioSampleBuffer& outputAudio,
  133. const MidiBuffer& midiData,
  134. int startSample,
  135. int numSamples)
  136. {
  137. // must set the sample rate before using this!
  138. wassert (sampleRate != 0);
  139. const int targetChannels = outputAudio.getNumChannels();
  140. MidiBuffer::Iterator midiIterator (midiData);
  141. midiIterator.setNextSamplePosition (startSample);
  142. bool firstEvent = true;
  143. int midiEventPos;
  144. MidiMessage m;
  145. while (numSamples > 0)
  146. {
  147. if (! midiIterator.getNextEvent (m, midiEventPos))
  148. {
  149. if (targetChannels > 0)
  150. renderVoices (outputAudio, startSample, numSamples);
  151. return;
  152. }
  153. const int samplesToNextMidiMessage = midiEventPos - startSample;
  154. if (samplesToNextMidiMessage >= numSamples)
  155. {
  156. if (targetChannels > 0)
  157. renderVoices (outputAudio, startSample, numSamples);
  158. handleMidiEvent (m);
  159. break;
  160. }
  161. if (samplesToNextMidiMessage < ((firstEvent && ! subBlockSubdivisionIsStrict) ? 1 : minimumSubBlockSize))
  162. {
  163. handleMidiEvent (m);
  164. continue;
  165. }
  166. firstEvent = false;
  167. if (targetChannels > 0)
  168. renderVoices (outputAudio, startSample, samplesToNextMidiMessage);
  169. handleMidiEvent (m);
  170. startSample += samplesToNextMidiMessage;
  171. numSamples -= samplesToNextMidiMessage;
  172. }
  173. while (midiIterator.getNextEvent (m, midiEventPos))
  174. handleMidiEvent (m);
  175. }
  176. void Synthesiser::renderVoices (AudioSampleBuffer& buffer, int startSample, int numSamples)
  177. {
  178. for (int i = voices.size(); --i >= 0;)
  179. voices.getUnchecked (i)->renderNextBlock (buffer, startSample, numSamples);
  180. }
  181. void Synthesiser::handleMidiEvent (const MidiMessage& m)
  182. {
  183. const int channel = m.getChannel();
  184. if (m.isNoteOn())
  185. {
  186. noteOn (channel, m.getNoteNumber(), m.getFloatVelocity());
  187. }
  188. else if (m.isNoteOff())
  189. {
  190. noteOff (channel, m.getNoteNumber(), m.getFloatVelocity(), true);
  191. }
  192. else if (m.isAllNotesOff() || m.isAllSoundOff())
  193. {
  194. allNotesOff (channel, true);
  195. }
  196. else if (m.isPitchWheel())
  197. {
  198. const int wheelPos = m.getPitchWheelValue();
  199. lastPitchWheelValues [channel - 1] = wheelPos;
  200. handlePitchWheel (channel, wheelPos);
  201. }
  202. else if (m.isAftertouch())
  203. {
  204. handleAftertouch (channel, m.getNoteNumber(), m.getAfterTouchValue());
  205. }
  206. else if (m.isChannelPressure())
  207. {
  208. handleChannelPressure (channel, m.getChannelPressureValue());
  209. }
  210. else if (m.isController())
  211. {
  212. handleController (channel, m.getControllerNumber(), m.getControllerValue());
  213. }
  214. else if (m.isProgramChange())
  215. {
  216. handleProgramChange (channel, m.getProgramChangeNumber());
  217. }
  218. }
  219. //==============================================================================
  220. void Synthesiser::noteOn (const int midiChannel,
  221. const int midiNoteNumber,
  222. const float velocity)
  223. {
  224. for (int i = sounds.size(); --i >= 0;)
  225. {
  226. SynthesiserSound* const sound = sounds.getUnchecked(i);
  227. if (sound->appliesToNote (midiNoteNumber)
  228. && sound->appliesToChannel (midiChannel))
  229. {
  230. // If hitting a note that's still ringing, stop it first (it could be
  231. // still playing because of the sustain or sostenuto pedal).
  232. for (int j = voices.size(); --j >= 0;)
  233. {
  234. SynthesiserVoice* const voice = voices.getUnchecked (j);
  235. if (voice->getCurrentlyPlayingNote() == midiNoteNumber
  236. && voice->isPlayingChannel (midiChannel))
  237. stopVoice (voice, 1.0f, true);
  238. }
  239. startVoice (findFreeVoice (sound, midiChannel, midiNoteNumber, shouldStealNotes),
  240. sound, midiChannel, midiNoteNumber, velocity);
  241. }
  242. }
  243. }
  244. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  245. SynthesiserSound* const sound,
  246. const int midiChannel,
  247. const int midiNoteNumber,
  248. const float velocity)
  249. {
  250. if (voice != nullptr && sound != nullptr)
  251. {
  252. CARLA_SAFE_ASSERT_RETURN(midiChannel > 0 && midiChannel <= 16,);
  253. if (voice->currentlyPlayingSound != nullptr)
  254. voice->stopNote (0.0f, false);
  255. voice->currentlyPlayingNote = midiNoteNumber;
  256. voice->currentPlayingMidiChannel = midiChannel;
  257. voice->noteOnTime = ++lastNoteOnCounter;
  258. voice->currentlyPlayingSound = sound;
  259. voice->keyIsDown = true;
  260. voice->sostenutoPedalDown = false;
  261. voice->sustainPedalDown = sustainPedalsDown[midiChannel];
  262. voice->startNote (midiNoteNumber, velocity, sound,
  263. lastPitchWheelValues [midiChannel - 1]);
  264. }
  265. }
  266. void Synthesiser::stopVoice (SynthesiserVoice* voice, float velocity, const bool allowTailOff)
  267. {
  268. wassert (voice != nullptr);
  269. voice->stopNote (velocity, allowTailOff);
  270. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  271. wassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  272. }
  273. void Synthesiser::noteOff (const int midiChannel,
  274. const int midiNoteNumber,
  275. const float velocity,
  276. const bool allowTailOff)
  277. {
  278. CARLA_SAFE_ASSERT_RETURN(midiChannel > 0 && midiChannel <= 16,);
  279. for (int i = voices.size(); --i >= 0;)
  280. {
  281. SynthesiserVoice* const voice = voices.getUnchecked (i);
  282. if (voice->getCurrentlyPlayingNote() == midiNoteNumber
  283. && voice->isPlayingChannel (midiChannel))
  284. {
  285. if (SynthesiserSound* const sound = voice->getCurrentlyPlayingSound())
  286. {
  287. if (sound->appliesToNote (midiNoteNumber)
  288. && sound->appliesToChannel (midiChannel))
  289. {
  290. CARLA_SAFE_ASSERT_RETURN (! voice->keyIsDown || voice->sustainPedalDown == sustainPedalsDown [midiChannel],);
  291. voice->keyIsDown = false;
  292. if (! (voice->sustainPedalDown || voice->sostenutoPedalDown))
  293. stopVoice (voice, velocity, allowTailOff);
  294. }
  295. }
  296. }
  297. }
  298. }
  299. void Synthesiser::allNotesOff (const int midiChannel, const bool allowTailOff)
  300. {
  301. for (int i = voices.size(); --i >= 0;)
  302. {
  303. SynthesiserVoice* const voice = voices.getUnchecked (i);
  304. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  305. voice->stopNote (1.0f, allowTailOff);
  306. }
  307. zerostruct(sustainPedalsDown);
  308. }
  309. void Synthesiser::handlePitchWheel (const int midiChannel, const int wheelValue)
  310. {
  311. for (int i = voices.size(); --i >= 0;)
  312. {
  313. SynthesiserVoice* const voice = voices.getUnchecked (i);
  314. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  315. voice->pitchWheelMoved (wheelValue);
  316. }
  317. }
  318. void Synthesiser::handleController (const int midiChannel,
  319. const int controllerNumber,
  320. const int controllerValue)
  321. {
  322. switch (controllerNumber)
  323. {
  324. case 0x40: handleSustainPedal (midiChannel, controllerValue >= 64); break;
  325. case 0x42: handleSostenutoPedal (midiChannel, controllerValue >= 64); break;
  326. case 0x43: handleSoftPedal (midiChannel, controllerValue >= 64); break;
  327. default: break;
  328. }
  329. for (int i = voices.size(); --i >= 0;)
  330. {
  331. SynthesiserVoice* const voice = voices.getUnchecked (i);
  332. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  333. voice->controllerMoved (controllerNumber, controllerValue);
  334. }
  335. }
  336. void Synthesiser::handleAftertouch (int midiChannel, int midiNoteNumber, int aftertouchValue)
  337. {
  338. for (int i = voices.size(); --i >= 0;)
  339. {
  340. SynthesiserVoice* const voice = voices.getUnchecked (i);
  341. if (voice->getCurrentlyPlayingNote() == midiNoteNumber
  342. && (midiChannel <= 0 || voice->isPlayingChannel (midiChannel)))
  343. voice->aftertouchChanged (aftertouchValue);
  344. }
  345. }
  346. void Synthesiser::handleChannelPressure (int midiChannel, int channelPressureValue)
  347. {
  348. for (int i = voices.size(); --i >= 0;)
  349. {
  350. SynthesiserVoice* const voice = voices.getUnchecked (i);
  351. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  352. voice->channelPressureChanged (channelPressureValue);
  353. }
  354. }
  355. void Synthesiser::handleSustainPedal (int midiChannel, bool isDown)
  356. {
  357. CARLA_SAFE_ASSERT_RETURN(midiChannel > 0 && midiChannel <= 16,);
  358. if (isDown)
  359. {
  360. sustainPedalsDown[midiChannel] = true;
  361. for (int i = voices.size(); --i >= 0;)
  362. {
  363. SynthesiserVoice* const voice = voices.getUnchecked (i);
  364. if (voice->isPlayingChannel (midiChannel) && voice->isKeyDown())
  365. voice->sustainPedalDown = true;
  366. }
  367. }
  368. else
  369. {
  370. for (int i = voices.size(); --i >= 0;)
  371. {
  372. SynthesiserVoice* const voice = voices.getUnchecked (i);
  373. if (voice->isPlayingChannel (midiChannel))
  374. {
  375. voice->sustainPedalDown = false;
  376. if (! voice->isKeyDown())
  377. stopVoice (voice, 1.0f, true);
  378. }
  379. }
  380. sustainPedalsDown[midiChannel] = false;
  381. }
  382. }
  383. void Synthesiser::handleSostenutoPedal (int midiChannel, bool isDown)
  384. {
  385. wassert (midiChannel > 0 && midiChannel <= 16);
  386. for (int i = voices.size(); --i >= 0;)
  387. {
  388. SynthesiserVoice* const voice = voices.getUnchecked (i);
  389. if (voice->isPlayingChannel (midiChannel))
  390. {
  391. if (isDown)
  392. voice->sostenutoPedalDown = true;
  393. else if (voice->sostenutoPedalDown)
  394. stopVoice (voice, 1.0f, true);
  395. }
  396. }
  397. }
  398. void Synthesiser::handleSoftPedal (int midiChannel, bool /*isDown*/)
  399. {
  400. ignoreUnused (midiChannel);
  401. wassert (midiChannel > 0 && midiChannel <= 16);
  402. }
  403. void Synthesiser::handleProgramChange (int midiChannel, int programNumber)
  404. {
  405. ignoreUnused (midiChannel, programNumber);
  406. wassert (midiChannel > 0 && midiChannel <= 16);
  407. }
  408. //==============================================================================
  409. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  410. int midiChannel, int midiNoteNumber,
  411. const bool stealIfNoneAvailable) const
  412. {
  413. for (size_t i = 0; i < voices.size(); ++i)
  414. {
  415. SynthesiserVoice* const voice = voices.getUnchecked (i);
  416. if ((! voice->isVoiceActive()) && voice->canPlaySound (soundToPlay))
  417. return voice;
  418. }
  419. if (stealIfNoneAvailable)
  420. return findVoiceToSteal (soundToPlay, midiChannel, midiNoteNumber);
  421. return nullptr;
  422. }
  423. struct VoiceAgeSorter
  424. {
  425. static int compareElements (SynthesiserVoice* v1, SynthesiserVoice* v2) noexcept
  426. {
  427. return v1->wasStartedBefore (*v2) ? -1 : (v2->wasStartedBefore (*v1) ? 1 : 0);
  428. }
  429. };
  430. SynthesiserVoice* Synthesiser::findVoiceToSteal (SynthesiserSound* soundToPlay,
  431. int /*midiChannel*/, int midiNoteNumber) const
  432. {
  433. // This voice-stealing algorithm applies the following heuristics:
  434. // - Re-use the oldest notes first
  435. // - Protect the lowest & topmost notes, even if sustained, but not if they've been released.
  436. // apparently you are trying to render audio without having any voices...
  437. wassert (voices.size() > 0);
  438. // These are the voices we want to protect (ie: only steal if unavoidable)
  439. SynthesiserVoice* low = nullptr; // Lowest sounding note, might be sustained, but NOT in release phase
  440. SynthesiserVoice* top = nullptr; // Highest sounding note, might be sustained, but NOT in release phase
  441. // this is a list of voices we can steal, sorted by how long they've been running
  442. Array<SynthesiserVoice*> usableVoices;
  443. usableVoices.ensureStorageAllocated (voices.size());
  444. for (size_t i = 0; i < voices.size(); ++i)
  445. {
  446. SynthesiserVoice* const voice = voices.getUnchecked (i);
  447. if (voice->canPlaySound (soundToPlay))
  448. {
  449. wassert (voice->isVoiceActive()); // We wouldn't be here otherwise
  450. VoiceAgeSorter sorter;
  451. usableVoices.addSorted (sorter, voice);
  452. if (! voice->isPlayingButReleased()) // Don't protect released notes
  453. {
  454. const int note = voice->getCurrentlyPlayingNote();
  455. if (low == nullptr || note < low->getCurrentlyPlayingNote())
  456. low = voice;
  457. if (top == nullptr || note > top->getCurrentlyPlayingNote())
  458. top = voice;
  459. }
  460. }
  461. }
  462. // Eliminate pathological cases (ie: only 1 note playing): we always give precedence to the lowest note(s)
  463. if (top == low)
  464. top = nullptr;
  465. const int numUsableVoices = usableVoices.size();
  466. // The oldest note that's playing with the target pitch is ideal..
  467. for (int i = 0; i < numUsableVoices; ++i)
  468. {
  469. SynthesiserVoice* const voice = usableVoices.getUnchecked (i);
  470. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  471. return voice;
  472. }
  473. // Oldest voice that has been released (no finger on it and not held by sustain pedal)
  474. for (int i = 0; i < numUsableVoices; ++i)
  475. {
  476. SynthesiserVoice* const voice = usableVoices.getUnchecked (i);
  477. if (voice != low && voice != top && voice->isPlayingButReleased())
  478. return voice;
  479. }
  480. // Oldest voice that doesn't have a finger on it:
  481. for (int i = 0; i < numUsableVoices; ++i)
  482. {
  483. SynthesiserVoice* const voice = usableVoices.getUnchecked (i);
  484. if (voice != low && voice != top && ! voice->isKeyDown())
  485. return voice;
  486. }
  487. // Oldest voice that isn't protected
  488. for (int i = 0; i < numUsableVoices; ++i)
  489. {
  490. SynthesiserVoice* const voice = usableVoices.getUnchecked (i);
  491. if (voice != low && voice != top)
  492. return voice;
  493. }
  494. // We've only got "protected" voices now: lowest note takes priority
  495. wassert (low != nullptr);
  496. // Duophonic synth: give priority to the bass note:
  497. if (top != nullptr)
  498. return top;
  499. return low;
  500. }
  501. }