New Class to handle UI
[juce-lv2.git] / juce / source / src / audio / processors / juce_AudioProcessor.h
blobb679717ec0850487c71655c0549db42f5b58f8e6
1 /*
2 ==============================================================================
4 This file is part of the JUCE library - "Jules' Utility Class Extensions"
5 Copyright 2004-11 by Raw Material Software Ltd.
7 ------------------------------------------------------------------------------
9 JUCE can be redistributed and/or modified under the terms of the GNU General
10 Public License (Version 2), as published by the Free Software Foundation.
11 A copy of the license is included in the JUCE distribution, or can be found
12 online at www.gnu.org/licenses.
14 JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
15 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
16 A PARTICULAR PURPOSE. See the GNU General Public License for more details.
18 ------------------------------------------------------------------------------
20 To release a closed-source product which uses JUCE, commercial licenses are
21 available: visit www.rawmaterialsoftware.com/juce for more information.
23 ==============================================================================
26 #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
27 #define __JUCE_AUDIOPROCESSOR_JUCEHEADER__
29 #include "juce_AudioProcessorEditor.h"
30 #include "../dsp/juce_AudioSampleBuffer.h"
31 #include "../midi/juce_MidiBuffer.h"
32 #include "../../text/juce_XmlElement.h"
33 #include "../../maths/juce_BigInteger.h"
34 #include "juce_AudioProcessorListener.h"
35 #include "juce_AudioPlayHead.h"
38 //==============================================================================
39 /**
40 Base class for audio processing filters or plugins.
42 This is intended to act as a base class of audio filter that is general enough to
43 be wrapped as a VST, AU, RTAS, etc, or used internally.
45 It is also used by the plugin hosting code as the wrapper around an instance
46 of a loaded plugin.
48 Derive your filter class from this base class, and if you're building a plugin,
49 you should implement a global function called createPluginFilter() which creates
50 and returns a new instance of your subclass.
52 class JUCE_API AudioProcessor
54 protected:
55 //==============================================================================
56 /** Constructor.
58 You can also do your initialisation tasks in the initialiseFilterInfo()
59 call, which will be made after this object has been created.
61 AudioProcessor();
63 public:
64 /** Destructor. */
65 virtual ~AudioProcessor();
67 //==============================================================================
68 /** Returns the name of this processor.
70 virtual const String getName() const = 0;
72 //==============================================================================
73 /** Called before playback starts, to let the filter prepare itself.
75 The sample rate is the target sample rate, and will remain constant until
76 playback stops.
78 The estimatedSamplesPerBlock value is a HINT about the typical number of
79 samples that will be processed for each callback, but isn't any kind
80 of guarantee. The actual block sizes that the host uses may be different
81 each time the callback happens, and may be more or less than this value.
83 virtual void prepareToPlay (double sampleRate,
84 int estimatedSamplesPerBlock) = 0;
86 /** Called after playback has stopped, to let the filter free up any resources it
87 no longer needs.
89 virtual void releaseResources() = 0;
91 /** Renders the next block.
93 When this method is called, the buffer contains a number of channels which is
94 at least as great as the maximum number of input and output channels that
95 this filter is using. It will be filled with the filter's input data and
96 should be replaced with the filter's output.
98 So for example if your filter has 2 input channels and 4 output channels, then
99 the buffer will contain 4 channels, the first two being filled with the
100 input data. Your filter should read these, do its processing, and replace
101 the contents of all 4 channels with its output.
103 Or if your filter has 5 inputs and 2 outputs, the buffer will have 5 channels,
104 all filled with data, and your filter should overwrite the first 2 of these
105 with its output. But be VERY careful not to write anything to the last 3
106 channels, as these might be mapped to memory that the host assumes is read-only!
108 Note that if you have more outputs than inputs, then only those channels that
109 correspond to an input channel are guaranteed to contain sensible data - e.g.
110 in the case of 2 inputs and 4 outputs, the first two channels contain the input,
111 but the last two channels may contain garbage, so you should be careful not to
112 let this pass through without being overwritten or cleared.
114 Also note that the buffer may have more channels than are strictly necessary,
115 but your should only read/write from the ones that your filter is supposed to
116 be using.
118 The number of samples in these buffers is NOT guaranteed to be the same for every
119 callback, and may be more or less than the estimated value given to prepareToPlay().
120 Your code must be able to cope with variable-sized blocks, or you're going to get
121 clicks and crashes!
123 If the filter is receiving a midi input, then the midiMessages array will be filled
124 with the midi messages for this block. Each message's timestamp will indicate the
125 message's time, as a number of samples from the start of the block.
127 Any messages left in the midi buffer when this method has finished are assumed to
128 be the filter's midi output. This means that your filter should be careful to
129 clear any incoming messages from the array if it doesn't want them to be passed-on.
131 Be very careful about what you do in this callback - it's going to be called by
132 the audio thread, so any kind of interaction with the UI is absolutely
133 out of the question. If you change a parameter in here and need to tell your UI to
134 update itself, the best way is probably to inherit from a ChangeBroadcaster, let
135 the UI components register as listeners, and then call sendChangeMessage() inside the
136 processBlock() method to send out an asynchronous message. You could also use
137 the AsyncUpdater class in a similar way.
139 virtual void processBlock (AudioSampleBuffer& buffer,
140 MidiBuffer& midiMessages) = 0;
142 //==============================================================================
143 /** Returns the current AudioPlayHead object that should be used to find
144 out the state and position of the playhead.
146 You can call this from your processBlock() method, and use the AudioPlayHead
147 object to get the details about the time of the start of the block currently
148 being processed.
150 If the host hasn't supplied a playhead object, this will return 0.
152 AudioPlayHead* getPlayHead() const noexcept { return playHead; }
155 //==============================================================================
156 /** Returns the current sample rate.
158 This can be called from your processBlock() method - it's not guaranteed
159 to be valid at any other time, and may return 0 if it's unknown.
161 double getSampleRate() const noexcept { return sampleRate; }
163 /** Returns the current typical block size that is being used.
165 This can be called from your processBlock() method - it's not guaranteed
166 to be valid at any other time.
168 Remember it's not the ONLY block size that may be used when calling
169 processBlock, it's just the normal one. The actual block sizes used may be
170 larger or smaller than this, and will vary between successive calls.
172 int getBlockSize() const noexcept { return blockSize; }
174 //==============================================================================
175 /** Returns the number of input channels that the host will be sending the filter.
177 If writing a plugin, your JucePluginCharacteristics.h file should specify the
178 number of channels that your filter would prefer to have, and this method lets
179 you know how many the host is actually using.
181 Note that this method is only valid during or after the prepareToPlay()
182 method call. Until that point, the number of channels will be unknown.
184 int getNumInputChannels() const noexcept { return numInputChannels; }
186 /** Returns the number of output channels that the host will be sending the filter.
188 If writing a plugin, your JucePluginCharacteristics.h file should specify the
189 number of channels that your filter would prefer to have, and this method lets
190 you know how many the host is actually using.
192 Note that this method is only valid during or after the prepareToPlay()
193 method call. Until that point, the number of channels will be unknown.
195 int getNumOutputChannels() const noexcept { return numOutputChannels; }
197 /** Returns the name of one of the input channels, as returned by the host.
199 The host might not supply very useful names for channels, and this might be
200 something like "1", "2", "left", "right", etc.
202 virtual const String getInputChannelName (int channelIndex) const = 0;
204 /** Returns the name of one of the output channels, as returned by the host.
206 The host might not supply very useful names for channels, and this might be
207 something like "1", "2", "left", "right", etc.
209 virtual const String getOutputChannelName (int channelIndex) const = 0;
211 /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
212 virtual bool isInputChannelStereoPair (int index) const = 0;
214 /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
215 virtual bool isOutputChannelStereoPair (int index) const = 0;
217 /** This returns the number of samples delay that the filter imposes on the audio
218 passing through it.
220 The host will call this to find the latency - the filter itself should set this value
221 by calling setLatencySamples() as soon as it can during its initialisation.
223 int getLatencySamples() const noexcept { return latencySamples; }
225 /** The filter should call this to set the number of samples delay that it introduces.
227 The filter should call this as soon as it can during initialisation, and can call it
228 later if the value changes.
230 void setLatencySamples (int newLatency);
232 /** Returns true if the processor wants midi messages. */
233 virtual bool acceptsMidi() const = 0;
235 /** Returns true if the processor produces midi messages. */
236 virtual bool producesMidi() const = 0;
238 //==============================================================================
239 /** This returns a critical section that will automatically be locked while the host
240 is calling the processBlock() method.
242 Use it from your UI or other threads to lock access to variables that are used
243 by the process callback, but obviously be careful not to keep it locked for
244 too long, because that could cause stuttering playback. If you need to do something
245 that'll take a long time and need the processing to stop while it happens, use the
246 suspendProcessing() method instead.
248 @see suspendProcessing
250 const CriticalSection& getCallbackLock() const noexcept { return callbackLock; }
252 /** Enables and disables the processing callback.
254 If you need to do something time-consuming on a thread and would like to make sure
255 the audio processing callback doesn't happen until you've finished, use this
256 to disable the callback and re-enable it again afterwards.
258 E.g.
259 @code
260 void loadNewPatch()
262 suspendProcessing (true);
264 ..do something that takes ages..
266 suspendProcessing (false);
268 @endcode
270 If the host tries to make an audio callback while processing is suspended, the
271 filter will return an empty buffer, but won't block the audio thread like it would
272 do if you use the getCallbackLock() critical section to synchronise access.
274 If you're going to use this, your processBlock() method must call isSuspended() and
275 check whether it's suspended or not. If it is, then it should skip doing any real
276 processing, either emitting silence or passing the input through unchanged.
278 @see getCallbackLock
280 void suspendProcessing (bool shouldBeSuspended);
282 /** Returns true if processing is currently suspended.
283 @see suspendProcessing
285 bool isSuspended() const noexcept { return suspended; }
287 /** A plugin can override this to be told when it should reset any playing voices.
289 The default implementation does nothing, but a host may call this to tell the
290 plugin that it should stop any tails or sounds that have been left running.
292 virtual void reset();
294 //==============================================================================
295 /** Returns true if the processor is being run in an offline mode for rendering.
297 If the processor is being run live on realtime signals, this returns false.
298 If the mode is unknown, this will assume it's realtime and return false.
300 This value may be unreliable until the prepareToPlay() method has been called,
301 and could change each time prepareToPlay() is called.
303 @see setNonRealtime()
305 bool isNonRealtime() const noexcept { return nonRealtime; }
307 /** Called by the host to tell this processor whether it's being used in a non-realime
308 capacity for offline rendering or bouncing.
310 Whatever value is passed-in will be
312 void setNonRealtime (bool isNonRealtime) noexcept;
314 //==============================================================================
315 /** Creates the filter's UI.
317 This can return 0 if you want a UI-less filter, in which case the host may create
318 a generic UI that lets the user twiddle the parameters directly.
320 If you do want to pass back a component, the component should be created and set to
321 the correct size before returning it. If you implement this method, you must
322 also implement the hasEditor() method and make it return true.
324 Remember not to do anything silly like allowing your filter to keep a pointer to
325 the component that gets created - it could be deleted later without any warning, which
326 would make your pointer into a dangler. Use the getActiveEditor() method instead.
328 The correct way to handle the connection between an editor component and its
329 filter is to use something like a ChangeBroadcaster so that the editor can
330 register itself as a listener, and be told when a change occurs. This lets them
331 safely unregister themselves when they are deleted.
333 Here are a few things to bear in mind when writing an editor:
335 - Initially there won't be an editor, until the user opens one, or they might
336 not open one at all. Your filter mustn't rely on it being there.
337 - An editor object may be deleted and a replacement one created again at any time.
338 - It's safe to assume that an editor will be deleted before its filter.
340 @see hasEditor
342 virtual AudioProcessorEditor* createEditor() = 0;
344 /** Your filter must override this and return true if it can create an editor component.
345 @see createEditor
347 virtual bool hasEditor() const = 0;
349 //==============================================================================
350 /** Returns the active editor, if there is one.
352 Bear in mind this can return 0, even if an editor has previously been
353 opened.
355 AudioProcessorEditor* getActiveEditor() const noexcept { return activeEditor; }
357 /** Returns the active editor, or if there isn't one, it will create one.
359 This may call createEditor() internally to create the component.
361 AudioProcessorEditor* createEditorIfNeeded();
363 //==============================================================================
364 /** This must return the correct value immediately after the object has been
365 created, and mustn't change the number of parameters later.
367 virtual int getNumParameters() = 0;
369 /** Returns the name of a particular parameter. */
370 virtual const String getParameterName (int parameterIndex) = 0;
372 /** Called by the host to find out the value of one of the filter's parameters.
374 The host will expect the value returned to be between 0 and 1.0.
376 This could be called quite frequently, so try to make your code efficient.
377 It's also likely to be called by non-UI threads, so the code in here should
378 be thread-aware.
380 virtual float getParameter (int parameterIndex) = 0;
382 /** Returns the value of a parameter as a text string. */
383 virtual const String getParameterText (int parameterIndex) = 0;
385 /** The host will call this method to change the value of one of the filter's parameters.
387 The host may call this at any time, including during the audio processing
388 callback, so the filter has to process this very fast and avoid blocking.
390 If you want to set the value of a parameter internally, e.g. from your
391 editor component, then don't call this directly - instead, use the
392 setParameterNotifyingHost() method, which will also send a message to
393 the host telling it about the change. If the message isn't sent, the host
394 won't be able to automate your parameters properly.
396 The value passed will be between 0 and 1.0.
398 virtual void setParameter (int parameterIndex,
399 float newValue) = 0;
401 /** Your filter can call this when it needs to change one of its parameters.
403 This could happen when the editor or some other internal operation changes
404 a parameter. This method will call the setParameter() method to change the
405 value, and will then send a message to the host telling it about the change.
407 Note that to make sure the host correctly handles automation, you should call
408 the beginParameterChangeGesture() and endParameterChangeGesture() methods to
409 tell the host when the user has started and stopped changing the parameter.
411 void setParameterNotifyingHost (int parameterIndex,
412 float newValue);
414 /** Returns true if the host can automate this parameter.
416 By default, this returns true for all parameters.
418 virtual bool isParameterAutomatable (int parameterIndex) const;
420 /** Should return true if this parameter is a "meta" parameter.
422 A meta-parameter is a parameter that changes other params. It is used
423 by some hosts (e.g. AudioUnit hosts).
425 By default this returns false.
427 virtual bool isMetaParameter (int parameterIndex) const;
429 /** Sends a signal to the host to tell it that the user is about to start changing this
430 parameter.
432 This allows the host to know when a parameter is actively being held by the user, and
433 it may use this information to help it record automation.
435 If you call this, it must be matched by a later call to endParameterChangeGesture().
437 void beginParameterChangeGesture (int parameterIndex);
439 /** Tells the host that the user has finished changing this parameter.
441 This allows the host to know when a parameter is actively being held by the user, and
442 it may use this information to help it record automation.
444 A call to this method must follow a call to beginParameterChangeGesture().
446 void endParameterChangeGesture (int parameterIndex);
448 /** The filter can call this when something (apart from a parameter value) has changed.
450 It sends a hint to the host that something like the program, number of parameters,
451 etc, has changed, and that it should update itself.
453 void updateHostDisplay();
455 //==============================================================================
456 /** Returns the number of preset programs the filter supports.
458 The value returned must be valid as soon as this object is created, and
459 must not change over its lifetime.
461 This value shouldn't be less than 1.
463 virtual int getNumPrograms() = 0;
465 /** Returns the number of the currently active program.
467 virtual int getCurrentProgram() = 0;
469 /** Called by the host to change the current program.
471 virtual void setCurrentProgram (int index) = 0;
473 /** Must return the name of a given program. */
474 virtual const String getProgramName (int index) = 0;
476 /** Called by the host to rename a program.
478 virtual void changeProgramName (int index, const String& newName) = 0;
480 //==============================================================================
481 /** The host will call this method when it wants to save the filter's internal state.
483 This must copy any info about the filter's state into the block of memory provided,
484 so that the host can store this and later restore it using setStateInformation().
486 Note that there's also a getCurrentProgramStateInformation() method, which only
487 stores the current program, not the state of the entire filter.
489 See also the helper function copyXmlToBinary() for storing settings as XML.
491 @see getCurrentProgramStateInformation
493 virtual void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData) = 0;
495 /** The host will call this method if it wants to save the state of just the filter's
496 current program.
498 Unlike getStateInformation, this should only return the current program's state.
500 Not all hosts support this, and if you don't implement it, the base class
501 method just calls getStateInformation() instead. If you do implement it, be
502 sure to also implement getCurrentProgramStateInformation.
504 @see getStateInformation, setCurrentProgramStateInformation
506 virtual void getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
508 /** This must restore the filter's state from a block of data previously created
509 using getStateInformation().
511 Note that there's also a setCurrentProgramStateInformation() method, which tries
512 to restore just the current program, not the state of the entire filter.
514 See also the helper function getXmlFromBinary() for loading settings as XML.
516 @see setCurrentProgramStateInformation
518 virtual void setStateInformation (const void* data, int sizeInBytes) = 0;
520 /** The host will call this method if it wants to restore the state of just the filter's
521 current program.
523 Not all hosts support this, and if you don't implement it, the base class
524 method just calls setStateInformation() instead. If you do implement it, be
525 sure to also implement getCurrentProgramStateInformation.
527 @see setStateInformation, getCurrentProgramStateInformation
529 virtual void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
532 //==============================================================================
533 /** Adds a listener that will be called when an aspect of this processor changes. */
534 void addListener (AudioProcessorListener* newListener);
536 /** Removes a previously added listener. */
537 void removeListener (AudioProcessorListener* listenerToRemove);
539 //==============================================================================
540 /** Tells the processor to use this playhead object.
541 The processor will not take ownership of the object, so the caller must delete it when
542 it is no longer being used.
544 void setPlayHead (AudioPlayHead* newPlayHead) noexcept;
546 //==============================================================================
547 /** Not for public use - this is called before deleting an editor component. */
548 void editorBeingDeleted (AudioProcessorEditor* editor) noexcept;
550 /** Not for public use - this is called to initialise the processor before playing. */
551 void setPlayConfigDetails (int numIns, int numOuts,
552 double sampleRate,
553 int blockSize) noexcept;
555 protected:
556 //==============================================================================
557 /** Helper function that just converts an xml element into a binary blob.
559 Use this in your filter's getStateInformation() method if you want to
560 store its state as xml.
562 Then use getXmlFromBinary() to reverse this operation and retrieve the XML
563 from a binary blob.
565 static void copyXmlToBinary (const XmlElement& xml,
566 JUCE_NAMESPACE::MemoryBlock& destData);
568 /** Retrieves an XML element that was stored as binary with the copyXmlToBinary() method.
570 This might return 0 if the data's unsuitable or corrupted. Otherwise it will return
571 an XmlElement object that the caller must delete when no longer needed.
573 static XmlElement* getXmlFromBinary (const void* data, int sizeInBytes);
575 /** @internal */
576 AudioPlayHead* playHead;
578 /** @internal */
579 void sendParamChangeMessageToListeners (int parameterIndex, float newValue);
581 private:
582 Array <AudioProcessorListener*> listeners;
583 Component::SafePointer<AudioProcessorEditor> activeEditor;
584 double sampleRate;
585 int blockSize, numInputChannels, numOutputChannels, latencySamples;
586 bool suspended, nonRealtime;
587 CriticalSection callbackLock, listenerLock;
589 #if JUCE_DEBUG
590 BigInteger changingParams;
591 #endif
593 JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioProcessor);
597 #endif // __JUCE_AUDIOPROCESSOR_JUCEHEADER__