OscillatorNode.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. /*
  2. * Copyright (C) 2012, 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 "OscillatorNode.h"
  27. #include "AudioContext.h"
  28. #include "AudioNodeOutput.h"
  29. #include "AudioUtilities.h"
  30. #include "ExceptionCode.h"
  31. #include "VectorMath.h"
  32. #include "WaveTable.h"
  33. #include <algorithm>
  34. #include <wtf/MathExtras.h>
  35. using namespace std;
  36. namespace WebCore {
  37. using namespace VectorMath;
  38. WaveTable* OscillatorNode::s_waveTableSine = 0;
  39. WaveTable* OscillatorNode::s_waveTableSquare = 0;
  40. WaveTable* OscillatorNode::s_waveTableSawtooth = 0;
  41. WaveTable* OscillatorNode::s_waveTableTriangle = 0;
  42. PassRefPtr<OscillatorNode> OscillatorNode::create(AudioContext* context, float sampleRate)
  43. {
  44. return adoptRef(new OscillatorNode(context, sampleRate));
  45. }
  46. OscillatorNode::OscillatorNode(AudioContext* context, float sampleRate)
  47. : AudioScheduledSourceNode(context, sampleRate)
  48. , m_type(SINE)
  49. , m_firstRender(true)
  50. , m_virtualReadIndex(0)
  51. , m_phaseIncrements(AudioNode::ProcessingSizeInFrames)
  52. , m_detuneValues(AudioNode::ProcessingSizeInFrames)
  53. {
  54. setNodeType(NodeTypeOscillator);
  55. // Use musical pitch standard A440 as a default.
  56. m_frequency = AudioParam::create(context, "frequency", 440, 0, 100000);
  57. // Default to no detuning.
  58. m_detune = AudioParam::create(context, "detune", 0, -4800, 4800);
  59. // Sets up default wavetable.
  60. setType(m_type);
  61. // An oscillator is always mono.
  62. addOutput(adoptPtr(new AudioNodeOutput(this, 1)));
  63. initialize();
  64. }
  65. OscillatorNode::~OscillatorNode()
  66. {
  67. uninitialize();
  68. }
  69. String OscillatorNode::type() const
  70. {
  71. switch (m_type) {
  72. case SINE:
  73. return "sine";
  74. case SQUARE:
  75. return "square";
  76. case SAWTOOTH:
  77. return "sawtooth";
  78. case TRIANGLE:
  79. return "triangle";
  80. case CUSTOM:
  81. return "custom";
  82. default:
  83. ASSERT_NOT_REACHED();
  84. return "custom";
  85. }
  86. }
  87. void OscillatorNode::setType(const String& type)
  88. {
  89. if (type == "sine")
  90. setType(SINE);
  91. else if (type == "square")
  92. setType(SQUARE);
  93. else if (type == "sawtooth")
  94. setType(SAWTOOTH);
  95. else if (type == "triangle")
  96. setType(TRIANGLE);
  97. else
  98. ASSERT_NOT_REACHED();
  99. }
  100. bool OscillatorNode::setType(unsigned type)
  101. {
  102. WaveTable* waveTable = 0;
  103. float sampleRate = this->sampleRate();
  104. switch (type) {
  105. case SINE:
  106. if (!s_waveTableSine)
  107. s_waveTableSine = WaveTable::createSine(sampleRate).leakRef();
  108. waveTable = s_waveTableSine;
  109. break;
  110. case SQUARE:
  111. if (!s_waveTableSquare)
  112. s_waveTableSquare = WaveTable::createSquare(sampleRate).leakRef();
  113. waveTable = s_waveTableSquare;
  114. break;
  115. case SAWTOOTH:
  116. if (!s_waveTableSawtooth)
  117. s_waveTableSawtooth = WaveTable::createSawtooth(sampleRate).leakRef();
  118. waveTable = s_waveTableSawtooth;
  119. break;
  120. case TRIANGLE:
  121. if (!s_waveTableTriangle)
  122. s_waveTableTriangle = WaveTable::createTriangle(sampleRate).leakRef();
  123. waveTable = s_waveTableTriangle;
  124. break;
  125. case CUSTOM:
  126. default:
  127. // Return error for invalid types, including CUSTOM since setWaveTable() method must be
  128. // called explicitly.
  129. return false;
  130. }
  131. setWaveTable(waveTable);
  132. m_type = type;
  133. return true;
  134. }
  135. bool OscillatorNode::calculateSampleAccuratePhaseIncrements(size_t framesToProcess)
  136. {
  137. bool isGood = framesToProcess <= m_phaseIncrements.size() && framesToProcess <= m_detuneValues.size();
  138. ASSERT(isGood);
  139. if (!isGood)
  140. return false;
  141. if (m_firstRender) {
  142. m_firstRender = false;
  143. m_frequency->resetSmoothedValue();
  144. m_detune->resetSmoothedValue();
  145. }
  146. bool hasSampleAccurateValues = false;
  147. bool hasFrequencyChanges = false;
  148. float* phaseIncrements = m_phaseIncrements.data();
  149. float finalScale = m_waveTable->rateScale();
  150. if (m_frequency->hasSampleAccurateValues()) {
  151. hasSampleAccurateValues = true;
  152. hasFrequencyChanges = true;
  153. // Get the sample-accurate frequency values and convert to phase increments.
  154. // They will be converted to phase increments below.
  155. m_frequency->calculateSampleAccurateValues(phaseIncrements, framesToProcess);
  156. } else {
  157. // Handle ordinary parameter smoothing/de-zippering if there are no scheduled changes.
  158. m_frequency->smooth();
  159. float frequency = m_frequency->smoothedValue();
  160. finalScale *= frequency;
  161. }
  162. if (m_detune->hasSampleAccurateValues()) {
  163. hasSampleAccurateValues = true;
  164. // Get the sample-accurate detune values.
  165. float* detuneValues = hasFrequencyChanges ? m_detuneValues.data() : phaseIncrements;
  166. m_detune->calculateSampleAccurateValues(detuneValues, framesToProcess);
  167. // Convert from cents to rate scalar.
  168. float k = 1.0 / 1200;
  169. vsmul(detuneValues, 1, &k, detuneValues, 1, framesToProcess);
  170. for (unsigned i = 0; i < framesToProcess; ++i)
  171. detuneValues[i] = powf(2, detuneValues[i]); // FIXME: converting to expf() will be faster.
  172. if (hasFrequencyChanges) {
  173. // Multiply frequencies by detune scalings.
  174. vmul(detuneValues, 1, phaseIncrements, 1, phaseIncrements, 1, framesToProcess);
  175. }
  176. } else {
  177. // Handle ordinary parameter smoothing/de-zippering if there are no scheduled changes.
  178. m_detune->smooth();
  179. float detune = m_detune->smoothedValue();
  180. float detuneScale = powf(2, detune / 1200);
  181. finalScale *= detuneScale;
  182. }
  183. if (hasSampleAccurateValues) {
  184. // Convert from frequency to wavetable increment.
  185. vsmul(phaseIncrements, 1, &finalScale, phaseIncrements, 1, framesToProcess);
  186. }
  187. return hasSampleAccurateValues;
  188. }
  189. void OscillatorNode::process(size_t framesToProcess)
  190. {
  191. AudioBus* outputBus = output(0)->bus();
  192. if (!isInitialized() || !outputBus->numberOfChannels()) {
  193. outputBus->zero();
  194. return;
  195. }
  196. ASSERT(framesToProcess <= m_phaseIncrements.size());
  197. if (framesToProcess > m_phaseIncrements.size())
  198. return;
  199. // The audio thread can't block on this lock, so we call tryLock() instead.
  200. MutexTryLocker tryLocker(m_processLock);
  201. if (!tryLocker.locked()) {
  202. // Too bad - the tryLock() failed. We must be in the middle of changing wave-tables.
  203. outputBus->zero();
  204. return;
  205. }
  206. // We must access m_waveTable only inside the lock.
  207. if (!m_waveTable.get()) {
  208. outputBus->zero();
  209. return;
  210. }
  211. size_t quantumFrameOffset;
  212. size_t nonSilentFramesToProcess;
  213. updateSchedulingInfo(framesToProcess, outputBus, quantumFrameOffset, nonSilentFramesToProcess);
  214. if (!nonSilentFramesToProcess) {
  215. outputBus->zero();
  216. return;
  217. }
  218. unsigned waveTableSize = m_waveTable->waveTableSize();
  219. double invWaveTableSize = 1.0 / waveTableSize;
  220. float* destP = outputBus->channel(0)->mutableData();
  221. ASSERT(quantumFrameOffset <= framesToProcess);
  222. // We keep virtualReadIndex double-precision since we're accumulating values.
  223. double virtualReadIndex = m_virtualReadIndex;
  224. float rateScale = m_waveTable->rateScale();
  225. float invRateScale = 1 / rateScale;
  226. bool hasSampleAccurateValues = calculateSampleAccuratePhaseIncrements(framesToProcess);
  227. float frequency = 0;
  228. float* higherWaveData = 0;
  229. float* lowerWaveData = 0;
  230. float tableInterpolationFactor;
  231. if (!hasSampleAccurateValues) {
  232. frequency = m_frequency->smoothedValue();
  233. float detune = m_detune->smoothedValue();
  234. float detuneScale = powf(2, detune / 1200);
  235. frequency *= detuneScale;
  236. m_waveTable->waveDataForFundamentalFrequency(frequency, lowerWaveData, higherWaveData, tableInterpolationFactor);
  237. }
  238. float incr = frequency * rateScale;
  239. float* phaseIncrements = m_phaseIncrements.data();
  240. unsigned readIndexMask = waveTableSize - 1;
  241. // Start rendering at the correct offset.
  242. destP += quantumFrameOffset;
  243. int n = nonSilentFramesToProcess;
  244. while (n--) {
  245. unsigned readIndex = static_cast<unsigned>(virtualReadIndex);
  246. unsigned readIndex2 = readIndex + 1;
  247. // Contain within valid range.
  248. readIndex = readIndex & readIndexMask;
  249. readIndex2 = readIndex2 & readIndexMask;
  250. if (hasSampleAccurateValues) {
  251. incr = *phaseIncrements++;
  252. frequency = invRateScale * incr;
  253. m_waveTable->waveDataForFundamentalFrequency(frequency, lowerWaveData, higherWaveData, tableInterpolationFactor);
  254. }
  255. float sample1Lower = lowerWaveData[readIndex];
  256. float sample2Lower = lowerWaveData[readIndex2];
  257. float sample1Higher = higherWaveData[readIndex];
  258. float sample2Higher = higherWaveData[readIndex2];
  259. // Linearly interpolate within each table (lower and higher).
  260. float interpolationFactor = static_cast<float>(virtualReadIndex) - readIndex;
  261. float sampleHigher = (1 - interpolationFactor) * sample1Higher + interpolationFactor * sample2Higher;
  262. float sampleLower = (1 - interpolationFactor) * sample1Lower + interpolationFactor * sample2Lower;
  263. // Then interpolate between the two tables.
  264. float sample = (1 - tableInterpolationFactor) * sampleHigher + tableInterpolationFactor * sampleLower;
  265. *destP++ = sample;
  266. // Increment virtual read index and wrap virtualReadIndex into the range 0 -> waveTableSize.
  267. virtualReadIndex += incr;
  268. virtualReadIndex -= floor(virtualReadIndex * invWaveTableSize) * waveTableSize;
  269. }
  270. m_virtualReadIndex = virtualReadIndex;
  271. outputBus->clearSilentFlag();
  272. }
  273. void OscillatorNode::reset()
  274. {
  275. m_virtualReadIndex = 0;
  276. }
  277. void OscillatorNode::setWaveTable(WaveTable* waveTable)
  278. {
  279. ASSERT(isMainThread());
  280. // This synchronizes with process().
  281. MutexLocker processLocker(m_processLock);
  282. m_waveTable = waveTable;
  283. m_type = CUSTOM;
  284. }
  285. bool OscillatorNode::propagatesSilence() const
  286. {
  287. return !isPlayingOrScheduled() || hasFinished() || !m_waveTable.get();
  288. }
  289. } // namespace WebCore
  290. #endif // ENABLE(WEB_AUDIO)