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.

353 lines
11KB

  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. // All major OSes use double-locking so this will be lock- and wait-free as long as stealLock is not
  147. // contended. This is always the case if you do not call findVoiceToSteal on multiple threads at
  148. // the same time.
  149. const ScopedLock sl (stealLock);
  150. // this is a list of voices we can steal, sorted by how long they've been running
  151. usableVoicesToStealArray.clear();
  152. for (auto* voice : voices)
  153. {
  154. jassert (voice->isActive()); // We wouldn't be here otherwise
  155. usableVoicesToStealArray.add (voice);
  156. // NB: Using a functor rather than a lambda here due to scare-stories about
  157. // compilers generating code containing heap allocations..
  158. struct Sorter
  159. {
  160. bool operator() (const MPESynthesiserVoice* a, const MPESynthesiserVoice* b) const noexcept { return a->noteOnTime < b->noteOnTime; }
  161. };
  162. std::sort (usableVoicesToStealArray.begin(), usableVoicesToStealArray.end(), Sorter());
  163. if (! voice->isPlayingButReleased()) // Don't protect released notes
  164. {
  165. auto noteNumber = voice->getCurrentlyPlayingNote().initialNote;
  166. if (low == nullptr || noteNumber < low->getCurrentlyPlayingNote().initialNote)
  167. low = voice;
  168. if (top == nullptr || noteNumber > top->getCurrentlyPlayingNote().initialNote)
  169. top = voice;
  170. }
  171. }
  172. // Eliminate pathological cases (ie: only 1 note playing): we always give precedence to the lowest note(s)
  173. if (top == low)
  174. top = nullptr;
  175. // If we want to re-use the voice to trigger a new note,
  176. // then The oldest note that's playing the same note number is ideal.
  177. if (noteToStealVoiceFor.isValid())
  178. for (auto* voice : usableVoicesToStealArray)
  179. if (voice->getCurrentlyPlayingNote().initialNote == noteToStealVoiceFor.initialNote)
  180. return voice;
  181. // Oldest voice that has been released (no finger on it and not held by sustain pedal)
  182. for (auto* voice : usableVoicesToStealArray)
  183. if (voice != low && voice != top && voice->isPlayingButReleased())
  184. return voice;
  185. // Oldest voice that doesn't have a finger on it:
  186. for (auto* voice : usableVoicesToStealArray)
  187. if (voice != low && voice != top
  188. && voice->getCurrentlyPlayingNote().keyState != MPENote::keyDown
  189. && voice->getCurrentlyPlayingNote().keyState != MPENote::keyDownAndSustained)
  190. return voice;
  191. // Oldest voice that isn't protected
  192. for (auto* voice : usableVoicesToStealArray)
  193. if (voice != low && voice != top)
  194. return voice;
  195. // We've only got "protected" voices now: lowest note takes priority
  196. jassert (low != nullptr);
  197. // Duophonic synth: give priority to the bass note:
  198. if (top != nullptr)
  199. return top;
  200. return low;
  201. }
  202. //==============================================================================
  203. void MPESynthesiser::addVoice (MPESynthesiserVoice* const newVoice)
  204. {
  205. {
  206. const ScopedLock sl (voicesLock);
  207. newVoice->setCurrentSampleRate (getSampleRate());
  208. voices.add (newVoice);
  209. }
  210. {
  211. const ScopedLock sl (stealLock);
  212. usableVoicesToStealArray.ensureStorageAllocated (voices.size() + 1);
  213. }
  214. }
  215. void MPESynthesiser::clearVoices()
  216. {
  217. const ScopedLock sl (voicesLock);
  218. voices.clear();
  219. }
  220. MPESynthesiserVoice* MPESynthesiser::getVoice (const int index) const
  221. {
  222. const ScopedLock sl (voicesLock);
  223. return voices [index];
  224. }
  225. void MPESynthesiser::removeVoice (const int index)
  226. {
  227. const ScopedLock sl (voicesLock);
  228. voices.remove (index);
  229. }
  230. void MPESynthesiser::reduceNumVoices (const int newNumVoices)
  231. {
  232. // we can't possibly get to a negative number of voices...
  233. jassert (newNumVoices >= 0);
  234. const ScopedLock sl (voicesLock);
  235. while (voices.size() > newNumVoices)
  236. {
  237. if (auto* voice = findFreeVoice ({}, true))
  238. voices.removeObject (voice);
  239. else
  240. voices.remove (0); // if there's no voice to steal, kill the oldest voice
  241. }
  242. }
  243. void MPESynthesiser::turnOffAllVoices (bool allowTailOff)
  244. {
  245. {
  246. const ScopedLock sl (voicesLock);
  247. // first turn off all voices (it's more efficient to do this immediately
  248. // rather than to go through the MPEInstrument for this).
  249. for (auto* voice : voices)
  250. {
  251. voice->currentlyPlayingNote.noteOffVelocity = MPEValue::from7BitInt (64); // some reasonable number
  252. voice->currentlyPlayingNote.keyState = MPENote::off;
  253. voice->noteStopped (allowTailOff);
  254. }
  255. }
  256. // finally make sure the MPE Instrument also doesn't have any notes anymore.
  257. instrument.releaseAllNotes();
  258. }
  259. //==============================================================================
  260. void MPESynthesiser::renderNextSubBlock (AudioBuffer<float>& 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. void MPESynthesiser::renderNextSubBlock (AudioBuffer<double>& buffer, int startSample, int numSamples)
  270. {
  271. const ScopedLock sl (voicesLock);
  272. for (auto* voice : voices)
  273. {
  274. if (voice->isActive())
  275. voice->renderNextBlock (buffer, startSample, numSamples);
  276. }
  277. }
  278. } // namespace juce