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.

600 lines
20KB

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