The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
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.

570 lines
18KB

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