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.

juce_Synthesiser.h 21KB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  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. protected:
  151. //==============================================================================
  152. /** Returns the current target sample rate at which rendering is being done.
  153. This is available for subclasses so they can pitch things correctly.
  154. */
  155. double getSampleRate() const { return currentSampleRate; }
  156. /** Resets the state of this voice after a sound has finished playing.
  157. The subclass must call this when it finishes playing a note and becomes available
  158. to play new ones.
  159. It must either call it in the stopNote() method, or if the voice is tailing off,
  160. then it should call it later during the renderNextBlock method, as soon as it
  161. finishes its tail-off.
  162. It can also be called at any time during the render callback if the sound happens
  163. to have finished, e.g. if it's playing a sample and the sample finishes.
  164. */
  165. void clearCurrentNote();
  166. private:
  167. //==============================================================================
  168. friend class Synthesiser;
  169. double currentSampleRate;
  170. int currentlyPlayingNote;
  171. uint32 noteOnTime;
  172. SynthesiserSound::Ptr currentlyPlayingSound;
  173. bool keyIsDown, sostenutoPedalDown;
  174. JUCE_LEAK_DETECTOR (SynthesiserVoice)
  175. };
  176. //==============================================================================
  177. /**
  178. Base class for a musical device that can play sounds.
  179. To create a synthesiser, you'll need to create a subclass of SynthesiserSound
  180. to describe each sound available to your synth, and a subclass of SynthesiserVoice
  181. which can play back one of these sounds.
  182. Then you can use the addVoice() and addSound() methods to give the synthesiser a
  183. set of sounds, and a set of voices it can use to play them. If you only give it
  184. one voice it will be monophonic - the more voices it has, the more polyphony it'll
  185. have available.
  186. Then repeatedly call the renderNextBlock() method to produce the audio. Any midi
  187. events that go in will be scanned for note on/off messages, and these are used to
  188. start and stop the voices playing the appropriate sounds.
  189. While it's playing, you can also cause notes to be triggered by calling the noteOn(),
  190. noteOff() and other controller methods.
  191. Before rendering, be sure to call the setCurrentPlaybackSampleRate() to tell it
  192. what the target playback rate is. This value is passed on to the voices so that
  193. they can pitch their output correctly.
  194. */
  195. class JUCE_API Synthesiser
  196. {
  197. public:
  198. //==============================================================================
  199. /** Creates a new synthesiser.
  200. You'll need to add some sounds and voices before it'll make any sound..
  201. */
  202. Synthesiser();
  203. /** Destructor. */
  204. virtual ~Synthesiser();
  205. //==============================================================================
  206. /** Deletes all voices. */
  207. void clearVoices();
  208. /** Returns the number of voices that have been added. */
  209. int getNumVoices() const noexcept { return voices.size(); }
  210. /** Returns one of the voices that have been added. */
  211. SynthesiserVoice* getVoice (int index) const;
  212. /** Adds a new voice to the synth.
  213. All the voices should be the same class of object and are treated equally.
  214. The object passed in will be managed by the synthesiser, which will delete
  215. it later on when no longer needed. The caller should not retain a pointer to the
  216. voice.
  217. */
  218. void addVoice (SynthesiserVoice* newVoice);
  219. /** Deletes one of the voices. */
  220. void removeVoice (int index);
  221. //==============================================================================
  222. /** Deletes all sounds. */
  223. void clearSounds();
  224. /** Returns the number of sounds that have been added to the synth. */
  225. int getNumSounds() const noexcept { return sounds.size(); }
  226. /** Returns one of the sounds. */
  227. SynthesiserSound* getSound (int index) const noexcept { return sounds [index]; }
  228. /** Adds a new sound to the synthesiser.
  229. The object passed in is reference counted, so will be deleted when it is removed
  230. from the synthesiser, and when no voices are still using it.
  231. */
  232. void addSound (const SynthesiserSound::Ptr& newSound);
  233. /** Removes and deletes one of the sounds. */
  234. void removeSound (int index);
  235. //==============================================================================
  236. /** If set to true, then the synth will try to take over an existing voice if
  237. it runs out and needs to play another note.
  238. The value of this boolean is passed into findFreeVoice(), so the result will
  239. depend on the implementation of this method.
  240. */
  241. void setNoteStealingEnabled (bool shouldStealNotes);
  242. /** Returns true if note-stealing is enabled.
  243. @see setNoteStealingEnabled
  244. */
  245. bool isNoteStealingEnabled() const noexcept { return shouldStealNotes; }
  246. //==============================================================================
  247. /** Triggers a note-on event.
  248. The default method here will find all the sounds that want to be triggered by
  249. this note/channel. For each sound, it'll try to find a free voice, and use the
  250. voice to start playing the sound.
  251. Subclasses might want to override this if they need a more complex algorithm.
  252. This method will be called automatically according to the midi data passed into
  253. renderNextBlock(), but may be called explicitly too.
  254. The midiChannel parameter is the channel, between 1 and 16 inclusive.
  255. */
  256. virtual void noteOn (int midiChannel,
  257. int midiNoteNumber,
  258. float velocity);
  259. /** Triggers a note-off event.
  260. This will turn off any voices that are playing a sound for the given note/channel.
  261. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  262. (if they can do). If this is false, the notes will all be cut off immediately.
  263. This method will be called automatically according to the midi data passed into
  264. renderNextBlock(), but may be called explicitly too.
  265. The midiChannel parameter is the channel, between 1 and 16 inclusive.
  266. */
  267. virtual void noteOff (int midiChannel,
  268. int midiNoteNumber,
  269. bool allowTailOff);
  270. /** Turns off all notes.
  271. This will turn off any voices that are playing a sound on the given midi channel.
  272. If midiChannel is 0 or less, then all voices will be turned off, regardless of
  273. which channel they're playing. Otherwise it represents a valid midi channel, from
  274. 1 to 16 inclusive.
  275. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  276. (if they can do). If this is false, the notes will all be cut off immediately.
  277. This method will be called automatically according to the midi data passed into
  278. renderNextBlock(), but may be called explicitly too.
  279. */
  280. virtual void allNotesOff (int midiChannel,
  281. bool allowTailOff);
  282. /** Sends a pitch-wheel message to any active voices.
  283. This will send a pitch-wheel message to any voices that are playing sounds on
  284. the given midi channel.
  285. This method will be called automatically according to the midi data passed into
  286. renderNextBlock(), but may be called explicitly too.
  287. @param midiChannel the midi channel, from 1 to 16 inclusive
  288. @param wheelValue the wheel position, from 0 to 0x3fff, as returned by MidiMessage::getPitchWheelValue()
  289. */
  290. virtual void handlePitchWheel (int midiChannel,
  291. int wheelValue);
  292. /** Sends a midi controller message to any active voices.
  293. This will send a midi controller message to any voices that are playing sounds on
  294. the given midi channel.
  295. This method will be called automatically according to the midi data passed into
  296. renderNextBlock(), but may be called explicitly too.
  297. @param midiChannel the midi channel, from 1 to 16 inclusive
  298. @param controllerNumber the midi controller type, as returned by MidiMessage::getControllerNumber()
  299. @param controllerValue the midi controller value, between 0 and 127, as returned by MidiMessage::getControllerValue()
  300. */
  301. virtual void handleController (int midiChannel,
  302. int controllerNumber,
  303. int controllerValue);
  304. /** Sends an aftertouch message.
  305. This will send an aftertouch message to any voices that are playing sounds on
  306. the given midi channel and note number.
  307. This method will be called automatically according to the midi data passed into
  308. renderNextBlock(), but may be called explicitly too.
  309. @param midiChannel the midi channel, from 1 to 16 inclusive
  310. @param midiNoteNumber the midi note number, 0 to 127
  311. @param aftertouchValue the aftertouch value, between 0 and 127,
  312. as returned by MidiMessage::getAftertouchValue()
  313. */
  314. virtual void handleAftertouch (int midiChannel, int midiNoteNumber, int aftertouchValue);
  315. /** Handles a sustain pedal event. */
  316. virtual void handleSustainPedal (int midiChannel, bool isDown);
  317. /** Handles a sostenuto pedal event. */
  318. virtual void handleSostenutoPedal (int midiChannel, bool isDown);
  319. /** Can be overridden to handle soft pedal events. */
  320. virtual void handleSoftPedal (int midiChannel, bool isDown);
  321. //==============================================================================
  322. /** Tells the synthesiser what the sample rate is for the audio it's being used to render.
  323. This value is propagated to the voices so that they can use it to render the correct
  324. pitches.
  325. */
  326. void setCurrentPlaybackSampleRate (double sampleRate);
  327. /** Creates the next block of audio output.
  328. This will process the next numSamples of data from all the voices, and add that output
  329. to the audio block supplied, starting from the offset specified. Note that the
  330. data will be added to the current contents of the buffer, so you should clear it
  331. before calling this method if necessary.
  332. The midi events in the inputMidi buffer are parsed for note and controller events,
  333. and these are used to trigger the voices. Note that the startSample offset applies
  334. both to the audio output buffer and the midi input buffer, so any midi events
  335. with timestamps outside the specified region will be ignored.
  336. */
  337. void renderNextBlock (AudioSampleBuffer& outputAudio,
  338. const MidiBuffer& inputMidi,
  339. int startSample,
  340. int numSamples);
  341. protected:
  342. //==============================================================================
  343. /** This is used to control access to the rendering callback and the note trigger methods. */
  344. CriticalSection lock;
  345. OwnedArray<SynthesiserVoice> voices;
  346. ReferenceCountedArray<SynthesiserSound> sounds;
  347. /** The last pitch-wheel values for each midi channel. */
  348. int lastPitchWheelValues [16];
  349. /** Searches through the voices to find one that's not currently playing, and which
  350. can play the given sound.
  351. Returns nullptr if all voices are busy and stealing isn't enabled.
  352. This can be overridden to implement custom voice-stealing algorithms.
  353. */
  354. virtual SynthesiserVoice* findFreeVoice (SynthesiserSound* soundToPlay,
  355. const bool stealIfNoneAvailable) const;
  356. /** Starts a specified voice playing a particular sound.
  357. You'll probably never need to call this, it's used internally by noteOn(), but
  358. may be needed by subclasses for custom behaviours.
  359. */
  360. void startVoice (SynthesiserVoice* voice,
  361. SynthesiserSound* sound,
  362. int midiChannel,
  363. int midiNoteNumber,
  364. float velocity);
  365. /** Can be overridden to do custom handling of incoming midi events. */
  366. virtual void handleMidiEvent (const MidiMessage&);
  367. private:
  368. //==============================================================================
  369. double sampleRate;
  370. uint32 lastNoteOnCounter;
  371. bool shouldStealNotes;
  372. BigInteger sustainPedalsDown;
  373. void stopVoice (SynthesiserVoice*, bool allowTailOff);
  374. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  375. // Note the new parameters for this method.
  376. virtual int findFreeVoice (const bool) const { return 0; }
  377. #endif
  378. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Synthesiser)
  379. };
  380. #endif // JUCE_SYNTHESISER_H_INCLUDED