AudioSynthWaveform object, bug fix and improved phase behaviour

neurofun

Well-known member
The main motivation for this post is using the Audiolib in a synthesizer application.
The following modifications were done to the AudioSynthWaveform object in order to fix some errors and improve functionality and behaviour:

  • fix frequency and phase errors
    all waveforms have now the same period, and phase moves all the waveforms in the same direction.
    all waveforms now use 32 bit phase accumulators and count up.
  • invert WAVEFORM_PULSE and fix initialisation error for variable tone_width
  • add new member dutyCycle()
    allows to set the pulsewidth from 0% to 100% instead of 0% to 50% for pulseWidth()
  • enable phase modulation
    this was not possible before, since member phase() restarted the waveform at the absolute phase position
    Phase(), now shifts the waveform from the current phase to the desired phase
    for resetting or starting the waveform at specified phase use begin(), if phase() was set at 90deg before, begin() will restart the waveform at 90deg
  • add new member waveform() for selecting waveforms without affecting the current phase

Here is the full code for AudioSynthWaveform with comments where I changed stuff, also attached a zip file with all comments removed.
View attachment synth_waveform.zip

synth_waveform.h
Code:
/* Audio Library for Teensy 3.X
 * Copyright (c) 2014, Paul Stoffregen, paul@pjrc.com
 *
 * Development of this audio library was funded by PJRC.COM, LLC by sales of
 * Teensy and Audio Adaptor boards.  Please support PJRC's efforts to develop
 * open source software by purchasing Teensy or other PJRC products.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice, development funding notice, and this permission
 * notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#ifndef synth_waveform_h_
#define synth_waveform_h_

#include "Arduino.h"
#include "AudioStream.h"
#include "arm_math.h"

// waveforms.c
extern "C" {
extern const int16_t AudioWaveformSine[257];
}

#define AUDIO_SAMPLE_RATE_ROUNDED (44118)

#define DELAY_PASSTHRU -1

#define WAVEFORM_SINE      0
#define WAVEFORM_SAWTOOTH  1
#define WAVEFORM_SQUARE    2
#define WAVEFORM_TRIANGLE  3
#define WAVEFORM_ARBITRARY 4
#define WAVEFORM_PULSE     5
#define WAVEFORM_SAWTOOTH_REVERSE 6
#define WAVEFORM_SAMPLE_HOLD 7

// todo: remove these...
#define TONE_TYPE_SINE     0
#define TONE_TYPE_SAWTOOTH 1
#define TONE_TYPE_SQUARE   2
#define TONE_TYPE_TRIANGLE 3

class AudioSynthWaveform : 
public AudioStream
{
public:
  AudioSynthWaveform(void) : 
  AudioStream(0,NULL), tone_amp(0), tone_freq(0),
  // tone_phase(0), tone_width(0.25), tone_incr(0), tone_type(0),
  tone_phase(0), tone_phase_offset(0), tone_width(0x7fffffffLL), tone_incr(0), tone_type(0),  //neurofun default pulseWidth 50%, add phase modulation
  tone_offset(0), arbdata(NULL)
  { 
  }
  
  void frequency(float t_freq) {
    if (t_freq < 0.0) t_freq = 0.0;
    else if (t_freq > AUDIO_SAMPLE_RATE_EXACT / 2) t_freq = AUDIO_SAMPLE_RATE_EXACT / 2;
    // tone_incr = (t_freq * (0x80000000LL/AUDIO_SAMPLE_RATE_EXACT)) + 0.5;
    tone_incr = (t_freq * (0x100000000LL/AUDIO_SAMPLE_RATE_EXACT)) + 0.5; //neurofun fix freq & phase errors, 32bit phase acc
  }
  void phase(float angle) {
    if (angle < 0.0) angle = 0.0;
    else if (angle > 360.0) {
      angle = angle - 360.0;
      if (angle >= 360.0) return;
    }
    // tone_phase = angle * (2147483648.0 / 360.0);
    uint32_t phase = angle * (4294967296.0 / 360.0);  //neurofun add phase modulation, fix freq & phase errors, 32bit phase acc
    tone_phase += (phase -tone_phase_offset); //neurofun add phase modulation
    tone_phase_offset = phase; //neurofun add phase modulation
  }
  void amplitude(float n) {        // 0 to 1.0
    if (n < 0) n = 0;
    else if (n > 1.0) n = 1.0;
    if ((tone_amp == 0) && n) {
      // reset the phase when the amplitude was zero
      // and has now been increased.
      tone_phase = 0;
    }
    // set new magnitude
    tone_amp = n * 32767.0;
  }
  void offset(float n) {
    if (n < -1.0) n = -1.0;
    else if (n > 1.0) n = 1.0;
    tone_offset = n * 32767.0;
  }
  void pulseWidth(float n) {          // 0.0 to 1.0
    if (n < 0) n = 0;
    else if (n > 1.0) n = 1.0;
    tone_width = n * 0x7fffffffLL; 
    // pulse width is stored as the equivalent phase
  }
  void dutyCycle(float n) { //neurofun same as pulseWidth() but with full range
    if (n < 0) n = 0;
    else if (n > 1.0) n = 1.0;
    tone_width = n * 0xffffffffLL;  //neurofun dutycycle 0% -> 100% instead of 0% -> 50% 
  }
  void begin(short t_type) {
	// tone_phase = 0;
  tone_phase = tone_phase_offset; //neurofun add phase modulation
	tone_type = t_type;
  }
  void waveform(short t_type) { //neurofun switch waveforms without resetting the phase
	tone_type = t_type;
  }
  void begin(float t_amp, float t_freq, short t_type) {
	amplitude(t_amp);
	frequency(t_freq);
	begin(t_type);
  }
  void arbitraryWaveform(const int16_t *data, float maxFreq) {
	arbdata = data;
  }
  virtual void update(void);
  
private:
  short    tone_amp;
  short    tone_freq;
  uint32_t tone_phase;
  uint32_t tone_phase_offset; //neurofun add phase modulation
  uint32_t tone_width;
  // sample for SAMPLE_HOLD
  short sample;
  // volatile prevents the compiler optimizing out the frequency function
  volatile uint32_t tone_incr;
  short    tone_type;
  int16_t  tone_offset;
  const int16_t *arbdata;
};



#endif
synth_waveform.cpp
Code:
/* Audio Library for Teensy 3.X
 * Copyright (c) 2014, Paul Stoffregen, paul@pjrc.com
 *
 * Development of this audio library was funded by PJRC.COM, LLC by sales of
 * Teensy and Audio Adaptor boards.  Please support PJRC's efforts to develop
 * open source software by purchasing Teensy or other PJRC products.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice, development funding notice, and this permission
 * notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include "synth_waveform.h"
#include "arm_math.h"
#include "utility/dspinst.h"


/******************************************************************/
// PAH 140415 - change sin to use Paul's interpolation which is much
//				faster than arm's sin function
// PAH 140316 - fix calculation of sample (amplitude error)
// PAH 140314 - change t_hi from int to float


