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.

319 lines
11KB

  1. /*
  2. ==============================================================================
  3. This file is part of the dRowAudio JUCE module
  4. Copyright 2004-13 by dRowAudio.
  5. ------------------------------------------------------------------------------
  6. dRowAudio is provided under the terms of The MIT License (MIT):
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13. The above copyright notice and this permission notice shall be included in all
  14. copies or substantial portions of the Software.
  15. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. SOFTWARE.
  22. ==============================================================================
  23. */
  24. //==============================================================================
  25. PitchDetector::PitchDetector()
  26. : detectionMethod (autoCorrelationFunction),
  27. sampleRate (44100.0),
  28. minFrequency (50), maxFrequency (1600),
  29. buffer1 (512), buffer2 (512),
  30. numSamplesNeededForDetection (int ((sampleRate / minFrequency) * 2)),
  31. currentBlockBuffer (numSamplesNeededForDetection),
  32. inputFifoBuffer (numSamplesNeededForDetection * 2),
  33. mostRecentPitch (0.0)
  34. {
  35. updateFiltersAndBlockSizes();
  36. }
  37. PitchDetector::~PitchDetector()
  38. {
  39. }
  40. void PitchDetector::processSamples (const float* samples, int numSamples) noexcept
  41. {
  42. if (inputFifoBuffer.getNumFree() < numSamples)
  43. inputFifoBuffer.setSizeKeepingExisting (inputFifoBuffer.getSize() * 2);
  44. inputFifoBuffer.writeSamples (samples, numSamples);
  45. while (inputFifoBuffer.getNumAvailable() >= numSamplesNeededForDetection)
  46. {
  47. inputFifoBuffer.readSamples (currentBlockBuffer.getData(), currentBlockBuffer.getSize());
  48. mostRecentPitch = detectPitchForBlock (currentBlockBuffer.getData(), currentBlockBuffer.getSize());
  49. }
  50. }
  51. //==============================================================================
  52. double PitchDetector::detectPitch (float* samples, int numSamples) noexcept
  53. {
  54. Array<double> pitches;
  55. pitches.ensureStorageAllocated (int (numSamples / numSamplesNeededForDetection));
  56. while (numSamples >= numSamplesNeededForDetection)
  57. {
  58. double pitch = detectPitchForBlock (samples, numSamplesNeededForDetection);//0.0;
  59. if (pitch > 0.0)
  60. pitches.add (pitch);
  61. numSamples -= numSamplesNeededForDetection;
  62. samples += numSamplesNeededForDetection;
  63. }
  64. if (pitches.size() == 1)
  65. {
  66. return pitches[0];
  67. }
  68. else if (pitches.size() > 1)
  69. {
  70. DefaultElementComparator<double> sorter;
  71. pitches.sort (sorter);
  72. const double stdDev = findStandardDeviation (pitches.getRawDataPointer(), pitches.size());
  73. const double medianSample = findMedian (pitches.getRawDataPointer(), pitches.size());
  74. const double lowerLimit = medianSample - stdDev;
  75. const double upperLimit = medianSample + stdDev;
  76. Array<double> correctedPitches;
  77. correctedPitches.ensureStorageAllocated (pitches.size());
  78. for (int i = 0; i < pitches.size(); ++i)
  79. {
  80. const double pitch = pitches.getUnchecked (i);
  81. if (pitch >= lowerLimit && pitch <= upperLimit)
  82. correctedPitches.add (pitch);
  83. }
  84. const double finalPitch = findMean (correctedPitches.getRawDataPointer(), correctedPitches.size());
  85. return finalPitch;
  86. }
  87. return 0.0;
  88. }
  89. //==============================================================================
  90. void PitchDetector::setSampleRate (double newSampleRate) noexcept
  91. {
  92. sampleRate = newSampleRate;
  93. updateFiltersAndBlockSizes();
  94. }
  95. void PitchDetector::setDetectionMethod (DetectionMethod newMethod)
  96. {
  97. detectionMethod = newMethod;
  98. }
  99. void PitchDetector::setMinMaxFrequency (float newMinFrequency, float newMaxFrequency) noexcept
  100. {
  101. minFrequency = newMinFrequency;
  102. maxFrequency = newMaxFrequency;
  103. updateFiltersAndBlockSizes();
  104. }
  105. //==============================================================================
  106. Buffer* PitchDetector::getBuffer (int stageIndex)
  107. {
  108. switch (stageIndex)
  109. {
  110. case 1: return &buffer1; break;
  111. case 2: return &buffer2; break;
  112. default: return nullptr;
  113. }
  114. return nullptr;
  115. }
  116. //==============================================================================
  117. void PitchDetector::updateFiltersAndBlockSizes()
  118. {
  119. lowFilter.setCoefficients (IIRCoefficients::makeLowPass (sampleRate, maxFrequency));
  120. highFilter.setCoefficients (IIRCoefficients::makeHighPass (sampleRate, minFrequency));
  121. numSamplesNeededForDetection = int (sampleRate / minFrequency) * 2;
  122. inputFifoBuffer.setSizeKeepingExisting (numSamplesNeededForDetection * 2);
  123. currentBlockBuffer.setSize (numSamplesNeededForDetection);
  124. buffer1.setSizeQuick (numSamplesNeededForDetection);
  125. buffer2.setSizeQuick (numSamplesNeededForDetection);
  126. }
  127. //==============================================================================
  128. double PitchDetector::detectPitchForBlock (float* samples, int numSamples)
  129. {
  130. switch (detectionMethod)
  131. {
  132. case autoCorrelationFunction: return detectAcfPitchForBlock (samples, numSamples);
  133. case squareDifferenceFunction: return detectSdfPitchForBlock (samples, numSamples);
  134. default: return 0.0;
  135. }
  136. }
  137. double PitchDetector::detectAcfPitchForBlock (float* samples, int numSamples)
  138. {
  139. const int minSample = int (sampleRate / maxFrequency);
  140. const int maxSample = int (sampleRate / minFrequency);
  141. lowFilter.reset();
  142. highFilter.reset();
  143. lowFilter.processSamples (samples, numSamples);
  144. highFilter.processSamples (samples, numSamples);
  145. autocorrelate (samples, numSamples, buffer1.getData());
  146. normalise (buffer1.getData(), buffer1.getSize());
  147. // float max = 0.0f;
  148. // int sampleIndex = 0;
  149. // for (int i = minSample; i < maxSample; ++i)
  150. // {
  151. // const float sample = buffer1.getData()[i];
  152. // if (sample > max)
  153. // {
  154. // max = sample;
  155. // sampleIndex = i;
  156. // }
  157. // }
  158. float* bufferData = buffer1.getData();
  159. // const int bufferSize = buffer1.getSize();
  160. int firstNegativeZero = 0;
  161. // first peak method
  162. for (int i = 0; i < numSamples - 1; ++i)
  163. {
  164. if (bufferData[i] >= 0.0f && bufferData[i + 1] < 0.0f)
  165. {
  166. firstNegativeZero = i;
  167. break;
  168. }
  169. }
  170. // apply gain ramp
  171. // float rampDelta = 1.0f / numSamples;
  172. // float rampLevel = 1.0f;
  173. // for (int i = 0; i < numSamples - 1; ++i)
  174. // {
  175. // bufferData[i] *= cubeNumber (rampLevel);
  176. // rampLevel -= rampDelta;
  177. // }
  178. float max = -1.0f;
  179. int sampleIndex = 0;
  180. for (int i = jmax (firstNegativeZero, minSample); i < maxSample; ++i)
  181. {
  182. if (bufferData[i] > max)
  183. {
  184. max = bufferData[i];
  185. sampleIndex = i;
  186. }
  187. }
  188. // buffer2.setSizeQuick (numSamples);
  189. /* autocorrelate (buffer1.getData(), buffer1.getSize(), buffer2.getData());
  190. normalise (buffer2.getData(), buffer2.getSize());*/
  191. //buffer2.quickCopy (buffer1.getData(), buffer1.getSize());
  192. // differentiate (buffer1.getData(), buffer1.getSize(), buffer2.getData());
  193. // normalise (buffer2.getData()+2, buffer2.getSize()-2);
  194. // differentiate (buffer2.getData(), buffer2.getSize(), buffer2.getData());
  195. /* for (int i = minSample + 1; i < maxSample - 1; ++i)
  196. {
  197. const float previousSample = buffer2.getData()[i - 1];
  198. const float sample = buffer2.getData()[i];
  199. const float nextSample = buffer2.getData()[i + 1];
  200. if (sample > previousSample
  201. && sample > nextSample
  202. && sample > 0.5f)
  203. sampleIndex = i;
  204. }*/
  205. //differentiate (buffer2.getData(), buffer2.getSize(), buffer2.getData());
  206. //normalise (buffer2.getData() + minSample, buffer2.getSize() - minSample);
  207. // float min = 0.0f;
  208. // int sampleIndex = 0;
  209. // for (int i = minSample; i < maxSample; ++i)
  210. // {
  211. // const float sample = buffer2.getData()[i];
  212. // if (sample < min)
  213. // {
  214. // min = sample;
  215. // sampleIndex = i;
  216. // }
  217. // }
  218. if (sampleIndex > 0)
  219. return sampleRate / sampleIndex;
  220. else
  221. return 0.0;
  222. }
  223. double PitchDetector::detectSdfPitchForBlock (float* samples, int numSamples)
  224. {
  225. const int minSample = int (sampleRate / maxFrequency);
  226. const int maxSample = int (sampleRate / minFrequency);
  227. lowFilter.reset();
  228. highFilter.reset();
  229. lowFilter.processSamples (samples, numSamples);
  230. highFilter.processSamples (samples, numSamples);
  231. sdfAutocorrelate (samples, numSamples, buffer1.getData());
  232. normalise (buffer1.getData(), buffer1.getSize());
  233. // find first minimum that is below a threshold
  234. const float threshold = 0.25f;
  235. const float* sdfData = buffer1.getData();
  236. float min = 1.0f;
  237. int index = 0;
  238. for (int i = minSample; i < maxSample; ++i)
  239. {
  240. const float prevSample = sdfData[i - 1];
  241. const float sample = sdfData[i];
  242. const float nextSample = sdfData[i + 1];
  243. if (sample < prevSample
  244. && sample < nextSample
  245. && sample < threshold)
  246. {
  247. if (sample < min)
  248. {
  249. min = sample;
  250. index = i;
  251. }
  252. // return sampleRate / i;
  253. // break;
  254. }
  255. }
  256. if (index != 0)
  257. return sampleRate / index;
  258. return 0.0;
  259. }