AudioProcessorValueTreeState Improvements

You can dynamic_cast it to the more specialised parameter type.

Something like this would do the job:

Another option is to store pointers to the derived types before adding them to the APVTS, thereby avoiding dynamic_cast:

auto myParam = std::make_unique<DerivedParamType> (/*...*/);
derivedParamTypePtr = myParam.get(); // derivedParamTypePtr is a DerivedParamType* data member
apvts.createAndAddParameter (std::move (myParam));

I’m sorry, but that sounds like a terrible anti-pattern. Imho dynamic_cast() is overly used as it is, and this change trades in one nuisance for another.

Why not (add) something along these lines?

template <typename Derivative, typename... Args>
Derivative* createAndAddParameter(Args&&... args)
{
    auto param = std::make_unique<Derivative>(std::forward<Args>(args)...);
    auto ptr = param.get();
    createAndAddParameter(std::move(param));
    return ptr;
}

param = createAndAddParameter<AudioParameterFloat>(...);

At least that’ll return the proper type.

1 Like

You could always add that as a non-member helper function if this is something you find yourself doing a lot.

Sure, but since JUCE is first and foremost an audio-plugin framework I can’t imagine I’d be the only one doing this a lot. :stuck_out_tongue:

Sure, I was just suggesting something that was easy to fit into the initialization list.

AudioProcessorValueTreeState::ParameterLayout createParameterLayout()
{
    std::vector<std::unique_ptr<RangedAudioParameter>> params;

    // Add your other parameters programmatically

    auto param = std::make_unique<AudioParameterInt> ("intParam", "Int Param", 2, 7, 5);
    yourIntParam = param.get();
    params.push_back (std::move (param));

    return { params.begin(), params.end() };
}

YourProcessor()
{
    // Do something with yourIntParam
    DBG (*yourIntParam);
}

AudioParameterInt* yourIntParam = nullptr;
AudioProcessorValueTreeState parameters { *this, nullptr, "PARAMS", createParameterLayout() };

The ParameterLayout also has a variadic constructor, so you could avoid the std::vector if you don’t need to add parameters programatically.

2 Likes

Alright, thanks, that makes more sense! So the basic pattern is: create your unique_ptr, store the derivative ptr in your processor, pass the unique_ptr to the tree.

1 Like

The recommended way is now to construct the AudioProcessorValueTreeState directly with a ParameterLayout containing all the parameters.

I got some code where I pass around the valueTreeState to different classes at construction, and create a couple of parameters within my mainProcessor, and some other ones in those other classes. something along those lines :

struct MainProcessor : public AudioProcessor
{
    MainProcessor()
    : state (*this, nullptr)
    , anotherProcessorClass (state)
    {
        state.createAndAddParameter (...);
    }

    AudioProcessorValueTreeState state;
    AnotherProcessorClass anotherProcessorClass;
};

struct AnotherProcessorClass
{
    AnotherProcessorClass (AudioProcessorValueTreeState& state)
    {
        state.addListener (this);
        state.createAndAddParameter (...);
    }
};

Was it bad practice?
It seems to me I can’t really do that anymore with the new recommended AudioProcessorValueTreeState constructor no? (I only had a quick look, so perhaps I’m missing something simple)

Is there a straightforward way of attaching Projucer-generated GUI elements (e.g. Sliders, Buttons etc) to AudioProcessorValueTreeState?

===
I am using Projucer [v5.4.1] to add a Slider as a GUI subcomponent.
I would like to be able to use SliderAttachment to attach that Projucer-made Slider to a parameter within the APVTS, but with Projucer, I end up with following code:

in AudioPluginEditor.h

private:
//[UserVariables] – You can add your own custom variables in this section.

AudioProcessorValueTreeState &valueTreeState;
typedef AudioProcessorValueTreeState::SliderAttachment SliderAttachment;
std::unique_ptr<SliderAttachment> testAttachment;

//[/UserVariables]

//==================================================== 
std::unique_ptr<Slider> test_slider;

in AudioPluginEditor.ccp

// constructor...
testAttachment.reset(new SliderAttachment(valueTreeState, "test_int", *test_slider.get()));

// destructor ...
///[/Destructor_pre]
test_slider = nullptr;
//[Destructor]. You can add your own custom destruction code here...

The problem is that “test_slider = nullptr” throws an exception:

“Exception thrown: read access violation.”

… , but, when I add my own - not Projucer-generated - code for a Slider& as a class member:

Slider &member_slider;

and

testAttachment.reset(new SliderAttachment(valueTreeState, "test_int", member_slider));

… it works fine.

The above suggests some rather inelegant, makeshift workarounds involving copy&paste, but I am wondering if there exists a more systemic approach.

If you have a set number of elements I would just make them members, in the case of that generated code they’re destroying test_slider before the slider attachment which isn’t allowed (you’ll have to add testAttachment = nullptr before the line where test_slider is set to nullptr)

If your slider is a member and the slider attachment is heap allocated to a std::unique_ptr then the destruction order will be fine

