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.

271 lines
10KB

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