PageRenderTime 34ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/Source/modules/webaudio/OscillatorNode.cpp

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