PageRenderTime 52ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/src/qt/qtwebkit/Source/WebCore/platform/audio/HRTFPanner.cpp

https://gitlab.com/x33n/phantomjs
C++ | 316 lines | 205 code | 49 blank | 62 comment | 53 complexity | a7761fae3a4b043416078ee6e795acb9 MD5 | raw file
  1. /*
  2. * Copyright (C) 2010, Google Inc. All rights reserved.
  3. *
  4. * Redistribution and use in source and binary forms, with or without
  5. * modification, are permitted provided that the following conditions
  6. * are met:
  7. * 1. Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * 2. Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. *
  13. * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
  14. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  15. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  16. * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
  17. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  18. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  19. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  20. * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  21. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  22. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  23. */
  24. #include "config.h"
  25. #if ENABLE(WEB_AUDIO)
  26. #include "HRTFPanner.h"
  27. #include "AudioBus.h"
  28. #include "FFTConvolver.h"
  29. #include "HRTFDatabase.h"
  30. #include "HRTFDatabaseLoader.h"
  31. #include <algorithm>
  32. #include <wtf/MathExtras.h>
  33. #include <wtf/RefPtr.h>
  34. using namespace std;
  35. namespace WebCore {
  36. // The value of 2 milliseconds is larger than the largest delay which exists in any HRTFKernel from the default HRTFDatabase (0.0136 seconds).
  37. // We ASSERT the delay values used in process() with this value.
  38. const double MaxDelayTimeSeconds = 0.002;
  39. const int UninitializedAzimuth = -1;
  40. const unsigned RenderingQuantum = 128;
  41. HRTFPanner::HRTFPanner(float sampleRate, HRTFDatabaseLoader* databaseLoader)
  42. : Panner(PanningModelHRTF)
  43. , m_databaseLoader(databaseLoader)
  44. , m_sampleRate(sampleRate)
  45. , m_crossfadeSelection(CrossfadeSelection1)
  46. , m_azimuthIndex1(UninitializedAzimuth)
  47. , m_elevation1(0)
  48. , m_azimuthIndex2(UninitializedAzimuth)
  49. , m_elevation2(0)
  50. , m_crossfadeX(0)
  51. , m_crossfadeIncr(0)
  52. , m_convolverL1(fftSizeForSampleRate(sampleRate))
  53. , m_convolverR1(fftSizeForSampleRate(sampleRate))
  54. , m_convolverL2(fftSizeForSampleRate(sampleRate))
  55. , m_convolverR2(fftSizeForSampleRate(sampleRate))
  56. , m_delayLineL(MaxDelayTimeSeconds, sampleRate)
  57. , m_delayLineR(MaxDelayTimeSeconds, sampleRate)
  58. , m_tempL1(RenderingQuantum)
  59. , m_tempR1(RenderingQuantum)
  60. , m_tempL2(RenderingQuantum)
  61. , m_tempR2(RenderingQuantum)
  62. {
  63. ASSERT(databaseLoader);
  64. }
  65. HRTFPanner::~HRTFPanner()
  66. {
  67. }
  68. size_t HRTFPanner::fftSizeForSampleRate(float sampleRate)
  69. {
  70. // The HRTF impulse responses (loaded as audio resources) are 512 sample-frames @44.1KHz.
  71. // Currently, we truncate the impulse responses to half this size, but an FFT-size of twice impulse response size is needed (for convolution).
  72. // So for sample rates around 44.1KHz an FFT size of 512 is good. We double the FFT-size only for sample rates at least double this.
  73. ASSERT(sampleRate >= 44100 && sampleRate <= 96000.0);
  74. return (sampleRate < 88200.0) ? 512 : 1024;
  75. }
  76. void HRTFPanner::reset()
  77. {
  78. m_convolverL1.reset();
  79. m_convolverR1.reset();
  80. m_convolverL2.reset();
  81. m_convolverR2.reset();
  82. m_delayLineL.reset();
  83. m_delayLineR.reset();
  84. }
  85. int HRTFPanner::calculateDesiredAzimuthIndexAndBlend(double azimuth, double& azimuthBlend)
  86. {
  87. // Convert the azimuth angle from the range -180 -> +180 into the range 0 -> 360.
  88. // The azimuth index may then be calculated from this positive value.
  89. if (azimuth < 0)
  90. azimuth += 360.0;
  91. HRTFDatabase* database = m_databaseLoader->database();
  92. ASSERT(database);
  93. int numberOfAzimuths = database->numberOfAzimuths();
  94. const double angleBetweenAzimuths = 360.0 / numberOfAzimuths;
  95. // Calculate the azimuth index and the blend (0 -> 1) for interpolation.
  96. double desiredAzimuthIndexFloat = azimuth / angleBetweenAzimuths;
  97. int desiredAzimuthIndex = static_cast<int>(desiredAzimuthIndexFloat);
  98. azimuthBlend = desiredAzimuthIndexFloat - static_cast<double>(desiredAzimuthIndex);
  99. // We don't immediately start using this azimuth index, but instead approach this index from the last index we rendered at.
  100. // This minimizes the clicks and graininess for moving sources which occur otherwise.
  101. desiredAzimuthIndex = max(0, desiredAzimuthIndex);
  102. desiredAzimuthIndex = min(numberOfAzimuths - 1, desiredAzimuthIndex);
  103. return desiredAzimuthIndex;
  104. }
  105. void HRTFPanner::pan(double desiredAzimuth, double elevation, const AudioBus* inputBus, AudioBus* outputBus, size_t framesToProcess)
  106. {
  107. unsigned numInputChannels = inputBus ? inputBus->numberOfChannels() : 0;
  108. bool isInputGood = inputBus && numInputChannels >= 1 && numInputChannels <= 2;
  109. ASSERT(isInputGood);
  110. bool isOutputGood = outputBus && outputBus->numberOfChannels() == 2 && framesToProcess <= outputBus->length();
  111. ASSERT(isOutputGood);
  112. if (!isInputGood || !isOutputGood) {
  113. if (outputBus)
  114. outputBus->zero();
  115. return;
  116. }
  117. // This code only runs as long as the context is alive and after database has been loaded.
  118. HRTFDatabase* database = m_databaseLoader->database();
  119. ASSERT(database);
  120. if (!database) {
  121. outputBus->zero();
  122. return;
  123. }
  124. // IRCAM HRTF azimuths values from the loaded database is reversed from the panner's notion of azimuth.
  125. double azimuth = -desiredAzimuth;
  126. bool isAzimuthGood = azimuth >= -180.0 && azimuth <= 180.0;
  127. ASSERT(isAzimuthGood);
  128. if (!isAzimuthGood) {
  129. outputBus->zero();
  130. return;
  131. }
  132. // Normally, we'll just be dealing with mono sources.
  133. // If we have a stereo input, implement stereo panning with left source processed by left HRTF, and right source by right HRTF.
  134. const AudioChannel* inputChannelL = inputBus->channelByType(AudioBus::ChannelLeft);
  135. const AudioChannel* inputChannelR = numInputChannels > 1 ? inputBus->channelByType(AudioBus::ChannelRight) : 0;
  136. // Get source and destination pointers.
  137. const float* sourceL = inputChannelL->data();
  138. const float* sourceR = numInputChannels > 1 ? inputChannelR->data() : sourceL;
  139. float* destinationL = outputBus->channelByType(AudioBus::ChannelLeft)->mutableData();
  140. float* destinationR = outputBus->channelByType(AudioBus::ChannelRight)->mutableData();
  141. double azimuthBlend;
  142. int desiredAzimuthIndex = calculateDesiredAzimuthIndexAndBlend(azimuth, azimuthBlend);
  143. // Initially snap azimuth and elevation values to first values encountered.
  144. if (m_azimuthIndex1 == UninitializedAzimuth) {
  145. m_azimuthIndex1 = desiredAzimuthIndex;
  146. m_elevation1 = elevation;
  147. }
  148. if (m_azimuthIndex2 == UninitializedAzimuth) {
  149. m_azimuthIndex2 = desiredAzimuthIndex;
  150. m_elevation2 = elevation;
  151. }
  152. // Cross-fade / transition over a period of around 45 milliseconds.
  153. // This is an empirical value tuned to be a reasonable trade-off between
  154. // smoothness and speed.
  155. const double fadeFrames = sampleRate() <= 48000 ? 2048 : 4096;
  156. // Check for azimuth and elevation changes, initiating a cross-fade if needed.
  157. if (!m_crossfadeX && m_crossfadeSelection == CrossfadeSelection1) {
  158. if (desiredAzimuthIndex != m_azimuthIndex1 || elevation != m_elevation1) {
  159. // Cross-fade from 1 -> 2
  160. m_crossfadeIncr = 1 / fadeFrames;
  161. m_azimuthIndex2 = desiredAzimuthIndex;
  162. m_elevation2 = elevation;
  163. }
  164. }
  165. if (m_crossfadeX == 1 && m_crossfadeSelection == CrossfadeSelection2) {
  166. if (desiredAzimuthIndex != m_azimuthIndex2 || elevation != m_elevation2) {
  167. // Cross-fade from 2 -> 1
  168. m_crossfadeIncr = -1 / fadeFrames;
  169. m_azimuthIndex1 = desiredAzimuthIndex;
  170. m_elevation1 = elevation;
  171. }
  172. }
  173. // This algorithm currently requires that we process in power-of-two size chunks at least RenderingQuantum.
  174. ASSERT(1UL << static_cast<int>(log2(framesToProcess)) == framesToProcess);
  175. ASSERT(framesToProcess >= RenderingQuantum);
  176. const unsigned framesPerSegment = RenderingQuantum;
  177. const unsigned numberOfSegments = framesToProcess / framesPerSegment;
  178. for (unsigned segment = 0; segment < numberOfSegments; ++segment) {
  179. // Get the HRTFKernels and interpolated delays.
  180. HRTFKernel* kernelL1;
  181. HRTFKernel* kernelR1;
  182. HRTFKernel* kernelL2;
  183. HRTFKernel* kernelR2;
  184. double frameDelayL1;
  185. double frameDelayR1;
  186. double frameDelayL2;
  187. double frameDelayR2;
  188. database->getKernelsFromAzimuthElevation(azimuthBlend, m_azimuthIndex1, m_elevation1, kernelL1, kernelR1, frameDelayL1, frameDelayR1);
  189. database->getKernelsFromAzimuthElevation(azimuthBlend, m_azimuthIndex2, m_elevation2, kernelL2, kernelR2, frameDelayL2, frameDelayR2);
  190. bool areKernelsGood = kernelL1 && kernelR1 && kernelL2 && kernelR2;
  191. ASSERT(areKernelsGood);
  192. if (!areKernelsGood) {
  193. outputBus->zero();
  194. return;
  195. }
  196. ASSERT(frameDelayL1 / sampleRate() < MaxDelayTimeSeconds && frameDelayR1 / sampleRate() < MaxDelayTimeSeconds);
  197. ASSERT(frameDelayL2 / sampleRate() < MaxDelayTimeSeconds && frameDelayR2 / sampleRate() < MaxDelayTimeSeconds);
  198. // Crossfade inter-aural delays based on transitions.
  199. double frameDelayL = (1 - m_crossfadeX) * frameDelayL1 + m_crossfadeX * frameDelayL2;
  200. double frameDelayR = (1 - m_crossfadeX) * frameDelayR1 + m_crossfadeX * frameDelayR2;
  201. // Calculate the source and destination pointers for the current segment.
  202. unsigned offset = segment * framesPerSegment;
  203. const float* segmentSourceL = sourceL + offset;
  204. const float* segmentSourceR = sourceR + offset;
  205. float* segmentDestinationL = destinationL + offset;
  206. float* segmentDestinationR = destinationR + offset;
  207. // First run through delay lines for inter-aural time difference.
  208. m_delayLineL.setDelayFrames(frameDelayL);
  209. m_delayLineR.setDelayFrames(frameDelayR);
  210. m_delayLineL.process(segmentSourceL, segmentDestinationL, framesPerSegment);
  211. m_delayLineR.process(segmentSourceR, segmentDestinationR, framesPerSegment);
  212. bool needsCrossfading = m_crossfadeIncr;
  213. // Have the convolvers render directly to the final destination if we're not cross-fading.
  214. float* convolutionDestinationL1 = needsCrossfading ? m_tempL1.data() : segmentDestinationL;
  215. float* convolutionDestinationR1 = needsCrossfading ? m_tempR1.data() : segmentDestinationR;
  216. float* convolutionDestinationL2 = needsCrossfading ? m_tempL2.data() : segmentDestinationL;
  217. float* convolutionDestinationR2 = needsCrossfading ? m_tempR2.data() : segmentDestinationR;
  218. // Now do the convolutions.
  219. // Note that we avoid doing convolutions on both sets of convolvers if we're not currently cross-fading.
  220. if (m_crossfadeSelection == CrossfadeSelection1 || needsCrossfading) {
  221. m_convolverL1.process(kernelL1->fftFrame(), segmentDestinationL, convolutionDestinationL1, framesPerSegment);
  222. m_convolverR1.process(kernelR1->fftFrame(), segmentDestinationR, convolutionDestinationR1, framesPerSegment);
  223. }
  224. if (m_crossfadeSelection == CrossfadeSelection2 || needsCrossfading) {
  225. m_convolverL2.process(kernelL2->fftFrame(), segmentDestinationL, convolutionDestinationL2, framesPerSegment);
  226. m_convolverR2.process(kernelR2->fftFrame(), segmentDestinationR, convolutionDestinationR2, framesPerSegment);
  227. }
  228. if (needsCrossfading) {
  229. // Apply linear cross-fade.
  230. float x = m_crossfadeX;
  231. float incr = m_crossfadeIncr;
  232. for (unsigned i = 0; i < framesPerSegment; ++i) {
  233. segmentDestinationL[i] = (1 - x) * convolutionDestinationL1[i] + x * convolutionDestinationL2[i];
  234. segmentDestinationR[i] = (1 - x) * convolutionDestinationR1[i] + x * convolutionDestinationR2[i];
  235. x += incr;
  236. }
  237. // Update cross-fade value from local.
  238. m_crossfadeX = x;
  239. if (m_crossfadeIncr > 0 && fabs(m_crossfadeX - 1) < m_crossfadeIncr) {
  240. // We've fully made the crossfade transition from 1 -> 2.
  241. m_crossfadeSelection = CrossfadeSelection2;
  242. m_crossfadeX = 1;
  243. m_crossfadeIncr = 0;
  244. } else if (m_crossfadeIncr < 0 && fabs(m_crossfadeX) < -m_crossfadeIncr) {
  245. // We've fully made the crossfade transition from 2 -> 1.
  246. m_crossfadeSelection = CrossfadeSelection1;
  247. m_crossfadeX = 0;
  248. m_crossfadeIncr = 0;
  249. }
  250. }
  251. }
  252. }
  253. double HRTFPanner::tailTime() const
  254. {
  255. // Because HRTFPanner is implemented with a DelayKernel and a FFTConvolver, the tailTime of the HRTFPanner
  256. // is the sum of the tailTime of the DelayKernel and the tailTime of the FFTConvolver, which is MaxDelayTimeSeconds
  257. // and fftSize() / 2, respectively.
  258. return MaxDelayTimeSeconds + (fftSize() / 2) / static_cast<double>(sampleRate());
  259. }
  260. double HRTFPanner::latencyTime() const
  261. {
  262. // The latency of a FFTConvolver is also fftSize() / 2, and is in addition to its tailTime of the
  263. // same value.
  264. return (fftSize() / 2) / static_cast<double>(sampleRate());
  265. }
  266. } // namespace WebCore
  267. #endif // ENABLE(WEB_AUDIO)