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.

342 lines
10KB

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