void AudioSynthWaveform::update(void)
{
  audio_block_t *block;
  short *bp, *end;
  int32_t val1, val2, val3;
  uint32_t index, scale;
  
  // temporaries for TRIANGLE
  uint32_t mag;
  short tmp_amp;
  
  if(tone_amp == 0) return;
  block = allocate();
  if (block) {
    bp = block->data;
    switch(tone_type) {
    case WAVEFORM_SINE:
      for(int i = 0;i < AUDIO_BLOCK_SAMPLES;i++) {
      	// Calculate interpolated sin
		// index = tone_phase >> 23;
    index = tone_phase >> 24; //neurofun fix freq & phase errors, 32bit phase acc
		val1 = AudioWaveformSine[index];
		val2 = AudioWaveformSine[index+1];
		// scale = (tone_phase >> 7) & 0xFFFF;
    scale = (tone_phase >> 8) & 0xFFFF; //neurofun fix freq & phase errors, 32bit phase acc
		val2 *= scale;
		val1 *= 0xFFFF - scale;
		val3 = (val1 + val2) >> 16;
		*bp++ = (short)((val3 * tone_amp) >> 15);
        
        // phase and incr are both unsigned 32-bit fractions
        tone_phase += tone_incr;
        // If tone_phase has overflowed, truncate the top bit 
        // if(tone_phase & 0x80000000)tone_phase &= 0x7fffffff; //neurofun fix freq & phase errors, 32bit phase acc
      }
      break;

    case WAVEFORM_ARBITRARY:
      if (!arbdata) {
		release(block);
		return;
      }
      // len = 256
      for (int i = 0; i < AUDIO_BLOCK_SAMPLES;i++) {
		// index = tone_phase >> 23;
    index = tone_phase >> 24; //neurofun fix freq & phase errors, 32bit phase acc
		val1 = *(arbdata + index);
		val2 = *(arbdata + ((index + 1) & 255));
		// scale = (tone_phase >> 7) & 0xFFFF;
    scale = (tone_phase >> 8) & 0xFFFF; //neurofun fix freq & phase errors, 32bit phase acc
		val2 *= scale;
		val1 *= 0xFFFF - scale;
		val3 = (val1 + val2) >> 16;
		*bp++ = (short)((val3 * tone_amp) >> 15);
		tone_phase += tone_incr;
		// tone_phase &= 0x7fffffff; //neurofun fix freq & phase errors, 32bit phase acc
      }
      break;
      
    case WAVEFORM_SQUARE:
      for(int i = 0;i < AUDIO_BLOCK_SAMPLES;i++) {
        // if(tone_phase & 0x40000000)*bp++ = -tone_amp;
        if(tone_phase & 0x80000000)*bp++ = -tone_amp; //neurofun fix freq & phase errors, 32bit phase acc
        else *bp++ = tone_amp;
        // phase and incr are both unsigned 32-bit fractions
        tone_phase += tone_incr;
      }
      break;
      
    case WAVEFORM_SAWTOOTH:
      for(int i = 0;i < AUDIO_BLOCK_SAMPLES;i++) {
        // *bp++ = ((short)(tone_phase>>15)*tone_amp) >> 15;
        *bp++ = ((short)(tone_phase>>16)*tone_amp) >> 15; //neurofun fix freq & phase errors, 32bit phase acc
        // phase and incr are both unsigned 32-bit fractions
        tone_phase += tone_incr;    
      }
      break;

    case WAVEFORM_SAWTOOTH_REVERSE:
      for(int i = 0;i < AUDIO_BLOCK_SAMPLES;i++) {
        // *bp++ = ((short)(tone_phase>>15)*tone_amp) >> 15;
        *bp++ = -((short)(tone_phase>>16)*tone_amp) >> 15; //neurofun fix freq & phase errors, 32bit phase acc
         // phase and incr are both unsigned 32-bit fractions
         // tone_phase -= tone_incr;
         tone_phase += tone_incr; //neurofun fix freq & phase errors, 32bit phase acc
      }
      break;

    case WAVEFORM_TRIANGLE:
      for(int i = 0;i < AUDIO_BLOCK_SAMPLES;i++) {
        if(tone_phase & 0x80000000) {
          // negative half-cycle
          tmp_amp = -tone_amp;
        } 
        else {
          // positive half-cycle
          tmp_amp = tone_amp;
        }
        mag = tone_phase << 2;
        // Determine which quadrant
        if(tone_phase & 0x40000000) {
          // negate the magnitude
          mag = ~mag + 1;
        }
        *bp++ = ((short)(mag>>17)*tmp_amp) >> 15;
        // tone_phase += 2*tone_incr;
        tone_phase += tone_incr; //neurofun fix freq & phase errors, 32bit phase acc
      }
      break;
      
    case WAVEFORM_PULSE:
      for(int i = 0;i < AUDIO_BLOCK_SAMPLES;i++) {
        // if(tone_phase < tone_width)*bp++ = -tone_amp;
        // else *bp++ = tone_amp;
        if(tone_phase < tone_width)*bp++ = tone_amp;  //neurofun invert WAVEFORM_PULSE
        else *bp++ = -tone_amp;  //neurofun invert WAVEFORM_PULSE
        tone_phase += tone_incr;
      }
      break;
      
    case WAVEFORM_SAMPLE_HOLD:
      for(int i = 0;i < AUDIO_BLOCK_SAMPLES;i++) {
        if(tone_phase < tone_incr) {
          sample = random(-tone_amp, tone_amp);
        }
        *bp++ = sample;
        tone_phase += tone_incr;
      }
      break;
    }
    if (tone_offset) {
	bp = block->data;
	end = bp + AUDIO_BLOCK_SAMPLES;
	do {
		val1 = *bp;
		*bp++ = signed_saturate_rshift(val1 + tone_offset, 16, 0);
	} while (bp < end);
    }
    transmit(block,0);
    release(block);
  }
}
The following test program is meant to be used with an oscilloscope. It will show that all waveforms have same period and behave exactly the same way when changing the phase.
Connect dac0 or left to channel 1 and dac1 or right to channel 2 of your scope and select channel 1 as source for the trigger.
Channel1 gives you a 500hz reference square wave.
Channel2 will cycle through all the waveforms and sweep the phase in the following pattern,
0deg->360deg->90deg->180deg->0deg
Code:
#include <Audio.h>

