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.

631 lines
21KB

  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. 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. virtual ~SmoothedValueBase() {}
  48. //==============================================================================
  49. /** Returns true if the current value is currently being interpolated. */
  50. bool isSmoothing() const noexcept { return countdown > 0; }
  51. /** Returns the current value of the ramp. */
  52. FloatType getCurrentValue() const noexcept { return currentValue; }
  53. //==============================================================================
  54. /** Returns the target value towards which the smoothed value is currently moving. */
  55. FloatType getTargetValue() const noexcept { return target; }
  56. /** Sets the current value and the target value.
  57. @param newValue the new value to take
  58. */
  59. void setCurrentAndTargetValue (FloatType newValue)
  60. {
  61. target = currentValue = newValue;
  62. countdown = 0;
  63. }
  64. //==============================================================================
  65. /** Applies a smoothed gain to a stream of samples
  66. S[i] *= gain
  67. @param samples Pointer to a raw array of samples
  68. @param numSamples Length of array of samples
  69. */
  70. void applyGain (FloatType* samples, int numSamples) noexcept
  71. {
  72. jassert (numSamples >= 0);
  73. if (isSmoothing())
  74. {
  75. for (int i = 0; i < numSamples; ++i)
  76. samples[i] *= getNextSmoothedValue();
  77. }
  78. else
  79. {
  80. FloatVectorOperations::multiply (samples, target, numSamples);
  81. }
  82. }
  83. /** Computes output as a smoothed gain applied to a stream of samples.
  84. Sout[i] = Sin[i] * gain
  85. @param samplesOut A pointer to a raw array of output samples
  86. @param samplesIn A pointer to a raw array of input samples
  87. @param numSamples The length of the array of samples
  88. */
  89. void applyGain (FloatType* samplesOut, const FloatType* samplesIn, int numSamples) noexcept
  90. {
  91. jassert (numSamples >= 0);
  92. if (isSmoothing())
  93. {
  94. for (int i = 0; i < numSamples; ++i)
  95. samplesOut[i] = samplesIn[i] * getNextSmoothedValue();
  96. }
  97. else
  98. {
  99. FloatVectorOperations::multiply (samplesOut, samplesIn, target, numSamples);
  100. }
  101. }
  102. /** Applies a smoothed gain to a buffer */
  103. void applyGain (AudioBuffer<FloatType>& buffer, int numSamples) noexcept
  104. {
  105. jassert (numSamples >= 0);
  106. if (isSmoothing())
  107. {
  108. if (buffer.getNumChannels() == 1)
  109. {
  110. auto* samples = buffer.getWritePointer (0);
  111. for (int i = 0; i < numSamples; ++i)
  112. samples[i] *= getNextSmoothedValue();
  113. }
  114. else
  115. {
  116. for (auto i = 0; i < numSamples; ++i)
  117. {
  118. auto gain = getNextSmoothedValue();
  119. for (int channel = 0; channel < buffer.getNumChannels(); channel++)
  120. buffer.setSample (channel, i, buffer.getSample (channel, i) * gain);
  121. }
  122. }
  123. }
  124. else
  125. {
  126. buffer.applyGain (0, numSamples, target);
  127. }
  128. }
  129. private:
  130. //==============================================================================
  131. FloatType getNextSmoothedValue() noexcept
  132. {
  133. return static_cast <SmoothedValueType*> (this)->getNextValue();
  134. }
  135. protected:
  136. //==============================================================================
  137. FloatType currentValue = 0;
  138. FloatType target = currentValue;
  139. int countdown = 0;
  140. };
  141. //==============================================================================
  142. /**
  143. A namespace containing a set of types used for specifying the smoothing
  144. behaviour of the SmoothedValue class.
  145. For example:
  146. @code
  147. SmoothedValue<float, ValueSmoothingTypes::Multiplicative> frequency (1.0f);
  148. @endcode
  149. */
  150. namespace ValueSmoothingTypes
  151. {
  152. /**
  153. Used to indicate a linear smoothing between values.
  154. @tags{Audio}
  155. */
  156. struct Linear {};
  157. /**
  158. Used to indicate a smoothing between multiplicative values.
  159. @tags{Audio}
  160. */
  161. struct Multiplicative {};
  162. }
  163. //==============================================================================
  164. /**
  165. A utility class for values that need smoothing to avoid audio glitches.
  166. A ValueSmoothingTypes::Linear template parameter selects linear smoothing,
  167. which increments the SmoothedValue linearly towards its target value.
  168. @code
  169. SmoothedValue<float, ValueSmoothingTypes::Linear> yourSmoothedValue;
  170. @endcode
  171. A ValueSmoothingTypes::Multiplicative template parameter selects
  172. multiplicative smoothing increments towards the target value.
  173. @code
  174. SmoothedValue<float, ValueSmoothingTypes::Multiplicative> yourSmoothedValue;
  175. @endcode
  176. Multiplicative smoothing is useful when you are dealing with
  177. exponential/logarithmic values like volume in dB or frequency in Hz. For
  178. example a 12 step ramp from 440.0 Hz (A4) to 880.0 Hz (A5) will increase the
  179. frequency with an equal temperament tuning across the octave. A 10 step
  180. smoothing from 1.0 (0 dB) to 3.16228 (10 dB) will increase the value in
  181. increments of 1 dB.
  182. Note that when you are using multiplicative smoothing you cannot ever reach a
  183. target value of zero!
  184. @tags{Audio}
  185. */
  186. template <typename FloatType, typename SmoothingType = ValueSmoothingTypes::Linear>
  187. class SmoothedValue : public SmoothedValueBase <SmoothedValue <FloatType, SmoothingType>>
  188. {
  189. public:
  190. //==============================================================================
  191. /** Constructor. */
  192. SmoothedValue() noexcept
  193. : SmoothedValue ((FloatType) (std::is_same<SmoothingType, ValueSmoothingTypes::Linear>::value ? 0 : 1))
  194. {
  195. }
  196. /** Constructor. */
  197. SmoothedValue (FloatType initialValue) noexcept
  198. {
  199. // Multiplicative smoothed values cannot ever reach 0!
  200. jassert (! (std::is_same<SmoothingType, ValueSmoothingTypes::Multiplicative>::value && initialValue == 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 (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<SmoothingType, ValueSmoothingTypes::Multiplicative>::value && newValue == 0));
  238. this->target = newValue;
  239. this->countdown = stepsToTarget;
  240. setStepSize();
  241. }
  242. //==============================================================================
  243. /** Compute the next value.
  244. @returns Smoothed value
  245. */
  246. FloatType getNextValue() noexcept
  247. {
  248. if (! this->isSmoothing())
  249. return this->target;
  250. --(this->countdown);
  251. if (this->isSmoothing())
  252. setNextValue();
  253. else
  254. this->currentValue = this->target;
  255. return this->currentValue;
  256. }
  257. //==============================================================================
  258. /** Skip the next numSamples samples.
  259. This is identical to calling getNextValue numSamples times. It returns
  260. the new current value.
  261. @see getNextValue
  262. */
  263. FloatType skip (int numSamples) noexcept
  264. {
  265. if (numSamples >= this->countdown)
  266. {
  267. this->setCurrentAndTargetValue (this->target);
  268. return this->target;
  269. }
  270. skipCurrentValue (numSamples);
  271. this->countdown -= numSamples;
  272. return this->currentValue;
  273. }
  274. //==============================================================================
  275. /** THIS FUNCTION IS DEPRECATED.
  276. Use `setTargetValue (float)` and `setCurrentAndTargetValue()` instead:
  277. lsv.setValue (x, false); -> lsv.setTargetValue (x);
  278. lsv.setValue (x, true); -> lsv.setCurrentAndTargetValue (x);
  279. @param newValue The new target value
  280. @param force If true, the value will be set immediately, bypassing the ramp
  281. */
  282. JUCE_DEPRECATED_WITH_BODY (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. private:
  292. //==============================================================================
  293. template <typename T>
  294. using LinearVoid = typename std::enable_if <std::is_same <T, ValueSmoothingTypes::Linear>::value, void>::type;
  295. template <typename T>
  296. using MultiplicativeVoid = typename std::enable_if <std::is_same <T, ValueSmoothingTypes::Multiplicative>::value, void>::type;
  297. //==============================================================================
  298. template <typename T = SmoothingType>
  299. LinearVoid<T> setStepSize() noexcept
  300. {
  301. step = (this->target - this->currentValue) / (FloatType) this->countdown;
  302. }
  303. template <typename T = SmoothingType>
  304. MultiplicativeVoid<T> setStepSize()
  305. {
  306. step = std::exp ((std::log (std::abs (this->target)) - std::log (std::abs (this->currentValue))) / this->countdown);
  307. }
  308. //==============================================================================
  309. template <typename T = SmoothingType>
  310. LinearVoid<T> setNextValue() noexcept
  311. {
  312. this->currentValue += step;
  313. }
  314. template <typename T = SmoothingType>
  315. MultiplicativeVoid<T> setNextValue() noexcept
  316. {
  317. this->currentValue *= step;
  318. }
  319. //==============================================================================
  320. template <typename T = SmoothingType>
  321. LinearVoid<T> skipCurrentValue (int numSamples) noexcept
  322. {
  323. this->currentValue += step * (FloatType) numSamples;
  324. }
  325. template <typename T = SmoothingType>
  326. MultiplicativeVoid<T> skipCurrentValue (int numSamples)
  327. {
  328. this->currentValue *= (FloatType) std::pow (step, numSamples);
  329. }
  330. //==============================================================================
  331. FloatType step = FloatType();
  332. int stepsToTarget = 0;
  333. };
  334. template <typename FloatType>
  335. using LinearSmoothedValue = SmoothedValue <FloatType, ValueSmoothingTypes::Linear>;
  336. //==============================================================================
  337. //==============================================================================
  338. #if JUCE_UNIT_TESTS
  339. template <class SmoothedValueType>
  340. class CommonSmoothedValueTests : public UnitTest
  341. {
  342. public:
  343. CommonSmoothedValueTests()
  344. : UnitTest ("CommonSmoothedValueTests", UnitTestCategories::smoothedValues)
  345. {}
  346. void runTest() override
  347. {
  348. beginTest ("Initial state");
  349. {
  350. SmoothedValueType sv;
  351. auto value = sv.getCurrentValue();
  352. expectEquals (sv.getTargetValue(), value);
  353. sv.getNextValue();
  354. expectEquals (sv.getCurrentValue(), value);
  355. expect (! sv.isSmoothing());
  356. }
  357. beginTest ("Resetting");
  358. {
  359. auto initialValue = 15.0f;
  360. SmoothedValueType sv (initialValue);
  361. sv.reset (3);
  362. expectEquals (sv.getCurrentValue(), initialValue);
  363. auto targetValue = initialValue + 1.0f;
  364. sv.setTargetValue (targetValue);
  365. expectEquals (sv.getTargetValue(), targetValue);
  366. expectEquals (sv.getCurrentValue(), initialValue);
  367. expect (sv.isSmoothing());
  368. auto currentValue = sv.getNextValue();
  369. expect (currentValue > initialValue);
  370. expectEquals (sv.getCurrentValue(), currentValue);
  371. expectEquals (sv.getTargetValue(), targetValue);
  372. expect (sv.isSmoothing());
  373. sv.reset (5);
  374. expectEquals (sv.getCurrentValue(), targetValue);
  375. expectEquals (sv.getTargetValue(), targetValue);
  376. expect (! sv.isSmoothing());
  377. sv.getNextValue();
  378. expectEquals (sv.getCurrentValue(), targetValue);
  379. sv.setTargetValue (1.5f);
  380. sv.getNextValue();
  381. float newStart = 0.2f;
  382. sv.setCurrentAndTargetValue (newStart);
  383. expectEquals (sv.getNextValue(), newStart);
  384. expectEquals (sv.getTargetValue(), newStart);
  385. expectEquals (sv.getCurrentValue(), newStart);
  386. expect (! sv.isSmoothing());
  387. }
  388. beginTest ("Sample rate");
  389. {
  390. SmoothedValueType svSamples { 3.0f };
  391. auto svTime = svSamples;
  392. auto numSamples = 12;
  393. svSamples.reset (numSamples);
  394. svTime.reset (numSamples * 2, 1.0);
  395. for (int i = 0; i < numSamples; ++i)
  396. {
  397. svTime.skip (1);
  398. expectWithinAbsoluteError (svSamples.getNextValue(),
  399. svTime.getNextValue(),
  400. 1.0e-7f);
  401. }
  402. }
  403. beginTest ("Block processing");
  404. {
  405. SmoothedValueType sv (1.0f);
  406. sv.reset (12);
  407. sv.setTargetValue (2.0f);
  408. const auto numSamples = 15;
  409. AudioBuffer<float> referenceData (1, numSamples);
  410. for (int i = 0; i < numSamples; ++i)
  411. referenceData.setSample (0, i, sv.getNextValue());
  412. expect (referenceData.getSample (0, 0) > 0);
  413. expect (referenceData.getSample (0, 10) < sv.getTargetValue());
  414. expectWithinAbsoluteError (referenceData.getSample (0, 11),
  415. sv.getTargetValue(),
  416. 1.0e-7f);
  417. auto getUnitData = [] (int numSamplesToGenerate)
  418. {
  419. AudioBuffer<float> result (1, numSamplesToGenerate);
  420. for (int i = 0; i < numSamplesToGenerate; ++i)
  421. result.setSample (0, i, 1.0f);
  422. return result;
  423. };
  424. auto compareData = [this](const AudioBuffer<float>& test,
  425. const AudioBuffer<float>& reference)
  426. {
  427. for (int i = 0; i < test.getNumSamples(); ++i)
  428. expectWithinAbsoluteError (test.getSample (0, i),
  429. reference.getSample (0, i),
  430. 1.0e-7f);
  431. };
  432. auto testData = getUnitData (numSamples);
  433. sv.setCurrentAndTargetValue (1.0f);
  434. sv.setTargetValue (2.0f);
  435. sv.applyGain (testData.getWritePointer (0), numSamples);
  436. compareData (testData, referenceData);
  437. testData = getUnitData (numSamples);
  438. AudioBuffer<float> destData (1, numSamples);
  439. sv.setCurrentAndTargetValue (1.0f);
  440. sv.setTargetValue (2.0f);
  441. sv.applyGain (destData.getWritePointer (0),
  442. testData.getReadPointer (0),
  443. numSamples);
  444. compareData (destData, referenceData);
  445. compareData (testData, getUnitData (numSamples));
  446. testData = getUnitData (numSamples);
  447. sv.setCurrentAndTargetValue (1.0f);
  448. sv.setTargetValue (2.0f);
  449. sv.applyGain (testData, numSamples);
  450. compareData (testData, referenceData);
  451. }
  452. beginTest ("Skip");
  453. {
  454. SmoothedValueType sv;
  455. sv.reset (12);
  456. sv.setCurrentAndTargetValue (1.0f);
  457. sv.setTargetValue (2.0f);
  458. Array<float> reference;
  459. for (int i = 0; i < 15; ++i)
  460. reference.add (sv.getNextValue());
  461. sv.setCurrentAndTargetValue (1.0f);
  462. sv.setTargetValue (2.0f);
  463. expectWithinAbsoluteError (sv.skip (1), reference[0], 1.0e-6f);
  464. expectWithinAbsoluteError (sv.skip (1), reference[1], 1.0e-6f);
  465. expectWithinAbsoluteError (sv.skip (2), reference[3], 1.0e-6f);
  466. sv.skip (3);
  467. expectWithinAbsoluteError (sv.getCurrentValue(), reference[6], 1.0e-6f);
  468. expectEquals (sv.skip (300), sv.getTargetValue());
  469. expectEquals (sv.getCurrentValue(), sv.getTargetValue());
  470. }
  471. beginTest ("Negative");
  472. {
  473. SmoothedValueType sv;
  474. auto numValues = 12;
  475. sv.reset (numValues);
  476. std::vector<std::pair<float, float>> ranges = { { -1.0f, -2.0f },
  477. { -100.0f, -3.0f } };
  478. for (auto range : ranges)
  479. {
  480. auto start = range.first, end = range.second;
  481. sv.setCurrentAndTargetValue (start);
  482. sv.setTargetValue (end);
  483. auto val = sv.skip (numValues / 2);
  484. if (end > start)
  485. expect (val > start && val < end);
  486. else
  487. expect (val < start && val > end);
  488. auto nextVal = sv.getNextValue();
  489. expect (end > start ? (nextVal > val) : (nextVal < val));
  490. auto endVal = sv.skip (500);
  491. expectEquals (endVal, end);
  492. expectEquals (sv.getNextValue(), end);
  493. expectEquals (sv.getCurrentValue(), end);
  494. sv.setCurrentAndTargetValue (start);
  495. sv.setTargetValue (end);
  496. SmoothedValueType positiveSv { -start };
  497. positiveSv.reset (numValues);
  498. positiveSv.setTargetValue (-end);
  499. for (int i = 0; i < numValues + 2; ++i)
  500. expectEquals (sv.getNextValue(), -positiveSv.getNextValue());
  501. }
  502. }
  503. }
  504. };
  505. #endif
  506. } // namespace juce