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.

281 lines
11KB

  1. /*
  2. ==============================================================================
  3. This file is part of the juce_core module of the JUCE library.
  4. Copyright (c) 2016 - ROLI Ltd.
  5. Permission to use, copy, modify, and/or distribute this software for any purpose with
  6. or without fee is hereby granted, provided that the above copyright notice and this
  7. permission notice appear in all copies.
  8. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
  9. TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
  10. NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
  11. DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
  12. IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  13. CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  14. ------------------------------------------------------------------------------
  15. NOTE! This permissive ISC license applies ONLY to files within the juce_core module!
  16. All other JUCE modules are covered by a dual GPL/commercial license, so if you are
  17. using any other modules, be sure to check that you also comply with their license.
  18. For more details, visit www.juce.com
  19. ==============================================================================
  20. */
  21. #pragma once
  22. #include "../JuceLibraryCode/JuceHeader.h"
  23. #include <mutex>
  24. //==============================================================================
  25. class MainContentComponent : public AudioAppComponent,
  26. private Timer
  27. {
  28. public:
  29. //==============================================================================
  30. MainContentComponent()
  31. {
  32. setSize (400, 400);
  33. setAudioChannels (0, 2);
  34. initGui();
  35. Desktop::getInstance().setScreenSaverEnabled (false);
  36. startTimer (1000);
  37. }
  38. ~MainContentComponent()
  39. {
  40. shutdownAudio();
  41. }
  42. //==============================================================================
  43. void prepareToPlay (int bufferSize, double sampleRate) override
  44. {
  45. currentSampleRate = sampleRate;
  46. allocateBuffers (bufferSize);
  47. printHeader();
  48. }
  49. void releaseResources() override
  50. {
  51. a.clear();
  52. b.clear();
  53. c.clear();
  54. currentSampleRate = 0.0;
  55. }
  56. //==============================================================================
  57. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) override
  58. {
  59. const double startTimeMs = getPreciseTimeMs();
  60. AudioBuffer<float>& outputAudio = *bufferToFill.buffer;
  61. std::size_t bufferSize = (std::size_t) outputAudio.getNumSamples();
  62. initialiseBuffers (bufferToFill, bufferSize);
  63. for (int ch = 0; ch < outputAudio.getNumChannels(); ++ch)
  64. crunchSomeNumbers (outputAudio.getWritePointer (ch), bufferSize, numLoopIterationsPerCallback);
  65. std::lock_guard<std::mutex> lock (metricMutex);
  66. double endTimeMs = getPreciseTimeMs();
  67. addCallbackMetrics (startTimeMs, endTimeMs);
  68. }
  69. //==============================================================================
  70. void addCallbackMetrics (double startTimeMs, double endTimeMs)
  71. {
  72. double runtimeMs = endTimeMs - startTimeMs;
  73. audioCallbackRuntimeMs.addValue (runtimeMs);
  74. if (runtimeMs > getPhysicalTimeLimitMs())
  75. numCallbacksOverPhysicalTimeLimit++;
  76. if (lastCallbackStartTimeMs > 0.0)
  77. {
  78. double gapMs = startTimeMs - lastCallbackStartTimeMs;
  79. audioCallbackGapMs.addValue (gapMs);
  80. if (gapMs > 1.5 * getPhysicalTimeLimitMs())
  81. numLateCallbacks++;
  82. }
  83. lastCallbackStartTimeMs = startTimeMs;
  84. }
  85. //==============================================================================
  86. void paint (Graphics& g) override
  87. {
  88. g.fillAll (Colours::black);
  89. g.setFont (Font (16.0f));
  90. g.setColour (Colours::white);
  91. g.drawText ("loop iterations / audio callback",
  92. getLocalBounds().withY (loopIterationsSlider.getHeight()), Justification::centred, true);
  93. }
  94. //==============================================================================
  95. void resized() override
  96. {
  97. loopIterationsSlider.setBounds (getLocalBounds().withSizeKeepingCentre (proportionOfWidth (0.9f), 50));
  98. }
  99. private:
  100. //==============================================================================
  101. void initGui()
  102. {
  103. loopIterationsSlider.setSliderStyle (Slider::LinearBar);
  104. loopIterationsSlider.setRange (0, 30000, 250);
  105. loopIterationsSlider.setValue (15000);
  106. loopIterationsSlider.setColour (Slider::thumbColourId, Colours::white);
  107. loopIterationsSlider.setColour (Slider::textBoxTextColourId, Colours::grey);
  108. updateNumLoopIterationsPerCallback();
  109. addAndMakeVisible (loopIterationsSlider);
  110. }
  111. //==============================================================================
  112. void allocateBuffers (std::size_t bufferSize)
  113. {
  114. a.resize (bufferSize);
  115. b.resize (bufferSize);
  116. c.resize (bufferSize);
  117. }
  118. //==============================================================================
  119. void initialiseBuffers (const AudioSourceChannelInfo& bufferToFill, std::size_t bufferSize)
  120. {
  121. if (bufferSize != a.size())
  122. {
  123. jassertfalse;
  124. Logger::writeToLog ("WARNING: Unexpected buffer size received."
  125. "expected: " + String (a.size()) +
  126. ", actual: " + String (bufferSize));
  127. if (bufferSize > a.size())
  128. Logger::writeToLog ("WARNING: Need to allocate larger buffers on audio thread!");
  129. allocateBuffers (bufferSize);
  130. }
  131. bufferToFill.clearActiveBufferRegion();
  132. std::fill (a.begin(), a.end(), 0.09f);
  133. std::fill (b.begin(), b.end(), 0.1f );
  134. std::fill (c.begin(), c.end(), 0.11f);
  135. }
  136. //==============================================================================
  137. void crunchSomeNumbers (float* outBuffer, std::size_t bufferSize, int numIterations) noexcept
  138. {
  139. jassert (a.size() == bufferSize && b.size() == bufferSize && c.size() == bufferSize);
  140. for (int i = 0; i < numIterations; ++i)
  141. {
  142. FloatVectorOperations::multiply (c.data(), a.data(), b.data(), (int) bufferSize);
  143. FloatVectorOperations::addWithMultiply (outBuffer, b.data(), c.data(), (int) bufferSize);
  144. }
  145. }
  146. //==============================================================================
  147. void timerCallback() override
  148. {
  149. printAndResetPerformanceMetrics();
  150. }
  151. //==============================================================================
  152. void printHeader() const
  153. {
  154. Logger::writeToLog ("buffer size = " + String (a.size()) + " samples");
  155. Logger::writeToLog ("sample rate = " + String (currentSampleRate) + " Hz");
  156. Logger::writeToLog ("physical time limit / callback = " + String (getPhysicalTimeLimitMs() )+ " ms");
  157. Logger::writeToLog ("");
  158. Logger::writeToLog (" | callback exec time / physLimit | callback time gap / physLimit | callback counters ");
  159. Logger::writeToLog ("numLoops | avg min max stddev | avg min max stddev | called late >limit ");
  160. Logger::writeToLog ("----- | ----- ----- ----- ----- | ----- ----- ----- ----- | --- --- --- ");
  161. }
  162. //==============================================================================
  163. void printAndResetPerformanceMetrics()
  164. {
  165. std::unique_lock<std::mutex> lock (metricMutex);
  166. auto runtimeMetric = audioCallbackRuntimeMs;
  167. auto gapMetric = audioCallbackGapMs;
  168. auto late = numLateCallbacks;
  169. auto overLimit = numCallbacksOverPhysicalTimeLimit;
  170. resetPerformanceMetrics();
  171. updateNumLoopIterationsPerCallback();
  172. lock.unlock();
  173. Logger::writeToLog (String (numLoopIterationsPerCallback).paddedRight (' ', 8) + " | "
  174. + getPercentFormattedMetricString (runtimeMetric) + " | "
  175. + getPercentFormattedMetricString (gapMetric) + " | "
  176. + String (runtimeMetric.getCount()).paddedRight (' ', 8)
  177. + String (late).paddedRight (' ', 8)
  178. + String (overLimit).paddedRight (' ', 8) + " | ");
  179. }
  180. //==============================================================================
  181. String getPercentFormattedMetricString (const StatisticsAccumulator<double> metric) const
  182. {
  183. auto physTimeLimit = getPhysicalTimeLimitMs();
  184. return (String (100.0 * metric.getAverage() / physTimeLimit, 1) + "%").paddedRight (' ', 8)
  185. + (String (100.0 * metric.getMinValue() / physTimeLimit, 1) + "%").paddedRight (' ', 8)
  186. + (String (100.0 * metric.getMaxValue() / physTimeLimit, 1) + "%").paddedRight (' ', 8)
  187. + String (metric.getStandardDeviation(), 3).paddedRight (' ', 8);
  188. }
  189. //==============================================================================
  190. void resetPerformanceMetrics()
  191. {
  192. audioCallbackRuntimeMs.reset();
  193. audioCallbackGapMs.reset();
  194. numLateCallbacks = 0;
  195. numCallbacksOverPhysicalTimeLimit = 0;
  196. }
  197. //==============================================================================
  198. void updateNumLoopIterationsPerCallback()
  199. {
  200. numLoopIterationsPerCallback = (int) loopIterationsSlider.getValue();
  201. }
  202. //==============================================================================
  203. static double getPreciseTimeMs() noexcept
  204. {
  205. return 1000.0 * Time::getHighResolutionTicks() / (double) Time::getHighResolutionTicksPerSecond();
  206. }
  207. //==============================================================================
  208. double getPhysicalTimeLimitMs() const noexcept
  209. {
  210. return 1000.0 * a.size() / currentSampleRate;
  211. }
  212. //==============================================================================
  213. std::vector<float> a, b, c; // must always be of size == current bufferSize
  214. double currentSampleRate = 0.0;
  215. StatisticsAccumulator<double> audioCallbackRuntimeMs;
  216. StatisticsAccumulator<double> audioCallbackGapMs;
  217. double lastCallbackStartTimeMs = 0.0;
  218. int numLateCallbacks = 0;
  219. int numCallbacksOverPhysicalTimeLimit = 0;
  220. int numLoopIterationsPerCallback;
  221. Slider loopIterationsSlider;
  222. std::mutex metricMutex;
  223. //==============================================================================
  224. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MainContentComponent)
  225. };
  226. // (This function is called by the app startup code to create our main component)
  227. Component* createMainContentComponent() { return new MainContentComponent(); }