extern const int16_t AudioWaveformSine[257];

AudioControlSGTL5000     sgtl5000_1;
AudioSynthWaveform       waveform1;
AudioSynthWaveform       waveform2;
AudioOutputI2S           audioOutput;
AudioOutputAnalogStereo  dacs1;
AudioConnection          patchCord1(waveform1, 0, audioOutput, 0);
AudioConnection          patchCord2(waveform2, 0, audioOutput, 1);
AudioConnection          patchCord3(waveform1, 0, dacs1, 0);
AudioConnection          patchCord4(waveform2, 0, dacs1, 1);

int wave_type[] = {
  WAVEFORM_SINE,
  WAVEFORM_TRIANGLE,
  WAVEFORM_SAWTOOTH,
  WAVEFORM_SAWTOOTH_REVERSE,
  WAVEFORM_SQUARE,
  WAVEFORM_PULSE,
  WAVEFORM_SAMPLE_HOLD,
  WAVEFORM_ARBITRARY,
};
String wave_name[] = {
  "WAVEFORM_SINE",
  "WAVEFORM_TRIANGLE",
  "WAVEFORM_SAWTOOTH",
  "WAVEFORM_SAWTOOTH_REVERSE",
  "WAVEFORM_SQUARE",
  "WAVEFORM_PULSE",
  "WAVEFORM_SAMPLE_HOLD",
  "WAVEFORM_ARBITRARY",
};

