The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

962 lines
37KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 6 End-User License
  8. Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
  9. End User License Agreement: www.juce.com/juce-6-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. namespace juce
  19. {
  20. //==============================================================================
  21. AudioProcessorValueTreeState::Parameter::Parameter (const String& parameterID,
  22. const String& parameterName,
  23. const String& labelText,
  24. NormalisableRange<float> valueRange,
  25. float defaultParameterValue,
  26. std::function<String (float)> valueToTextFunction,
  27. std::function<float (const String&)> textToValueFunction,
  28. bool isMetaParameter,
  29. bool isAutomatableParameter,
  30. bool isDiscrete,
  31. AudioProcessorParameter::Category parameterCategory,
  32. bool isBoolean)
  33. : AudioParameterFloat (parameterID,
  34. parameterName,
  35. valueRange,
  36. defaultParameterValue,
  37. labelText,
  38. parameterCategory,
  39. valueToTextFunction == nullptr ? std::function<String (float v, int)>()
  40. : [valueToTextFunction] (float v, int) { return valueToTextFunction (v); },
  41. std::move (textToValueFunction)),
  42. unsnappedDefault (valueRange.convertTo0to1 (defaultParameterValue)),
  43. metaParameter (isMetaParameter),
  44. automatable (isAutomatableParameter),
  45. discrete (isDiscrete),
  46. boolean (isBoolean)
  47. {
  48. }
  49. float AudioProcessorValueTreeState::Parameter::getDefaultValue() const { return unsnappedDefault; }
  50. int AudioProcessorValueTreeState::Parameter::getNumSteps() const { return RangedAudioParameter::getNumSteps(); }
  51. bool AudioProcessorValueTreeState::Parameter::isMetaParameter() const { return metaParameter; }
  52. bool AudioProcessorValueTreeState::Parameter::isAutomatable() const { return automatable; }
  53. bool AudioProcessorValueTreeState::Parameter::isDiscrete() const { return discrete; }
  54. bool AudioProcessorValueTreeState::Parameter::isBoolean() const { return boolean; }
  55. void AudioProcessorValueTreeState::Parameter::valueChanged (float newValue)
  56. {
  57. if (lastValue == newValue)
  58. return;
  59. lastValue = newValue;
  60. if (onValueChanged != nullptr)
  61. onValueChanged();
  62. }
  63. //==============================================================================
  64. class AudioProcessorValueTreeState::ParameterAdapter : private AudioProcessorParameter::Listener
  65. {
  66. private:
  67. using Listener = AudioProcessorValueTreeState::Listener;
  68. public:
  69. explicit ParameterAdapter (RangedAudioParameter& parameterIn)
  70. : parameter (parameterIn),
  71. // For legacy reasons, the unnormalised value should *not* be snapped on construction
  72. unnormalisedValue (getRange().convertFrom0to1 (parameter.getDefaultValue()))
  73. {
  74. parameter.addListener (this);
  75. if (auto* ptr = dynamic_cast<Parameter*> (&parameter))
  76. ptr->onValueChanged = [this] { parameterValueChanged ({}, {}); };
  77. }
  78. ~ParameterAdapter() override { parameter.removeListener (this); }
  79. void addListener (Listener* l) { listeners.add (l); }
  80. void removeListener (Listener* l) { listeners.remove (l); }
  81. RangedAudioParameter& getParameter() { return parameter; }
  82. const RangedAudioParameter& getParameter() const { return parameter; }
  83. const NormalisableRange<float>& getRange() const { return parameter.getNormalisableRange(); }
  84. float getDenormalisedDefaultValue() const { return denormalise (parameter.getDefaultValue()); }
  85. void setDenormalisedValue (float value)
  86. {
  87. if (value == unnormalisedValue)
  88. return;
  89. setNormalisedValue (normalise (value));
  90. }
  91. float getDenormalisedValueForText (const String& text) const
  92. {
  93. return denormalise (parameter.getValueForText (text));
  94. }
  95. String getTextForDenormalisedValue (float value) const
  96. {
  97. return parameter.getText (normalise (value), 0);
  98. }
  99. float getDenormalisedValue() const { return unnormalisedValue; }
  100. std::atomic<float>& getRawDenormalisedValue() { return unnormalisedValue; }
  101. bool flushToTree (const Identifier& key, UndoManager* um)
  102. {
  103. auto needsUpdateTestValue = true;
  104. if (! needsUpdate.compare_exchange_strong (needsUpdateTestValue, false))
  105. return false;
  106. if (auto valueProperty = tree.getPropertyPointer (key))
  107. {
  108. if ((float) *valueProperty != unnormalisedValue)
  109. {
  110. ScopedValueSetter<bool> svs (ignoreParameterChangedCallbacks, true);
  111. tree.setProperty (key, unnormalisedValue.load(), um);
  112. }
  113. }
  114. else
  115. {
  116. tree.setProperty (key, unnormalisedValue.load(), nullptr);
  117. }
  118. return true;
  119. }
  120. ValueTree tree;
  121. private:
  122. void parameterGestureChanged (int, bool) override {}
  123. void parameterValueChanged (int, float) override
  124. {
  125. const auto newValue = denormalise (parameter.getValue());
  126. if (unnormalisedValue == newValue && ! listenersNeedCalling)
  127. return;
  128. unnormalisedValue = newValue;
  129. listeners.call ([=] (Listener& l) { l.parameterChanged (parameter.paramID, unnormalisedValue); });
  130. listenersNeedCalling = false;
  131. needsUpdate = true;
  132. }
  133. float denormalise (float normalised) const
  134. {
  135. return getParameter().convertFrom0to1 (normalised);
  136. }
  137. float normalise (float denormalised) const
  138. {
  139. return getParameter().convertTo0to1 (denormalised);
  140. }
  141. void setNormalisedValue (float value)
  142. {
  143. if (ignoreParameterChangedCallbacks)
  144. return;
  145. parameter.setValueNotifyingHost (value);
  146. }
  147. class LockedListeners
  148. {
  149. public:
  150. template <typename Fn>
  151. void call (Fn&& fn)
  152. {
  153. const CriticalSection::ScopedLockType lock (mutex);
  154. listeners.call (std::forward<Fn> (fn));
  155. }
  156. void add (Listener* l)
  157. {
  158. const CriticalSection::ScopedLockType lock (mutex);
  159. listeners.add (l);
  160. }
  161. void remove (Listener* l)
  162. {
  163. const CriticalSection::ScopedLockType lock (mutex);
  164. listeners.remove (l);
  165. }
  166. private:
  167. CriticalSection mutex;
  168. ListenerList<Listener> listeners;
  169. };
  170. RangedAudioParameter& parameter;
  171. LockedListeners listeners;
  172. std::atomic<float> unnormalisedValue { 0.0f };
  173. std::atomic<bool> needsUpdate { true }, listenersNeedCalling { true };
  174. bool ignoreParameterChangedCallbacks { false };
  175. };
  176. //==============================================================================
  177. AudioProcessorValueTreeState::AudioProcessorValueTreeState (AudioProcessor& processorToConnectTo,
  178. UndoManager* undoManagerToUse,
  179. const Identifier& valueTreeType,
  180. ParameterLayout parameterLayout)
  181. : AudioProcessorValueTreeState (processorToConnectTo, undoManagerToUse)
  182. {
  183. struct PushBackVisitor : ParameterLayout::Visitor
  184. {
  185. explicit PushBackVisitor (AudioProcessorValueTreeState& stateIn)
  186. : state (&stateIn) {}
  187. void visit (std::unique_ptr<RangedAudioParameter> param) const override
  188. {
  189. if (param == nullptr)
  190. {
  191. jassertfalse;
  192. return;
  193. }
  194. state->addParameterAdapter (*param);
  195. state->processor.addParameter (param.release());
  196. }
  197. void visit (std::unique_ptr<AudioProcessorParameterGroup> group) const override
  198. {
  199. if (group == nullptr)
  200. {
  201. jassertfalse;
  202. return;
  203. }
  204. for (const auto param : group->getParameters (true))
  205. {
  206. if (const auto rangedParam = dynamic_cast<RangedAudioParameter*> (param))
  207. {
  208. state->addParameterAdapter (*rangedParam);
  209. }
  210. else
  211. {
  212. // If you hit this assertion then you are attempting to add a parameter that is
  213. // not derived from RangedAudioParameter to the AudioProcessorValueTreeState.
  214. jassertfalse;
  215. }
  216. }
  217. state->processor.addParameterGroup (move (group));
  218. }
  219. AudioProcessorValueTreeState* state;
  220. };
  221. for (auto& item : parameterLayout.parameters)
  222. item->accept (PushBackVisitor (*this));
  223. state = ValueTree (valueTreeType);
  224. }
  225. AudioProcessorValueTreeState::AudioProcessorValueTreeState (AudioProcessor& p, UndoManager* um)
  226. : processor (p), undoManager (um)
  227. {
  228. startTimerHz (10);
  229. state.addListener (this);
  230. }
  231. AudioProcessorValueTreeState::~AudioProcessorValueTreeState()
  232. {
  233. stopTimer();
  234. }
  235. //==============================================================================
  236. RangedAudioParameter* AudioProcessorValueTreeState::createAndAddParameter (const String& paramID,
  237. const String& paramName,
  238. const String& labelText,
  239. NormalisableRange<float> range,
  240. float defaultVal,
  241. std::function<String (float)> valueToTextFunction,
  242. std::function<float (const String&)> textToValueFunction,
  243. bool isMetaParameter,
  244. bool isAutomatableParameter,
  245. bool isDiscreteParameter,
  246. AudioProcessorParameter::Category category,
  247. bool isBooleanParameter)
  248. {
  249. return createAndAddParameter (std::make_unique<Parameter> (paramID,
  250. paramName,
  251. labelText,
  252. range,
  253. defaultVal,
  254. std::move (valueToTextFunction),
  255. std::move (textToValueFunction),
  256. isMetaParameter,
  257. isAutomatableParameter,
  258. isDiscreteParameter,
  259. category,
  260. isBooleanParameter));
  261. }
  262. RangedAudioParameter* AudioProcessorValueTreeState::createAndAddParameter (std::unique_ptr<RangedAudioParameter> param)
  263. {
  264. if (param == nullptr)
  265. return nullptr;
  266. // All parameters must be created before giving this manager a ValueTree state!
  267. jassert (! state.isValid());
  268. if (getParameter (param->paramID) != nullptr)
  269. return nullptr;
  270. addParameterAdapter (*param);
  271. processor.addParameter (param.get());
  272. return param.release();
  273. }
  274. //==============================================================================
  275. void AudioProcessorValueTreeState::addParameterAdapter (RangedAudioParameter& param)
  276. {
  277. adapterTable.emplace (param.paramID, std::make_unique<ParameterAdapter> (param));
  278. }
  279. AudioProcessorValueTreeState::ParameterAdapter* AudioProcessorValueTreeState::getParameterAdapter (StringRef paramID) const
  280. {
  281. auto it = adapterTable.find (paramID);
  282. return it == adapterTable.end() ? nullptr : it->second.get();
  283. }
  284. void AudioProcessorValueTreeState::addParameterListener (StringRef paramID, Listener* listener)
  285. {
  286. if (auto* p = getParameterAdapter (paramID))
  287. p->addListener (listener);
  288. }
  289. void AudioProcessorValueTreeState::removeParameterListener (StringRef paramID, Listener* listener)
  290. {
  291. if (auto* p = getParameterAdapter (paramID))
  292. p->removeListener (listener);
  293. }
  294. Value AudioProcessorValueTreeState::getParameterAsValue (StringRef paramID) const
  295. {
  296. if (auto* adapter = getParameterAdapter (paramID))
  297. if (adapter->tree.isValid())
  298. return adapter->tree.getPropertyAsValue (valuePropertyID, undoManager);
  299. return {};
  300. }
  301. NormalisableRange<float> AudioProcessorValueTreeState::getParameterRange (StringRef paramID) const noexcept
  302. {
  303. if (auto* p = getParameterAdapter (paramID))
  304. return p->getRange();
  305. return {};
  306. }
  307. RangedAudioParameter* AudioProcessorValueTreeState::getParameter (StringRef paramID) const noexcept
  308. {
  309. if (auto adapter = getParameterAdapter (paramID))
  310. return &adapter->getParameter();
  311. return nullptr;
  312. }
  313. std::atomic<float>* AudioProcessorValueTreeState::getRawParameterValue (StringRef paramID) const noexcept
  314. {
  315. if (auto* p = getParameterAdapter (paramID))
  316. return &p->getRawDenormalisedValue();
  317. return nullptr;
  318. }
  319. ValueTree AudioProcessorValueTreeState::copyState()
  320. {
  321. ScopedLock lock (valueTreeChanging);
  322. flushParameterValuesToValueTree();
  323. return state.createCopy();
  324. }
  325. void AudioProcessorValueTreeState::replaceState (const ValueTree& newState)
  326. {
  327. ScopedLock lock (valueTreeChanging);
  328. state = newState;
  329. if (undoManager != nullptr)
  330. undoManager->clearUndoHistory();
  331. }
  332. void AudioProcessorValueTreeState::setNewState (ValueTree vt)
  333. {
  334. jassert (vt.getParent() == state);
  335. if (auto* p = getParameterAdapter (vt.getProperty (idPropertyID).toString()))
  336. {
  337. p->tree = vt;
  338. p->setDenormalisedValue (p->tree.getProperty (valuePropertyID, p->getDenormalisedDefaultValue()));
  339. }
  340. }
  341. void AudioProcessorValueTreeState::updateParameterConnectionsToChildTrees()
  342. {
  343. ScopedLock lock (valueTreeChanging);
  344. for (auto& p : adapterTable)
  345. p.second->tree = ValueTree();
  346. for (const auto& child : state)
  347. setNewState (child);
  348. for (auto& p : adapterTable)
  349. {
  350. auto& adapter = *p.second;
  351. if (! adapter.tree.isValid())
  352. {
  353. adapter.tree = ValueTree (valueType);
  354. adapter.tree.setProperty (idPropertyID, adapter.getParameter().paramID, nullptr);
  355. state.appendChild (adapter.tree, nullptr);
  356. }
  357. }
  358. flushParameterValuesToValueTree();
  359. }
  360. void AudioProcessorValueTreeState::valueTreePropertyChanged (ValueTree& tree, const Identifier&)
  361. {
  362. if (tree.hasType (valueType) && tree.getParent() == state)
  363. setNewState (tree);
  364. }
  365. void AudioProcessorValueTreeState::valueTreeChildAdded (ValueTree& parent, ValueTree& tree)
  366. {
  367. if (parent == state && tree.hasType (valueType))
  368. setNewState (tree);
  369. }
  370. void AudioProcessorValueTreeState::valueTreeRedirected (ValueTree& v)
  371. {
  372. if (v == state)
  373. updateParameterConnectionsToChildTrees();
  374. }
  375. bool AudioProcessorValueTreeState::flushParameterValuesToValueTree()
  376. {
  377. ScopedLock lock (valueTreeChanging);
  378. bool anyUpdated = false;
  379. for (auto& p : adapterTable)
  380. anyUpdated |= p.second->flushToTree (valuePropertyID, undoManager);
  381. return anyUpdated;
  382. }
  383. void AudioProcessorValueTreeState::timerCallback()
  384. {
  385. auto anythingUpdated = flushParameterValuesToValueTree();
  386. startTimer (anythingUpdated ? 1000 / 50
  387. : jlimit (50, 500, getTimerInterval() + 20));
  388. }
  389. //==============================================================================
  390. template <typename Attachment, typename Control>
  391. std::unique_ptr<Attachment> makeAttachment (const AudioProcessorValueTreeState& stateToUse,
  392. const String& parameterID,
  393. Control& control)
  394. {
  395. if (auto* parameter = stateToUse.getParameter (parameterID))
  396. return std::make_unique<Attachment> (*parameter, control, stateToUse.undoManager);
  397. jassertfalse;
  398. return nullptr;
  399. }
  400. AudioProcessorValueTreeState::SliderAttachment::SliderAttachment (AudioProcessorValueTreeState& stateToUse,
  401. const String& parameterID,
  402. Slider& slider)
  403. : attachment (makeAttachment<SliderParameterAttachment> (stateToUse, parameterID, slider))
  404. {
  405. }
  406. AudioProcessorValueTreeState::ComboBoxAttachment::ComboBoxAttachment (AudioProcessorValueTreeState& stateToUse,
  407. const String& parameterID,
  408. ComboBox& combo)
  409. : attachment (makeAttachment<ComboBoxParameterAttachment> (stateToUse, parameterID, combo))
  410. {
  411. }
  412. AudioProcessorValueTreeState::ButtonAttachment::ButtonAttachment (AudioProcessorValueTreeState& stateToUse,
  413. const String& parameterID,
  414. Button& button)
  415. : attachment (makeAttachment<ButtonParameterAttachment> (stateToUse, parameterID, button))
  416. {
  417. }
  418. //==============================================================================
  419. //==============================================================================
  420. #if JUCE_UNIT_TESTS
  421. struct ParameterAdapterTests : public UnitTest
  422. {
  423. ParameterAdapterTests()
  424. : UnitTest ("Parameter Adapter", UnitTestCategories::audioProcessorParameters)
  425. {}
  426. void runTest() override
  427. {
  428. beginTest ("The default value is returned correctly");
  429. {
  430. const auto test = [&] (NormalisableRange<float> range, float value)
  431. {
  432. AudioParameterFloat param ({}, {}, range, value, {});
  433. AudioProcessorValueTreeState::ParameterAdapter adapter (param);
  434. expectEquals (adapter.getDenormalisedDefaultValue(), value);
  435. };
  436. test ({ -100, 100 }, 0);
  437. test ({ -2.5, 12.5 }, 10);
  438. }
  439. beginTest ("Denormalised parameter values can be retrieved");
  440. {
  441. const auto test = [&] (NormalisableRange<float> range, float value)
  442. {
  443. AudioParameterFloat param ({}, {}, range, {}, {});
  444. AudioProcessorValueTreeState::ParameterAdapter adapter (param);
  445. adapter.setDenormalisedValue (value);
  446. expectEquals (adapter.getDenormalisedValue(), value);
  447. expectEquals (adapter.getRawDenormalisedValue().load(), value);
  448. };
  449. test ({ -20, -10 }, -15);
  450. test ({ 0, 7.5 }, 2.5);
  451. }
  452. beginTest ("Floats can be converted to text");
  453. {
  454. const auto test = [&] (NormalisableRange<float> range, float value, String expected)
  455. {
  456. AudioParameterFloat param ({}, {}, range, {}, {});
  457. AudioProcessorValueTreeState::ParameterAdapter adapter (param);
  458. expectEquals (adapter.getTextForDenormalisedValue (value), expected);
  459. };
  460. test ({ -100, 100 }, 0, "0.0000000");
  461. test ({ -2.5, 12.5 }, 10, "10.0000000");
  462. test ({ -20, -10 }, -15, "-15.0000000");
  463. test ({ 0, 7.5 }, 2.5, "2.5000000");
  464. }
  465. beginTest ("Text can be converted to floats");
  466. {
  467. const auto test = [&] (NormalisableRange<float> range, String text, float expected)
  468. {
  469. AudioParameterFloat param ({}, {}, range, {}, {});
  470. AudioProcessorValueTreeState::ParameterAdapter adapter (param);
  471. expectEquals (adapter.getDenormalisedValueForText (text), expected);
  472. };
  473. test ({ -100, 100 }, "0.0", 0);
  474. test ({ -2.5, 12.5 }, "10.0", 10);
  475. test ({ -20, -10 }, "-15.0", -15);
  476. test ({ 0, 7.5 }, "2.5", 2.5);
  477. }
  478. }
  479. };
  480. static ParameterAdapterTests parameterAdapterTests;
  481. namespace
  482. {
  483. template <typename ValueType>
  484. inline bool operator== (const NormalisableRange<ValueType>& a,
  485. const NormalisableRange<ValueType>& b)
  486. {
  487. return std::tie (a.start, a.end, a.interval, a.skew, a.symmetricSkew)
  488. == std::tie (b.start, b.end, b.interval, b.skew, b.symmetricSkew);
  489. }
  490. template <typename ValueType>
  491. inline bool operator!= (const NormalisableRange<ValueType>& a,
  492. const NormalisableRange<ValueType>& b)
  493. {
  494. return ! (a == b);
  495. }
  496. } // namespace
  497. class AudioProcessorValueTreeStateTests : public UnitTest
  498. {
  499. private:
  500. using Parameter = AudioProcessorValueTreeState::Parameter;
  501. using ParameterGroup = AudioProcessorParameterGroup;
  502. using ParameterLayout = AudioProcessorValueTreeState::ParameterLayout;
  503. class TestAudioProcessor : public AudioProcessor
  504. {
  505. public:
  506. TestAudioProcessor() = default;
  507. explicit TestAudioProcessor (ParameterLayout layout)
  508. : state (*this, nullptr, "state", std::move (layout)) {}
  509. const String getName() const override { return {}; }
  510. void prepareToPlay (double, int) override {}
  511. void releaseResources() override {}
  512. void processBlock (AudioBuffer<float>&, MidiBuffer&) override {}
  513. using AudioProcessor::processBlock;
  514. double getTailLengthSeconds() const override { return {}; }
  515. bool acceptsMidi() const override { return {}; }
  516. bool producesMidi() const override { return {}; }
  517. AudioProcessorEditor* createEditor() override { return {}; }
  518. bool hasEditor() const override { return {}; }
  519. int getNumPrograms() override { return 1; }
  520. int getCurrentProgram() override { return {}; }
  521. void setCurrentProgram (int) override {}
  522. const String getProgramName (int) override { return {}; }
  523. void changeProgramName (int, const String&) override {}
  524. void getStateInformation (MemoryBlock&) override {}
  525. void setStateInformation (const void*, int) override {}
  526. AudioProcessorValueTreeState state { *this, nullptr };
  527. };
  528. struct Listener final : public AudioProcessorValueTreeState::Listener
  529. {
  530. void parameterChanged (const String& idIn, float valueIn) override
  531. {
  532. id = idIn;
  533. value = valueIn;
  534. }
  535. String id;
  536. float value{};
  537. };
  538. public:
  539. AudioProcessorValueTreeStateTests()
  540. : UnitTest ("Audio Processor Value Tree State", UnitTestCategories::audioProcessorParameters)
  541. {}
  542. void runTest() override
  543. {
  544. ScopedJuceInitialiser_GUI scopedJuceInitialiser_gui;
  545. beginTest ("After calling createAndAddParameter, the number of parameters increases by one");
  546. {
  547. TestAudioProcessor proc;
  548. proc.state.createAndAddParameter (std::make_unique<Parameter> (String(), String(), String(), NormalisableRange<float>(),
  549. 0.0f, nullptr, nullptr));
  550. expectEquals (proc.getParameters().size(), 1);
  551. }
  552. beginTest ("After creating a normal named parameter, we can later retrieve that parameter");
  553. {
  554. TestAudioProcessor proc;
  555. const auto key = "id";
  556. const auto param = proc.state.createAndAddParameter (std::make_unique<Parameter> (key, String(), String(), NormalisableRange<float>(),
  557. 0.0f, nullptr, nullptr));
  558. expect (proc.state.getParameter (key) == param);
  559. }
  560. beginTest ("After construction, the value tree has the expected format");
  561. {
  562. TestAudioProcessor proc ({
  563. std::make_unique<AudioProcessorParameterGroup> ("", "", "",
  564. std::make_unique<AudioParameterBool> ("a", "", false),
  565. std::make_unique<AudioParameterFloat> ("b", "", NormalisableRange<float>{}, 0.0f)),
  566. std::make_unique<AudioProcessorParameterGroup> ("", "", "",
  567. std::make_unique<AudioParameterInt> ("c", "", 0, 1, 0),
  568. std::make_unique<AudioParameterChoice> ("d", "", StringArray { "foo", "bar" }, 0)) });
  569. const auto valueTree = proc.state.copyState();
  570. expectEquals (valueTree.getNumChildren(), 4);
  571. for (auto child : valueTree)
  572. {
  573. expect (child.hasType ("PARAM"));
  574. expect (child.hasProperty ("id"));
  575. expect (child.hasProperty ("value"));
  576. }
  577. }
  578. beginTest ("Meta parameters can be created");
  579. {
  580. TestAudioProcessor proc;
  581. const auto key = "id";
  582. const auto param = proc.state.createAndAddParameter (std::make_unique<Parameter> (key, String(), String(), NormalisableRange<float>(),
  583. 0.0f, nullptr, nullptr, true));
  584. expect (param->isMetaParameter());
  585. }
  586. beginTest ("Automatable parameters can be created");
  587. {
  588. TestAudioProcessor proc;
  589. const auto key = "id";
  590. const auto param = proc.state.createAndAddParameter (std::make_unique<Parameter> (key, String(), String(), NormalisableRange<float>(),
  591. 0.0f, nullptr, nullptr, false, true));
  592. expect (param->isAutomatable());
  593. }
  594. beginTest ("Discrete parameters can be created");
  595. {
  596. TestAudioProcessor proc;
  597. const auto key = "id";
  598. const auto param = proc.state.createAndAddParameter (std::make_unique<Parameter> (key, String(), String(), NormalisableRange<float>(),
  599. 0.0f, nullptr, nullptr, false, false, true));
  600. expect (param->isDiscrete());
  601. }
  602. beginTest ("Custom category parameters can be created");
  603. {
  604. TestAudioProcessor proc;
  605. const auto key = "id";
  606. const auto param = proc.state.createAndAddParameter (std::make_unique<Parameter> (key, String(), String(), NormalisableRange<float>(),
  607. 0.0f, nullptr, nullptr, false, false, false,
  608. AudioProcessorParameter::Category::inputMeter));
  609. expect (param->category == AudioProcessorParameter::Category::inputMeter);
  610. }
  611. beginTest ("Boolean parameters can be created");
  612. {
  613. TestAudioProcessor proc;
  614. const auto key = "id";
  615. const auto param = proc.state.createAndAddParameter (std::make_unique<Parameter> (key, String(), String(), NormalisableRange<float>(),
  616. 0.0f, nullptr, nullptr, false, false, false,
  617. AudioProcessorParameter::Category::genericParameter, true));
  618. expect (param->isBoolean());
  619. }
  620. beginTest ("After creating a custom named parameter, we can later retrieve that parameter");
  621. {
  622. const auto key = "id";
  623. auto param = std::make_unique<AudioParameterBool> (key, "", false);
  624. const auto paramPtr = param.get();
  625. TestAudioProcessor proc (std::move (param));
  626. expect (proc.state.getParameter (key) == paramPtr);
  627. }
  628. beginTest ("After adding a normal parameter that already exists, the AudioProcessor parameters are unchanged");
  629. {
  630. TestAudioProcessor proc;
  631. const auto key = "id";
  632. const auto param = proc.state.createAndAddParameter (std::make_unique<Parameter> (key, String(), String(), NormalisableRange<float>(),
  633. 0.0f, nullptr, nullptr));
  634. proc.state.createAndAddParameter (std::make_unique<Parameter> (key, String(), String(), NormalisableRange<float>(),
  635. 0.0f, nullptr, nullptr));
  636. expectEquals (proc.getParameters().size(), 1);
  637. expect (proc.getParameters().getFirst() == param);
  638. }
  639. beginTest ("After setting a parameter value, that value is reflected in the state");
  640. {
  641. TestAudioProcessor proc;
  642. const auto key = "id";
  643. const auto param = proc.state.createAndAddParameter (std::make_unique<Parameter> (key, String(), String(), NormalisableRange<float>(),
  644. 0.0f, nullptr, nullptr));
  645. const auto value = 0.5f;
  646. param->setValueNotifyingHost (value);
  647. expectEquals (proc.state.getRawParameterValue (key)->load(), value);
  648. }
  649. beginTest ("After adding an APVTS::Parameter, its value is the default value");
  650. {
  651. TestAudioProcessor proc;
  652. const auto key = "id";
  653. const auto value = 5.0f;
  654. proc.state.createAndAddParameter (std::make_unique<Parameter> (
  655. key,
  656. String(),
  657. String(),
  658. NormalisableRange<float> (0.0f, 100.0f, 10.0f),
  659. value,
  660. nullptr,
  661. nullptr));
  662. expectEquals (proc.state.getRawParameterValue (key)->load(), value);
  663. }
  664. beginTest ("Listeners receive notifications when parameters change");
  665. {
  666. Listener listener;
  667. TestAudioProcessor proc;
  668. const auto key = "id";
  669. const auto param = proc.state.createAndAddParameter (std::make_unique<Parameter> (key, String(), String(), NormalisableRange<float>(),
  670. 0.0f, nullptr, nullptr));
  671. proc.state.addParameterListener (key, &listener);
  672. const auto value = 0.5f;
  673. param->setValueNotifyingHost (value);
  674. expectEquals (listener.id, String { key });
  675. expectEquals (listener.value, value);
  676. }
  677. beginTest ("Bool parameters have a range of 0-1");
  678. {
  679. const auto key = "id";
  680. TestAudioProcessor proc (std::make_unique<AudioParameterBool> (key, "", false));
  681. expect (proc.state.getParameterRange (key) == NormalisableRange<float> (0.0f, 1.0f, 1.0f));
  682. }
  683. beginTest ("Float parameters retain their specified range");
  684. {
  685. const auto key = "id";
  686. const auto range = NormalisableRange<float> { -100, 100, 0.7f, 0.2f, true };
  687. TestAudioProcessor proc (std::make_unique<AudioParameterFloat> (key, "", range, 0.0f));
  688. expect (proc.state.getParameterRange (key) == range);
  689. }
  690. beginTest ("Int parameters retain their specified range");
  691. {
  692. const auto key = "id";
  693. const auto min = -27;
  694. const auto max = 53;
  695. TestAudioProcessor proc (std::make_unique<AudioParameterInt> (key, "", min, max, 0));
  696. expect (proc.state.getParameterRange (key) == NormalisableRange<float> (float (min), float (max), 1.0f));
  697. }
  698. beginTest ("Choice parameters retain their specified range");
  699. {
  700. const auto key = "id";
  701. const auto choices = StringArray { "", "", "" };
  702. TestAudioProcessor proc (std::make_unique<AudioParameterChoice> (key, "", choices, 0));
  703. expect (proc.state.getParameterRange (key) == NormalisableRange<float> (0.0f, (float) (choices.size() - 1), 1.0f));
  704. expect (proc.state.getParameter (key)->getNumSteps() == choices.size());
  705. }
  706. beginTest ("When the parameter value is changed, normal parameter values are updated");
  707. {
  708. TestAudioProcessor proc;
  709. const auto key = "id";
  710. const auto initialValue = 0.2f;
  711. auto param = proc.state.createAndAddParameter (std::make_unique<Parameter> (key, String(), String(), NormalisableRange<float>(),
  712. initialValue, nullptr, nullptr));
  713. proc.state.state = ValueTree { "state" };
  714. auto value = proc.state.getParameterAsValue (key);
  715. expectEquals (float (value.getValue()), initialValue);
  716. const auto newValue = 0.75f;
  717. value = newValue;
  718. expectEquals (param->getValue(), newValue);
  719. expectEquals (proc.state.getRawParameterValue (key)->load(), newValue);
  720. }
  721. beginTest ("When the parameter value is changed, custom parameter values are updated");
  722. {
  723. const auto key = "id";
  724. const auto choices = StringArray ("foo", "bar", "baz");
  725. auto param = std::make_unique<AudioParameterChoice> (key, "", choices, 0);
  726. const auto paramPtr = param.get();
  727. TestAudioProcessor proc (std::move (param));
  728. const auto newValue = 2.0f;
  729. auto value = proc.state.getParameterAsValue (key);
  730. value = newValue;
  731. expectEquals (paramPtr->getCurrentChoiceName(), choices[int (newValue)]);
  732. expectEquals (proc.state.getRawParameterValue (key)->load(), newValue);
  733. }
  734. beginTest ("When the parameter value is changed, listeners are notified");
  735. {
  736. Listener listener;
  737. TestAudioProcessor proc;
  738. const auto key = "id";
  739. proc.state.createAndAddParameter (std::make_unique<Parameter> (key, String(), String(), NormalisableRange<float>(),
  740. 0.0f, nullptr, nullptr));
  741. proc.state.addParameterListener (key, &listener);
  742. proc.state.state = ValueTree { "state" };
  743. const auto newValue = 0.75f;
  744. proc.state.getParameterAsValue (key) = newValue;
  745. expectEquals (listener.value, newValue);
  746. expectEquals (listener.id, String { key });
  747. }
  748. beginTest ("When the parameter value is changed, listeners are notified");
  749. {
  750. const auto key = "id";
  751. const auto choices = StringArray { "foo", "bar", "baz" };
  752. Listener listener;
  753. TestAudioProcessor proc (std::make_unique<AudioParameterChoice> (key, "", choices, 0));
  754. proc.state.addParameterListener (key, &listener);
  755. const auto newValue = 2.0f;
  756. proc.state.getParameterAsValue (key) = newValue;
  757. expectEquals (listener.value, newValue);
  758. expectEquals (listener.id, String (key));
  759. }
  760. }
  761. };
  762. static AudioProcessorValueTreeStateTests audioProcessorValueTreeStateTests;
  763. #endif
  764. } // namespace juce