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.

634 lines
28KB

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