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.

285 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. #ifndef MAINCOMPONENT_H_INCLUDED
  22. #define MAINCOMPONENT_H_INCLUDED
  23. #include "../JuceLibraryCode/JuceHeader.h"
  24. #include <mutex>
  25. //==============================================================================
  26. class MainContentComponent : public AudioAppComponent,
  27. private Timer
  28. {
  29. public:
  30. //==============================================================================
  31. MainContentComponent()
  32. {
  33. setSize (400, 400);
  34. setAudioChannels (0, 2);
  35. initGui();
  36. Desktop::getInstance().setScreenSaverEnabled (false);
  37. startTimer (1000);
  38. }
  39. ~MainContentComponent()
  40. {
  41. shutdownAudio();
  42. }
  43. //==============================================================================
  44. void prepareToPlay (int bufferSize, double sampleRate) override
  45. {
  46. currentSampleRate = sampleRate;
  47. allocateBuffers (bufferSize);
  48. printHeader();
  49. }
  50. void releaseResources() override
  51. {
  52. a.clear();
  53. b.clear();
  54. c.clear();
  55. currentSampleRate = 0.0;
  56. }
  57. //==============================================================================
  58. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) override
  59. {
  60. const double startTimeMs = getPreciseTimeMs();
  61. AudioBuffer<float>& outputAudio = *bufferToFill.buffer;
  62. std::size_t bufferSize = (std::size_t) outputAudio.getNumSamples();
  63. initialiseBuffers (bufferToFill, bufferSize);
  64. for (int ch = 0; ch < outputAudio.getNumChannels(); ++ch)
  65. crunchSomeNumbers (outputAudio.getWritePointer (ch), bufferSize, numLoopIterationsPerCallback);
  66. std::lock_guard<std::mutex> lock (metricMutex);
  67. double endTimeMs = getPreciseTimeMs();
  68. addCallbackMetrics (startTimeMs, endTimeMs);
  69. }
  70. //==============================================================================
  71. void addCallbackMetrics (double startTimeMs, double endTimeMs)
  72. {
  73. double runtimeMs = endTimeMs - startTimeMs;
  74. audioCallbackRuntimeMs.addValue (runtimeMs);
  75. if (runtimeMs > getPhysicalTimeLimitMs())
  76. numCallbacksOverPhysicalTimeLimit++;
  77. if (lastCallbackStartTimeMs > 0.0)
  78. {
  79. double gapMs = startTimeMs - lastCallbackStartTimeMs;
  80. audioCallbackGapMs.addValue (gapMs);
  81. if (gapMs > 1.5 * getPhysicalTimeLimitMs())
  82. numLateCallbacks++;
  83. }
  84. lastCallbackStartTimeMs = startTimeMs;
  85. }
  86. //==============================================================================
  87. void paint (Graphics& g) override
  88. {
  89. g.fillAll (Colours::black);
  90. g.setFont (Font (16.0f));
  91. g.setColour (Colours::white);
  92. g.drawText ("loop iterations / audio callback",
  93. getLocalBounds().withY (loopIterationsSlider.getHeight()), Justification::centred, true);
  94. }
  95. //==============================================================================
  96. void resized() override
  97. {
  98. loopIterationsSlider.setBounds (getLocalBounds().withSizeKeepingCentre (proportionOfWidth (0.9f), 50));
  99. }
  100. private:
  101. //==============================================================================
  102. void initGui()
  103. {
  104. loopIterationsSlider.setSliderStyle (Slider::LinearBar);
  105. loopIterationsSlider.setRange (0, 30000, 250);
  106. loopIterationsSlider.setValue (15000);
  107. loopIterationsSlider.setColour (Slider::thumbColourId, Colours::white);
  108. loopIterationsSlider.setColour (Slider::textBoxTextColourId, Colours::grey);
  109. updateNumLoopIterationsPerCallback();
  110. addAndMakeVisible (loopIterationsSlider);
  111. }
  112. //==============================================================================
  113. void allocateBuffers (std::size_t bufferSize)
  114. {
  115. a.resize (bufferSize);
  116. b.resize (bufferSize);
  117. c.resize (bufferSize);
  118. }
  119. //==============================================================================
  120. void initialiseBuffers (const AudioSourceChannelInfo& bufferToFill, std::size_t bufferSize)
  121. {
  122. if (bufferSize != a.size())
  123. {
  124. jassertfalse;
  125. Logger::writeToLog ("WARNING: Unexpected buffer size received."
  126. "expected: " + String (a.size()) +
  127. ", actual: " + String (bufferSize));
  128. if (bufferSize > a.size())
  129. Logger::writeToLog ("WARNING: Need to allocate larger buffers on audio thread!");
  130. allocateBuffers (bufferSize);
  131. }
  132. bufferToFill.clearActiveBufferRegion();
  133. std::fill (a.begin(), a.end(), 0.09f);
  134. std::fill (b.begin(), b.end(), 0.1f );
  135. std::fill (c.begin(), c.end(), 0.11f);
  136. }
  137. //==============================================================================
  138. void crunchSomeNumbers (float* outBuffer, std::size_t bufferSize, int numIterations) noexcept
  139. {
  140. jassert (a.size() == bufferSize && b.size() == bufferSize && c.size() == bufferSize);
  141. for (int i = 0; i < numIterations; ++i)
  142. {
  143. FloatVectorOperations::multiply (c.data(), a.data(), b.data(), (int) bufferSize);
  144. FloatVectorOperations::addWithMultiply (outBuffer, b.data(), c.data(), (int) bufferSize);
  145. }
  146. }
  147. //==============================================================================
  148. void timerCallback() override
  149. {
  150. printAndResetPerformanceMetrics();
  151. }
  152. //==============================================================================
  153. void printHeader() const
  154. {
  155. Logger::writeToLog ("buffer size = " + String (a.size()) + " samples");
  156. Logger::writeToLog ("sample rate = " + String (currentSampleRate) + " Hz");
  157. Logger::writeToLog ("physical time limit / callback = " + String (getPhysicalTimeLimitMs() )+ " ms");
  158. Logger::writeToLog ("");
  159. Logger::writeToLog (" | callback exec time / physLimit | callback time gap / physLimit | callback counters ");
  160. Logger::writeToLog ("numLoops | avg min max stddev | avg min max stddev | called late >limit ");
  161. Logger::writeToLog ("----- | ----- ----- ----- ----- | ----- ----- ----- ----- | --- --- --- ");
  162. }
  163. //==============================================================================
  164. void printAndResetPerformanceMetrics()
  165. {
  166. std::unique_lock<std::mutex> lock (metricMutex);
  167. auto runtimeMetric = audioCallbackRuntimeMs;
  168. auto gapMetric = audioCallbackGapMs;
  169. auto late = numLateCallbacks;
  170. auto overLimit = numCallbacksOverPhysicalTimeLimit;
  171. resetPerformanceMetrics();
  172. updateNumLoopIterationsPerCallback();
  173. lock.unlock();
  174. Logger::writeToLog (String (numLoopIterationsPerCallback).paddedRight (' ', 8) + " | "
  175. + getPercentFormattedMetricString (runtimeMetric) + " | "
  176. + getPercentFormattedMetricString (gapMetric) + " | "
  177. + String (runtimeMetric.getCount()).paddedRight (' ', 8)
  178. + String (late).paddedRight (' ', 8)
  179. + String (overLimit).paddedRight (' ', 8) + " | ");
  180. }
  181. //==============================================================================
  182. String getPercentFormattedMetricString (const StatisticsAccumulator<double> metric) const
  183. {
  184. auto physTimeLimit = getPhysicalTimeLimitMs();
  185. return (String (100.0 * metric.getAverage() / physTimeLimit, 1) + "%").paddedRight (' ', 8)
  186. + (String (100.0 * metric.getMinValue() / physTimeLimit, 1) + "%").paddedRight (' ', 8)
  187. + (String (100.0 * metric.getMaxValue() / physTimeLimit, 1) + "%").paddedRight (' ', 8)
  188. + String (metric.getStandardDeviation(), 3).paddedRight (' ', 8);
  189. }
  190. //==============================================================================
  191. void resetPerformanceMetrics()
  192. {
  193. audioCallbackRuntimeMs.reset();
  194. audioCallbackGapMs.reset();
  195. numLateCallbacks = 0;
  196. numCallbacksOverPhysicalTimeLimit = 0;
  197. }
  198. //==============================================================================
  199. void updateNumLoopIterationsPerCallback()
  200. {
  201. numLoopIterationsPerCallback = (int) loopIterationsSlider.getValue();
  202. }
  203. //==============================================================================
  204. static double getPreciseTimeMs() noexcept
  205. {
  206. return 1000.0 * Time::getHighResolutionTicks() / (double) Time::getHighResolutionTicksPerSecond();
  207. }
  208. //==============================================================================
  209. double getPhysicalTimeLimitMs() const noexcept
  210. {
  211. return 1000.0 * a.size() / currentSampleRate;
  212. }
  213. //==============================================================================
  214. std::vector<float> a, b, c; // must always be of size == current bufferSize
  215. double currentSampleRate = 0.0;
  216. StatisticsAccumulator<double> audioCallbackRuntimeMs;
  217. StatisticsAccumulator<double> audioCallbackGapMs;
  218. double lastCallbackStartTimeMs = 0.0;
  219. int numLateCallbacks = 0;
  220. int numCallbacksOverPhysicalTimeLimit = 0;
  221. int numLoopIterationsPerCallback;
  222. Slider loopIterationsSlider;
  223. std::mutex metricMutex;
  224. //==============================================================================
  225. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MainContentComponent)
  226. };
  227. // (This function is called by the app startup code to create our main component)
  228. Component* createMainContentComponent() { return new MainContentComponent(); }
  229. #endif // MAINCOMPONENT_H_INCLUDED