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.

623 lines
27KB

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