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.

526 lines
22KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2013 - Raw Material Software Ltd.
  5. Permission is granted to use this software under the terms of either:
  6. a) the GPL v2 (or any later version)
  7. b) the Affero GPL v3
  8. Details of these licenses can be found at: www.gnu.org/licenses
  9. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  11. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. ------------------------------------------------------------------------------
  13. To release a closed-source product which uses JUCE, commercial licenses are
  14. available: visit www.juce.com for more information.
  15. ==============================================================================
  16. */
  17. #ifndef JUCE_SYNTHESISER_H_INCLUDED
  18. #define JUCE_SYNTHESISER_H_INCLUDED
  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. */
  29. class JUCE_API SynthesiserSound : public ReferenceCountedObject
  30. {
  31. protected:
  32. //==============================================================================
  33. SynthesiserSound();
  34. public:
  35. /** Destructor. */
  36. virtual ~SynthesiserSound();
  37. //==============================================================================
  38. /** Returns true if this sound should be played when a given midi note is pressed.
  39. The Synthesiser will use this information when deciding which sounds to trigger
  40. for a given note.
  41. */
  42. virtual bool appliesToNote (const int midiNoteNumber) = 0;
  43. /** Returns true if the sound should be triggered by midi events on a given channel.
  44. The Synthesiser will use this information when deciding which sounds to trigger
  45. for a given note.
  46. */
  47. virtual bool appliesToChannel (const int midiChannel) = 0;
  48. /** The class is reference-counted, so this is a handy pointer class for it. */
  49. typedef ReferenceCountedObjectPtr<SynthesiserSound> Ptr;
  50. private:
  51. //==============================================================================
  52. JUCE_LEAK_DETECTOR (SynthesiserSound)
  53. };
  54. //==============================================================================
  55. /**
  56. Represents a voice that a Synthesiser can use to play a SynthesiserSound.
  57. A voice plays a single sound at a time, and a synthesiser holds an array of
  58. voices so that it can play polyphonically.
  59. @see Synthesiser, SynthesiserSound
  60. */
  61. class JUCE_API SynthesiserVoice
  62. {
  63. public:
  64. //==============================================================================
  65. /** Creates a voice. */
  66. SynthesiserVoice();
  67. /** Destructor. */
  68. virtual ~SynthesiserVoice();
  69. //==============================================================================
  70. /** Returns the midi note that this voice is currently playing.
  71. Returns a value less than 0 if no note is playing.
  72. */
  73. int getCurrentlyPlayingNote() const noexcept { return currentlyPlayingNote; }
  74. /** Returns the sound that this voice is currently playing.
  75. Returns nullptr if it's not playing.
  76. */
  77. SynthesiserSound::Ptr getCurrentlyPlayingSound() const noexcept { return currentlyPlayingSound; }
  78. /** Must return true if this voice object is capable of playing the given sound.
  79. If there are different classes of sound, and different classes of voice, a voice can
  80. choose which ones it wants to take on.
  81. A typical implementation of this method may just return true if there's only one type
  82. of voice and sound, or it might check the type of the sound object passed-in and
  83. see if it's one that it understands.
  84. */
  85. virtual bool canPlaySound (SynthesiserSound*) = 0;
  86. /** Called to start a new note.
  87. This will be called during the rendering callback, so must be fast and thread-safe.
  88. */
  89. virtual void startNote (int midiNoteNumber,
  90. float velocity,
  91. SynthesiserSound* sound,
  92. int currentPitchWheelPosition) = 0;
  93. /** Called to stop a note.
  94. This will be called during the rendering callback, so must be fast and thread-safe.
  95. If allowTailOff is false or the voice doesn't want to tail-off, then it must stop all
  96. sound immediately, and must call clearCurrentNote() to reset the state of this voice
  97. and allow the synth to reassign it another sound.
  98. If allowTailOff is true and the voice decides to do a tail-off, then it's allowed to
  99. begin fading out its sound, and it can stop playing until it's finished. As soon as it
  100. finishes playing (during the rendering callback), it must make sure that it calls
  101. clearCurrentNote().
  102. */
  103. virtual void stopNote (bool allowTailOff) = 0;
  104. /** Called to let the voice know that the pitch wheel has been moved.
  105. This will be called during the rendering callback, so must be fast and thread-safe.
  106. */
  107. virtual void pitchWheelMoved (int newPitchWheelValue) = 0;
  108. /** Called to let the voice know that a midi controller has been moved.
  109. This will be called during the rendering callback, so must be fast and thread-safe.
  110. */
  111. virtual void controllerMoved (int controllerNumber, int newControllerValue) = 0;
  112. /** Called to let the voice know that the aftertouch has changed.
  113. This will be called during the rendering callback, so must be fast and thread-safe.
  114. */
  115. virtual void aftertouchChanged (int newAftertouchValue);
  116. //==============================================================================
  117. /** Renders the next block of data for this voice.
  118. The output audio data must be added to the current contents of the buffer provided.
  119. Only the region of the buffer between startSample and (startSample + numSamples)
  120. should be altered by this method.
  121. If the voice is currently silent, it should just return without doing anything.
  122. If the sound that the voice is playing finishes during the course of this rendered
  123. block, it must call clearCurrentNote(), to tell the synthesiser that it has finished.
  124. The size of the blocks that are rendered can change each time it is called, and may
  125. involve rendering as little as 1 sample at a time. In between rendering callbacks,
  126. the voice's methods will be called to tell it about note and controller events.
  127. */
  128. virtual void renderNextBlock (AudioSampleBuffer& outputBuffer,
  129. int startSample,
  130. int numSamples) = 0;
  131. /** Returns true if the voice is currently playing a sound which is mapped to the given
  132. midi channel.
  133. If it's not currently playing, this will return false.
  134. */
  135. bool isPlayingChannel (int midiChannel) const;
  136. /** Changes the voice's reference sample rate.
  137. The rate is set so that subclasses know the output rate and can set their pitch
  138. accordingly.
  139. This method is called by the synth, and subclasses can access the current rate with
  140. the currentSampleRate member.
  141. */
  142. void setCurrentPlaybackSampleRate (double newRate);
  143. /** Returns true if the key that triggered this voice is still held down.
  144. Note that the voice may still be playing after the key was released (e.g because the
  145. sostenuto pedal is down).
  146. */
  147. bool isKeyDown() const noexcept { return keyIsDown; }
  148. /** Returns true if the sostenuto pedal is currently active for this voice. */
  149. bool isSostenutoPedalDown() const noexcept { return sostenutoPedalDown; }
  150. /** Returns true if this voice started playing its current note before the other voice did. */
  151. bool wasStartedBefore (const SynthesiserVoice& other) const noexcept;
  152. protected:
  153. //==============================================================================
  154. /** Returns the current target sample rate at which rendering is being done.
  155. This is available for subclasses so they can pitch things correctly.
  156. */
  157. double getSampleRate() const { return currentSampleRate; }
  158. /** Resets the state of this voice after a sound has finished playing.
  159. The subclass must call this when it finishes playing a note and becomes available
  160. to play new ones.
  161. It must either call it in the stopNote() method, or if the voice is tailing off,
  162. then it should call it later during the renderNextBlock method, as soon as it
  163. finishes its tail-off.
  164. It can also be called at any time during the render callback if the sound happens
  165. to have finished, e.g. if it's playing a sample and the sample finishes.
  166. */
  167. void clearCurrentNote();
  168. private:
  169. //==============================================================================
  170. friend class Synthesiser;
  171. double currentSampleRate;
  172. int currentlyPlayingNote;
  173. uint32 noteOnTime;
  174. SynthesiserSound::Ptr currentlyPlayingSound;
  175. bool keyIsDown, sostenutoPedalDown;
  176. JUCE_LEAK_DETECTOR (SynthesiserVoice)
  177. };
  178. //==============================================================================
  179. /**
  180. Base class for a musical device that can play sounds.
  181. To create a synthesiser, you'll need to create a subclass of SynthesiserSound
  182. to describe each sound available to your synth, and a subclass of SynthesiserVoice
  183. which can play back one of these sounds.
  184. Then you can use the addVoice() and addSound() methods to give the synthesiser a
  185. set of sounds, and a set of voices it can use to play them. If you only give it
  186. one voice it will be monophonic - the more voices it has, the more polyphony it'll
  187. have available.
  188. Then repeatedly call the renderNextBlock() method to produce the audio. Any midi
  189. events that go in will be scanned for note on/off messages, and these are used to
  190. start and stop the voices playing the appropriate sounds.
  191. While it's playing, you can also cause notes to be triggered by calling the noteOn(),
  192. noteOff() and other controller methods.
  193. Before rendering, be sure to call the setCurrentPlaybackSampleRate() to tell it
  194. what the target playback rate is. This value is passed on to the voices so that
  195. they can pitch their output correctly.
  196. */
  197. class JUCE_API Synthesiser
  198. {
  199. public:
  200. //==============================================================================
  201. /** Creates a new synthesiser.
  202. You'll need to add some sounds and voices before it'll make any sound..
  203. */
  204. Synthesiser();
  205. /** Destructor. */
  206. virtual ~Synthesiser();
  207. //==============================================================================
  208. /** Deletes all voices. */
  209. void clearVoices();
  210. /** Returns the number of voices that have been added. */
  211. int getNumVoices() const noexcept { return voices.size(); }
  212. /** Returns one of the voices that have been added. */
  213. SynthesiserVoice* getVoice (int index) const;
  214. /** Adds a new voice to the synth.
  215. All the voices should be the same class of object and are treated equally.
  216. The object passed in will be managed by the synthesiser, which will delete
  217. it later on when no longer needed. The caller should not retain a pointer to the
  218. voice.
  219. */
  220. SynthesiserVoice* addVoice (SynthesiserVoice* newVoice);
  221. /** Deletes one of the voices. */
  222. void removeVoice (int index);
  223. //==============================================================================
  224. /** Deletes all sounds. */
  225. void clearSounds();
  226. /** Returns the number of sounds that have been added to the synth. */
  227. int getNumSounds() const noexcept { return sounds.size(); }
  228. /** Returns one of the sounds. */
  229. SynthesiserSound* getSound (int index) const noexcept { return sounds [index]; }
  230. /** Adds a new sound to the synthesiser.
  231. The object passed in is reference counted, so will be deleted when the
  232. synthesiser and all voices are no longer using it.
  233. */
  234. SynthesiserSound* addSound (const SynthesiserSound::Ptr& newSound);
  235. /** Removes and deletes one of the sounds. */
  236. void removeSound (int index);
  237. //==============================================================================
  238. /** If set to true, then the synth will try to take over an existing voice if
  239. it runs out and needs to play another note.
  240. The value of this boolean is passed into findFreeVoice(), so the result will
  241. depend on the implementation of this method.
  242. */
  243. void setNoteStealingEnabled (bool shouldStealNotes);
  244. /** Returns true if note-stealing is enabled.
  245. @see setNoteStealingEnabled
  246. */
  247. bool isNoteStealingEnabled() const noexcept { return shouldStealNotes; }
  248. //==============================================================================
  249. /** Triggers a note-on event.
  250. The default method here will find all the sounds that want to be triggered by
  251. this note/channel. For each sound, it'll try to find a free voice, and use the
  252. voice to start playing the sound.
  253. Subclasses might want to override this if they need a more complex algorithm.
  254. This method will be called automatically according to the midi data passed into
  255. renderNextBlock(), but may be called explicitly too.
  256. The midiChannel parameter is the channel, between 1 and 16 inclusive.
  257. */
  258. virtual void noteOn (int midiChannel,
  259. int midiNoteNumber,
  260. float velocity);
  261. /** Triggers a note-off event.
  262. This will turn off any voices that are playing a sound for the given note/channel.
  263. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  264. (if they can do). If this is false, the notes will all be cut off immediately.
  265. This method will be called automatically according to the midi data passed into
  266. renderNextBlock(), but may be called explicitly too.
  267. The midiChannel parameter is the channel, between 1 and 16 inclusive.
  268. */
  269. virtual void noteOff (int midiChannel,
  270. int midiNoteNumber,
  271. bool allowTailOff);
  272. /** Turns off all notes.
  273. This will turn off any voices that are playing a sound on the given midi channel.
  274. If midiChannel is 0 or less, then all voices will be turned off, regardless of
  275. which channel they're playing. Otherwise it represents a valid midi channel, from
  276. 1 to 16 inclusive.
  277. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  278. (if they can do). If this is false, the notes will all be cut off immediately.
  279. This method will be called automatically according to the midi data passed into
  280. renderNextBlock(), but may be called explicitly too.
  281. */
  282. virtual void allNotesOff (int midiChannel,
  283. bool allowTailOff);
  284. /** Sends a pitch-wheel message to any active voices.
  285. This will send a pitch-wheel message to any voices that are playing sounds on
  286. the given midi channel.
  287. This method will be called automatically according to the midi data passed into
  288. renderNextBlock(), but may be called explicitly too.
  289. @param midiChannel the midi channel, from 1 to 16 inclusive
  290. @param wheelValue the wheel position, from 0 to 0x3fff, as returned by MidiMessage::getPitchWheelValue()
  291. */
  292. virtual void handlePitchWheel (int midiChannel,
  293. int wheelValue);
  294. /** Sends a midi controller message to any active voices.
  295. This will send a midi controller message to any voices that are playing sounds on
  296. the given midi channel.
  297. This method will be called automatically according to the midi data passed into
  298. renderNextBlock(), but may be called explicitly too.
  299. @param midiChannel the midi channel, from 1 to 16 inclusive
  300. @param controllerNumber the midi controller type, as returned by MidiMessage::getControllerNumber()
  301. @param controllerValue the midi controller value, between 0 and 127, as returned by MidiMessage::getControllerValue()
  302. */
  303. virtual void handleController (int midiChannel,
  304. int controllerNumber,
  305. int controllerValue);
  306. /** Sends an aftertouch message.
  307. This will send an aftertouch message to any voices that are playing sounds on
  308. the given midi channel and note number.
  309. This method will be called automatically according to the midi data passed into
  310. renderNextBlock(), but may be called explicitly too.
  311. @param midiChannel the midi channel, from 1 to 16 inclusive
  312. @param midiNoteNumber the midi note number, 0 to 127
  313. @param aftertouchValue the aftertouch value, between 0 and 127,
  314. as returned by MidiMessage::getAftertouchValue()
  315. */
  316. virtual void handleAftertouch (int midiChannel, int midiNoteNumber, int aftertouchValue);
  317. /** Handles a sustain pedal event. */
  318. virtual void handleSustainPedal (int midiChannel, bool isDown);
  319. /** Handles a sostenuto pedal event. */
  320. virtual void handleSostenutoPedal (int midiChannel, bool isDown);
  321. /** Can be overridden to handle soft pedal events. */
  322. virtual void handleSoftPedal (int midiChannel, bool isDown);
  323. //==============================================================================
  324. /** Tells the synthesiser what the sample rate is for the audio it's being used to render.
  325. This value is propagated to the voices so that they can use it to render the correct
  326. pitches.
  327. */
  328. void setCurrentPlaybackSampleRate (double sampleRate);
  329. /** Creates the next block of audio output.
  330. This will process the next numSamples of data from all the voices, and add that output
  331. to the audio block supplied, starting from the offset specified. Note that the
  332. data will be added to the current contents of the buffer, so you should clear it
  333. before calling this method if necessary.
  334. The midi events in the inputMidi buffer are parsed for note and controller events,
  335. and these are used to trigger the voices. Note that the startSample offset applies
  336. both to the audio output buffer and the midi input buffer, so any midi events
  337. with timestamps outside the specified region will be ignored.
  338. */
  339. void renderNextBlock (AudioSampleBuffer& outputAudio,
  340. const MidiBuffer& inputMidi,
  341. int startSample,
  342. int numSamples);
  343. protected:
  344. //==============================================================================
  345. /** This is used to control access to the rendering callback and the note trigger methods. */
  346. CriticalSection lock;
  347. OwnedArray<SynthesiserVoice> voices;
  348. ReferenceCountedArray<SynthesiserSound> sounds;
  349. /** The last pitch-wheel values for each midi channel. */
  350. int lastPitchWheelValues [16];
  351. /** Searches through the voices to find one that's not currently playing, and which
  352. can play the given sound.
  353. Returns nullptr if all voices are busy and stealing isn't enabled.
  354. This can be overridden to implement custom voice-stealing algorithms.
  355. */
  356. virtual SynthesiserVoice* findFreeVoice (SynthesiserSound* soundToPlay,
  357. const bool stealIfNoneAvailable) const;
  358. /** Chooses a voice that is most suitable for being re-used.
  359. The default method returns the one that has been playing for the longest, but
  360. you may want to override this and do something more cunning instead.
  361. */
  362. virtual SynthesiserVoice* findVoiceToSteal (SynthesiserSound* soundToPlay) const;
  363. /** Starts a specified voice playing a particular sound.
  364. You'll probably never need to call this, it's used internally by noteOn(), but
  365. may be needed by subclasses for custom behaviours.
  366. */
  367. void startVoice (SynthesiserVoice* voice,
  368. SynthesiserSound* sound,
  369. int midiChannel,
  370. int midiNoteNumber,
  371. float velocity);
  372. /** Can be overridden to do custom handling of incoming midi events. */
  373. virtual void handleMidiEvent (const MidiMessage&);
  374. private:
  375. //==============================================================================
  376. double sampleRate;
  377. uint32 lastNoteOnCounter;
  378. bool shouldStealNotes;
  379. BigInteger sustainPedalsDown;
  380. void stopVoice (SynthesiserVoice*, bool allowTailOff);
  381. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  382. // Note the new parameters for this method.
  383. virtual int findFreeVoice (const bool) const { return 0; }
  384. #endif
  385. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Synthesiser)
  386. };
  387. #endif // JUCE_SYNTHESISER_H_INCLUDED