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.

623 lines
19KB

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