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.

638 lines
28KB

  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. //==============================================================================
  20. /**
  21. Describes one of the sounds that a Synthesiser can play.
  22. A synthesiser can contain one or more sounds, and a sound can choose which
  23. midi notes and channels can trigger it.
  24. The SynthesiserSound is a passive class that just describes what the sound is -
  25. the actual audio rendering for a sound is done by a SynthesiserVoice. This allows
  26. more than one SynthesiserVoice to play the same sound at the same time.
  27. @see Synthesiser, SynthesiserVoice
  28. @tags{Audio}
  29. */
  30. class JUCE_API SynthesiserSound : public ReferenceCountedObject
  31. {
  32. protected:
  33. //==============================================================================
  34. SynthesiserSound();
  35. public:
  36. /** Destructor. */
  37. ~SynthesiserSound() override;
  38. //==============================================================================
  39. /** Returns true if this sound should be played when a given midi note is pressed.
  40. The Synthesiser will use this information when deciding which sounds to trigger
  41. for a given note.
  42. */
  43. virtual bool appliesToNote (int midiNoteNumber) = 0;
  44. /** Returns true if the sound should be triggered by midi events on a given channel.
  45. The Synthesiser will use this information when deciding which sounds to trigger
  46. for a given note.
  47. */
  48. virtual bool appliesToChannel (int midiChannel) = 0;
  49. /** The class is reference-counted, so this is a handy pointer class for it. */
  50. using Ptr = ReferenceCountedObjectPtr<SynthesiserSound>;
  51. private:
  52. //==============================================================================
  53. JUCE_LEAK_DETECTOR (SynthesiserSound)
  54. };
  55. //==============================================================================
  56. /**
  57. Represents a voice that a Synthesiser can use to play a SynthesiserSound.
  58. A voice plays a single sound at a time, and a synthesiser holds an array of
  59. voices so that it can play polyphonically.
  60. @see Synthesiser, SynthesiserSound
  61. @tags{Audio}
  62. */
  63. class JUCE_API SynthesiserVoice
  64. {
  65. public:
  66. //==============================================================================
  67. /** Creates a voice. */
  68. SynthesiserVoice();
  69. /** Destructor. */
  70. virtual ~SynthesiserVoice();
  71. //==============================================================================
  72. /** Returns the midi note that this voice is currently playing.
  73. Returns a value less than 0 if no note is playing.
  74. */
  75. int getCurrentlyPlayingNote() const noexcept { return currentlyPlayingNote; }
  76. /** Returns the sound that this voice is currently playing.
  77. Returns nullptr if it's not playing.
  78. */
  79. SynthesiserSound::Ptr getCurrentlyPlayingSound() const noexcept { return currentlyPlayingSound; }
  80. /** Must return true if this voice object is capable of playing the given sound.
  81. If there are different classes of sound, and different classes of voice, a voice can
  82. choose which ones it wants to take on.
  83. A typical implementation of this method may just return true if there's only one type
  84. of voice and sound, or it might check the type of the sound object passed-in and
  85. see if it's one that it understands.
  86. */
  87. virtual bool canPlaySound (SynthesiserSound*) = 0;
  88. /** Called to start a new note.
  89. This will be called during the rendering callback, so must be fast and thread-safe.
  90. */
  91. virtual void startNote (int midiNoteNumber,
  92. float velocity,
  93. SynthesiserSound* sound,
  94. int currentPitchWheelPosition) = 0;
  95. /** Called to stop a note.
  96. This will be called during the rendering callback, so must be fast and thread-safe.
  97. The velocity indicates how quickly the note was released - 0 is slowly, 1 is quickly.
  98. If allowTailOff is false or the voice doesn't want to tail-off, then it must stop all
  99. sound immediately, and must call clearCurrentNote() to reset the state of this voice
  100. and allow the synth to reassign it another sound.
  101. If allowTailOff is true and the voice decides to do a tail-off, then it's allowed to
  102. begin fading out its sound, and it can stop playing until it's finished. As soon as it
  103. finishes playing (during the rendering callback), it must make sure that it calls
  104. clearCurrentNote().
  105. */
  106. virtual void stopNote (float velocity, bool allowTailOff) = 0;
  107. /** Returns true if this voice is currently busy playing a sound.
  108. By default this just checks the getCurrentlyPlayingNote() value, but can
  109. be overridden for more advanced checking.
  110. */
  111. virtual bool isVoiceActive() const;
  112. /** Called to let the voice know that the pitch wheel has been moved.
  113. This will be called during the rendering callback, so must be fast and thread-safe.
  114. */
  115. virtual void pitchWheelMoved (int newPitchWheelValue) = 0;
  116. /** Called to let the voice know that a midi controller has been moved.
  117. This will be called during the rendering callback, so must be fast and thread-safe.
  118. */
  119. virtual void controllerMoved (int controllerNumber, int newControllerValue) = 0;
  120. /** Called to let the voice know that the aftertouch has changed.
  121. This will be called during the rendering callback, so must be fast and thread-safe.
  122. */
  123. virtual void aftertouchChanged (int newAftertouchValue);
  124. /** Called to let the voice know that the channel pressure has changed.
  125. This will be called during the rendering callback, so must be fast and thread-safe.
  126. */
  127. virtual void channelPressureChanged (int newChannelPressureValue);
  128. //==============================================================================
  129. /** Renders the next block of data for this voice.
  130. The output audio data must be added to the current contents of the buffer provided.
  131. Only the region of the buffer between startSample and (startSample + numSamples)
  132. should be altered by this method.
  133. If the voice is currently silent, it should just return without doing anything.
  134. If the sound that the voice is playing finishes during the course of this rendered
  135. block, it must call clearCurrentNote(), to tell the synthesiser that it has finished.
  136. The size of the blocks that are rendered can change each time it is called, and may
  137. involve rendering as little as 1 sample at a time. In between rendering callbacks,
  138. the voice's methods will be called to tell it about note and controller events.
  139. */
  140. virtual void renderNextBlock (AudioBuffer<float>& outputBuffer,
  141. int startSample,
  142. int numSamples) = 0;
  143. /** A double-precision version of renderNextBlock() */
  144. virtual void renderNextBlock (AudioBuffer<double>& outputBuffer,
  145. int startSample,
  146. int numSamples);
  147. /** Changes the voice's reference sample rate.
  148. The rate is set so that subclasses know the output rate and can set their pitch
  149. accordingly.
  150. This method is called by the synth, and subclasses can access the current rate with
  151. the currentSampleRate member.
  152. */
  153. virtual void setCurrentPlaybackSampleRate (double newRate);
  154. /** Returns true if the voice is currently playing a sound which is mapped to the given
  155. midi channel.
  156. If it's not currently playing, this will return false.
  157. */
  158. virtual bool isPlayingChannel (int midiChannel) const;
  159. /** Returns the current target sample rate at which rendering is being done.
  160. Subclasses may need to know this so that they can pitch things correctly.
  161. */
  162. double getSampleRate() const noexcept { return currentSampleRate; }
  163. /** Returns true if the key that triggered this voice is still held down.
  164. Note that the voice may still be playing after the key was released (e.g because the
  165. sostenuto pedal is down).
  166. */
  167. bool isKeyDown() const noexcept { return keyIsDown; }
  168. /** Allows you to modify the flag indicating that the key that triggered this voice is still held down.
  169. @see isKeyDown
  170. */
  171. void setKeyDown (bool isNowDown) noexcept { keyIsDown = isNowDown; }
  172. /** Returns true if the sustain pedal is currently active for this voice. */
  173. bool isSustainPedalDown() const noexcept { return sustainPedalDown; }
  174. /** Modifies the sustain pedal flag. */
  175. void setSustainPedalDown (bool isNowDown) noexcept { sustainPedalDown = isNowDown; }
  176. /** Returns true if the sostenuto pedal is currently active for this voice. */
  177. bool isSostenutoPedalDown() const noexcept { return sostenutoPedalDown; }
  178. /** Modifies the sostenuto pedal flag. */
  179. void setSostenutoPedalDown (bool isNowDown) noexcept { sostenutoPedalDown = isNowDown; }
  180. /** Returns true if a voice is sounding in its release phase **/
  181. bool isPlayingButReleased() const noexcept
  182. {
  183. return isVoiceActive() && ! (isKeyDown() || isSostenutoPedalDown() || isSustainPedalDown());
  184. }
  185. /** Returns true if this voice started playing its current note before the other voice did. */
  186. bool wasStartedBefore (const SynthesiserVoice& other) const noexcept;
  187. protected:
  188. /** Resets the state of this voice after a sound has finished playing.
  189. The subclass must call this when it finishes playing a note and becomes available
  190. to play new ones.
  191. It must either call it in the stopNote() method, or if the voice is tailing off,
  192. then it should call it later during the renderNextBlock method, as soon as it
  193. finishes its tail-off.
  194. It can also be called at any time during the render callback if the sound happens
  195. to have finished, e.g. if it's playing a sample and the sample finishes.
  196. */
  197. void clearCurrentNote();
  198. private:
  199. //==============================================================================
  200. friend class Synthesiser;
  201. double currentSampleRate = 44100.0;
  202. int currentlyPlayingNote = -1, currentPlayingMidiChannel = 0;
  203. uint32 noteOnTime = 0;
  204. SynthesiserSound::Ptr currentlyPlayingSound;
  205. bool keyIsDown = false, sustainPedalDown = false, sostenutoPedalDown = false;
  206. AudioBuffer<float> tempBuffer;
  207. JUCE_LEAK_DETECTOR (SynthesiserVoice)
  208. };
  209. //==============================================================================
  210. /**
  211. Base class for a musical device that can play sounds.
  212. To create a synthesiser, you'll need to create a subclass of SynthesiserSound
  213. to describe each sound available to your synth, and a subclass of SynthesiserVoice
  214. which can play back one of these sounds.
  215. Then you can use the addVoice() and addSound() methods to give the synthesiser a
  216. set of sounds, and a set of voices it can use to play them. If you only give it
  217. one voice it will be monophonic - the more voices it has, the more polyphony it'll
  218. have available.
  219. Then repeatedly call the renderNextBlock() method to produce the audio. Any midi
  220. events that go in will be scanned for note on/off messages, and these are used to
  221. start and stop the voices playing the appropriate sounds.
  222. While it's playing, you can also cause notes to be triggered by calling the noteOn(),
  223. noteOff() and other controller methods.
  224. Before rendering, be sure to call the setCurrentPlaybackSampleRate() to tell it
  225. what the target playback rate is. This value is passed on to the voices so that
  226. they can pitch their output correctly.
  227. @tags{Audio}
  228. */
  229. class JUCE_API Synthesiser
  230. {
  231. public:
  232. //==============================================================================
  233. /** Creates a new synthesiser.
  234. You'll need to add some sounds and voices before it'll make any sound.
  235. */
  236. Synthesiser();
  237. /** Destructor. */
  238. virtual ~Synthesiser();
  239. //==============================================================================
  240. /** Deletes all voices. */
  241. void clearVoices();
  242. /** Returns the number of voices that have been added. */
  243. int getNumVoices() const noexcept { return voices.size(); }
  244. /** Returns one of the voices that have been added. */
  245. SynthesiserVoice* getVoice (int index) const;
  246. /** Adds a new voice to the synth.
  247. All the voices should be the same class of object and are treated equally.
  248. The object passed in will be managed by the synthesiser, which will delete
  249. it later on when no longer needed. The caller should not retain a pointer to the
  250. voice.
  251. */
  252. SynthesiserVoice* addVoice (SynthesiserVoice* newVoice);
  253. /** Deletes one of the voices. */
  254. void removeVoice (int index);
  255. //==============================================================================
  256. /** Deletes all sounds. */
  257. void clearSounds();
  258. /** Returns the number of sounds that have been added to the synth. */
  259. int getNumSounds() const noexcept { return sounds.size(); }
  260. /** Returns one of the sounds. */
  261. SynthesiserSound::Ptr getSound (int index) const noexcept { return sounds[index]; }
  262. /** Adds a new sound to the synthesiser.
  263. The object passed in is reference counted, so will be deleted when the
  264. synthesiser and all voices are no longer using it.
  265. */
  266. SynthesiserSound* addSound (const SynthesiserSound::Ptr& newSound);
  267. /** Removes and deletes one of the sounds. */
  268. void removeSound (int index);
  269. //==============================================================================
  270. /** If set to true, then the synth will try to take over an existing voice if
  271. it runs out and needs to play another note.
  272. The value of this boolean is passed into findFreeVoice(), so the result will
  273. depend on the implementation of this method.
  274. */
  275. void setNoteStealingEnabled (bool shouldStealNotes);
  276. /** Returns true if note-stealing is enabled.
  277. @see setNoteStealingEnabled
  278. */
  279. bool isNoteStealingEnabled() const noexcept { return shouldStealNotes; }
  280. //==============================================================================
  281. /** Triggers a note-on event.
  282. The default method here will find all the sounds that want to be triggered by
  283. this note/channel. For each sound, it'll try to find a free voice, and use the
  284. voice to start playing the sound.
  285. Subclasses might want to override this if they need a more complex algorithm.
  286. This method will be called automatically according to the midi data passed into
  287. renderNextBlock(), but may be called explicitly too.
  288. The midiChannel parameter is the channel, between 1 and 16 inclusive.
  289. */
  290. virtual void noteOn (int midiChannel,
  291. int midiNoteNumber,
  292. float velocity);
  293. /** Triggers a note-off event.
  294. This will turn off any voices that are playing a sound for the given note/channel.
  295. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  296. (if they can do). If this is false, the notes will all be cut off immediately.
  297. This method will be called automatically according to the midi data passed into
  298. renderNextBlock(), but may be called explicitly too.
  299. The midiChannel parameter is the channel, between 1 and 16 inclusive.
  300. */
  301. virtual void noteOff (int midiChannel,
  302. int midiNoteNumber,
  303. float velocity,
  304. bool allowTailOff);
  305. /** Turns off all notes.
  306. This will turn off any voices that are playing a sound on the given midi channel.
  307. If midiChannel is 0 or less, then all voices will be turned off, regardless of
  308. which channel they're playing. Otherwise it represents a valid midi channel, from
  309. 1 to 16 inclusive.
  310. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  311. (if they can do). If this is false, the notes will all be cut off immediately.
  312. This method will be called automatically according to the midi data passed into
  313. renderNextBlock(), but may be called explicitly too.
  314. */
  315. virtual void allNotesOff (int midiChannel,
  316. bool allowTailOff);
  317. /** Sends a pitch-wheel message to any active voices.
  318. This will send a pitch-wheel message to any voices that are playing sounds on
  319. the given midi channel.
  320. This method will be called automatically according to the midi data passed into
  321. renderNextBlock(), but may be called explicitly too.
  322. @param midiChannel the midi channel, from 1 to 16 inclusive
  323. @param wheelValue the wheel position, from 0 to 0x3fff, as returned by MidiMessage::getPitchWheelValue()
  324. */
  325. virtual void handlePitchWheel (int midiChannel,
  326. int wheelValue);
  327. /** Sends a midi controller message to any active voices.
  328. This will send a midi controller message to any voices that are playing sounds on
  329. the given midi channel.
  330. This method will be called automatically according to the midi data passed into
  331. renderNextBlock(), but may be called explicitly too.
  332. @param midiChannel the midi channel, from 1 to 16 inclusive
  333. @param controllerNumber the midi controller type, as returned by MidiMessage::getControllerNumber()
  334. @param controllerValue the midi controller value, between 0 and 127, as returned by MidiMessage::getControllerValue()
  335. */
  336. virtual void handleController (int midiChannel,
  337. int controllerNumber,
  338. int controllerValue);
  339. /** Sends an aftertouch message.
  340. This will send an aftertouch message to any voices that are playing sounds on
  341. the given midi channel and note number.
  342. This method will be called automatically according to the midi data passed into
  343. renderNextBlock(), but may be called explicitly too.
  344. @param midiChannel the midi channel, from 1 to 16 inclusive
  345. @param midiNoteNumber the midi note number, 0 to 127
  346. @param aftertouchValue the aftertouch value, between 0 and 127,
  347. as returned by MidiMessage::getAftertouchValue()
  348. */
  349. virtual void handleAftertouch (int midiChannel, int midiNoteNumber, int aftertouchValue);
  350. /** Sends a channel pressure message.
  351. This will send a channel pressure message to any voices that are playing sounds on
  352. the given midi channel.
  353. This method will be called automatically according to the midi data passed into
  354. renderNextBlock(), but may be called explicitly too.
  355. @param midiChannel the midi channel, from 1 to 16 inclusive
  356. @param channelPressureValue the pressure value, between 0 and 127, as returned
  357. by MidiMessage::getChannelPressureValue()
  358. */
  359. virtual void handleChannelPressure (int midiChannel, int channelPressureValue);
  360. /** Handles a sustain pedal event. */
  361. virtual void handleSustainPedal (int midiChannel, bool isDown);
  362. /** Handles a sostenuto pedal event. */
  363. virtual void handleSostenutoPedal (int midiChannel, bool isDown);
  364. /** Can be overridden to handle soft pedal events. */
  365. virtual void handleSoftPedal (int midiChannel, bool isDown);
  366. /** Can be overridden to handle an incoming program change message.
  367. The base class implementation of this has no effect, but you may want to make your
  368. own synth react to program changes.
  369. */
  370. virtual void handleProgramChange (int midiChannel,
  371. int programNumber);
  372. //==============================================================================
  373. /** Tells the synthesiser what the sample rate is for the audio it's being used to render.
  374. This value is propagated to the voices so that they can use it to render the correct
  375. pitches.
  376. */
  377. virtual void setCurrentPlaybackSampleRate (double sampleRate);
  378. /** Creates the next block of audio output.
  379. This will process the next numSamples of data from all the voices, and add that output
  380. to the audio block supplied, starting from the offset specified. Note that the
  381. data will be added to the current contents of the buffer, so you should clear it
  382. before calling this method if necessary.
  383. The midi events in the inputMidi buffer are parsed for note and controller events,
  384. and these are used to trigger the voices. Note that the startSample offset applies
  385. both to the audio output buffer and the midi input buffer, so any midi events
  386. with timestamps outside the specified region will be ignored.
  387. */
  388. void renderNextBlock (AudioBuffer<float>& outputAudio,
  389. const MidiBuffer& inputMidi,
  390. int startSample,
  391. int numSamples);
  392. void renderNextBlock (AudioBuffer<double>& outputAudio,
  393. const MidiBuffer& inputMidi,
  394. int startSample,
  395. int numSamples);
  396. /** Returns the current target sample rate at which rendering is being done.
  397. Subclasses may need to know this so that they can pitch things correctly.
  398. */
  399. double getSampleRate() const noexcept { return sampleRate; }
  400. /** Sets a minimum limit on the size to which audio sub-blocks will be divided when rendering.
  401. When rendering, the audio blocks that are passed into renderNextBlock() will be split up
  402. into smaller blocks that lie between all the incoming midi messages, and it is these smaller
  403. sub-blocks that are rendered with multiple calls to renderVoices().
  404. Obviously in a pathological case where there are midi messages on every sample, then
  405. renderVoices() could be called once per sample and lead to poor performance, so this
  406. setting allows you to set a lower limit on the block size.
  407. The default setting is 32, which means that midi messages are accurate to about < 1ms
  408. accuracy, which is probably fine for most purposes, but you may want to increase or
  409. decrease this value for your synth.
  410. If shouldBeStrict is true, the audio sub-blocks will strictly never be smaller than numSamples.
  411. If shouldBeStrict is false (default), the first audio sub-block in the buffer is allowed
  412. to be smaller, to make sure that the first MIDI event in a buffer will always be sample-accurate
  413. (this can sometimes help to avoid quantisation or phasing issues).
  414. */
  415. void setMinimumRenderingSubdivisionSize (int numSamples, bool shouldBeStrict = false) noexcept;
  416. protected:
  417. //==============================================================================
  418. /** This is used to control access to the rendering callback and the note trigger methods. */
  419. CriticalSection lock;
  420. OwnedArray<SynthesiserVoice> voices;
  421. ReferenceCountedArray<SynthesiserSound> sounds;
  422. /** The last pitch-wheel values for each midi channel. */
  423. int lastPitchWheelValues [16];
  424. /** Renders the voices for the given range.
  425. By default this just calls renderNextBlock() on each voice, but you may need
  426. to override it to handle custom cases.
  427. */
  428. virtual void renderVoices (AudioBuffer<float>& outputAudio,
  429. int startSample, int numSamples);
  430. virtual void renderVoices (AudioBuffer<double>& outputAudio,
  431. int startSample, int numSamples);
  432. /** Searches through the voices to find one that's not currently playing, and
  433. which can play the given sound.
  434. Returns nullptr if all voices are busy and stealing isn't enabled.
  435. To implement a custom note-stealing algorithm, you can either override this
  436. method, or (preferably) override findVoiceToSteal().
  437. */
  438. virtual SynthesiserVoice* findFreeVoice (SynthesiserSound* soundToPlay,
  439. int midiChannel,
  440. int midiNoteNumber,
  441. bool stealIfNoneAvailable) const;
  442. /** Chooses a voice that is most suitable for being re-used.
  443. The default method will attempt to find the oldest voice that isn't the
  444. bottom or top note being played. If that's not suitable for your synth,
  445. you can override this method and do something more cunning instead.
  446. */
  447. virtual SynthesiserVoice* findVoiceToSteal (SynthesiserSound* soundToPlay,
  448. int midiChannel,
  449. int midiNoteNumber) const;
  450. /** Starts a specified voice playing a particular sound.
  451. You'll probably never need to call this, it's used internally by noteOn(), but
  452. may be needed by subclasses for custom behaviours.
  453. */
  454. void startVoice (SynthesiserVoice* voice,
  455. SynthesiserSound* sound,
  456. int midiChannel,
  457. int midiNoteNumber,
  458. float velocity);
  459. /** Stops a given voice.
  460. You should never need to call this, it's used internally by noteOff, but is protected
  461. in case it's useful for some custom subclasses. It basically just calls through to
  462. SynthesiserVoice::stopNote(), and has some assertions to sanity-check a few things.
  463. */
  464. void stopVoice (SynthesiserVoice*, float velocity, bool allowTailOff);
  465. /** Can be overridden to do custom handling of incoming midi events. */
  466. virtual void handleMidiEvent (const MidiMessage&);
  467. private:
  468. //==============================================================================
  469. double sampleRate = 0;
  470. uint32 lastNoteOnCounter = 0;
  471. int minimumSubBlockSize = 32;
  472. bool subBlockSubdivisionIsStrict = false;
  473. bool shouldStealNotes = true;
  474. BigInteger sustainPedalsDown;
  475. template <typename floatType>
  476. void processNextBlock (AudioBuffer<floatType>&, const MidiBuffer&, int startSample, int numSamples);
  477. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Synthesiser)
  478. };
  479. } // namespace juce