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.

juce_Synthesiser.cpp 18KB

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