Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

juce_SmoothedValue.h 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. namespace juce
  18. {
  19. //==============================================================================
  20. /**
  21. A base class for the smoothed value classes.
  22. This class is used to provide common functionality to the SmoothedValue and
  23. dsp::LogRampedValue classes.
  24. @tags{Audio}
  25. */
  26. template <typename SmoothedValueType>
  27. class SmoothedValueBase
  28. {
  29. private:
  30. //==============================================================================
  31. template <typename T> struct FloatTypeHelper;
  32. template <template <typename> class SmoothedValueClass, typename FloatType>
  33. struct FloatTypeHelper <SmoothedValueClass <FloatType>>
  34. {
  35. using Type = FloatType;
  36. };
  37. template <template <typename, typename> class SmoothedValueClass, typename FloatType, typename SmoothingType>
  38. struct FloatTypeHelper <SmoothedValueClass <FloatType, SmoothingType>>
  39. {
  40. using Type = FloatType;
  41. };
  42. public:
  43. using FloatType = typename FloatTypeHelper<SmoothedValueType>::Type;
  44. //==============================================================================
  45. /** Constructor. */
  46. SmoothedValueBase() = default;
  47. //==============================================================================
  48. /** Returns true if the current value is currently being interpolated. */
  49. bool isSmoothing() const noexcept { return countdown > 0; }
  50. /** Returns the current value of the ramp. */
  51. FloatType getCurrentValue() const noexcept { return currentValue; }
  52. //==============================================================================
  53. /** Returns the target value towards which the smoothed value is currently moving. */
  54. FloatType getTargetValue() const noexcept { return target; }
  55. /** Sets the current value and the target value.
  56. @param newValue the new value to take
  57. */
  58. void setCurrentAndTargetValue (FloatType newValue)
  59. {
  60. target = currentValue = newValue;
  61. countdown = 0;
  62. }
  63. //==============================================================================
  64. /** Applies a smoothed gain to a stream of samples
  65. S[i] *= gain
  66. @param samples Pointer to a raw array of samples
  67. @param numSamples Length of array of samples
  68. */
  69. void applyGain (FloatType* samples, int numSamples) noexcept
  70. {
  71. jassert (numSamples >= 0);
  72. if (isSmoothing())
  73. {
  74. for (int i = 0; i < numSamples; ++i)
  75. samples[i] *= getNextSmoothedValue();
  76. }
  77. else
  78. {
  79. FloatVectorOperations::multiply (samples, target, numSamples);
  80. }
  81. }
  82. /** Computes output as a smoothed gain applied to a stream of samples.
  83. Sout[i] = Sin[i] * gain
  84. @param samplesOut A pointer to a raw array of output samples
  85. @param samplesIn A pointer to a raw array of input samples
  86. @param numSamples The length of the array of samples
  87. */
  88. void applyGain (FloatType* samplesOut, const FloatType* samplesIn, int numSamples) noexcept
  89. {
  90. jassert (numSamples >= 0);
  91. if (isSmoothing())
  92. {
  93. for (int i = 0; i < numSamples; ++i)
  94. samplesOut[i] = samplesIn[i] * getNextSmoothedValue();
  95. }
  96. else
  97. {
  98. FloatVectorOperations::multiply (samplesOut, samplesIn, target, numSamples);
  99. }
  100. }
  101. /** Applies a smoothed gain to a buffer */
  102. void applyGain (AudioBuffer<FloatType>& buffer, int numSamples) noexcept
  103. {
  104. jassert (numSamples >= 0);
  105. if (isSmoothing())
  106. {
  107. if (buffer.getNumChannels() == 1)
  108. {
  109. auto* samples = buffer.getWritePointer (0);
  110. for (int i = 0; i < numSamples; ++i)
  111. samples[i] *= getNextSmoothedValue();
  112. }
  113. else
  114. {
  115. for (auto i = 0; i < numSamples; ++i)
  116. {
  117. auto gain = getNextSmoothedValue();
  118. for (int channel = 0; channel < buffer.getNumChannels(); channel++)
  119. buffer.setSample (channel, i, buffer.getSample (channel, i) * gain);
  120. }
  121. }
  122. }
  123. else
  124. {
  125. buffer.applyGain (0, numSamples, target);
  126. }
  127. }
  128. private:
  129. //==============================================================================
  130. FloatType getNextSmoothedValue() noexcept
  131. {
  132. return static_cast <SmoothedValueType*> (this)->getNextValue();
  133. }
  134. protected:
  135. //==============================================================================
  136. FloatType currentValue = 0;
  137. FloatType target = currentValue;
  138. int countdown = 0;
  139. };
  140. //==============================================================================
  141. /**
  142. A namespace containing a set of types used for specifying the smoothing
  143. behaviour of the SmoothedValue class.
  144. For example:
  145. @code
  146. SmoothedValue<float, ValueSmoothingTypes::Multiplicative> frequency (1.0f);
  147. @endcode
  148. */
  149. namespace ValueSmoothingTypes
  150. {
  151. /**
  152. Used to indicate a linear smoothing between values.
  153. @tags{Audio}
  154. */
  155. struct Linear {};
  156. /**
  157. Used to indicate a smoothing between multiplicative values.
  158. @tags{Audio}
  159. */
  160. struct Multiplicative {};
  161. }
  162. //==============================================================================
  163. /**
  164. A utility class for values that need smoothing to avoid audio glitches.
  165. A ValueSmoothingTypes::Linear template parameter selects linear smoothing,
  166. which increments the SmoothedValue linearly towards its target value.
  167. @code
  168. SmoothedValue<float, ValueSmoothingTypes::Linear> yourSmoothedValue;
  169. @endcode
  170. A ValueSmoothingTypes::Multiplicative template parameter selects
  171. multiplicative smoothing increments towards the target value.
  172. @code
  173. SmoothedValue<float, ValueSmoothingTypes::Multiplicative> yourSmoothedValue;
  174. @endcode
  175. Multiplicative smoothing is useful when you are dealing with
  176. exponential/logarithmic values like volume in dB or frequency in Hz. For
  177. example a 12 step ramp from 440.0 Hz (A4) to 880.0 Hz (A5) will increase the
  178. frequency with an equal temperament tuning across the octave. A 10 step
  179. smoothing from 1.0 (0 dB) to 3.16228 (10 dB) will increase the value in
  180. increments of 1 dB.
  181. Note that when you are using multiplicative smoothing you cannot ever reach a
  182. target value of zero!
  183. @tags{Audio}
  184. */
  185. template <typename FloatType, typename SmoothingType = ValueSmoothingTypes::Linear>
  186. class SmoothedValue : public SmoothedValueBase <SmoothedValue <FloatType, SmoothingType>>
  187. {
  188. public:
  189. //==============================================================================
  190. /** Constructor. */
  191. SmoothedValue() noexcept
  192. : SmoothedValue ((FloatType) (std::is_same<SmoothingType, ValueSmoothingTypes::Linear>::value ? 0 : 1))
  193. {
  194. }
  195. /** Constructor. */
  196. SmoothedValue (FloatType initialValue) noexcept
  197. {
  198. // Multiplicative smoothed values cannot ever reach 0!
  199. jassert (! (std::is_same<SmoothingType, ValueSmoothingTypes::Multiplicative>::value && initialValue == 0));
  200. // Visual Studio can't handle base class initialisation with CRTP
  201. this->currentValue = initialValue;
  202. this->target = this->currentValue;
  203. }
  204. //==============================================================================
  205. /** Reset to a new sample rate and ramp length.
  206. @param sampleRate The sample rate
  207. @param rampLengthInSeconds The duration of the ramp in seconds
  208. */
  209. void reset (double sampleRate, double rampLengthInSeconds) noexcept
  210. {
  211. jassert (sampleRate > 0 && rampLengthInSeconds >= 0);
  212. reset ((int) std::floor (rampLengthInSeconds * sampleRate));
  213. }
  214. /** Set a new ramp length directly in samples.
  215. @param numSteps The number of samples over which the ramp should be active
  216. */
  217. void reset (int numSteps) noexcept
  218. {
  219. stepsToTarget = numSteps;
  220. this->setCurrentAndTargetValue (this->target);
  221. }
  222. //==============================================================================
  223. /** Set the next value to ramp towards.
  224. @param newValue The new target value
  225. */
  226. void setTargetValue (FloatType newValue) noexcept
  227. {
  228. if (newValue == this->target)
  229. return;
  230. if (stepsToTarget <= 0)
  231. {
  232. this->setCurrentAndTargetValue (newValue);
  233. return;
  234. }
  235. // Multiplicative smoothed values cannot ever reach 0!
  236. jassert (! (std::is_same<SmoothingType, ValueSmoothingTypes::Multiplicative>::value && newValue == 0));
  237. this->target = newValue;
  238. this->countdown = stepsToTarget;
  239. setStepSize();
  240. }
  241. //==============================================================================
  242. /** Compute the next value.
  243. @returns Smoothed value
  244. */
  245. FloatType getNextValue() noexcept
  246. {
  247. if (! this->isSmoothing())
  248. return this->target;
  249. --(this->countdown);
  250. if (this->isSmoothing())
  251. setNextValue();
  252. else
  253. this->currentValue = this->target;
  254. return this->currentValue;
  255. }
  256. //==============================================================================
  257. /** Skip the next numSamples samples.
  258. This is identical to calling getNextValue numSamples times. It returns
  259. the new current value.
  260. @see getNextValue
  261. */
  262. FloatType skip (int numSamples) noexcept
  263. {
  264. if (numSamples >= this->countdown)
  265. {
  266. this->setCurrentAndTargetValue (this->target);
  267. return this->target;
  268. }
  269. skipCurrentValue (numSamples);
  270. this->countdown -= numSamples;
  271. return this->currentValue;
  272. }
  273. //==============================================================================
  274. #ifndef DOXYGEN
  275. /** Using the new methods:
  276. lsv.setValue (x, false); -> lsv.setTargetValue (x);
  277. lsv.setValue (x, true); -> lsv.setCurrentAndTargetValue (x);
  278. @param newValue The new target value
  279. @param force If true, the value will be set immediately, bypassing the ramp
  280. */
  281. [[deprecated ("Use setTargetValue and setCurrentAndTargetValue instead.")]]
  282. void setValue (FloatType newValue, bool force = false) noexcept
  283. {
  284. if (force)
  285. {
  286. this->setCurrentAndTargetValue (newValue);
  287. return;
  288. }
  289. setTargetValue (newValue);
  290. }
  291. #endif
  292. private:
  293. //==============================================================================
  294. template <typename T>
  295. using LinearVoid = typename std::enable_if <std::is_same <T, ValueSmoothingTypes::Linear>::value, void>::type;
  296. template <typename T>
  297. using MultiplicativeVoid = typename std::enable_if <std::is_same <T, ValueSmoothingTypes::Multiplicative>::value, void>::type;
  298. //==============================================================================
  299. template <typename T = SmoothingType>
  300. LinearVoid<T> setStepSize() noexcept
  301. {
  302. step = (this->target - this->currentValue) / (FloatType) this->countdown;
  303. }
  304. template <typename T = SmoothingType>
  305. MultiplicativeVoid<T> setStepSize()
  306. {
  307. step = std::exp ((std::log (std::abs (this->target)) - std::log (std::abs (this->currentValue))) / (FloatType) this->countdown);
  308. }
  309. //==============================================================================
  310. template <typename T = SmoothingType>
  311. LinearVoid<T> setNextValue() noexcept
  312. {
  313. this->currentValue += step;
  314. }
  315. template <typename T = SmoothingType>
  316. MultiplicativeVoid<T> setNextValue() noexcept
  317. {
  318. this->currentValue *= step;
  319. }
  320. //==============================================================================
  321. template <typename T = SmoothingType>
  322. LinearVoid<T> skipCurrentValue (int numSamples) noexcept
  323. {
  324. this->currentValue += step * (FloatType) numSamples;
  325. }
  326. template <typename T = SmoothingType>
  327. MultiplicativeVoid<T> skipCurrentValue (int numSamples)
  328. {
  329. this->currentValue *= (FloatType) std::pow (step, numSamples);
  330. }
  331. //==============================================================================
  332. FloatType step = FloatType();
  333. int stepsToTarget = 0;
  334. };
  335. template <typename FloatType>
  336. using LinearSmoothedValue = SmoothedValue <FloatType, ValueSmoothingTypes::Linear>;
  337. //==============================================================================
  338. //==============================================================================
  339. #if JUCE_UNIT_TESTS
  340. template <class SmoothedValueType>
  341. class CommonSmoothedValueTests : public UnitTest
  342. {
  343. public:
  344. CommonSmoothedValueTests()
  345. : UnitTest ("CommonSmoothedValueTests", UnitTestCategories::smoothedValues)
  346. {}
  347. void runTest() override
  348. {
  349. beginTest ("Initial state");
  350. {
  351. SmoothedValueType sv;
  352. auto value = sv.getCurrentValue();
  353. expectEquals (sv.getTargetValue(), value);
  354. sv.getNextValue();
  355. expectEquals (sv.getCurrentValue(), value);
  356. expect (! sv.isSmoothing());
  357. }
  358. beginTest ("Resetting");
  359. {
  360. auto initialValue = 15.0f;
  361. SmoothedValueType sv (initialValue);
  362. sv.reset (3);
  363. expectEquals (sv.getCurrentValue(), initialValue);
  364. auto targetValue = initialValue + 1.0f;
  365. sv.setTargetValue (targetValue);
  366. expectEquals (sv.getTargetValue(), targetValue);
  367. expectEquals (sv.getCurrentValue(), initialValue);
  368. expect (sv.isSmoothing());
  369. auto currentValue = sv.getNextValue();
  370. expect (currentValue > initialValue);
  371. expectEquals (sv.getCurrentValue(), currentValue);
  372. expectEquals (sv.getTargetValue(), targetValue);
  373. expect (sv.isSmoothing());
  374. sv.reset (5);
  375. expectEquals (sv.getCurrentValue(), targetValue);
  376. expectEquals (sv.getTargetValue(), targetValue);
  377. expect (! sv.isSmoothing());
  378. sv.getNextValue();
  379. expectEquals (sv.getCurrentValue(), targetValue);
  380. sv.setTargetValue (1.5f);
  381. sv.getNextValue();
  382. float newStart = 0.2f;
  383. sv.setCurrentAndTargetValue (newStart);
  384. expectEquals (sv.getNextValue(), newStart);
  385. expectEquals (sv.getTargetValue(), newStart);
  386. expectEquals (sv.getCurrentValue(), newStart);
  387. expect (! sv.isSmoothing());
  388. }
  389. beginTest ("Sample rate");
  390. {
  391. SmoothedValueType svSamples { 3.0f };
  392. auto svTime = svSamples;
  393. auto numSamples = 12;
  394. svSamples.reset (numSamples);
  395. svTime.reset (numSamples * 2, 1.0);
  396. for (int i = 0; i < numSamples; ++i)
  397. {
  398. svTime.skip (1);
  399. expectWithinAbsoluteError (svSamples.getNextValue(),
  400. svTime.getNextValue(),
  401. 1.0e-7f);
  402. }
  403. }
  404. beginTest ("Block processing");
  405. {
  406. SmoothedValueType sv (1.0f);
  407. sv.reset (12);
  408. sv.setTargetValue (2.0f);
  409. const auto numSamples = 15;
  410. AudioBuffer<float> referenceData (1, numSamples);
  411. for (int i = 0; i < numSamples; ++i)
  412. referenceData.setSample (0, i, sv.getNextValue());
  413. expect (referenceData.getSample (0, 0) > 0);
  414. expect (referenceData.getSample (0, 10) < sv.getTargetValue());
  415. expectWithinAbsoluteError (referenceData.getSample (0, 11),
  416. sv.getTargetValue(),
  417. 2.0e-7f);
  418. auto getUnitData = [] (int numSamplesToGenerate)
  419. {
  420. AudioBuffer<float> result (1, numSamplesToGenerate);
  421. for (int i = 0; i < numSamplesToGenerate; ++i)
  422. result.setSample (0, i, 1.0f);
  423. return result;
  424. };
  425. auto compareData = [this] (const AudioBuffer<float>& test,
  426. const AudioBuffer<float>& reference)
  427. {
  428. for (int i = 0; i < test.getNumSamples(); ++i)
  429. expectWithinAbsoluteError (test.getSample (0, i),
  430. reference.getSample (0, i),
  431. 2.0e-7f);
  432. };
  433. auto testData = getUnitData (numSamples);
  434. sv.setCurrentAndTargetValue (1.0f);
  435. sv.setTargetValue (2.0f);
  436. sv.applyGain (testData.getWritePointer (0), numSamples);
  437. compareData (testData, referenceData);
  438. testData = getUnitData (numSamples);
  439. AudioBuffer<float> destData (1, numSamples);
  440. sv.setCurrentAndTargetValue (1.0f);
  441. sv.setTargetValue (2.0f);
  442. sv.applyGain (destData.getWritePointer (0),
  443. testData.getReadPointer (0),
  444. numSamples);
  445. compareData (destData, referenceData);
  446. compareData (testData, getUnitData (numSamples));
  447. testData = getUnitData (numSamples);
  448. sv.setCurrentAndTargetValue (1.0f);
  449. sv.setTargetValue (2.0f);
  450. sv.applyGain (testData, numSamples);
  451. compareData (testData, referenceData);
  452. }
  453. beginTest ("Skip");
  454. {
  455. SmoothedValueType sv;
  456. sv.reset (12);
  457. sv.setCurrentAndTargetValue (1.0f);
  458. sv.setTargetValue (2.0f);
  459. Array<float> reference;
  460. for (int i = 0; i < 15; ++i)
  461. reference.add (sv.getNextValue());
  462. sv.setCurrentAndTargetValue (1.0f);
  463. sv.setTargetValue (2.0f);
  464. expectWithinAbsoluteError (sv.skip (1), reference[0], 1.0e-6f);
  465. expectWithinAbsoluteError (sv.skip (1), reference[1], 1.0e-6f);
  466. expectWithinAbsoluteError (sv.skip (2), reference[3], 1.0e-6f);
  467. sv.skip (3);
  468. expectWithinAbsoluteError (sv.getCurrentValue(), reference[6], 1.0e-6f);
  469. expectEquals (sv.skip (300), sv.getTargetValue());
  470. expectEquals (sv.getCurrentValue(), sv.getTargetValue());
  471. }
  472. beginTest ("Negative");
  473. {
  474. SmoothedValueType sv;
  475. auto numValues = 12;
  476. sv.reset (numValues);
  477. std::vector<std::pair<float, float>> ranges = { { -1.0f, -2.0f },
  478. { -100.0f, -3.0f } };
  479. for (auto range : ranges)
  480. {
  481. auto start = range.first, end = range.second;
  482. sv.setCurrentAndTargetValue (start);
  483. sv.setTargetValue (end);
  484. auto val = sv.skip (numValues / 2);
  485. if (end > start)
  486. expect (val > start && val < end);
  487. else
  488. expect (val < start && val > end);
  489. auto nextVal = sv.getNextValue();
  490. expect (end > start ? (nextVal > val) : (nextVal < val));
  491. auto endVal = sv.skip (500);
  492. expectEquals (endVal, end);
  493. expectEquals (sv.getNextValue(), end);
  494. expectEquals (sv.getCurrentValue(), end);
  495. sv.setCurrentAndTargetValue (start);
  496. sv.setTargetValue (end);
  497. SmoothedValueType positiveSv { -start };
  498. positiveSv.reset (numValues);
  499. positiveSv.setTargetValue (-end);
  500. for (int i = 0; i < numValues + 2; ++i)
  501. expectEquals (sv.getNextValue(), -positiveSv.getNextValue());
  502. }
  503. }
  504. }
  505. };
  506. #endif
  507. } // namespace juce