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_MPESynthesiser.cpp 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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. MPESynthesiser::MPESynthesiser()
  20. {
  21. MPEZoneLayout zoneLayout;
  22. zoneLayout.setLowerZone (15);
  23. setZoneLayout (zoneLayout);
  24. }
  25. MPESynthesiser::MPESynthesiser (MPEInstrument* mpeInstrument) : MPESynthesiserBase (mpeInstrument)
  26. {
  27. }
  28. MPESynthesiser::~MPESynthesiser()
  29. {
  30. }
  31. //==============================================================================
  32. void MPESynthesiser::startVoice (MPESynthesiserVoice* voice, MPENote noteToStart)
  33. {
  34. jassert (voice != nullptr);
  35. voice->currentlyPlayingNote = noteToStart;
  36. voice->noteOnTime = lastNoteOnCounter++;
  37. voice->noteStarted();
  38. }
  39. void MPESynthesiser::stopVoice (MPESynthesiserVoice* voice, MPENote noteToStop, bool allowTailOff)
  40. {
  41. jassert (voice != nullptr);
  42. voice->currentlyPlayingNote = noteToStop;
  43. voice->noteStopped (allowTailOff);
  44. }
  45. //==============================================================================
  46. void MPESynthesiser::noteAdded (MPENote newNote)
  47. {
  48. const ScopedLock sl (voicesLock);
  49. if (auto* voice = findFreeVoice (newNote, shouldStealVoices))
  50. startVoice (voice, newNote);
  51. }
  52. void MPESynthesiser::notePressureChanged (MPENote changedNote)
  53. {
  54. const ScopedLock sl (voicesLock);
  55. for (auto* voice : voices)
  56. {
  57. if (voice->isCurrentlyPlayingNote (changedNote))
  58. {
  59. voice->currentlyPlayingNote = changedNote;
  60. voice->notePressureChanged();
  61. }
  62. }
  63. }
  64. void MPESynthesiser::notePitchbendChanged (MPENote changedNote)
  65. {
  66. const ScopedLock sl (voicesLock);
  67. for (auto* voice : voices)
  68. {
  69. if (voice->isCurrentlyPlayingNote (changedNote))
  70. {
  71. voice->currentlyPlayingNote = changedNote;
  72. voice->notePitchbendChanged();
  73. }
  74. }
  75. }
  76. void MPESynthesiser::noteTimbreChanged (MPENote changedNote)
  77. {
  78. const ScopedLock sl (voicesLock);
  79. for (auto* voice : voices)
  80. {
  81. if (voice->isCurrentlyPlayingNote (changedNote))
  82. {
  83. voice->currentlyPlayingNote = changedNote;
  84. voice->noteTimbreChanged();
  85. }
  86. }
  87. }
  88. void MPESynthesiser::noteKeyStateChanged (MPENote changedNote)
  89. {
  90. const ScopedLock sl (voicesLock);
  91. for (auto* voice : voices)
  92. {
  93. if (voice->isCurrentlyPlayingNote (changedNote))
  94. {
  95. voice->currentlyPlayingNote = changedNote;
  96. voice->noteKeyStateChanged();
  97. }
  98. }
  99. }
  100. void MPESynthesiser::noteReleased (MPENote finishedNote)
  101. {
  102. const ScopedLock sl (voicesLock);
  103. for (auto i = voices.size(); --i >= 0;)
  104. {
  105. auto* voice = voices.getUnchecked (i);
  106. if (voice->isCurrentlyPlayingNote(finishedNote))
  107. stopVoice (voice, finishedNote, true);
  108. }
  109. }
  110. void MPESynthesiser::setCurrentPlaybackSampleRate (const double newRate)
  111. {
  112. MPESynthesiserBase::setCurrentPlaybackSampleRate (newRate);
  113. const ScopedLock sl (voicesLock);
  114. turnOffAllVoices (false);
  115. for (auto i = voices.size(); --i >= 0;)
  116. voices.getUnchecked (i)->setCurrentSampleRate (newRate);
  117. }
  118. void MPESynthesiser::handleMidiEvent (const MidiMessage& m)
  119. {
  120. if (m.isController())
  121. handleController (m.getChannel(), m.getControllerNumber(), m.getControllerValue());
  122. else if (m.isProgramChange())
  123. handleProgramChange (m.getChannel(), m.getProgramChangeNumber());
  124. MPESynthesiserBase::handleMidiEvent (m);
  125. }
  126. MPESynthesiserVoice* MPESynthesiser::findFreeVoice (MPENote noteToFindVoiceFor, bool stealIfNoneAvailable) const
  127. {
  128. const ScopedLock sl (voicesLock);
  129. for (auto* voice : voices)
  130. {
  131. if (! voice->isActive())
  132. return voice;
  133. }
  134. if (stealIfNoneAvailable)
  135. return findVoiceToSteal (noteToFindVoiceFor);
  136. return nullptr;
  137. }
  138. MPESynthesiserVoice* MPESynthesiser::findVoiceToSteal (MPENote noteToStealVoiceFor) const
  139. {
  140. // This voice-stealing algorithm applies the following heuristics:
  141. // - Re-use the oldest notes first
  142. // - Protect the lowest & topmost notes, even if sustained, but not if they've been released.
  143. // apparently you are trying to render audio without having any voices...
  144. jassert (voices.size() > 0);
  145. // These are the voices we want to protect (ie: only steal if unavoidable)
  146. MPESynthesiserVoice* low = nullptr; // Lowest sounding note, might be sustained, but NOT in release phase
  147. MPESynthesiserVoice* top = nullptr; // Highest sounding note, might be sustained, but NOT in release phase
  148. // this is a list of voices we can steal, sorted by how long they've been running
  149. Array<MPESynthesiserVoice*> usableVoices;
  150. usableVoices.ensureStorageAllocated (voices.size());
  151. for (auto* voice : voices)
  152. {
  153. jassert (voice->isActive()); // We wouldn't be here otherwise
  154. usableVoices.add (voice);
  155. // NB: Using a functor rather than a lambda here due to scare-stories about
  156. // compilers generating code containing heap allocations..
  157. struct Sorter
  158. {
  159. bool operator() (const MPESynthesiserVoice* a, const MPESynthesiserVoice* b) const noexcept { return a->noteOnTime < b->noteOnTime; }
  160. };
  161. std::sort (usableVoices.begin(), usableVoices.end(), Sorter());
  162. if (! voice->isPlayingButReleased()) // Don't protect released notes
  163. {
  164. auto noteNumber = voice->getCurrentlyPlayingNote().initialNote;
  165. if (low == nullptr || noteNumber < low->getCurrentlyPlayingNote().initialNote)
  166. low = voice;
  167. if (top == nullptr || noteNumber > top->getCurrentlyPlayingNote().initialNote)
  168. top = voice;
  169. }
  170. }
  171. // Eliminate pathological cases (ie: only 1 note playing): we always give precedence to the lowest note(s)
  172. if (top == low)
  173. top = nullptr;
  174. // If we want to re-use the voice to trigger a new note,
  175. // then The oldest note that's playing the same note number is ideal.
  176. if (noteToStealVoiceFor.isValid())
  177. for (auto* voice : usableVoices)
  178. if (voice->getCurrentlyPlayingNote().initialNote == noteToStealVoiceFor.initialNote)
  179. return voice;
  180. // Oldest voice that has been released (no finger on it and not held by sustain pedal)
  181. for (auto* voice : usableVoices)
  182. if (voice != low && voice != top && voice->isPlayingButReleased())
  183. return voice;
  184. // Oldest voice that doesn't have a finger on it:
  185. for (auto* voice : usableVoices)
  186. if (voice != low && voice != top
  187. && voice->getCurrentlyPlayingNote().keyState != MPENote::keyDown
  188. && voice->getCurrentlyPlayingNote().keyState != MPENote::keyDownAndSustained)
  189. return voice;
  190. // Oldest voice that isn't protected
  191. for (auto* voice : usableVoices)
  192. if (voice != low && voice != top)
  193. return voice;
  194. // We've only got "protected" voices now: lowest note takes priority
  195. jassert (low != nullptr);
  196. // Duophonic synth: give priority to the bass note:
  197. if (top != nullptr)
  198. return top;
  199. return low;
  200. }
  201. //==============================================================================
  202. void MPESynthesiser::addVoice (MPESynthesiserVoice* const newVoice)
  203. {
  204. const ScopedLock sl (voicesLock);
  205. newVoice->setCurrentSampleRate (getSampleRate());
  206. voices.add (newVoice);
  207. }
  208. void MPESynthesiser::clearVoices()
  209. {
  210. const ScopedLock sl (voicesLock);
  211. voices.clear();
  212. }
  213. MPESynthesiserVoice* MPESynthesiser::getVoice (const int index) const
  214. {
  215. const ScopedLock sl (voicesLock);
  216. return voices [index];
  217. }
  218. void MPESynthesiser::removeVoice (const int index)
  219. {
  220. const ScopedLock sl (voicesLock);
  221. voices.remove (index);
  222. }
  223. void MPESynthesiser::reduceNumVoices (const int newNumVoices)
  224. {
  225. // we can't possibly get to a negative number of voices...
  226. jassert (newNumVoices >= 0);
  227. const ScopedLock sl (voicesLock);
  228. while (voices.size() > newNumVoices)
  229. {
  230. if (auto* voice = findFreeVoice ({}, true))
  231. voices.removeObject (voice);
  232. else
  233. voices.remove (0); // if there's no voice to steal, kill the oldest voice
  234. }
  235. }
  236. void MPESynthesiser::turnOffAllVoices (bool allowTailOff)
  237. {
  238. {
  239. const ScopedLock sl (voicesLock);
  240. // first turn off all voices (it's more efficient to do this immediately
  241. // rather than to go through the MPEInstrument for this).
  242. for (auto* voice : voices)
  243. voice->noteStopped (allowTailOff);
  244. }
  245. // finally make sure the MPE Instrument also doesn't have any notes anymore.
  246. instrument->releaseAllNotes();
  247. }
  248. //==============================================================================
  249. void MPESynthesiser::renderNextSubBlock (AudioBuffer<float>& buffer, int startSample, int numSamples)
  250. {
  251. const ScopedLock sl (voicesLock);
  252. for (auto* voice : voices)
  253. {
  254. if (voice->isActive())
  255. voice->renderNextBlock (buffer, startSample, numSamples);
  256. }
  257. }
  258. void MPESynthesiser::renderNextSubBlock (AudioBuffer<double>& buffer, int startSample, int numSamples)
  259. {
  260. const ScopedLock sl (voicesLock);
  261. for (auto* voice : voices)
  262. {
  263. if (voice->isActive())
  264. voice->renderNextBlock (buffer, startSample, numSamples);
  265. }
  266. }
  267. } // namespace juce