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.

404 lines
14KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE examples.
  4. Copyright (c) 2017 - ROLI Ltd.
  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, vs2017, 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 : 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 audioDeviceIOCallback (const float** inputChannelData, int numInputChannels,
  110. float** outputChannelData, int numOutputChannels, int numSamples) override
  111. {
  112. const ScopedLock sl (lock);
  113. if (testIsRunning)
  114. {
  115. auto* recordingBuffer = recordedSound.getWritePointer (0);
  116. auto* playBuffer = testSound.getReadPointer (0);
  117. for (int i = 0; i < numSamples; ++i)
  118. {
  119. if (recordedSampleNum < recordedSound.getNumSamples())
  120. {
  121. auto inputSamp = 0.0f;
  122. for (auto j = numInputChannels; --j >= 0;)
  123. if (inputChannelData[j] != nullptr)
  124. inputSamp += inputChannelData[j][i];
  125. recordingBuffer[recordedSampleNum] = inputSamp;
  126. }
  127. ++recordedSampleNum;
  128. auto outputSamp = (playingSampleNum < testSound.getNumSamples()) ? playBuffer[playingSampleNum] : 0.0f;
  129. for (auto j = numOutputChannels; --j >= 0;)
  130. if (outputChannelData[j] != nullptr)
  131. outputChannelData[j][i] = outputSamp;
  132. ++playingSampleNum;
  133. }
  134. }
  135. else
  136. {
  137. // We need to clear the output buffers, in case they're full of junk..
  138. for (int i = 0; i < numOutputChannels; ++i)
  139. if (outputChannelData[i] != nullptr)
  140. zeromem (outputChannelData[i], sizeof (float) * (size_t) numSamples);
  141. }
  142. }
  143. private:
  144. TextEditor& resultsBox;
  145. AudioBuffer<float> testSound, recordedSound;
  146. Array<int> spikePositions;
  147. CriticalSection lock;
  148. int playingSampleNum = 0;
  149. int recordedSampleNum = -1;
  150. double sampleRate = 0.0;
  151. bool testIsRunning = false;
  152. int deviceInputLatency, deviceOutputLatency;
  153. //==============================================================================
  154. // create a test sound which consists of a series of randomly-spaced audio spikes..
  155. void createTestSound()
  156. {
  157. auto length = ((int) sampleRate) / 4;
  158. testSound.setSize (1, length);
  159. testSound.clear();
  160. Random rand;
  161. for (int i = 0; i < length; ++i)
  162. testSound.setSample (0, i, (rand.nextFloat() - rand.nextFloat() + rand.nextFloat() - rand.nextFloat()) * 0.06f);
  163. spikePositions.clear();
  164. int spikePos = 0;
  165. int spikeDelta = 50;
  166. while (spikePos < length - 1)
  167. {
  168. spikePositions.add (spikePos);
  169. testSound.setSample (0, spikePos, 0.99f);
  170. testSound.setSample (0, spikePos + 1, -0.99f);
  171. spikePos += spikeDelta;
  172. spikeDelta += spikeDelta / 6 + rand.nextInt (5);
  173. }
  174. }
  175. // Searches a buffer for a set of spikes that matches those in the test sound
  176. int findOffsetOfSpikes (const AudioBuffer<float>& buffer) const
  177. {
  178. auto minSpikeLevel = 5.0f;
  179. auto smooth = 0.975;
  180. auto* s = buffer.getReadPointer (0);
  181. int spikeDriftAllowed = 5;
  182. Array<int> spikesFound;
  183. spikesFound.ensureStorageAllocated (100);
  184. auto runningAverage = 0.0;
  185. int lastSpike = 0;
  186. for (int i = 0; i < buffer.getNumSamples() - 10; ++i)
  187. {
  188. auto samp = std::abs (s[i]);
  189. if (samp > runningAverage * minSpikeLevel && i > lastSpike + 20)
  190. {
  191. lastSpike = i;
  192. spikesFound.add (i);
  193. }
  194. runningAverage = runningAverage * smooth + (1.0 - smooth) * samp;
  195. }
  196. int bestMatch = -1;
  197. auto bestNumMatches = spikePositions.size() / 3; // the minimum number of matches required
  198. if (spikesFound.size() < bestNumMatches)
  199. return -1;
  200. for (int offsetToTest = 0; offsetToTest < buffer.getNumSamples() - 2048; ++offsetToTest)
  201. {
  202. int numMatchesHere = 0;
  203. int foundIndex = 0;
  204. for (int refIndex = 0; refIndex < spikePositions.size(); ++refIndex)
  205. {
  206. auto referenceSpike = spikePositions.getUnchecked (refIndex) + offsetToTest;
  207. int spike = 0;
  208. while ((spike = spikesFound.getUnchecked (foundIndex)) < referenceSpike - spikeDriftAllowed
  209. && foundIndex < spikesFound.size() - 1)
  210. ++foundIndex;
  211. if (spike >= referenceSpike - spikeDriftAllowed && spike <= referenceSpike + spikeDriftAllowed)
  212. ++numMatchesHere;
  213. }
  214. if (numMatchesHere > bestNumMatches)
  215. {
  216. bestNumMatches = numMatchesHere;
  217. bestMatch = offsetToTest;
  218. if (numMatchesHere == spikePositions.size())
  219. break;
  220. }
  221. }
  222. return bestMatch;
  223. }
  224. int calculateLatencySamples() const
  225. {
  226. // Detect the sound in both our test sound and the recording of it, and measure the difference
  227. // in their start times..
  228. auto referenceStart = findOffsetOfSpikes (testSound);
  229. jassert (referenceStart >= 0);
  230. auto recordedStart = findOffsetOfSpikes (recordedSound);
  231. return (recordedStart < 0) ? -1
  232. : (recordedStart - referenceStart);
  233. }
  234. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LatencyTester)
  235. };
  236. //==============================================================================
  237. class AudioLatencyDemo : public Component
  238. {
  239. public:
  240. AudioLatencyDemo()
  241. {
  242. setOpaque (true);
  243. liveAudioScroller.reset (new LiveScrollingAudioDisplay());
  244. addAndMakeVisible (liveAudioScroller.get());
  245. addAndMakeVisible (resultsBox);
  246. resultsBox.setMultiLine (true);
  247. resultsBox.setReturnKeyStartsNewLine (true);
  248. resultsBox.setReadOnly (true);
  249. resultsBox.setScrollbarsShown (true);
  250. resultsBox.setCaretVisible (false);
  251. resultsBox.setPopupMenuEnabled (true);
  252. resultsBox.setColour (TextEditor::outlineColourId, Colour (0x1c000000));
  253. resultsBox.setColour (TextEditor::shadowColourId, Colour (0x16000000));
  254. resultsBox.setText ("Running this test measures the round-trip latency between the audio output and input "
  255. "devices you\'ve got selected.\n\n"
  256. "It\'ll play a sound, then try to measure the time at which the sound arrives "
  257. "back at the audio input. Obviously for this to work you need to have your "
  258. "microphone somewhere near your speakers...");
  259. addAndMakeVisible (startTestButton);
  260. startTestButton.onClick = [this] { startTest(); };
  261. #ifndef JUCE_DEMO_RUNNER
  262. RuntimePermissions::request (RuntimePermissions::recordAudio,
  263. [this] (bool granted)
  264. {
  265. int numInputChannels = granted ? 2 : 0;
  266. audioDeviceManager.initialise (numInputChannels, 2, nullptr, true, {}, nullptr);
  267. });
  268. #endif
  269. audioDeviceManager.addAudioCallback (liveAudioScroller.get());
  270. setSize (500, 500);
  271. }
  272. ~AudioLatencyDemo()
  273. {
  274. audioDeviceManager.removeAudioCallback (liveAudioScroller.get());
  275. audioDeviceManager.removeAudioCallback (latencyTester .get());
  276. latencyTester .reset();
  277. liveAudioScroller.reset();
  278. }
  279. void startTest()
  280. {
  281. if (latencyTester.get() == nullptr)
  282. {
  283. latencyTester.reset (new LatencyTester (resultsBox));
  284. audioDeviceManager.addAudioCallback (latencyTester.get());
  285. }
  286. latencyTester->beginTest();
  287. }
  288. void paint (Graphics& g) override
  289. {
  290. g.fillAll (findColour (ResizableWindow::backgroundColourId));
  291. }
  292. void resized() override
  293. {
  294. auto b = getLocalBounds().reduced (5);
  295. if (liveAudioScroller.get() != nullptr)
  296. {
  297. liveAudioScroller->setBounds (b.removeFromTop (b.getHeight() / 5));
  298. b.removeFromTop (10);
  299. }
  300. startTestButton.setBounds (b.removeFromBottom (b.getHeight() / 10));
  301. b.removeFromBottom (10);
  302. resultsBox.setBounds (b);
  303. }
  304. private:
  305. // if this PIP is running inside the demo runner, we'll use the shared device manager instead
  306. #ifndef JUCE_DEMO_RUNNER
  307. AudioDeviceManager audioDeviceManager;
  308. #else
  309. AudioDeviceManager& audioDeviceManager { getSharedAudioDeviceManager (1, 2) };
  310. #endif
  311. std::unique_ptr<LatencyTester> latencyTester;
  312. std::unique_ptr<LiveScrollingAudioDisplay> liveAudioScroller;
  313. TextButton startTestButton { "Test Latency" };
  314. TextEditor resultsBox;
  315. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioLatencyDemo)
  316. };