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.

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