Thanks.
The point is that I am already spoiled by Projucer’s interactive GUI layout features and don’t want to regress to adding GUI class members by hand.
In the “days of yore”, Projucer used to make “plain” members.
Perhaps it would be a good enhancement to add an option to Projucer that would allow a choice between heap and stack allocation. Just an idea that may turn out to be naive in the context of other forces at play.

AFAIK the GUI editor is basically there for legacy reasons, in this post it’s mentioned they don’t plan to add any features to it.

1 Like

I’m looking at one of my first plugins to bring it up to date with what I’ve learned in the last year and to use 5.4.1 but I can’t seem to get an AudioParameterChoice to initialise using the example given.
This is the sort of thing I’m doing :

auto choice = std::make_unique<AudioParameterChoice> ("choice", "Choice", {"Choice 1", "Choice 2", "Choice 3", "Choice 4"}, 1);

but the compiler complains No matching function for call to 'make_unique'

However my original code doing something like :

auto choice = new AudioParameterChoice ("choice", "Choice", {"Choice 1", "Choice 2", "Choice 3", "Choice 4"}, 1);

or even doing :

std::unique_ptr<AudioParameterChoice> choice;
choice.reset( new AudioParameterChoice ("choice", "Choice", {"Choice 1", "Choice 2", "Choice 3", "Choice 4"}, 1) );

doesn’t complain at all.

What am I missing?

The previous version called the Constructor, so it had the proper type information available to implicitly cast the Strings initialiser list to a StringArray. The make_unique however doesn’t have the argument types of the constructor available, it just forwards the arguments.

The solution is, to supply the type like:

auto choice = std::make_unique<AudioParameterChoice> ("choice", 
                                                      "Choice", 
                                                      StringArray ({"Choice 1", "Choice 2", "Choice 3", "Choice 4"}), 
                                                      1);

Haven’t tested it, but something like that should work…

3 Likes

Thanks, exactly that! I even looked at that and thought, "no must be fine if it works with new". Useful to know that restriction about make_unique.

Could your AnotherProcessorClass have a method that returns an array of AudioProcessorParameters (or perhaps a group of them) which you could then pass to the ParameterLayout constructor after you’ve initialised?

Something roughly along the lines of:

struct MainProcessor : public AudioProcessor
{
    MainProcessor()
        : state (*this, nullptr, "state", anotherProcessorClass1.getParameters(), 
                                          anotherProcessorClass2.getParameters()), 
    {
    }

    AudioProcessorValueTreeState state;
    AnotherProcessorClass anotherProcessorClass;
};

not really, because my “AnotherProcessorClass” constructor is expecting the AudioProcessorValueTreeState as parameter.

Of course I could change that, do things differently, but I wanted to stress the point that the new way can imply quite a few changes.

I just hope you will keep the old constructor around for a while… (I’m really not against the latest changes, which are most likely an improvement, but it’s quite some work to stay up to date with changes and depreciations lately)

Hi All,
I am playing around tutorial Cascading plug-in effects using processors which already use APVTS, similar like @lalala mentioned.

For now I had implementation more or less like @t0m proposed, but I wondering if each processor could have its own APVTS. Then in main processor methods getStateInformation and setStateInformation would be a little more complicated. But I think AudioPluginHost has such implementation already. There is static function createNodeXml in FilterGraph which calls
node->getProcessor()->getStateInformation (m);

Is there anything against using own APVTS object in all “anotherProcessorClass-es”?
Does it sounds reasonable?

Kindly regards,
Mateusz

I think it’s good that you’ve got the AudioParameterX classes back into the APVTS stuff. However, the best practice method seems to make it hard (impossible?) to use NormalisableRange::setSkewForCentre().

To grab an existing chunk of code as an example:

auto bwp_range = NormalisableRange<float>(MINUS_THIRTY_SIX_DB, 1.0f); bwp_range.setSkewForCentre(Decibels::decibelsToGain(-8.0f)); brick_wall_param = parameters.createAndAddParameter(std::make_unique<Parameter>("limit", "Target Max Signal", "dB", bwp_range, 1.0f, db_to_text, db_from_text));

Using parameters.getParameterRange("limit").setSkewForCentre(Decibels::decibelsToGain(-8.0f)); after the constructor block doesn’t work because getParameterRange returns a copy of the NormalisableRange.

parameters.getParameter("limit")->getNormalisableRange().setSkewForCentre(Decibels::decibelsToGain(-8.0f)); doesn’t work because this time it returns a const.

Any recommendations?

I haven’t tried it, but I would expect something like this to work:

juce::AudioProcessorValueTreeState::ParameterLayout makeParameters() {
  auto param = std::make_unique<juce::AudioParameterFloat>(...);
  param->range.setSkewForCentre(...);
  return { std::move(param), /* any extra parameters go here */ };
}

// When constructing your apvts
MyAudioProcessor()
  : apvts { *this, nullptr, "state", makeParameters() }
{
}
1 Like