1 /* 2 * Copyright (C) 2016 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 * 16 * This code was translated from the JSyn Java code. 17 * JSyn is Copyright 2009 Phil Burk, Mobileer Inc 18 * JSyn is licensed under the Apache License, Version 2.0 19 */ 20 21 #ifndef SYNTHMARK_SAWTOOTH_OSCILLATOR_H 22 #define SYNTHMARK_SAWTOOTH_OSCILLATOR_H 23 24 #include <cstdint> 25 #include <math.h> 26 #include "SynthTools.h" 27 #include "UnitGenerator.h" 28 #include "DifferentiatedParabola.h" 29 30 namespace marksynth { 31 /** 32 * Simple phasor that can be used to implement other oscillators. 33 * Note that this is NON-bandlimited and should not be used 34 * directly as a sound source. 35 */ 36 class SawtoothOscillator : public UnitGenerator 37 { 38 public: SawtoothOscillator()39 SawtoothOscillator() 40 : mPhase(0) {} 41 42 virtual ~SawtoothOscillator() = default; 43 generate(synth_float_t frequency,int32_t numSamples)44 void generate(synth_float_t frequency, int32_t numSamples) { 45 synth_float_t phase = mPhase; 46 synth_float_t phaseIncrement = 2.0 * frequency * mSamplePeriod; 47 for (int i = 0; i < numSamples; i++) { 48 output[i] = translatePhase(phase, phaseIncrement); 49 phase += phaseIncrement; 50 if (phase > 1.0) { 51 phase -= 2.0; 52 } 53 } 54 mPhase = phase; 55 } 56 generate(synth_float_t * frequencies,int32_t numSamples)57 void generate(synth_float_t *frequencies, int32_t numSamples) { 58 synth_float_t phase = mPhase; 59 for (int i = 0; i < numSamples; i++) { 60 synth_float_t phaseIncrement = 2.0 * frequencies[i] * mSamplePeriod; 61 output[i] = translatePhase(phase, phaseIncrement); 62 phase += phaseIncrement; 63 if (phase > 1.0) { 64 phase -= 2.0; 65 } 66 } 67 mPhase = phase; 68 } 69 translatePhase(synth_float_t phase,synth_float_t phaseIncrement)70 virtual synth_float_t translatePhase(synth_float_t phase, synth_float_t phaseIncrement) { 71 (void) phaseIncrement; 72 return phase; 73 } 74 75 private: 76 synth_float_t mPhase; // between -1.0 and +1.0 77 }; 78 79 }; 80 #endif // SYNTHMARK_SAWTOOTH_OSCILLATOR_H 81