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 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  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. auto midiIterator = midiData.findNextSamplePosition (startSample);
  136. bool firstEvent = true;
  137. const ScopedLock sl (lock);
  138. for (; numSamples > 0; ++midiIterator)
  139. {
  140. if (midiIterator == midiData.cend())
  141. {
  142. if (targetChannels > 0)
  143. renderVoices (outputAudio, startSample, numSamples);
  144. return;
  145. }
  146. const auto metadata = *midiIterator;
  147. const int samplesToNextMidiMessage = metadata.samplePosition - startSample;
  148. if (samplesToNextMidiMessage >= numSamples)
  149. {
  150. if (targetChannels > 0)
  151. renderVoices (outputAudio, startSample, numSamples);
  152. handleMidiEvent (metadata.getMessage());
  153. break;
  154. }
  155. if (samplesToNextMidiMessage < ((firstEvent && ! subBlockSubdivisionIsStrict) ? 1 : minimumSubBlockSize))
  156. {
  157. handleMidiEvent (metadata.getMessage());
  158. continue;
  159. }
  160. firstEvent = false;
  161. if (targetChannels > 0)
  162. renderVoices (outputAudio, startSample, samplesToNextMidiMessage);
  163. handleMidiEvent (metadata.getMessage());
  164. startSample += samplesToNextMidiMessage;
  165. numSamples -= samplesToNextMidiMessage;
  166. }
  167. std::for_each (midiIterator,
  168. midiData.cend(),
  169. [&] (const MidiMessageMetadata& meta) { handleMidiEvent (meta.getMessage()); });
  170. }
  171. // explicit template instantiation
  172. template void Synthesiser::processNextBlock<float> (AudioBuffer<float>&, const MidiBuffer&, int, int);
  173. template void Synthesiser::processNextBlock<double> (AudioBuffer<double>&, const MidiBuffer&, int, int);
  174. void Synthesiser::renderNextBlock (AudioBuffer<float>& outputAudio, const MidiBuffer& inputMidi,
  175. int startSample, int numSamples)
  176. {
  177. processNextBlock (outputAudio, inputMidi, startSample, numSamples);
  178. }
  179. void Synthesiser::renderNextBlock (AudioBuffer<double>& outputAudio, const MidiBuffer& inputMidi,
  180. int startSample, int numSamples)
  181. {
  182. processNextBlock (outputAudio, inputMidi, startSample, numSamples);
  183. }
  184. void Synthesiser::renderVoices (AudioBuffer<float>& buffer, int startSample, int numSamples)
  185. {
  186. for (auto* voice : voices)
  187. voice->renderNextBlock (buffer, startSample, numSamples);
  188. }
  189. void Synthesiser::renderVoices (AudioBuffer<double>& buffer, int startSample, int numSamples)
  190. {
  191. for (auto* voice : voices)
  192. voice->renderNextBlock (buffer, startSample, numSamples);
  193. }
  194. void Synthesiser::handleMidiEvent (const MidiMessage& m)
  195. {
  196. const int channel = m.getChannel();
  197. if (m.isNoteOn())
  198. {
  199. noteOn (channel, m.getNoteNumber(), m.getFloatVelocity());
  200. }
  201. else if (m.isNoteOff())
  202. {
  203. noteOff (channel, m.getNoteNumber(), m.getFloatVelocity(), true);
  204. }
  205. else if (m.isAllNotesOff() || m.isAllSoundOff())
  206. {
  207. allNotesOff (channel, true);
  208. }
  209. else if (m.isPitchWheel())
  210. {
  211. const int wheelPos = m.getPitchWheelValue();
  212. lastPitchWheelValues [channel - 1] = wheelPos;
  213. handlePitchWheel (channel, wheelPos);
  214. }
  215. else if (m.isAftertouch())
  216. {
  217. handleAftertouch (channel, m.getNoteNumber(), m.getAfterTouchValue());
  218. }
  219. else if (m.isChannelPressure())
  220. {
  221. handleChannelPressure (channel, m.getChannelPressureValue());
  222. }
  223. else if (m.isController())
  224. {
  225. handleController (channel, m.getControllerNumber(), m.getControllerValue());
  226. }
  227. else if (m.isProgramChange())
  228. {
  229. handleProgramChange (channel, m.getProgramChangeNumber());
  230. }
  231. }
  232. //==============================================================================
  233. void Synthesiser::noteOn (const int midiChannel,
  234. const int midiNoteNumber,
  235. const float velocity)
  236. {
  237. const ScopedLock sl (lock);
  238. for (auto* sound : sounds)
  239. {
  240. if (sound->appliesToNote (midiNoteNumber) && sound->appliesToChannel (midiChannel))
  241. {
  242. // If hitting a note that's still ringing, stop it first (it could be
  243. // still playing because of the sustain or sostenuto pedal).
  244. for (auto* voice : voices)
  245. if (voice->getCurrentlyPlayingNote() == midiNoteNumber && voice->isPlayingChannel (midiChannel))
  246. stopVoice (voice, 1.0f, true);
  247. startVoice (findFreeVoice (sound, midiChannel, midiNoteNumber, shouldStealNotes),
  248. sound, midiChannel, midiNoteNumber, velocity);
  249. }
  250. }
  251. }
  252. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  253. SynthesiserSound* const sound,
  254. const int midiChannel,
  255. const int midiNoteNumber,
  256. const float velocity)
  257. {
  258. if (voice != nullptr && sound != nullptr)
  259. {
  260. if (voice->currentlyPlayingSound != nullptr)
  261. voice->stopNote (0.0f, false);
  262. voice->currentlyPlayingNote = midiNoteNumber;
  263. voice->currentPlayingMidiChannel = midiChannel;
  264. voice->noteOnTime = ++lastNoteOnCounter;
  265. voice->currentlyPlayingSound = sound;
  266. voice->setKeyDown (true);
  267. voice->setSostenutoPedalDown (false);
  268. voice->setSustainPedalDown (sustainPedalsDown[midiChannel]);
  269. voice->startNote (midiNoteNumber, velocity, sound,
  270. lastPitchWheelValues [midiChannel - 1]);
  271. }
  272. }
  273. void Synthesiser::stopVoice (SynthesiserVoice* voice, float velocity, const bool allowTailOff)
  274. {
  275. jassert (voice != nullptr);
  276. voice->stopNote (velocity, allowTailOff);
  277. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  278. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == nullptr));
  279. }
  280. void Synthesiser::noteOff (const int midiChannel,
  281. const int midiNoteNumber,
  282. const float velocity,
  283. const bool allowTailOff)
  284. {
  285. const ScopedLock sl (lock);
  286. for (auto* voice : voices)
  287. {
  288. if (voice->getCurrentlyPlayingNote() == midiNoteNumber
  289. && voice->isPlayingChannel (midiChannel))
  290. {
  291. if (auto sound = voice->getCurrentlyPlayingSound())
  292. {
  293. if (sound->appliesToNote (midiNoteNumber)
  294. && sound->appliesToChannel (midiChannel))
  295. {
  296. jassert (! voice->keyIsDown || voice->isSustainPedalDown() == sustainPedalsDown [midiChannel]);
  297. voice->setKeyDown (false);
  298. if (! (voice->isSustainPedalDown() || voice->isSostenutoPedalDown()))
  299. stopVoice (voice, velocity, allowTailOff);
  300. }
  301. }
  302. }
  303. }
  304. }
  305. void Synthesiser::allNotesOff (const int midiChannel, const bool allowTailOff)
  306. {
  307. const ScopedLock sl (lock);
  308. for (auto* voice : voices)
  309. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  310. voice->stopNote (1.0f, allowTailOff);
  311. sustainPedalsDown.clear();
  312. }
  313. void Synthesiser::handlePitchWheel (const int midiChannel, const int wheelValue)
  314. {
  315. const ScopedLock sl (lock);
  316. for (auto* voice : voices)
  317. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  318. voice->pitchWheelMoved (wheelValue);
  319. }
  320. void Synthesiser::handleController (const int midiChannel,
  321. const int controllerNumber,
  322. const int controllerValue)
  323. {
  324. switch (controllerNumber)
  325. {
  326. case 0x40: handleSustainPedal (midiChannel, controllerValue >= 64); break;
  327. case 0x42: handleSostenutoPedal (midiChannel, controllerValue >= 64); break;
  328. case 0x43: handleSoftPedal (midiChannel, controllerValue >= 64); break;
  329. default: break;
  330. }
  331. const ScopedLock sl (lock);
  332. for (auto* voice : voices)
  333. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  334. voice->controllerMoved (controllerNumber, controllerValue);
  335. }
  336. void Synthesiser::handleAftertouch (int midiChannel, int midiNoteNumber, int aftertouchValue)
  337. {
  338. const ScopedLock sl (lock);
  339. for (auto* voice : voices)
  340. if (voice->getCurrentlyPlayingNote() == midiNoteNumber
  341. && (midiChannel <= 0 || voice->isPlayingChannel (midiChannel)))
  342. voice->aftertouchChanged (aftertouchValue);
  343. }
  344. void Synthesiser::handleChannelPressure (int midiChannel, int channelPressureValue)
  345. {
  346. const ScopedLock sl (lock);
  347. for (auto* voice : voices)
  348. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  349. voice->channelPressureChanged (channelPressureValue);
  350. }
  351. void Synthesiser::handleSustainPedal (int midiChannel, bool isDown)
  352. {
  353. jassert (midiChannel > 0 && midiChannel <= 16);
  354. const ScopedLock sl (lock);
  355. if (isDown)
  356. {
  357. sustainPedalsDown.setBit (midiChannel);
  358. for (auto* voice : voices)
  359. if (voice->isPlayingChannel (midiChannel) && voice->isKeyDown())
  360. voice->setSustainPedalDown (true);
  361. }
  362. else
  363. {
  364. for (auto* voice : voices)
  365. {
  366. if (voice->isPlayingChannel (midiChannel))
  367. {
  368. voice->setSustainPedalDown (false);
  369. if (! (voice->isKeyDown() || voice->isSostenutoPedalDown()))
  370. stopVoice (voice, 1.0f, true);
  371. }
  372. }
  373. sustainPedalsDown.clearBit (midiChannel);
  374. }
  375. }
  376. void Synthesiser::handleSostenutoPedal (int midiChannel, bool isDown)
  377. {
  378. jassert (midiChannel > 0 && midiChannel <= 16);
  379. const ScopedLock sl (lock);
  380. for (auto* voice : voices)
  381. {
  382. if (voice->isPlayingChannel (midiChannel))
  383. {
  384. if (isDown)
  385. voice->setSostenutoPedalDown (true);
  386. else if (voice->isSostenutoPedalDown())
  387. stopVoice (voice, 1.0f, true);
  388. }
  389. }
  390. }
  391. void Synthesiser::handleSoftPedal (int midiChannel, bool /*isDown*/)
  392. {
  393. ignoreUnused (midiChannel);
  394. jassert (midiChannel > 0 && midiChannel <= 16);
  395. }
  396. void Synthesiser::handleProgramChange (int midiChannel, int programNumber)
  397. {
  398. ignoreUnused (midiChannel, programNumber);
  399. jassert (midiChannel > 0 && midiChannel <= 16);
  400. }
  401. //==============================================================================
  402. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  403. int midiChannel, int midiNoteNumber,
  404. const bool stealIfNoneAvailable) const
  405. {
  406. const ScopedLock sl (lock);
  407. for (auto* voice : voices)
  408. if ((! voice->isVoiceActive()) && voice->canPlaySound (soundToPlay))
  409. return voice;
  410. if (stealIfNoneAvailable)
  411. return findVoiceToSteal (soundToPlay, midiChannel, midiNoteNumber);
  412. return nullptr;
  413. }
  414. SynthesiserVoice* Synthesiser::findVoiceToSteal (SynthesiserSound* soundToPlay,
  415. int /*midiChannel*/, int midiNoteNumber) const
  416. {
  417. // This voice-stealing algorithm applies the following heuristics:
  418. // - Re-use the oldest notes first
  419. // - Protect the lowest & topmost notes, even if sustained, but not if they've been released.
  420. // apparently you are trying to render audio without having any voices...
  421. jassert (! voices.isEmpty());
  422. // These are the voices we want to protect (ie: only steal if unavoidable)
  423. SynthesiserVoice* low = nullptr; // Lowest sounding note, might be sustained, but NOT in release phase
  424. SynthesiserVoice* top = nullptr; // Highest sounding note, might be sustained, but NOT in release phase
  425. // this is a list of voices we can steal, sorted by how long they've been running
  426. Array<SynthesiserVoice*> usableVoices;
  427. usableVoices.ensureStorageAllocated (voices.size());
  428. for (auto* voice : voices)
  429. {
  430. if (voice->canPlaySound (soundToPlay))
  431. {
  432. jassert (voice->isVoiceActive()); // We wouldn't be here otherwise
  433. usableVoices.add (voice);
  434. // NB: Using a functor rather than a lambda here due to scare-stories about
  435. // compilers generating code containing heap allocations..
  436. struct Sorter
  437. {
  438. bool operator() (const SynthesiserVoice* a, const SynthesiserVoice* b) const noexcept { return a->wasStartedBefore (*b); }
  439. };
  440. std::sort (usableVoices.begin(), usableVoices.end(), Sorter());
  441. if (! voice->isPlayingButReleased()) // Don't protect released notes
  442. {
  443. auto note = voice->getCurrentlyPlayingNote();
  444. if (low == nullptr || note < low->getCurrentlyPlayingNote())
  445. low = voice;
  446. if (top == nullptr || note > top->getCurrentlyPlayingNote())
  447. top = voice;
  448. }
  449. }
  450. }
  451. // Eliminate pathological cases (ie: only 1 note playing): we always give precedence to the lowest note(s)
  452. if (top == low)
  453. top = nullptr;
  454. // The oldest note that's playing with the target pitch is ideal..
  455. for (auto* voice : usableVoices)
  456. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  457. return voice;
  458. // Oldest voice that has been released (no finger on it and not held by sustain pedal)
  459. for (auto* voice : usableVoices)
  460. if (voice != low && voice != top && voice->isPlayingButReleased())
  461. return voice;
  462. // Oldest voice that doesn't have a finger on it:
  463. for (auto* voice : usableVoices)
  464. if (voice != low && voice != top && ! voice->isKeyDown())
  465. return voice;
  466. // Oldest voice that isn't protected
  467. for (auto* voice : usableVoices)
  468. if (voice != low && voice != top)
  469. return voice;
  470. // We've only got "protected" voices now: lowest note takes priority
  471. jassert (low != nullptr);
  472. // Duophonic synth: give priority to the bass note:
  473. if (top != nullptr)
  474. return top;
  475. return low;
  476. }
  477. } // namespace juce