void setup() {
  Serial.begin(250000);
  AudioMemory(20);

  sgtl5000_1.enable();
  sgtl5000_1.volume(0.5);

  waveform1.amplitude(1);
  waveform2.amplitude(1);
  waveform1.pulseWidth(.5);
  waveform2.pulseWidth(.5);
  waveform1.arbitraryWaveform(AudioWaveformSine, 0);
  waveform2.arbitraryWaveform(AudioWaveformSine, 0);
  waveform1.frequency(500);
  waveform2.frequency(500);
}

void loop() {
  for (int j = 0; j < sizeof(wave_type) / sizeof(wave_type[0]); j++) {
    Serial.println(wave_name[j]);
    waveform1.begin(wave_type[4]);
    waveform2.begin(wave_type[j]);
    delay(2000);
    for(float p = 0; p <= 360; p++){
      AudioNoInterrupts();
      waveform2.phase(p);  
      AudioInterrupts();
      delay(5);
    }
    delay(1000);
    for(float p = 360; p >= 90; p--){
      AudioNoInterrupts();
      waveform2.phase(p);  
      AudioInterrupts();
      delay(1);
    }
    delay(1000);
    for(float p = 90; p <= 180; p++){
      AudioNoInterrupts();
      waveform2.phase(p);  
      AudioInterrupts();
      delay(2);
    }
    delay(2000);
    for(float p = 180; p >= 0; p--){
      AudioNoInterrupts();
      waveform2.phase(p);  
      AudioInterrupts();
      delay(5);
    }
    delay(500);
  }
}

And here is a youtube video showing the output of the test program on a scope. First half of video is before the code update, second half is after the update:
https://youtu.be/VUCSt4CYFYQ

Any comments welcome.
 
Here is an example of a cool effect you can do with phase modulation.
Some kind of mutant quadrature oscillator with 4 outputs, of which each phase is evenly distanced, modulating the freq of 4 sine waves.
The only modulation happening in the code, is an up and down sweep of the phase.

This is also an example on how to use arrays of audiolib objects, which can make life quite easy.

Screen Shot 2017-12-18 at 01.54.30.png
Code:
//example for phase modulation

#include <Audio.h>

// GUItool: begin automatically generated code
// AudioSynthWaveform       waveform[0];      //xy=277,194
// AudioSynthWaveform       waveform[1]; //xy=283,235
// AudioSynthWaveform       waveform[2]; //xy=288,276
// AudioSynthWaveform       waveform[3]; //xy=293,317
// AudioSynthWaveformSineModulated sine_fm[0];       //xy=437,199
// AudioSynthWaveformSineModulated sine_fm[1]; //xy=443,240
// AudioSynthWaveformSineModulated sine_fm[2]; //xy=448,281
// AudioSynthWaveformSineModulated sine_fm[3]; //xy=453,322
AudioSynthWaveform*  waveform = new AudioSynthWaveform[4];  //not automatically generated code
AudioSynthWaveformSineModulated*  sine_fm = new AudioSynthWaveformSineModulated[4];  //not automatically generated code
AudioMixer4              mixer1;         //xy=630,252
AudioOutputI2S           i2s1;           //xy=776,259
AudioConnection          patchCord1(waveform[0], sine_fm[0]);
AudioConnection          patchCord2(waveform[1], sine_fm[1]);
AudioConnection          patchCord3(waveform[2], sine_fm[2]);
AudioConnection          patchCord4(waveform[3], sine_fm[3]);
AudioConnection          patchCord5(sine_fm[0], 0, mixer1, 0);
AudioConnection          patchCord6(sine_fm[1], 0, mixer1, 1);
AudioConnection          patchCord7(sine_fm[2], 0, mixer1, 2);
AudioConnection          patchCord8(sine_fm[3], 0, mixer1, 3);
AudioConnection          patchCord9(mixer1, 0, i2s1, 0);
AudioConnection          patchCord10(mixer1, 0, i2s1, 1);
AudioControlSGTL5000     sgtl5000_1;     //xy=630,319
// GUItool: end automatically generated code

