1 /*
2   ==============================================================================
3 
4    This file is part of the JUCE library.
5    Copyright (c) 2020 - Raw Material Software Limited
6 
7    JUCE is an open source library subject to commercial or open-source
8    licensing.
9 
10    By using JUCE, you agree to the terms of both the JUCE 6 End-User License
11    Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
12 
13    End User License Agreement: www.juce.com/juce-6-licence
14    Privacy Policy: www.juce.com/juce-privacy-policy
15 
16    Or: You may also use this code under the terms of the GPL v3 (see
17    www.gnu.org/licenses).
18 
19    JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
20    EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
21    DISCLAIMED.
22 
23   ==============================================================================
24 */
25 
26 namespace juce
27 {
28 
29 //==============================================================================
30 /**
31     Base class for audio processing classes or plugins.
32 
33     This is intended to act as a base class of audio processor that is general enough
34     to be wrapped as a VST, AU, RTAS, etc, or used internally.
35 
36     It is also used by the plugin hosting code as the wrapper around an instance
37     of a loaded plugin.
38 
39     You should derive your own class from this base class, and if you're building a
40     plugin, you should implement a global function called createPluginFilter() which
41     creates and returns a new instance of your subclass.
42 
43     @tags{Audio}
44 */
45 class JUCE_API  AudioProcessor
46 {
47 protected:
48     struct BusesProperties;
49 
50     //==============================================================================
51     /** Constructor.
52 
53         This constructor will create a main input and output bus which are disabled
54         by default. If you need more fine-grained control then use the other constructors.
55     */
56     AudioProcessor();
57 
58     /** Constructor for multi-bus AudioProcessors
59 
60         If your AudioProcessor supports multiple buses than use this constructor
61         to initialise the bus layouts and bus names of your plug-in.
62     */
63     AudioProcessor (const BusesProperties& ioLayouts);
64 
65     /** Constructor for AudioProcessors which use layout maps
66         If your AudioProcessor uses layout maps then use this constructor.
67     */
AudioProcessor(const std::initializer_list<const short[2]> & channelLayoutList)68     AudioProcessor (const std::initializer_list<const short[2]>& channelLayoutList)
69         : AudioProcessor (busesPropertiesFromLayoutArray (layoutListToArray (channelLayoutList)))
70     {
71     }
72 
73 public:
74     //==============================================================================
75     enum ProcessingPrecision
76     {
77         singlePrecision,
78         doublePrecision
79     };
80 
81     using ChangeDetails = AudioProcessorListener::ChangeDetails;
82 
83     //==============================================================================
84     /** Destructor. */
85     virtual ~AudioProcessor();
86 
87     //==============================================================================
88     /** Returns the name of this processor. */
89     virtual const String getName() const = 0;
90 
91     /** Returns a list of alternative names to use for this processor.
92 
93         Some hosts truncate the name of your AudioProcessor when there isn't enough
94         space in the GUI to show the full name. Overriding this method, allows the host
95         to choose an alternative name (such as an abbreviation) to better fit the
96         available space.
97     */
98     virtual StringArray getAlternateDisplayNames() const;
99 
100     //==============================================================================
101     /** Called before playback starts, to let the processor prepare itself.
102 
103         The sample rate is the target sample rate, and will remain constant until
104         playback stops.
105 
106         You can call getTotalNumInputChannels and getTotalNumOutputChannels
107         or query the busLayout member variable to find out the number of
108         channels your processBlock callback must process.
109 
110         The maximumExpectedSamplesPerBlock value is a strong hint about the maximum
111         number of samples that will be provided in each block. You may want to use
112         this value to resize internal buffers. You should program defensively in
113         case a buggy host exceeds this value. The actual block sizes that the host
114         uses may be different each time the callback happens: completely variable
115         block sizes can be expected from some hosts.
116 
117        @see busLayout, getTotalNumInputChannels, getTotalNumOutputChannels
118     */
119     virtual void prepareToPlay (double sampleRate,
120                                 int maximumExpectedSamplesPerBlock) = 0;
121 
122     /** Called after playback has stopped, to let the object free up any resources it
123         no longer needs.
124     */
125     virtual void releaseResources() = 0;
126 
127     /** Called by the host to indicate that you should reduce your memory footprint.
128 
129         You should override this method to free up some memory gracefully, if possible,
130         otherwise the host may forcibly unload your AudioProcessor.
131 
132         At the moment this method is only called when your AudioProcessor is an AUv3
133         plug-in running on iOS.
134     */
memoryWarningReceived()135     virtual void memoryWarningReceived()     { jassertfalse; }
136 
137     /** Renders the next block.
138 
139         When this method is called, the buffer contains a number of channels which is
140         at least as great as the maximum number of input and output channels that
141         this processor is using. It will be filled with the processor's input data and
142         should be replaced with the processor's output.
143 
144         So for example if your processor has a total of 2 input channels and 4 output
145         channels, then the buffer will contain 4 channels, the first two being filled
146         with the input data. Your processor should read these, do its processing, and
147         replace the contents of all 4 channels with its output.
148 
149         Or if your processor has a total of 5 inputs and 2 outputs, the buffer will have 5
150         channels, all filled with data, and your processor should overwrite the first 2 of
151         these with its output. But be VERY careful not to write anything to the last 3
152         channels, as these might be mapped to memory that the host assumes is read-only!
153 
154         If your plug-in has more than one input or output buses then the buffer passed
155         to the processBlock methods will contain a bundle of all channels of each bus.
156         Use getBusBuffer to obtain an audio buffer for a particular bus.
157 
158         Note that if you have more outputs than inputs, then only those channels that
159         correspond to an input channel are guaranteed to contain sensible data - e.g.
160         in the case of 2 inputs and 4 outputs, the first two channels contain the input,
161         but the last two channels may contain garbage, so you should be careful not to
162         let this pass through without being overwritten or cleared.
163 
164         Also note that the buffer may have more channels than are strictly necessary,
165         but you should only read/write from the ones that your processor is supposed to
166         be using.
167 
168         The number of samples in these buffers is NOT guaranteed to be the same for every
169         callback, and may be more or less than the estimated value given to prepareToPlay().
170         Your code must be able to cope with variable-sized blocks, or you're going to get
171         clicks and crashes!
172 
173         Also note that some hosts will occasionally decide to pass a buffer containing
174         zero samples, so make sure that your algorithm can deal with that!
175 
176         If the processor is receiving a MIDI input, then the midiMessages array will be filled
177         with the MIDI messages for this block. Each message's timestamp will indicate the
178         message's time, as a number of samples from the start of the block.
179 
180         Any messages left in the MIDI buffer when this method has finished are assumed to
181         be the processor's MIDI output. This means that your processor should be careful to
182         clear any incoming messages from the array if it doesn't want them to be passed-on.
183 
184         If you have implemented the getBypassParameter method, then you need to check the
185         value of this parameter in this callback and bypass your processing if the parameter
186         has a non-zero value.
187 
188         Note that when calling this method as a host, the result may still be bypassed as
189         the parameter that controls the bypass may be non-zero.
190 
191         Be very careful about what you do in this callback - it's going to be called by
192         the audio thread, so any kind of interaction with the UI is absolutely
193         out of the question. If you change a parameter in here and need to tell your UI to
194         update itself, the best way is probably to inherit from a ChangeBroadcaster, let
195         the UI components register as listeners, and then call sendChangeMessage() inside the
196         processBlock() method to send out an asynchronous message. You could also use
197         the AsyncUpdater class in a similar way.
198 
199         @see getBusBuffer
200     */
201     virtual void processBlock (AudioBuffer<float>& buffer,
202                                MidiBuffer& midiMessages) = 0;
203 
204     /** Renders the next block.
205 
206         When this method is called, the buffer contains a number of channels which is
207         at least as great as the maximum number of input and output channels that
208         this processor is using. It will be filled with the processor's input data and
209         should be replaced with the processor's output.
210 
211         So for example if your processor has a combined total of 2 input channels and
212         4 output channels, then the buffer will contain 4 channels, the first two
213         being filled with the input data. Your processor should read these, do its
214         processing, and replace the contents of all 4 channels with its output.
215 
216         Or if your processor has 5 inputs and 2 outputs, the buffer will have 5 channels,
217         all filled with data, and your processor should overwrite the first 2 of these
218         with its output. But be VERY careful not to write anything to the last 3
219         channels, as these might be mapped to memory that the host assumes is read-only!
220 
221         If your plug-in has more than one input or output buses then the buffer passed
222         to the processBlock methods will contain a bundle of all channels of
223         each bus. Use getBusBuffer to obtain a audio buffer for a particular bus.
224 
225         Note that if you have more outputs than inputs, then only those channels that
226         correspond to an input channel are guaranteed to contain sensible data - e.g.
227         in the case of 2 inputs and 4 outputs, the first two channels contain the input,
228         but the last two channels may contain garbage, so you should be careful not to
229         let this pass through without being overwritten or cleared.
230 
231         Also note that the buffer may have more channels than are strictly necessary,
232         but you should only read/write from the ones that your processor is supposed to
233         be using.
234 
235         If your plugin uses buses, then you should use getBusBuffer() or
236         getChannelIndexInProcessBlockBuffer() to find out which of the input and output
237         channels correspond to which of the buses.
238 
239         The number of samples in these buffers is NOT guaranteed to be the same for every
240         callback, and may be more or less than the estimated value given to prepareToPlay().
241         Your code must be able to cope with variable-sized blocks, or you're going to get
242         clicks and crashes!
243 
244         Also note that some hosts will occasionally decide to pass a buffer containing
245         zero samples, so make sure that your algorithm can deal with that!
246 
247         If the processor is receiving a MIDI input, then the midiMessages array will be filled
248         with the MIDI messages for this block. Each message's timestamp will indicate the
249         message's time, as a number of samples from the start of the block.
250 
251         Any messages left in the MIDI buffer when this method has finished are assumed to
252         be the processor's MIDI output. This means that your processor should be careful to
253         clear any incoming messages from the array if it doesn't want them to be passed-on.
254 
255         If you have implemented the getBypassParameter method, then you need to check the
256         value of this parameter in this callback and bypass your processing if the parameter
257         has a non-zero value.
258 
259         Note that when calling this method as a host, the result may still be bypassed as
260         the parameter that controls the bypass may be non-zero.
261 
262         Be very careful about what you do in this callback - it's going to be called by
263         the audio thread, so any kind of interaction with the UI is absolutely
264         out of the question. If you change a parameter in here and need to tell your UI to
265         update itself, the best way is probably to inherit from a ChangeBroadcaster, let
266         the UI components register as listeners, and then call sendChangeMessage() inside the
267         processBlock() method to send out an asynchronous message. You could also use
268         the AsyncUpdater class in a similar way.
269 
270         @see getBusBuffer
271     */
272     virtual void processBlock (AudioBuffer<double>& buffer,
273                                MidiBuffer& midiMessages);
274 
275     /** Renders the next block when the processor is being bypassed.
276 
277         The default implementation of this method will pass-through any incoming audio, but
278         you may override this method e.g. to add latency compensation to the data to match
279         the processor's latency characteristics. This will avoid situations where bypassing
280         will shift the signal forward in time, possibly creating pre-echo effects and odd timings.
281         Another use for this method would be to cross-fade or morph between the wet (not bypassed)
282         and dry (bypassed) signals.
283     */
284     virtual void processBlockBypassed (AudioBuffer<float>& buffer,
285                                        MidiBuffer& midiMessages);
286 
287     /** Renders the next block when the processor is being bypassed.
288 
289         The default implementation of this method will pass-through any incoming audio, but
290         you may override this method e.g. to add latency compensation to the data to match
291         the processor's latency characteristics. This will avoid situations where bypassing
292         will shift the signal forward in time, possibly creating pre-echo effects and odd timings.
293         Another use for this method would be to cross-fade or morph between the wet (not bypassed)
294         and dry (bypassed) signals.
295     */
296     virtual void processBlockBypassed (AudioBuffer<double>& buffer,
297                                        MidiBuffer& midiMessages);
298 
299 
300     //==============================================================================
301     /**
302         Represents the bus layout state of a plug-in
303     */
304     struct BusesLayout
305     {
306         /** An array containing the list of input buses that this processor supports. */
307         Array<AudioChannelSet> inputBuses;
308 
309         /** An array containing the list of output buses that this processor supports. */
310         Array<AudioChannelSet> outputBuses;
311 
312         /** Get the number of channels of a particular bus */
getNumChannelsBusesLayout313         int getNumChannels (bool isInput, int busIndex) const noexcept
314         {
315             auto& bus = (isInput ? inputBuses : outputBuses);
316             return isPositiveAndBelow (busIndex, bus.size()) ? bus.getReference (busIndex).size() : 0;
317         }
318 
319         /** Get the channel set of a particular bus */
getChannelSetBusesLayout320         AudioChannelSet& getChannelSet (bool isInput, int busIndex) noexcept
321         {
322             return (isInput ? inputBuses : outputBuses).getReference (busIndex);
323         }
324 
325         /** Get the channel set of a particular bus */
getChannelSetBusesLayout326         AudioChannelSet getChannelSet (bool isInput, int busIndex) const noexcept
327         {
328             return (isInput ? inputBuses : outputBuses)[busIndex];
329         }
330 
331         /** Get the input channel layout on the main bus. */
getMainInputChannelSetBusesLayout332         AudioChannelSet getMainInputChannelSet()  const noexcept    { return getChannelSet (true,  0); }
333 
334         /** Get the output channel layout on the main bus. */
getMainOutputChannelSetBusesLayout335         AudioChannelSet getMainOutputChannelSet() const noexcept    { return getChannelSet (false, 0); }
336 
337         /** Get the number of input channels on the main bus. */
getMainInputChannelsBusesLayout338         int getMainInputChannels()  const noexcept                  { return getNumChannels (true, 0); }
339 
340         /** Get the number of output channels on the main bus. */
getMainOutputChannelsBusesLayout341         int getMainOutputChannels() const noexcept                  { return getNumChannels (false, 0); }
342 
343         bool operator== (const BusesLayout& other) const noexcept   { return inputBuses == other.inputBuses && outputBuses == other.outputBuses; }
344         bool operator!= (const BusesLayout& other) const noexcept   { return inputBuses != other.inputBuses || outputBuses != other.outputBuses; }
345     };
346 
347     //==============================================================================
348     /**
349         Describes the layout and properties of an audio bus.
350         Effectively a bus description is a named set of channel types.
351 
352         @see AudioChannelSet, AudioProcessor::addBus
353      */
354     class Bus
355     {
356     public:
357         /** Returns true if this bus is an input bus. */
358         bool isInput() const noexcept;
359 
360         /** Returns the index of this bus. */
361         int getBusIndex() const noexcept;
362 
363         /** Returns true if the current bus is the main input or output bus. */
isMain()364         bool isMain() const noexcept                                    { return getBusIndex() == 0; }
365 
366         //==============================================================================
367         /** The bus's name. */
getName()368         const String& getName() const noexcept                          { return name; }
369 
370         /** Get the default layout of this bus.
371             @see AudioChannelSet
372         */
getDefaultLayout()373         const AudioChannelSet& getDefaultLayout() const noexcept        { return dfltLayout; }
374 
375         //==============================================================================
376         /** The bus's current layout. This will be AudioChannelSet::disabled() if the current
377             layout is disabled.
378             @see AudioChannelSet
379         */
getCurrentLayout()380         const AudioChannelSet& getCurrentLayout() const noexcept        { return layout; }
381 
382         /** Return the bus's last active channel layout.
383             If the bus is currently enabled then the result will be identical to getCurrentLayout
384             otherwise it will return the last enabled layout.
385             @see AudioChannelSet
386         */
getLastEnabledLayout()387         const AudioChannelSet& getLastEnabledLayout() const noexcept    { return lastLayout; }
388 
389         /** Sets the bus's current layout.
390             If the AudioProcessor does not support this layout then this will return false.
391             @see AudioChannelSet
392         */
393         bool setCurrentLayout (const AudioChannelSet& layout);
394 
395         /** Sets the bus's current layout without changing the enabled state.
396             If the AudioProcessor does not support this layout then this will return false.
397             @see AudioChannelSet
398          */
399         bool setCurrentLayoutWithoutEnabling (const AudioChannelSet& layout);
400 
401         /** Return the number of channels of the current bus. */
getNumberOfChannels()402         inline int getNumberOfChannels() const noexcept                 { return cachedChannelCount; }
403 
404         /** Set the number of channels of this bus. This will return false if the AudioProcessor
405             does not support this layout.
406         */
407         bool setNumberOfChannels (int channels);
408 
409         //==============================================================================
410         /** Checks if a particular layout is supported.
411 
412             @param set           The AudioChannelSet which is to be probed.
413             @param currentLayout If non-null, pretend that the current layout of the AudioProcessor is
414                                  currentLayout. On exit, currentLayout will be modified to
415                                  to represent the buses layouts of the AudioProcessor as if the layout
416                                  of the receiver had been successfully changed. This is useful as changing
417                                  the layout of the receiver may change the bus layout of other buses.
418 
419             @see AudioChannelSet
420         */
421         bool isLayoutSupported (const AudioChannelSet& set, BusesLayout* currentLayout = nullptr) const;
422 
423         /** Checks if this bus can support a given number of channels. */
424         bool isNumberOfChannelsSupported (int channels) const;
425 
426         /** Returns a ChannelSet that the bus supports with a given number of channels. */
427         AudioChannelSet supportedLayoutWithChannels (int channels) const;
428 
429         /** Returns the maximum number of channels that this bus can support.
430             @param limit The maximum value to return.
431         */
432         int getMaxSupportedChannels (int limit = AudioChannelSet::maxChannelsOfNamedLayout) const;
433 
434         /** Returns the resulting layouts of all buses after changing the layout of this bus.
435 
436             Changing an individual layout of a bus may also change the layout of all the other
437             buses. This method returns what the layouts of all the buses of the audio processor
438             would be, if you were to change the layout of this bus to the given layout. If there
439             is no way to support the given layout then this method will return the next best
440             layout.
441         */
442         BusesLayout getBusesLayoutForLayoutChangeOfBus (const AudioChannelSet& set) const;
443 
444         //==============================================================================
445         /** Returns true if the current bus is enabled. */
isEnabled()446         bool isEnabled() const noexcept                             { return ! layout.isDisabled(); }
447 
448         /** Enable or disable this bus. This will return false if the AudioProcessor
449             does not support disabling this bus. */
450         bool enable (bool shouldEnable = true);
451 
452         /** Returns if this bus is enabled by default. */
isEnabledByDefault()453         bool isEnabledByDefault() const noexcept                    { return enabledByDefault; }
454 
455         //==============================================================================
456         /** Returns the position of a bus's channels within the processBlock buffer.
457             This can be called in processBlock to figure out which channel of the master AudioBuffer
458             maps onto a specific bus's channel.
459         */
460         int getChannelIndexInProcessBlockBuffer (int channelIndex) const noexcept;
461 
462 
463         /** Returns an AudioBuffer containing a set of channel pointers for a specific bus.
464             This can be called in processBlock to get a buffer containing a sub-group of the master
465             AudioBuffer which contains all the plugin channels.
466         */
467         template <typename FloatType>
getBusBuffer(AudioBuffer<FloatType> & processBlockBuffer)468         AudioBuffer<FloatType> getBusBuffer (AudioBuffer<FloatType>& processBlockBuffer) const
469         {
470             auto di = getDirectionAndIndex();
471             return owner.getBusBuffer (processBlockBuffer, di.isInput, di.index);
472         }
473 
474     private:
475         friend class AudioProcessor;
476         Bus (AudioProcessor&, const String&, const AudioChannelSet&, bool);
477 
478         struct BusDirectionAndIndex
479         {
480             bool isInput;
481             int index;
482         };
483 
484         BusDirectionAndIndex getDirectionAndIndex() const noexcept;
485         void updateChannelCount() noexcept;
486 
487         AudioProcessor& owner;
488         String name;
489         AudioChannelSet layout, dfltLayout, lastLayout;
490         bool enabledByDefault;
491         int cachedChannelCount;
492 
493         JUCE_DECLARE_NON_COPYABLE (Bus)
494     };
495 
496     //==============================================================================
497     /** Returns the number of buses on the input or output side */
getBusCount(bool isInput)498     int getBusCount (bool isInput) const noexcept                   { return (isInput ? inputBuses : outputBuses).size(); }
499 
500     /** Returns the audio bus with a given index and direction.
501         If busIndex is invalid then this method will return a nullptr.
502     */
getBus(bool isInput,int busIndex)503     Bus* getBus (bool isInput, int busIndex) noexcept               { return (isInput ? inputBuses : outputBuses)[busIndex]; }
504 
505     /** Returns the audio bus with a given index and direction.
506         If busIndex is invalid then this method will return a nullptr.
507     */
getBus(bool isInput,int busIndex)508     const Bus* getBus (bool isInput, int busIndex) const noexcept   { return const_cast<AudioProcessor*> (this)->getBus (isInput, busIndex); }
509 
510     //==============================================================================
511     /**  Callback to query if a bus can currently be added.
512 
513          This callback probes if a bus can currently be added. You should override
514          this callback if you want to support dynamically adding/removing buses by
515          the host. This is useful for mixer audio processors.
516 
517          The default implementation will always return false.
518 
519          @see addBus
520     */
canAddBus(bool isInput)521     virtual bool canAddBus (bool isInput) const                     { ignoreUnused (isInput); return false; }
522 
523     /**  Callback to query if the last bus can currently be removed.
524 
525          This callback probes if the last bus can currently be removed. You should
526          override this callback if you want to support dynamically adding/removing
527          buses by the host. This is useful for mixer audio processors.
528 
529          If you return true in this callback then the AudioProcessor will go ahead
530          and delete the bus.
531 
532          The default implementation will always return false.
533     */
canRemoveBus(bool isInput)534     virtual bool canRemoveBus (bool isInput) const                  { ignoreUnused (isInput); return false; }
535 
536     /** Dynamically request an additional bus.
537 
538         Request an additional bus from the audio processor. If the audio processor
539         does not support adding additional buses then this method will return false.
540 
541         Most audio processors will not allow you to dynamically add/remove
542         audio buses and will return false.
543 
544         This method will invoke the canApplyBusCountChange callback to probe
545         if a bus can be added and, if yes, will use the supplied bus properties
546         of the canApplyBusCountChange callback to create a new bus.
547 
548         @see canApplyBusCountChange, removeBus
549     */
550     bool addBus (bool isInput);
551 
552     /** Dynamically remove the latest added bus.
553 
554         Request the removal of the last bus from the audio processor. If the
555         audio processor does not support removing buses then this method will
556         return false.
557 
558         Most audio processors will not allow you to dynamically add/remove
559         audio buses and will return false.
560 
561         The default implementation will return false.
562 
563         This method will invoke the canApplyBusCountChange callback to probe if
564         a bus can currently be removed and, if yes, will go ahead and remove it.
565 
566         @see addBus, canRemoveBus
567     */
568     bool removeBus (bool isInput);
569 
570     //==============================================================================
571     /** Set the channel layouts of this audio processor.
572 
573         If the layout is not supported by this audio processor then
574         this method will return false. You can use the checkBusesLayoutSupported
575         and getNextBestLayout methods to probe which layouts this audio
576         processor supports.
577     */
578     bool setBusesLayout (const BusesLayout&);
579 
580     /** Set the channel layouts of this audio processor without changing the
581         enablement state of the buses.
582 
583         If the layout is not supported by this audio processor then
584         this method will return false. You can use the checkBusesLayoutSupported
585         methods to probe which layouts this audio processor supports.
586     */
587     bool setBusesLayoutWithoutEnabling (const BusesLayout&);
588 
589     /** Provides the current channel layouts of this audio processor. */
590     BusesLayout getBusesLayout() const;
591 
592     /** Provides the channel layout of the bus with a given index and direction.
593 
594         If the index, direction combination is invalid then this will return an
595         AudioChannelSet with no channels.
596     */
597     AudioChannelSet getChannelLayoutOfBus (bool isInput, int busIndex) const noexcept;
598 
599     /** Set the channel layout of the bus with a given index and direction.
600 
601         If the index, direction combination is invalid or the layout is not
602         supported by the audio processor then this method will return false.
603     */
604     bool setChannelLayoutOfBus (bool isInput, int busIndex, const AudioChannelSet& layout);
605 
606     /** Provides the number of channels of the bus with a given index and direction.
607 
608         If the index, direction combination is invalid then this will return zero.
609     */
getChannelCountOfBus(bool isInput,int busIndex)610     inline int getChannelCountOfBus (bool isInput, int busIndex) const noexcept
611     {
612         if (auto* bus = getBus (isInput, busIndex))
613             return bus->getNumberOfChannels();
614 
615         return 0;
616     }
617 
618     /** Enables all buses */
619     bool enableAllBuses();
620 
621     /** Disables all non-main buses (aux and sidechains). */
622     bool disableNonMainBuses();
623 
624     //==============================================================================
625     /** Returns the position of a bus's channels within the processBlock buffer.
626         This can be called in processBlock to figure out which channel of the master AudioBuffer
627         maps onto a specific bus's channel.
628      */
629     int getChannelIndexInProcessBlockBuffer (bool isInput, int busIndex, int channelIndex) const noexcept;
630 
631     /** Returns the offset in a bus's buffer from an absolute channel index.
632 
633         This method returns the offset in a bus's buffer given an absolute channel index.
634         It also provides the bus index. For example, this method would return one
635         for a processor with two stereo buses when given the absolute channel index.
636     */
637     int getOffsetInBusBufferForAbsoluteChannelIndex (bool isInput, int absoluteChannelIndex, int& busIndex) const noexcept;
638 
639     /** Returns an AudioBuffer containing a set of channel pointers for a specific bus.
640         This can be called in processBlock to get a buffer containing a sub-group of the master
641         AudioBuffer which contains all the plugin channels.
642      */
643     template <typename FloatType>
getBusBuffer(AudioBuffer<FloatType> & processBlockBuffer,bool isInput,int busIndex)644     AudioBuffer<FloatType> getBusBuffer (AudioBuffer<FloatType>& processBlockBuffer, bool isInput, int busIndex) const
645     {
646         auto busNumChannels = getChannelCountOfBus (isInput, busIndex);
647         auto channelOffset = getChannelIndexInProcessBlockBuffer (isInput, busIndex, 0);
648 
649         return AudioBuffer<FloatType> (processBlockBuffer.getArrayOfWritePointers() + channelOffset,
650                                        busNumChannels, processBlockBuffer.getNumSamples());
651     }
652 
653     //==============================================================================
654     /** Returns true if the Audio processor is likely to support a given layout.
655         This can be called regardless if the processor is currently running.
656     */
657     bool checkBusesLayoutSupported (const BusesLayout&) const;
658 
659     //==============================================================================
660     /** Returns true if the Audio processor supports double precision floating point processing.
661         The default implementation will always return false.
662         If you return true here then you must override the double precision versions
663         of processBlock. Additionally, you must call getProcessingPrecision() in
664         your prepareToPlay method to determine the precision with which you need to
665         allocate your internal buffers.
666         @see getProcessingPrecision, setProcessingPrecision
667     */
668     virtual bool supportsDoublePrecisionProcessing() const;
669 
670     /** Returns the precision-mode of the processor.
671         Depending on the result of this method you MUST call the corresponding version
672         of processBlock. The default processing precision is single precision.
673         @see setProcessingPrecision, supportsDoublePrecisionProcessing
674     */
getProcessingPrecision()675     ProcessingPrecision getProcessingPrecision() const noexcept         { return processingPrecision; }
676 
677     /** Returns true if the current precision is set to doublePrecision. */
isUsingDoublePrecision()678     bool isUsingDoublePrecision() const noexcept                        { return processingPrecision == doublePrecision; }
679 
680     /** Changes the processing precision of the receiver. A client of the AudioProcessor
681         calls this function to indicate which version of processBlock (single or double
682         precision) it intends to call. The client MUST call this function before calling
683         the prepareToPlay method so that the receiver can do any necessary allocations
684         in the prepareToPlay() method. An implementation of prepareToPlay() should call
685         getProcessingPrecision() to determine with which precision it should allocate
686         it's internal buffers.
687 
688         Note that setting the processing precision to double floating point precision
689         on a receiver which does not support double precision processing (i.e.
690         supportsDoublePrecisionProcessing() returns false) will result in an assertion.
691 
692         @see getProcessingPrecision, supportsDoublePrecisionProcessing
693     */
694     void setProcessingPrecision (ProcessingPrecision newPrecision) noexcept;
695 
696     //==============================================================================
697     /** Returns the current AudioPlayHead object that should be used to find
698         out the state and position of the playhead.
699 
700         You can ONLY call this from your processBlock() method! Calling it at other
701         times will produce undefined behaviour, as the host may not have any context
702         in which a time would make sense, and some hosts will almost certainly have
703         multithreading issues if it's not called on the audio thread.
704 
705         The AudioPlayHead object that is returned can be used to get the details about
706         the time of the start of the block currently being processed. But do not
707         store this pointer or use it outside of the current audio callback, because
708         the host may delete or re-use it.
709 
710         If the host can't or won't provide any time info, this will return nullptr.
711     */
getPlayHead()712     AudioPlayHead* getPlayHead() const noexcept                 { return playHead; }
713 
714     //==============================================================================
715     /** Returns the total number of input channels.
716 
717         This method will return the total number of input channels by accumulating
718         the number of channels on each input bus. The number of channels of the
719         buffer passed to your processBlock callback will be equivalent to either
720         getTotalNumInputChannels or getTotalNumOutputChannels - which ever
721         is greater.
722 
723         Note that getTotalNumInputChannels is equivalent to
724         getMainBusNumInputChannels if your processor does not have any sidechains
725         or aux buses.
726      */
getTotalNumInputChannels()727     int getTotalNumInputChannels()  const noexcept              { return cachedTotalIns; }
728 
729     /** Returns the total number of output channels.
730 
731         This method will return the total number of output channels by accumulating
732         the number of channels on each output bus. The number of channels of the
733         buffer passed to your processBlock callback will be equivalent to either
734         getTotalNumInputChannels or getTotalNumOutputChannels - which ever
735         is greater.
736 
737         Note that getTotalNumOutputChannels is equivalent to
738         getMainBusNumOutputChannels if your processor does not have any sidechains
739         or aux buses.
740      */
getTotalNumOutputChannels()741     int getTotalNumOutputChannels() const noexcept              { return cachedTotalOuts; }
742 
743     /** Returns the number of input channels on the main bus. */
getMainBusNumInputChannels()744     inline int getMainBusNumInputChannels()   const noexcept    { return getChannelCountOfBus (true,  0); }
745 
746     /** Returns the number of output channels on the main bus. */
getMainBusNumOutputChannels()747     inline int getMainBusNumOutputChannels()  const noexcept    { return getChannelCountOfBus (false, 0); }
748 
749     //==============================================================================
750     /** Returns true if the channel layout map contains a certain layout.
751 
752         You can use this method to help you implement the checkBusesLayoutSupported
753         method. For example
754 
755         @code
756         bool checkBusesLayoutSupported (const BusesLayout& layouts) override
757         {
758             return containsLayout (layouts, {{1,1},{2,2}});
759         }
760         @endcode
761     */
containsLayout(const BusesLayout & layouts,const std::initializer_list<const short[2]> & channelLayoutList)762     static bool containsLayout (const BusesLayout& layouts, const std::initializer_list<const short[2]>& channelLayoutList)
763     {
764         return containsLayout (layouts, layoutListToArray (channelLayoutList));
765     }
766 
767     template <size_t numLayouts>
containsLayout(const BusesLayout & layouts,const short (& channelLayoutList)[numLayouts][2])768     static bool containsLayout (const BusesLayout& layouts, const short (&channelLayoutList) [numLayouts][2])
769     {
770         return containsLayout (layouts, layoutListToArray (channelLayoutList));
771     }
772 
773     /** Returns the next best layout which is contained in a channel layout map.
774 
775         You can use this method to help you implement getNextBestLayout. For example:
776 
777         @code
778         BusesLayout getNextBestLayout (const BusesLayout& layouts) override
779         {
780             return getNextBestLayoutInLayoutList (layouts, {{1,1},{2,2}});
781         }
782         @endcode
783     */
784     template <size_t numLayouts>
getNextBestLayoutInLayoutList(const BusesLayout & layouts,const short (& channelLayoutList)[numLayouts][2])785     BusesLayout getNextBestLayoutInLayoutList (const BusesLayout& layouts,
786                                                const short (&channelLayoutList) [numLayouts][2])
787     {
788         return getNextBestLayoutInList (layouts, layoutListToArray (channelLayoutList));
789     }
790 
791     //==============================================================================
792     /** Returns the current sample rate.
793 
794         This can be called from your processBlock() method - it's not guaranteed
795         to be valid at any other time, and may return 0 if it's unknown.
796     */
getSampleRate()797     double getSampleRate() const noexcept                       { return currentSampleRate; }
798 
799     /** Returns the current typical block size that is being used.
800 
801         This can be called from your processBlock() method - it's not guaranteed
802         to be valid at any other time.
803 
804         Remember it's not the ONLY block size that may be used when calling
805         processBlock, it's just the normal one. The actual block sizes used may be
806         larger or smaller than this, and will vary between successive calls.
807     */
getBlockSize()808     int getBlockSize() const noexcept                           { return blockSize; }
809 
810     //==============================================================================
811 
812     /** This returns the number of samples delay that the processor imposes on the audio
813         passing through it.
814 
815         The host will call this to find the latency - the processor itself should set this value
816         by calling setLatencySamples() as soon as it can during its initialisation.
817     */
getLatencySamples()818     int getLatencySamples() const noexcept                      { return latencySamples; }
819 
820     /** Your processor subclass should call this to set the number of samples delay that it introduces.
821 
822         The processor should call this as soon as it can during initialisation, and can call it
823         later if the value changes.
824     */
825     void setLatencySamples (int newLatency);
826 
827     /** Returns the length of the processor's tail, in seconds. */
828     virtual double getTailLengthSeconds() const = 0;
829 
830     /** Returns true if the processor wants MIDI messages. */
831     virtual bool acceptsMidi() const = 0;
832 
833     /** Returns true if the processor produces MIDI messages. */
834     virtual bool producesMidi() const = 0;
835 
836     /** Returns true if the processor supports MPE. */
supportsMPE()837     virtual bool supportsMPE() const                            { return false; }
838 
839     /** Returns true if this is a MIDI effect plug-in and does no audio processing. */
isMidiEffect()840     virtual bool isMidiEffect() const                           { return false; }
841 
842     //==============================================================================
843     /** This returns a critical section that will automatically be locked while the host
844         is calling the processBlock() method.
845 
846         Use it from your UI or other threads to lock access to variables that are used
847         by the process callback, but obviously be careful not to keep it locked for
848         too long, because that could cause stuttering playback. If you need to do something
849         that'll take a long time and need the processing to stop while it happens, use the
850         suspendProcessing() method instead.
851 
852         @see suspendProcessing
853     */
getCallbackLock()854     const CriticalSection& getCallbackLock() const noexcept     { return callbackLock; }
855 
856     /** Enables and disables the processing callback.
857 
858         If you need to do something time-consuming on a thread and would like to make sure
859         the audio processing callback doesn't happen until you've finished, use this
860         to disable the callback and re-enable it again afterwards.
861 
862         E.g.
863         @code
864         void loadNewPatch()
865         {
866             suspendProcessing (true);
867 
868             ..do something that takes ages..
869 
870             suspendProcessing (false);
871         }
872         @endcode
873 
874         If the host tries to make an audio callback while processing is suspended, the
875         processor will return an empty buffer, but won't block the audio thread like it would
876         do if you use the getCallbackLock() critical section to synchronise access.
877 
878         Any code that calls processBlock() should call isSuspended() before doing so, and
879         if the processor is suspended, it should avoid the call and emit silence or
880         whatever is appropriate.
881 
882         @see getCallbackLock
883     */
884     void suspendProcessing (bool shouldBeSuspended);
885 
886     /** Returns true if processing is currently suspended.
887         @see suspendProcessing
888     */
isSuspended()889     bool isSuspended() const noexcept                                   { return suspended; }
890 
891     /** A plugin can override this to be told when it should reset any playing voices.
892 
893         The default implementation does nothing, but a host may call this to tell the
894         plugin that it should stop any tails or sounds that have been left running.
895     */
896     virtual void reset();
897 
898     //==============================================================================
899     /** Returns the parameter that controls the AudioProcessor's bypass state.
900 
901         If this method returns a nullptr then you can still control the bypass by
902         calling processBlockBypassed instead of processBlock. On the other hand,
903         if this method returns a non-null value, you should never call
904         processBlockBypassed but use the returned parameter to control the bypass
905         state instead.
906 
907         A plug-in can override this function to return a parameter which control's your
908         plug-in's bypass. You should always check the value of this parameter in your
909         processBlock callback and bypass any effects if it is non-zero.
910     */
getBypassParameter()911     virtual AudioProcessorParameter* getBypassParameter() const        { return nullptr; }
912 
913     //==============================================================================
914     /** Returns true if the processor is being run in an offline mode for rendering.
915 
916         If the processor is being run live on realtime signals, this returns false.
917         If the mode is unknown, this will assume it's realtime and return false.
918 
919         This value may be unreliable until the prepareToPlay() method has been called,
920         and could change each time prepareToPlay() is called.
921 
922         @see setNonRealtime()
923     */
isNonRealtime()924     bool isNonRealtime() const noexcept                                 { return nonRealtime; }
925 
926     /** Called by the host to tell this processor whether it's being used in a non-realtime
927         capacity for offline rendering or bouncing.
928     */
929     virtual void setNonRealtime (bool isNonRealtime) noexcept;
930 
931     //==============================================================================
932     /** Creates the processor's GUI.
933 
934         This can return nullptr if you want a GUI-less processor, in which case the host
935         may create a generic UI that lets the user twiddle the parameters directly.
936 
937         If you do want to pass back a component, the component should be created and set to
938         the correct size before returning it. If you implement this method, you must
939         also implement the hasEditor() method and make it return true.
940 
941         Remember not to do anything silly like allowing your processor to keep a pointer to
942         the component that gets created - it could be deleted later without any warning, which
943         would make your pointer into a dangler. Use the getActiveEditor() method instead.
944 
945         The correct way to handle the connection between an editor component and its
946         processor is to use something like a ChangeBroadcaster so that the editor can
947         register itself as a listener, and be told when a change occurs. This lets them
948         safely unregister themselves when they are deleted.
949 
950         Here are a few things to bear in mind when writing an editor:
951 
952         - Initially there won't be an editor, until the user opens one, or they might
953           not open one at all. Your processor mustn't rely on it being there.
954         - An editor object may be deleted and a replacement one created again at any time.
955         - It's safe to assume that an editor will be deleted before its processor.
956 
957         @see hasEditor
958     */
959     virtual AudioProcessorEditor* createEditor() = 0;
960 
961     /** Your processor subclass must override this and return true if it can create an
962         editor component.
963         @see createEditor
964     */
965     virtual bool hasEditor() const = 0;
966 
967     //==============================================================================
968     /** Returns the active editor, if there is one. Bear in mind this can return nullptr
969         even if an editor has previously been opened.
970 
971         Note that you should only call this method from the message thread as the active
972         editor may be deleted by the message thread, causing a dangling pointer.
973     */
974     AudioProcessorEditor* getActiveEditor() const noexcept;
975 
976     /** Returns the active editor, or if there isn't one, it will create one.
977         This may call createEditor() internally to create the component.
978     */
979     AudioProcessorEditor* createEditorIfNeeded();
980 
981     //==============================================================================
982     /** Returns the default number of steps for a parameter.
983 
984         NOTE! This method is deprecated! It's recommended that you use
985         AudioProcessorParameter::getNumSteps() instead.
986 
987         @see getParameterNumSteps
988     */
989     static int getDefaultNumParameterSteps() noexcept;
990 
991     /** The processor can call this when something (apart from a parameter value) has changed.
992 
993         It sends a hint to the host that something like the program, number of parameters,
994         etc, has changed, and that it should update itself.
995     */
996     void updateHostDisplay (const ChangeDetails& details = ChangeDetails::getAllChanged());
997 
998     //==============================================================================
999     /** Adds a parameter to the AudioProcessor.
1000 
1001         The parameter object will be managed and deleted automatically by the
1002         AudioProcessor when no longer needed.
1003     */
1004     void addParameter (AudioProcessorParameter*);
1005 
1006     /** Adds a group of parameters to the AudioProcessor.
1007 
1008         All the parameter objects contained within the group will be managed and
1009         deleted automatically by the AudioProcessor when no longer needed.
1010 
1011         @see addParameter
1012      */
1013     void addParameterGroup (std::unique_ptr<AudioProcessorParameterGroup>);
1014 
1015     /** Returns the group of parameters managed by this AudioProcessor. */
1016     const AudioProcessorParameterGroup& getParameterTree() const;
1017 
1018     /** Sets the group of parameters managed by this AudioProcessor.
1019 
1020         Replacing the tree after your AudioProcessor has been constructed will
1021         crash many hosts, so don't do it! You may, however, change parameter and
1022         group names by iterating the tree returned by getParameterTree().
1023         Afterwards, call updateHostDisplay() to inform the host of the changes.
1024         Not all hosts support dynamic changes to parameters and group names.
1025     */
1026     void setParameterTree (AudioProcessorParameterGroup&& newTree);
1027 
1028     /** A processor should implement this method so that the host can ask it to
1029         rebuild its parameter tree.
1030 
1031         For most plug-ins it's enough to simply add your parameters in the
1032         constructor and leave this unimplemented.
1033     */
1034     virtual void refreshParameterList();
1035 
1036     /** Returns a flat list of the parameters in the current tree. */
1037     const Array<AudioProcessorParameter*>& getParameters() const;
1038 
1039     //==============================================================================
1040     /** Returns the number of preset programs the processor supports.
1041 
1042         The value returned must be valid as soon as this object is created, and
1043         must not change over its lifetime.
1044 
1045         This value shouldn't be less than 1.
1046     */
1047     virtual int getNumPrograms() = 0;
1048 
1049     /** Returns the number of the currently active program. */
1050     virtual int getCurrentProgram() = 0;
1051 
1052     /** Called by the host to change the current program. */
1053     virtual void setCurrentProgram (int index) = 0;
1054 
1055     /** Must return the name of a given program. */
1056     virtual const String getProgramName (int index) = 0;
1057 
1058     /** Called by the host to rename a program. */
1059     virtual void changeProgramName (int index, const String& newName) = 0;
1060 
1061     //==============================================================================
1062     /** The host will call this method when it wants to save the processor's internal state.
1063 
1064         This must copy any info about the processor's state into the block of memory provided,
1065         so that the host can store this and later restore it using setStateInformation().
1066 
1067         Note that there's also a getCurrentProgramStateInformation() method, which only
1068         stores the current program, not the state of the entire processor.
1069 
1070         See also the helper function copyXmlToBinary() for storing settings as XML.
1071 
1072         @see getCurrentProgramStateInformation
1073     */
1074     virtual void getStateInformation (juce::MemoryBlock& destData) = 0;
1075 
1076     /** The host will call this method if it wants to save the state of just the processor's
1077         current program.
1078 
1079         Unlike getStateInformation, this should only return the current program's state.
1080 
1081         Not all hosts support this, and if you don't implement it, the base class
1082         method just calls getStateInformation() instead. If you do implement it, be
1083         sure to also implement getCurrentProgramStateInformation.
1084 
1085         @see getStateInformation, setCurrentProgramStateInformation
1086     */
1087     virtual void getCurrentProgramStateInformation (juce::MemoryBlock& destData);
1088 
1089     /** This must restore the processor's state from a block of data previously created
1090         using getStateInformation().
1091 
1092         Note that there's also a setCurrentProgramStateInformation() method, which tries
1093         to restore just the current program, not the state of the entire processor.
1094 
1095         See also the helper function getXmlFromBinary() for loading settings as XML.
1096 
1097         @see setCurrentProgramStateInformation
1098     */
1099     virtual void setStateInformation (const void* data, int sizeInBytes) = 0;
1100 
1101     /** The host will call this method if it wants to restore the state of just the processor's
1102         current program.
1103 
1104         Not all hosts support this, and if you don't implement it, the base class
1105         method just calls setStateInformation() instead. If you do implement it, be
1106         sure to also implement getCurrentProgramStateInformation.
1107 
1108         @see setStateInformation, getCurrentProgramStateInformation
1109     */
1110     virtual void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
1111 
1112     /** This method is called when the total number of input or output channels is changed. */
1113     virtual void numChannelsChanged();
1114 
1115     /** This method is called when the number of buses is changed. */
1116     virtual void numBusesChanged();
1117 
1118     /** This method is called when the layout of the audio processor changes. */
1119     virtual void processorLayoutsChanged();
1120 
1121     //==============================================================================
1122     /** Adds a listener that will be called when an aspect of this processor changes. */
1123     virtual void addListener (AudioProcessorListener* newListener);
1124 
1125     /** Removes a previously added listener. */
1126     virtual void removeListener (AudioProcessorListener* listenerToRemove);
1127 
1128     //==============================================================================
1129     /** Tells the processor to use this playhead object.
1130         The processor will not take ownership of the object, so the caller must delete it when
1131         it is no longer being used.
1132     */
1133     virtual void setPlayHead (AudioPlayHead* newPlayHead);
1134 
1135     //==============================================================================
1136     /** This is called by the processor to specify its details before being played. Use this
1137         version of the function if you are not interested in any sidechain and/or aux buses
1138         and do not care about the layout of channels. Otherwise use setRateAndBufferSizeDetails.*/
1139     void setPlayConfigDetails (int numIns, int numOuts, double sampleRate, int blockSize);
1140 
1141     /** This is called by the processor to specify its details before being played. You
1142         should call this function after having informed the processor about the channel
1143         and bus layouts via setBusesLayout.
1144 
1145         @see setBusesLayout
1146     */
1147     void setRateAndBufferSizeDetails (double sampleRate, int blockSize) noexcept;
1148 
1149     //==============================================================================
1150     /** AAX plug-ins need to report a unique "plug-in id" for every audio layout
1151         configuration that your AudioProcessor supports on the main bus. Override this
1152         function if you want your AudioProcessor to use a custom "plug-in id" (for example
1153         to stay backward compatible with older versions of JUCE).
1154 
1155         The default implementation will compute a unique integer from the input and output
1156         layout and add this value to the 4 character code 'jcaa' (for native AAX) or 'jyaa'
1157         (for AudioSuite plug-ins).
1158     */
1159     virtual int32 getAAXPluginIDForMainBusConfig (const AudioChannelSet& mainInputLayout,
1160                                                   const AudioChannelSet& mainOutputLayout,
1161                                                   bool idForAudioSuite) const;
1162 
1163     //==============================================================================
1164     /** Some plug-ins support sharing response curve data with the host so that it can
1165         display this curve on a console or in the mixer panel. For example, ProTools
1166         allows you to see the total EQ curve of a track. It does this by interrogating
1167         each plug-in for their internal EQ curve. */
1168     struct CurveData
1169     {
1170         enum class Type  : int
1171         {
1172             EQ,             // an EQ curve - input is in Hz, output is in dB
1173             Dynamics,       // a dynamics curve - input and output is in dB
1174             GainReduction,  // a gain reduction curve - input and output is in dB
1175 
1176             Unknown = -1
1177         };
1178 
1179         std::function<float (float)> curve;   // a function which represents your curve (such as an eq)
1180         Range<float> xRange, yRange;          // the data range of your curve
1181 
1182         // For some curve types, your plug-in may already measure the current input and output values.
1183         // An host can use to indicate where on the curve the current signal is (for example
1184         // by putting a dot on the curve). Simply leave these strings empty if you do not want to
1185         // support this.
1186         String xMeterID, yMeterID;
1187     };
1188 
getResponseCurve(CurveData::Type)1189     virtual CurveData getResponseCurve (CurveData::Type /*curveType*/) const      { return {}; }
1190 
1191     //==============================================================================
1192     /** Not for public use - this is called before deleting an editor component. */
1193     void editorBeingDeleted (AudioProcessorEditor*) noexcept;
1194 
1195     /** Flags to indicate the type of plugin context in which a processor is being used. */
1196     enum WrapperType
1197     {
1198         wrapperType_Undefined = 0,
1199         wrapperType_VST,
1200         wrapperType_VST3,
1201         wrapperType_AudioUnit,
1202         wrapperType_AudioUnitv3,
1203         wrapperType_RTAS,
1204         wrapperType_AAX,
1205         wrapperType_Standalone,
1206         wrapperType_Unity
1207     };
1208 
1209     /** When loaded by a plugin wrapper, this flag will be set to indicate the type
1210         of plugin within which the processor is running.
1211     */
1212     WrapperType wrapperType;
1213 
1214     /** Returns a textual description of a WrapperType value */
1215     static const char* getWrapperTypeDescription (AudioProcessor::WrapperType) noexcept;
1216 
1217 
1218     /** A struct containing information about the DAW track inside which your
1219         AudioProcessor is loaded. */
1220     struct TrackProperties
1221     {
1222         String name;    // The name of the track - this will be empty if the track name is not known
1223         Colour colour;  // The colour of the track - this will be transparentBlack if the colour is not known
1224 
1225         // other properties may be added in the future
1226     };
1227 
1228     /** Informs the AudioProcessor that track properties such as the track's name or
1229         colour has been changed.
1230 
1231         If you are hosting this AudioProcessor then use this method to inform the
1232         AudioProcessor about which track the AudioProcessor is loaded on. This method
1233         may only be called on the message thread.
1234 
1235         If you are implementing an AudioProcessor then you can override this callback
1236         to do something useful with the track properties such as changing the colour
1237         of your AudioProcessor's editor. It's entirely up to the host when and how
1238         often this callback will be called.
1239 
1240         The default implementation of this callback will do nothing.
1241     */
1242     virtual void updateTrackProperties (const TrackProperties& properties);
1243 
1244     //==============================================================================
1245     /** Helper function that just converts an xml element into a binary blob.
1246 
1247         Use this in your processor's getStateInformation() method if you want to
1248         store its state as xml.
1249 
1250         Then use getXmlFromBinary() to reverse this operation and retrieve the XML
1251         from a binary blob.
1252     */
1253     static void copyXmlToBinary (const XmlElement& xml,
1254                                  juce::MemoryBlock& destData);
1255 
1256     /** Retrieves an XML element that was stored as binary with the copyXmlToBinary() method.
1257         This might return nullptr if the data's unsuitable or corrupted.
1258     */
1259     static std::unique_ptr<XmlElement> getXmlFromBinary (const void* data, int sizeInBytes);
1260 
1261     /** @internal */
1262     static void JUCE_CALLTYPE setTypeOfNextNewPlugin (WrapperType);
1263 
1264 protected:
1265     /** Callback to query if the AudioProcessor supports a specific layout.
1266 
1267         This callback is called when the host probes the supported bus layouts via
1268         the checkBusesLayoutSupported method. You should override this callback if you
1269         would like to limit the layouts that your AudioProcessor supports. The default
1270         implementation will accept any layout. JUCE does basic sanity checks so that
1271         the provided layouts parameter will have the same number of buses as your
1272         AudioProcessor.
1273 
1274         @see checkBusesLayoutSupported
1275     */
isBusesLayoutSupported(const BusesLayout &)1276     virtual bool isBusesLayoutSupported (const BusesLayout&) const          { return true; }
1277 
1278     /** Callback to check if a certain bus layout can now be applied.
1279 
1280         Most subclasses will not need to override this method and should instead
1281         override the isBusesLayoutSupported callback to reject certain layout changes.
1282 
1283         This callback is called when the user requests a layout change. It will only be
1284         called if processing of the AudioProcessor has been stopped by a previous call to
1285         releaseResources or after the construction of the AudioProcessor. It will be called
1286         just before the actual layout change. By returning false you will abort the layout
1287         change and setBusesLayout will return false indicating that the layout change
1288         was not successful.
1289 
1290         The default implementation will simply call isBusesLayoutSupported.
1291 
1292         You only need to override this method if there is a chance that your AudioProcessor
1293         may not accept a layout although you have previously claimed to support it via the
1294         isBusesLayoutSupported callback. This can occur if your AudioProcessor's supported
1295         layouts depend on other plug-in parameters which may have changed since the last
1296         call to isBusesLayoutSupported, such as the format of an audio file which can be
1297         selected by the user in the AudioProcessor's editor. This callback gives the
1298         AudioProcessor a last chance to reject a layout if conditions have changed as it
1299         is always called just before the actual layout change.
1300 
1301         As it is never called while the AudioProcessor is processing audio, it can also
1302         be used for AudioProcessors which wrap other plug-in formats to apply the current
1303         layout to the underlying plug-in. This callback gives such AudioProcessors a
1304         chance to reject the layout change should an error occur with the underlying plug-in
1305         during the layout change.
1306 
1307         @see isBusesLayoutSupported, setBusesLayout
1308     */
canApplyBusesLayout(const BusesLayout & layouts)1309     virtual bool canApplyBusesLayout (const BusesLayout& layouts) const     { return isBusesLayoutSupported (layouts); }
1310 
1311     /** This method will be called when a new bus layout needs to be applied.
1312 
1313         Most subclasses will not need to override this method and should just use the default
1314         implementation.
1315     */
1316     virtual bool applyBusLayouts (const BusesLayout& layouts);
1317 
1318     //==============================================================================
1319     /** Structure used for AudioProcessor Callbacks */
1320     struct BusProperties
1321     {
1322         /** The name of the bus */
1323         String busName;
1324 
1325         /** The default layout of the bus */
1326         AudioChannelSet defaultLayout;
1327 
1328         /** Is this bus activated by default? */
1329         bool isActivatedByDefault;
1330     };
1331 
1332     /** Structure used for AudioProcessor Callbacks */
1333     struct BusesProperties
1334     {
1335         /** The layouts of the input buses */
1336         Array<BusProperties> inputLayouts;
1337 
1338         /** The layouts of the output buses */
1339         Array<BusProperties> outputLayouts;
1340 
1341         void addBus (bool isInput, const String& name, const AudioChannelSet& defaultLayout, bool isActivatedByDefault = true);
1342 
1343         BusesProperties withInput  (const String& name, const AudioChannelSet& defaultLayout, bool isActivatedByDefault = true) const;
1344         BusesProperties withOutput (const String& name, const AudioChannelSet& defaultLayout, bool isActivatedByDefault = true) const;
1345     };
1346 
1347     /** Callback to query if adding/removing buses currently possible.
1348 
1349         This callback is called when the host calls addBus or removeBus.
1350         Similar to canApplyBusesLayout, this callback is only called while
1351         the AudioProcessor is stopped and gives the processor a last
1352         chance to reject a requested bus change. It can also be used to apply
1353         the bus count change to an underlying wrapped plug-in.
1354 
1355         When adding a bus, isAddingBuses will be true and the plug-in is
1356         expected to fill out outNewBusProperties with the properties of the
1357         bus which will be created just after the successful return of this callback.
1358 
1359         Implementations of AudioProcessor will rarely need to override this
1360         method. Only override this method if your processor supports adding
1361         and removing buses and if it needs more fine grain control over the
1362         naming of new buses or may reject bus number changes although canAddBus
1363         or canRemoveBus returned true.
1364 
1365         The default implementation will return false if canAddBus/canRemoveBus
1366         returns false (the default behavior). Otherwise, this method returns
1367         "Input #busIndex" for input buses and "Output #busIndex" for output buses
1368         where busIndex is the index for newly created buses. The default layout
1369         in this case will be the layout of the previous bus of the same direction.
1370     */
1371     virtual bool canApplyBusCountChange (bool isInput, bool isAddingBuses,
1372                                          BusProperties& outNewBusProperties);
1373 
1374     //==============================================================================
1375     /** @internal */
1376     std::atomic<AudioPlayHead*> playHead { nullptr };
1377 
1378     /** @internal */
1379     void sendParamChangeMessageToListeners (int parameterIndex, float newValue);
1380 
1381     //==============================================================================
1382    #ifndef DOXYGEN
1383 public:
1384     // These methods are all deprecated in favour of using AudioProcessorParameter
1385     // and AudioProcessorParameterGroup
1386     JUCE_DEPRECATED (virtual int getNumParameters());
1387     JUCE_DEPRECATED (virtual const String getParameterName (int parameterIndex));
1388     JUCE_DEPRECATED (virtual String getParameterID (int index));
1389     JUCE_DEPRECATED (virtual float getParameter (int parameterIndex));
1390     JUCE_DEPRECATED (virtual String getParameterName (int parameterIndex, int maximumStringLength));
1391     JUCE_DEPRECATED (virtual const String getParameterText (int parameterIndex));
1392     JUCE_DEPRECATED (virtual String getParameterText (int parameterIndex, int maximumStringLength));
1393     JUCE_DEPRECATED (virtual int getParameterNumSteps (int parameterIndex));
1394     JUCE_DEPRECATED (virtual bool isParameterDiscrete (int parameterIndex) const);
1395     JUCE_DEPRECATED (virtual float getParameterDefaultValue (int parameterIndex));
1396     JUCE_DEPRECATED (virtual String getParameterLabel (int index) const);
1397     JUCE_DEPRECATED (virtual bool isParameterOrientationInverted (int index) const);
1398     JUCE_DEPRECATED (virtual void setParameter (int parameterIndex, float newValue));
1399     JUCE_DEPRECATED (virtual bool isParameterAutomatable (int parameterIndex) const);
1400     JUCE_DEPRECATED (virtual bool isMetaParameter (int parameterIndex) const);
1401     JUCE_DEPRECATED (virtual AudioProcessorParameter::Category getParameterCategory (int parameterIndex) const);
1402     JUCE_DEPRECATED (void beginParameterChangeGesture (int parameterIndex));
1403     JUCE_DEPRECATED (void endParameterChangeGesture (int parameterIndex));
1404     JUCE_DEPRECATED (void setParameterNotifyingHost (int parameterIndex, float newValue));
1405 
1406     // These functions are deprecated: your audio processor can inform the host
1407     // on its bus and channel layouts and names using the AudioChannelSet and various bus classes.
1408     JUCE_DEPRECATED_WITH_BODY (int getNumInputChannels()  const noexcept, { return getTotalNumInputChannels(); })
1409     JUCE_DEPRECATED_WITH_BODY (int getNumOutputChannels() const noexcept, { return getTotalNumOutputChannels(); })
1410     JUCE_DEPRECATED_WITH_BODY (const String getInputSpeakerArrangement()  const noexcept, { return cachedInputSpeakerArrString; })
1411     JUCE_DEPRECATED_WITH_BODY (const String getOutputSpeakerArrangement() const noexcept, { return cachedOutputSpeakerArrString; })
1412     JUCE_DEPRECATED (virtual const String getInputChannelName  (int channelIndex) const);
1413     JUCE_DEPRECATED (virtual const String getOutputChannelName (int channelIndex) const);
1414     JUCE_DEPRECATED (virtual bool isInputChannelStereoPair  (int index) const);
1415     JUCE_DEPRECATED (virtual bool isOutputChannelStereoPair (int index) const);
1416    #endif
1417 
1418 private:
1419     //==============================================================================
1420     struct InOutChannelPair
1421     {
1422         InOutChannelPair() = default;
1423 
InOutChannelPairInOutChannelPair1424         InOutChannelPair (int16 inCh, int16 outCh) noexcept    : inChannels (inCh), outChannels (outCh) {}
InOutChannelPairInOutChannelPair1425         InOutChannelPair (const int16 (&config)[2]) noexcept   : inChannels (config[0]), outChannels (config[1]) {}
1426 
1427         bool operator== (const InOutChannelPair& other) const noexcept
1428         {
1429             return other.inChannels == inChannels && other.outChannels == outChannels;
1430         }
1431 
1432         int16 inChannels = 0, outChannels = 0;
1433     };
1434 
1435     template <size_t numLayouts>
layoutListToArray(const short (& configuration)[numLayouts][2])1436     static Array<InOutChannelPair> layoutListToArray (const short (&configuration) [numLayouts][2])
1437     {
1438         Array<InOutChannelPair> layouts;
1439 
1440         for (size_t i = 0; i < numLayouts; ++i)
1441             layouts.add (InOutChannelPair (configuration[(int) i]));
1442 
1443         return layouts;
1444     }
1445 
layoutListToArray(const std::initializer_list<const short[2]> & configuration)1446     static Array<InOutChannelPair> layoutListToArray (const std::initializer_list<const short[2]>& configuration)
1447     {
1448         Array<InOutChannelPair> layouts;
1449 
1450         for (auto&& i : configuration)
1451             layouts.add (InOutChannelPair (i));
1452 
1453         return layouts;
1454     }
1455 
1456     //==============================================================================
1457     static BusesProperties busesPropertiesFromLayoutArray (const Array<InOutChannelPair>&);
1458 
1459     BusesLayout getNextBestLayoutInList (const BusesLayout&, const Array<InOutChannelPair>&) const;
1460     static bool containsLayout (const BusesLayout&, const Array<InOutChannelPair>&);
1461 
1462     //==============================================================================
1463     void createBus (bool isInput, const BusProperties&);
1464 
1465     //==============================================================================
1466     Array<AudioProcessorListener*> listeners;
1467     Component::SafePointer<AudioProcessorEditor> activeEditor;
1468     double currentSampleRate = 0;
1469     int blockSize = 0, latencySamples = 0;
1470     bool suspended = false;
1471     std::atomic<bool> nonRealtime { false };
1472     ProcessingPrecision processingPrecision = singlePrecision;
1473     CriticalSection callbackLock, listenerLock, activeEditorLock;
1474 
1475     friend class Bus;
1476     mutable OwnedArray<Bus> inputBuses, outputBuses;
1477 
1478     String cachedInputSpeakerArrString, cachedOutputSpeakerArrString;
1479     int cachedTotalIns = 0, cachedTotalOuts = 0;
1480 
1481     AudioProcessorParameterGroup parameterTree;
1482     Array<AudioProcessorParameter*> flatParameterList;
1483 
1484     AudioProcessorParameter* getParamChecked (int) const;
1485 
1486    #if JUCE_DEBUG
1487     #if ! JUCE_DISABLE_AUDIOPROCESSOR_BEGIN_END_GESTURE_CHECKING
1488      BigInteger changingParams;
1489     #endif
1490 
1491     bool textRecursionCheck = false;
1492     std::unordered_set<String> paramIDs, groupIDs;
1493    #endif
1494 
1495     void checkForDuplicateParamID (AudioProcessorParameter*);
1496     void checkForDuplicateGroupIDs (const AudioProcessorParameterGroup&);
1497 
1498     AudioProcessorListener* getListenerLocked (int) const noexcept;
1499     void updateSpeakerFormatStrings();
1500     void audioIOChanged (bool busNumberChanged, bool channelNumChanged);
1501     void getNextBestLayout (const BusesLayout&, BusesLayout&) const;
1502 
1503     template <typename floatType>
1504     void processBypassed (AudioBuffer<floatType>&, MidiBuffer&);
1505 
1506     friend class AudioProcessorParameter;
1507     friend class LADSPAPluginInstance;
1508 
1509     // This method is no longer used - you can delete it from your AudioProcessor classes.
1510     JUCE_DEPRECATED_WITH_BODY (virtual bool silenceInProducesSilenceOut() const, { return false; })
1511 
1512     JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioProcessor)
1513 };
1514 
1515 } // namespace juce
1516