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.

407 lines
14KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE examples.
  4. Copyright (c) 2022 - Raw Material Software Limited
  5. The code included in this file is provided under the terms of the ISC license
  6. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  7. To use, copy, modify, and/or distribute this software for any purpose with or
  8. without fee is hereby granted provided that the above copyright notice and
  9. this permission notice appear in all copies.
  10. THE SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES,
  11. WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR
  12. PURPOSE, ARE DISCLAIMED.
  13. ==============================================================================
  14. */
  15. /*******************************************************************************
  16. The block below describes the properties of this PIP. A PIP is a short snippet
  17. of code that can be read by the Projucer and used to generate a JUCE project.
  18. BEGIN_JUCE_PIP_METADATA
  19. name: AudioLatencyDemo
  20. version: 1.0.0
  21. vendor: JUCE
  22. website: http://juce.com
  23. description: Tests the audio latency of a device.
  24. dependencies: juce_audio_basics, juce_audio_devices, juce_audio_formats,
  25. juce_audio_processors, juce_audio_utils, juce_core,
  26. juce_data_structures, juce_events, juce_graphics,
  27. juce_gui_basics, juce_gui_extra
  28. exporters: xcode_mac, vs2022, linux_make, androidstudio, xcode_iphone
  29. moduleFlags: JUCE_STRICT_REFCOUNTEDPOINTER=1
  30. type: Component
  31. mainClass: AudioLatencyDemo
  32. useLocalCopy: 1
  33. END_JUCE_PIP_METADATA
  34. *******************************************************************************/
  35. #pragma once
  36. #include "../Assets/DemoUtilities.h"
  37. #include "../Assets/AudioLiveScrollingDisplay.h"
  38. //==============================================================================
  39. class LatencyTester final : public AudioIODeviceCallback,
  40. private Timer
  41. {
  42. public:
  43. LatencyTester (TextEditor& editorBox)
  44. : resultsBox (editorBox)
  45. {}
  46. //==============================================================================
  47. void beginTest()
  48. {
  49. resultsBox.moveCaretToEnd();
  50. resultsBox.insertTextAtCaret (newLine + newLine + "Starting test..." + newLine);
  51. resultsBox.moveCaretToEnd();
  52. startTimer (50);
  53. const ScopedLock sl (lock);
  54. createTestSound();
  55. recordedSound.clear();
  56. playingSampleNum = recordedSampleNum = 0;
  57. testIsRunning = true;
  58. }
  59. void timerCallback() override
  60. {
  61. if (testIsRunning && recordedSampleNum >= recordedSound.getNumSamples())
  62. {
  63. testIsRunning = false;
  64. stopTimer();
  65. // Test has finished, so calculate the result..
  66. auto latencySamples = calculateLatencySamples();
  67. resultsBox.moveCaretToEnd();
  68. resultsBox.insertTextAtCaret (getMessageDescribingResult (latencySamples));
  69. resultsBox.moveCaretToEnd();
  70. }
  71. }
  72. String getMessageDescribingResult (int latencySamples)
  73. {
  74. String message;
  75. if (latencySamples >= 0)
  76. {
  77. message << newLine
  78. << "Results:" << newLine
  79. << latencySamples << " samples (" << String (latencySamples * 1000.0 / sampleRate, 1)
  80. << " milliseconds)" << newLine
  81. << "The audio device reports an input latency of "
  82. << deviceInputLatency << " samples, output latency of "
  83. << deviceOutputLatency << " samples." << newLine
  84. << "So the corrected latency = "
  85. << (latencySamples - deviceInputLatency - deviceOutputLatency)
  86. << " samples (" << String ((latencySamples - deviceInputLatency - deviceOutputLatency) * 1000.0 / sampleRate, 2)
  87. << " milliseconds)";
  88. }
  89. else
  90. {
  91. message << newLine
  92. << "Couldn't detect the test signal!!" << newLine
  93. << "Make sure there's no background noise that might be confusing it..";
  94. }
  95. return message;
  96. }
  97. //==============================================================================
  98. void audioDeviceAboutToStart (AudioIODevice* device) override
  99. {
  100. testIsRunning = false;
  101. playingSampleNum = recordedSampleNum = 0;
  102. sampleRate = device->getCurrentSampleRate();
  103. deviceInputLatency = device->getInputLatencyInSamples();
  104. deviceOutputLatency = device->getOutputLatencyInSamples();
  105. recordedSound.setSize (1, (int) (0.9 * sampleRate));
  106. recordedSound.clear();
  107. }
  108. void audioDeviceStopped() override {}
  109. void audioDeviceIOCallbackWithContext (const float* const* inputChannelData, int numInputChannels,
  110. float* const* outputChannelData, int numOutputChannels,
  111. int numSamples, const AudioIODeviceCallbackContext& context) override
  112. {
  113. ignoreUnused (context);
  114. const ScopedLock sl (lock);
  115. if (testIsRunning)
  116. {
  117. auto* recordingBuffer = recordedSound.getWritePointer (0);
  118. auto* playBuffer = testSound.getReadPointer (0);
  119. for (int i = 0; i < numSamples; ++i)
  120. {
  121. if (recordedSampleNum < recordedSound.getNumSamples())
  122. {
  123. auto inputSamp = 0.0f;
  124. for (auto j = numInputChannels; --j >= 0;)
  125. if (inputChannelData[j] != nullptr)
  126. inputSamp += inputChannelData[j][i];
  127. recordingBuffer[recordedSampleNum] = inputSamp;
  128. }
  129. ++recordedSampleNum;
  130. auto outputSamp = (playingSampleNum < testSound.getNumSamples()) ? playBuffer[playingSampleNum] : 0.0f;
  131. for (auto j = numOutputChannels; --j >= 0;)
  132. if (outputChannelData[j] != nullptr)
  133. outputChannelData[j][i] = outputSamp;
  134. ++playingSampleNum;
  135. }
  136. }
  137. else
  138. {
  139. // We need to clear the output buffers, in case they're full of junk..
  140. for (int i = 0; i < numOutputChannels; ++i)
  141. if (outputChannelData[i] != nullptr)
  142. zeromem (outputChannelData[i], (size_t) numSamples * sizeof (float));
  143. }
  144. }
  145. private:
  146. TextEditor& resultsBox;
  147. AudioBuffer<float> testSound, recordedSound;
  148. Array<int> spikePositions;
  149. CriticalSection lock;
  150. int playingSampleNum = 0;
  151. int recordedSampleNum = -1;
  152. double sampleRate = 0.0;
  153. bool testIsRunning = false;
  154. int deviceInputLatency, deviceOutputLatency;
  155. //==============================================================================
  156. // create a test sound which consists of a series of randomly-spaced audio spikes..
  157. void createTestSound()
  158. {
  159. auto length = ((int) sampleRate) / 4;
  160. testSound.setSize (1, length);
  161. testSound.clear();
  162. Random rand;
  163. for (int i = 0; i < length; ++i)
  164. testSound.setSample (0, i, (rand.nextFloat() - rand.nextFloat() + rand.nextFloat() - rand.nextFloat()) * 0.06f);
  165. spikePositions.clear();
  166. int spikePos = 0;
  167. int spikeDelta = 50;
  168. while (spikePos < length - 1)
  169. {
  170. spikePositions.add (spikePos);
  171. testSound.setSample (0, spikePos, 0.99f);
  172. testSound.setSample (0, spikePos + 1, -0.99f);
  173. spikePos += spikeDelta;
  174. spikeDelta += spikeDelta / 6 + rand.nextInt (5);
  175. }
  176. }
  177. // Searches a buffer for a set of spikes that matches those in the test sound
  178. int findOffsetOfSpikes (const AudioBuffer<float>& buffer) const
  179. {
  180. auto minSpikeLevel = 5.0f;
  181. auto smooth = 0.975;
  182. auto* s = buffer.getReadPointer (0);
  183. int spikeDriftAllowed = 5;
  184. Array<int> spikesFound;
  185. spikesFound.ensureStorageAllocated (100);
  186. auto runningAverage = 0.0;
  187. int lastSpike = 0;
  188. for (int i = 0; i < buffer.getNumSamples() - 10; ++i)
  189. {
  190. auto samp = std::abs (s[i]);
  191. if (samp > runningAverage * minSpikeLevel && i > lastSpike + 20)
  192. {
  193. lastSpike = i;
  194. spikesFound.add (i);
  195. }
  196. runningAverage = runningAverage * smooth + (1.0 - smooth) * samp;
  197. }
  198. int bestMatch = -1;
  199. auto bestNumMatches = spikePositions.size() / 3; // the minimum number of matches required
  200. if (spikesFound.size() < bestNumMatches)
  201. return -1;
  202. for (int offsetToTest = 0; offsetToTest < buffer.getNumSamples() - 2048; ++offsetToTest)
  203. {
  204. int numMatchesHere = 0;
  205. int foundIndex = 0;
  206. for (int refIndex = 0; refIndex < spikePositions.size(); ++refIndex)
  207. {
  208. auto referenceSpike = spikePositions.getUnchecked (refIndex) + offsetToTest;
  209. int spike = 0;
  210. while ((spike = spikesFound.getUnchecked (foundIndex)) < referenceSpike - spikeDriftAllowed
  211. && foundIndex < spikesFound.size() - 1)
  212. ++foundIndex;
  213. if (spike >= referenceSpike - spikeDriftAllowed && spike <= referenceSpike + spikeDriftAllowed)
  214. ++numMatchesHere;
  215. }
  216. if (numMatchesHere > bestNumMatches)
  217. {
  218. bestNumMatches = numMatchesHere;
  219. bestMatch = offsetToTest;
  220. if (numMatchesHere == spikePositions.size())
  221. break;
  222. }
  223. }
  224. return bestMatch;
  225. }
  226. int calculateLatencySamples() const
  227. {
  228. // Detect the sound in both our test sound and the recording of it, and measure the difference
  229. // in their start times..
  230. auto referenceStart = findOffsetOfSpikes (testSound);
  231. jassert (referenceStart >= 0);
  232. auto recordedStart = findOffsetOfSpikes (recordedSound);
  233. return (recordedStart < 0) ? -1
  234. : (recordedStart - referenceStart);
  235. }
  236. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LatencyTester)
  237. };
  238. //==============================================================================
  239. class AudioLatencyDemo final : public Component
  240. {
  241. public:
  242. AudioLatencyDemo()
  243. {
  244. setOpaque (true);
  245. liveAudioScroller.reset (new LiveScrollingAudioDisplay());
  246. addAndMakeVisible (liveAudioScroller.get());
  247. addAndMakeVisible (resultsBox);
  248. resultsBox.setMultiLine (true);
  249. resultsBox.setReturnKeyStartsNewLine (true);
  250. resultsBox.setReadOnly (true);
  251. resultsBox.setScrollbarsShown (true);
  252. resultsBox.setCaretVisible (false);
  253. resultsBox.setPopupMenuEnabled (true);
  254. resultsBox.setColour (TextEditor::outlineColourId, Colour (0x1c000000));
  255. resultsBox.setColour (TextEditor::shadowColourId, Colour (0x16000000));
  256. resultsBox.setText ("Running this test measures the round-trip latency between the audio output and input "
  257. "devices you\'ve got selected.\n\n"
  258. "It\'ll play a sound, then try to measure the time at which the sound arrives "
  259. "back at the audio input. Obviously for this to work you need to have your "
  260. "microphone somewhere near your speakers...");
  261. addAndMakeVisible (startTestButton);
  262. startTestButton.onClick = [this] { startTest(); };
  263. #ifndef JUCE_DEMO_RUNNER
  264. RuntimePermissions::request (RuntimePermissions::recordAudio,
  265. [this] (bool granted)
  266. {
  267. int numInputChannels = granted ? 2 : 0;
  268. audioDeviceManager.initialise (numInputChannels, 2, nullptr, true, {}, nullptr);
  269. });
  270. #endif
  271. audioDeviceManager.addAudioCallback (liveAudioScroller.get());
  272. setSize (500, 500);
  273. }
  274. ~AudioLatencyDemo() override
  275. {
  276. audioDeviceManager.removeAudioCallback (liveAudioScroller.get());
  277. audioDeviceManager.removeAudioCallback (latencyTester .get());
  278. latencyTester .reset();
  279. liveAudioScroller.reset();
  280. }
  281. void startTest()
  282. {
  283. if (latencyTester.get() == nullptr)
  284. {
  285. latencyTester.reset (new LatencyTester (resultsBox));
  286. audioDeviceManager.addAudioCallback (latencyTester.get());
  287. }
  288. latencyTester->beginTest();
  289. }
  290. void paint (Graphics& g) override
  291. {
  292. g.fillAll (findColour (ResizableWindow::backgroundColourId));
  293. }
  294. void resized() override
  295. {
  296. auto b = getLocalBounds().reduced (5);
  297. if (liveAudioScroller.get() != nullptr)
  298. {
  299. liveAudioScroller->setBounds (b.removeFromTop (b.getHeight() / 5));
  300. b.removeFromTop (10);
  301. }
  302. startTestButton.setBounds (b.removeFromBottom (b.getHeight() / 10));
  303. b.removeFromBottom (10);
  304. resultsBox.setBounds (b);
  305. }
  306. private:
  307. // if this PIP is running inside the demo runner, we'll use the shared device manager instead
  308. #ifndef JUCE_DEMO_RUNNER
  309. AudioDeviceManager audioDeviceManager;
  310. #else
  311. AudioDeviceManager& audioDeviceManager { getSharedAudioDeviceManager (1, 2) };
  312. #endif
  313. std::unique_ptr<LatencyTester> latencyTester;
  314. std::unique_ptr<LiveScrollingAudioDisplay> liveAudioScroller;
  315. TextButton startTestButton { "Test Latency" };
  316. TextEditor resultsBox;
  317. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioLatencyDemo)
  318. };