void setup() {
  Serial.begin(250000);
  AudioMemory(20);

  sgtl5000_1.enable();
  sgtl5000_1.volume(0.5);

  for(int i = 0; i < 4; i++) {
    mixer1.gain(i, 0.25);
  }
}

void loop() {
  Serial.println("sirens in the city");
  phaseSweep(WAVEFORM_SINE, .1, 3, 1000, 0, 90, 0.05, 0.05); //sirens in the city
  Serial.println("red alert");
  phaseSweep(WAVEFORM_SAWTOOTH, 0.9, .75, 500, 0, 90, 0.05, 0.5); //red alert
  Serial.println("helicopter flyby");
  phaseSweep(WAVEFORM_SAWTOOTH_REVERSE, 0.9, 20, 200, 5, 50, 0.05, 0.05); //helicopter flyby
  Serial.println("etheral winds");
  phaseSweep(WAVEFORM_SINE, 1.0, 0.01, 300, 0, 90, 0.01, 0.05);  //etheral winds
}

void phaseSweep(short t_type, float ampl_lfo, float freq_lfo, float freq_vco, float from_phase, float to_phase, float step_up, float step_down){
  //initialise lfo's & vco's
  for(int i = 0; i < 4; i++) {
    waveform[i].amplitude(ampl_lfo);
    waveform[i].frequency(freq_lfo);
    waveform[i].begin(t_type);
    waveform[i].phase(from_phase);
    sine_fm[i].amplitude(1);
    sine_fm[i].frequency(freq_vco);
  }
  waveform[0].phase(0); //phase of lfo0 always 0
  delay(2000);
  //sweep up phase of lfo's
  Serial.println("phase up");
  for(float p = from_phase; p <= to_phase; p+=step_up){
    AudioNoInterrupts();
    for (int i = 1; i < 4; i++) {
      waveform[i].phase(p * i);
    }
    AudioInterrupts();
    delay(10);
    Serial.print("phase up ");
    Serial.println(p);
  }
  Serial.println("phase steady");
  delay(2000);
  //sweep down phase of lfo's
  Serial.println("phase down");
  for(float p = to_phase; p >= from_phase; p-=step_down){
    AudioNoInterrupts();
    for (int i = 1; i < 4; i++) {
      waveform[i].phase(p * i);
    }
    AudioInterrupts();
    delay(10);
    Serial.print("phase down ");
    Serial.println(p);
  }
  Serial.println("phase steady");
  delay(2000);
}
 
I take it that this is "use at your own risk"? I was wondering if anyone else has used this yet, as I'm currently working on an LFO module for eurorack, and just discovered the current functionality of pulseWidth. This could definitely solve my issue, as I was hoping to set up a range from 0.01 to 0.99 duty cycle. I'd like to hear from others, but I'm extremely tempted to try it.

As a side note, i should mention for those wondering how I could use the Audio Shield for an LFO; I simply replaced the 2.2uF output caps with 0 ohm jumpers and am running the line out into summing op-amps where I level-shift the signal to be AC, works perfectly. It's coming along well, I'll try to post a new thread when I get closer to it being ready to go in my rack.
 
Oops, just realized Neurofun posted this today, so I'll ask him: how comfortable are you with others using this at this point? I get the impression from your posts that you've done a fair amount of testing.
 
I am fairly confident it will work and yes, I did a fair amount of testing but there is still the possibility that I overlooked something, so it would be nice for someone else to test it out and confirm it works as intended.
As for "use at your own risk", worst case scenario is that it doesn't work as expected. In that case, just revert to the original code.
As long as you don't use it to generate signals that control life critical applications, I don't see any problems.
 
Well, so far, so good! I substituted the library, and dutyCycle does exactly what i wanted. As I am using this as a CV for other modules, having the full range was critical. My application is fairly basic, so I'm sure this won't be the full workout you would like from others, but I'm excited that I can now get exactly what I need. Thanks for doing this.
 
Back
Top