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.

652 lines
21KB

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