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.

628 lines
21KB

  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_v<SmoothingType, ValueSmoothingTypes::Linear> ? 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_v<SmoothingType, ValueSmoothingTypes::Multiplicative>
  200. && approximatelyEqual (initialValue, (FloatType) 0)));
  201. // Visual Studio can't handle base class initialisation with CRTP
  202. this->currentValue = initialValue;
  203. this->target = this->currentValue;
  204. }
  205. //==============================================================================
  206. /** Reset to a new sample rate and ramp length.
  207. @param sampleRate The sample rate
  208. @param rampLengthInSeconds The duration of the ramp in seconds
  209. */
  210. void reset (double sampleRate, double rampLengthInSeconds) noexcept
  211. {
  212. jassert (sampleRate > 0 && rampLengthInSeconds >= 0);
  213. reset ((int) std::floor (rampLengthInSeconds * sampleRate));
  214. }
  215. /** Set a new ramp length directly in samples.
  216. @param numSteps The number of samples over which the ramp should be active
  217. */
  218. void reset (int numSteps) noexcept
  219. {
  220. stepsToTarget = numSteps;
  221. this->setCurrentAndTargetValue (this->target);
  222. }
  223. //==============================================================================
  224. /** Set the next value to ramp towards.
  225. @param newValue The new target value
  226. */
  227. void setTargetValue (FloatType newValue) noexcept
  228. {
  229. if (approximatelyEqual (newValue, this->target))
  230. return;
  231. if (stepsToTarget <= 0)
  232. {
  233. this->setCurrentAndTargetValue (newValue);
  234. return;
  235. }
  236. // Multiplicative smoothed values cannot ever reach 0!
  237. jassert (! (std::is_same_v<SmoothingType, ValueSmoothingTypes::Multiplicative>
  238. && approximatelyEqual (newValue, (FloatType) 0)));
  239. this->target = newValue;
  240. this->countdown = stepsToTarget;
  241. setStepSize();
  242. }
  243. //==============================================================================
  244. /** Compute the next value.
  245. @returns Smoothed value
  246. */
  247. FloatType getNextValue() noexcept
  248. {
  249. if (! this->isSmoothing())
  250. return this->target;
  251. --(this->countdown);
  252. if (this->isSmoothing())
  253. setNextValue();
  254. else
  255. this->currentValue = this->target;
  256. return this->currentValue;
  257. }
  258. //==============================================================================
  259. /** Skip the next numSamples samples.
  260. This is identical to calling getNextValue numSamples times. It returns
  261. the new current value.
  262. @see getNextValue
  263. */
  264. FloatType skip (int numSamples) noexcept
  265. {
  266. if (numSamples >= this->countdown)
  267. {
  268. this->setCurrentAndTargetValue (this->target);
  269. return this->target;
  270. }
  271. skipCurrentValue (numSamples);
  272. this->countdown -= numSamples;
  273. return this->currentValue;
  274. }
  275. //==============================================================================
  276. #ifndef DOXYGEN
  277. /** Using the new methods:
  278. lsv.setValue (x, false); -> lsv.setTargetValue (x);
  279. lsv.setValue (x, true); -> lsv.setCurrentAndTargetValue (x);
  280. @param newValue The new target value
  281. @param force If true, the value will be set immediately, bypassing the ramp
  282. */
  283. [[deprecated ("Use setTargetValue and setCurrentAndTargetValue instead.")]]
  284. void setValue (FloatType newValue, bool force = false) noexcept
  285. {
  286. if (force)
  287. {
  288. this->setCurrentAndTargetValue (newValue);
  289. return;
  290. }
  291. setTargetValue (newValue);
  292. }
  293. #endif
  294. private:
  295. //==============================================================================
  296. template <typename T = SmoothingType>
  297. void setStepSize() noexcept
  298. {
  299. if constexpr (std::is_same_v<T, ValueSmoothingTypes::Linear>)
  300. {
  301. step = (this->target - this->currentValue) / (FloatType) this->countdown;
  302. }
  303. else if constexpr (std::is_same_v<T, ValueSmoothingTypes::Multiplicative>)
  304. {
  305. step = std::exp ((std::log (std::abs (this->target)) - std::log (std::abs (this->currentValue))) / (FloatType) this->countdown);
  306. }
  307. }
  308. //==============================================================================
  309. template <typename T = SmoothingType>
  310. void setNextValue() noexcept
  311. {
  312. if constexpr (std::is_same_v<T, ValueSmoothingTypes::Linear>)
  313. {
  314. this->currentValue += step;
  315. }
  316. else if constexpr (std::is_same_v<T, ValueSmoothingTypes::Multiplicative>)
  317. {
  318. this->currentValue *= step;
  319. }
  320. }
  321. //==============================================================================
  322. template <typename T = SmoothingType>
  323. void skipCurrentValue (int numSamples) noexcept
  324. {
  325. if constexpr (std::is_same_v<T, ValueSmoothingTypes::Linear>)
  326. {
  327. this->currentValue += step * (FloatType) numSamples;
  328. }
  329. else if constexpr (std::is_same_v<T, ValueSmoothingTypes::Multiplicative>)
  330. {
  331. this->currentValue *= (FloatType) std::pow (step, numSamples);
  332. }
  333. }
  334. //==============================================================================
  335. FloatType step = FloatType();
  336. int stepsToTarget = 0;
  337. };
  338. template <typename FloatType>
  339. using LinearSmoothedValue = SmoothedValue <FloatType, ValueSmoothingTypes::Linear>;
  340. //==============================================================================
  341. //==============================================================================
  342. #if JUCE_UNIT_TESTS
  343. template <class SmoothedValueType>
  344. class CommonSmoothedValueTests : public UnitTest
  345. {
  346. public:
  347. CommonSmoothedValueTests()
  348. : UnitTest ("CommonSmoothedValueTests", UnitTestCategories::smoothedValues)
  349. {}
  350. void runTest() override
  351. {
  352. beginTest ("Initial state");
  353. {
  354. SmoothedValueType sv;
  355. auto value = sv.getCurrentValue();
  356. expectEquals (sv.getTargetValue(), value);
  357. sv.getNextValue();
  358. expectEquals (sv.getCurrentValue(), value);
  359. expect (! sv.isSmoothing());
  360. }
  361. beginTest ("Resetting");
  362. {
  363. auto initialValue = 15.0f;
  364. SmoothedValueType sv (initialValue);
  365. sv.reset (3);
  366. expectEquals (sv.getCurrentValue(), initialValue);
  367. auto targetValue = initialValue + 1.0f;
  368. sv.setTargetValue (targetValue);
  369. expectEquals (sv.getTargetValue(), targetValue);
  370. expectEquals (sv.getCurrentValue(), initialValue);
  371. expect (sv.isSmoothing());
  372. auto currentValue = sv.getNextValue();
  373. expect (currentValue > initialValue);
  374. expectEquals (sv.getCurrentValue(), currentValue);
  375. expectEquals (sv.getTargetValue(), targetValue);
  376. expect (sv.isSmoothing());
  377. sv.reset (5);
  378. expectEquals (sv.getCurrentValue(), targetValue);
  379. expectEquals (sv.getTargetValue(), targetValue);
  380. expect (! sv.isSmoothing());
  381. sv.getNextValue();
  382. expectEquals (sv.getCurrentValue(), targetValue);
  383. sv.setTargetValue (1.5f);
  384. sv.getNextValue();
  385. float newStart = 0.2f;
  386. sv.setCurrentAndTargetValue (newStart);
  387. expectEquals (sv.getNextValue(), newStart);
  388. expectEquals (sv.getTargetValue(), newStart);
  389. expectEquals (sv.getCurrentValue(), newStart);
  390. expect (! sv.isSmoothing());
  391. }
  392. beginTest ("Sample rate");
  393. {
  394. SmoothedValueType svSamples { 3.0f };
  395. auto svTime = svSamples;
  396. auto numSamples = 12;
  397. svSamples.reset (numSamples);
  398. svTime.reset (numSamples * 2, 1.0);
  399. for (int i = 0; i < numSamples; ++i)
  400. {
  401. svTime.skip (1);
  402. expectWithinAbsoluteError (svSamples.getNextValue(),
  403. svTime.getNextValue(),
  404. 1.0e-7f);
  405. }
  406. }
  407. beginTest ("Block processing");
  408. {
  409. SmoothedValueType sv (1.0f);
  410. sv.reset (12);
  411. sv.setTargetValue (2.0f);
  412. const auto numSamples = 15;
  413. AudioBuffer<float> referenceData (1, numSamples);
  414. for (int i = 0; i < numSamples; ++i)
  415. referenceData.setSample (0, i, sv.getNextValue());
  416. expect (referenceData.getSample (0, 0) > 0);
  417. expect (referenceData.getSample (0, 10) < sv.getTargetValue());
  418. expectWithinAbsoluteError (referenceData.getSample (0, 11),
  419. sv.getTargetValue(),
  420. 2.0e-7f);
  421. auto getUnitData = [] (int numSamplesToGenerate)
  422. {
  423. AudioBuffer<float> result (1, numSamplesToGenerate);
  424. for (int i = 0; i < numSamplesToGenerate; ++i)
  425. result.setSample (0, i, 1.0f);
  426. return result;
  427. };
  428. auto compareData = [this] (const AudioBuffer<float>& test,
  429. const AudioBuffer<float>& reference)
  430. {
  431. for (int i = 0; i < test.getNumSamples(); ++i)
  432. expectWithinAbsoluteError (test.getSample (0, i),
  433. reference.getSample (0, i),
  434. 2.0e-7f);
  435. };
  436. auto testData = getUnitData (numSamples);
  437. sv.setCurrentAndTargetValue (1.0f);
  438. sv.setTargetValue (2.0f);
  439. sv.applyGain (testData.getWritePointer (0), numSamples);
  440. compareData (testData, referenceData);
  441. testData = getUnitData (numSamples);
  442. AudioBuffer<float> destData (1, numSamples);
  443. sv.setCurrentAndTargetValue (1.0f);
  444. sv.setTargetValue (2.0f);
  445. sv.applyGain (destData.getWritePointer (0),
  446. testData.getReadPointer (0),
  447. numSamples);
  448. compareData (destData, referenceData);
  449. compareData (testData, getUnitData (numSamples));
  450. testData = getUnitData (numSamples);
  451. sv.setCurrentAndTargetValue (1.0f);
  452. sv.setTargetValue (2.0f);
  453. sv.applyGain (testData, numSamples);
  454. compareData (testData, referenceData);
  455. }
  456. beginTest ("Skip");
  457. {
  458. SmoothedValueType sv;
  459. sv.reset (12);
  460. sv.setCurrentAndTargetValue (1.0f);
  461. sv.setTargetValue (2.0f);
  462. Array<float> reference;
  463. for (int i = 0; i < 15; ++i)
  464. reference.add (sv.getNextValue());
  465. sv.setCurrentAndTargetValue (1.0f);
  466. sv.setTargetValue (2.0f);
  467. expectWithinAbsoluteError (sv.skip (1), reference[0], 1.0e-6f);
  468. expectWithinAbsoluteError (sv.skip (1), reference[1], 1.0e-6f);
  469. expectWithinAbsoluteError (sv.skip (2), reference[3], 1.0e-6f);
  470. sv.skip (3);
  471. expectWithinAbsoluteError (sv.getCurrentValue(), reference[6], 1.0e-6f);
  472. expectEquals (sv.skip (300), sv.getTargetValue());
  473. expectEquals (sv.getCurrentValue(), sv.getTargetValue());
  474. }
  475. beginTest ("Negative");
  476. {
  477. SmoothedValueType sv;
  478. auto numValues = 12;
  479. sv.reset (numValues);
  480. std::vector<std::pair<float, float>> ranges = { { -1.0f, -2.0f },
  481. { -100.0f, -3.0f } };
  482. for (auto range : ranges)
  483. {
  484. auto start = range.first, end = range.second;
  485. sv.setCurrentAndTargetValue (start);
  486. sv.setTargetValue (end);
  487. auto val = sv.skip (numValues / 2);
  488. if (end > start)
  489. expect (val > start && val < end);
  490. else
  491. expect (val < start && val > end);
  492. auto nextVal = sv.getNextValue();
  493. expect (end > start ? (nextVal > val) : (nextVal < val));
  494. auto endVal = sv.skip (500);
  495. expectEquals (endVal, end);
  496. expectEquals (sv.getNextValue(), end);
  497. expectEquals (sv.getCurrentValue(), end);
  498. sv.setCurrentAndTargetValue (start);
  499. sv.setTargetValue (end);
  500. SmoothedValueType positiveSv { -start };
  501. positiveSv.reset (numValues);
  502. positiveSv.setTargetValue (-end);
  503. for (int i = 0; i < numValues + 2; ++i)
  504. expectEquals (sv.getNextValue(), -positiveSv.getNextValue());
  505. }
  506. }
  507. }
  508. };
  509. #endif
  510. } // namespace juce