From 4ef153e85833f661ac51b3c34dc0bf61f86a37a9 Mon Sep 17 00:00:00 2001 From: Steve Lascos Date: Fri, 12 Oct 2018 17:44:47 -0400 Subject: [PATCH] Basic working tremolo --- .../TremoloDemoExpansion.ino | 191 ++++++++++++++++++ src/AudioEffectTremolo.h | 126 ++++++++++++ src/BAEffects.h | 1 + src/LibBasicFunctions.h | 55 +++++ src/common/LowFrequencyOscillator.cpp | 98 +++++++++ ...ernal.cpp => AudioEffectDelayExternal.cpp} | 0 src/effects/AudioEffectTremolo.cpp | 141 +++++++++++++ 7 files changed, 612 insertions(+) create mode 100644 examples/Modulation/TremoloDemoExpansion/TremoloDemoExpansion.ino create mode 100644 src/AudioEffectTremolo.h create mode 100644 src/common/LowFrequencyOscillator.cpp rename src/effects/{BAAudioEffectDelayExternal.cpp => AudioEffectDelayExternal.cpp} (100%) create mode 100644 src/effects/AudioEffectTremolo.cpp diff --git a/examples/Modulation/TremoloDemoExpansion/TremoloDemoExpansion.ino b/examples/Modulation/TremoloDemoExpansion/TremoloDemoExpansion.ino new file mode 100644 index 0000000..f7eb925 --- /dev/null +++ b/examples/Modulation/TremoloDemoExpansion/TremoloDemoExpansion.ino @@ -0,0 +1,191 @@ +/************************************************************************* + * This demo uses the BALibrary library to provide enhanced control of + * the TGA Pro board. + * + * The latest copy of the BA Guitar library can be obtained from + * https://github.com/Blackaddr/BALibrary + * + * This example demonstrates teh BAAudioEffectsTremolo effect. It can + * be controlled using the Blackaddr Audio "Expansion Control Board". + * + * POT1 (left) controls amount of delay + * POT2 (right) controls amount of feedback + * POT3 (center) controls the wet/dry mix + * SW1 will enable/bypass the audio effect. LED1 will be on when effect is enabled. + * SW2 will cycle through the 3 pre-programmed analog filters. LED2 will be on when SW2 is pressed. + * + * + * Using the Serial Montitor, send 'u' and 'd' characters to increase or decrease + * the headphone volume between values of 0 and 9. + */ +#define TGA_PRO_REVB // Set which hardware revision of the TGA Pro we're using +#define TGA_PRO_EXPAND_REV2 // pull in the pin definitions for the Blackaddr Audio Expansion Board. + +#include "BALibrary.h" +#include "BAEffects.h" + +using namespace BAEffects; +using namespace BALibrary; + +AudioInputI2S i2sIn; +AudioOutputI2S i2sOut; +BAAudioControlWM8731 codec; + +AudioEffectTremolo tremolo; + +AudioFilterBiquad cabFilter; // We'll want something to cut out the highs and smooth the tone, just like a guitar cab. + +// Simply connect the input to the delay, and the output +// to both i2s channels +AudioConnection input(i2sIn,0, tremolo,0); +AudioConnection delayOut(tremolo, 0, cabFilter, 0); +AudioConnection leftOut(cabFilter,0, i2sOut, 0); +AudioConnection rightOut(cabFilter,0, i2sOut, 1); + + +////////////////////////////////////////// +// SETUP PHYSICAL CONTROLS +// - POT1 (left) will control the rate +// - POT2 (right) will control the depth +// - POT3 (centre) will control the volume +// - SW1 (left) will be used as a bypass control +// - LED1 (left) will be illuminated when the effect is ON (not bypass) +// - SW2 (right) will be used to cycle through the the waveforms +// - LED2 (right) will illuminate when pressing SW2. +////////////////////////////////////////// +// To get the calibration values for your particular board, first run the +// BAExpansionCalibrate.ino example and +constexpr int potCalibMin = 1; +constexpr int potCalibMax = 1018; +constexpr bool potSwapDirection = true; + +// Create a control object using the number of switches, pots, encoders and outputs on the +// Blackaddr Audio Expansion Board. +BAPhysicalControls controls(BA_EXPAND_NUM_SW, BA_EXPAND_NUM_POT, BA_EXPAND_NUM_ENC, BA_EXPAND_NUM_LED); + +int loopCount = 0; +unsigned waveformIndex = 0; // variable for storing which analog filter we're currently using. +constexpr unsigned MAX_HEADPHONE_VOL = 10; +unsigned headphoneVolume = 8; // control headphone volume from 0 to 10. + +// BAPhysicalControls returns a handle when you register a new control. We'll uses these handles when working with the controls. +int bypassHandle, waveformHandle, rateHandle, depthHandle, volumeHandle, led1Handle, led2Handle; // Handles for the various controls + +void setup() { + delay(100); // wait a bit for serial to be available + Serial.begin(57600); // Start the serial port + delay(100); + + // Setup the controls. The return value is the handle to use when checking for control changes, etc. + // pushbuttons + bypassHandle = controls.addSwitch(BA_EXPAND_SW1_PIN); // will be used for bypass control + waveformHandle = controls.addSwitch(BA_EXPAND_SW2_PIN); // will be used for stepping through filters + // pots + rateHandle = controls.addPot(BA_EXPAND_POT1_PIN, potCalibMin, potCalibMax, potSwapDirection); // control the amount of delay + depthHandle = controls.addPot(BA_EXPAND_POT2_PIN, potCalibMin, potCalibMax, potSwapDirection); + volumeHandle = controls.addPot(BA_EXPAND_POT3_PIN, potCalibMin, potCalibMax, potSwapDirection); + // leds + led1Handle = controls.addOutput(BA_EXPAND_LED1_PIN); + led2Handle = controls.addOutput(BA_EXPAND_LED2_PIN); // will illuminate when pressing SW2 + + // Disable the audio codec first + codec.disable(); + AudioMemory(128); + + // Enable and configure the codec + Serial.println("Enabling codec...\n"); + codec.enable(); + codec.setHeadphoneVolume(1.0f); // Max headphone volume + + // Besure to enable the tremolo. When disabled, audio is is completely blocked by the effect + // to minimize resource usage to nearly to nearly zero. + tremolo.enable(); + + // Set some default values. + // These can be changed using the controls on the Blackaddr Audio Expansion Board + tremolo.bypass(false); + tremolo.rate(0.0f); + tremolo.depth(1.0f); + + ////////////////////////////////// + // Waveform selection // + // These are commented out, in this example we'll use SW2 to cycle through the different filters + //tremolo.setWaveform(Waveform::SINE); // The default waveform + + // Guitar cabinet: Setup 2-stages of LPF, cutoff 4500 Hz, Q-factor 0.7071 (a 'normal' Q-factor) + cabFilter.setLowpass(0, 4500, .7071); + cabFilter.setLowpass(1, 4500, .7071); +} + +void loop() { + + float potValue; + + // Check if SW1 has been toggled (pushed) + if (controls.isSwitchToggled(bypassHandle)) { + bool bypass = tremolo.isBypass(); // get the current state + bypass = !bypass; // change it + tremolo.bypass(bypass); // set the new state + controls.setOutput(led1Handle, !bypass); // Set the LED when NOT bypassed + Serial.println(String("BYPASS is ") + bypass); + } + + // Use SW2 to cycle through the waveforms + controls.setOutput(led2Handle, controls.getSwitchValue(led2Handle)); + if (controls.isSwitchToggled(waveformHandle)) { + waveformIndex = (waveformIndex + 1) % static_cast(Waveform::NUM_WAVEFORMS); + // cast the index + tremolo.setWaveform(static_cast(waveformIndex)); + Serial.println(String("Waveform set to ") + waveformIndex); + } + + // Use POT1 (left) to control the rate setting + if (controls.checkPotValue(rateHandle, potValue)) { + // Pot has changed + Serial.println(String("New RATE setting: ") + potValue); + tremolo.rate(potValue); + } + + // Use POT2 (right) to control the depth setting + if (controls.checkPotValue(depthHandle, potValue)) { + // Pot has changed + Serial.println(String("New DEPTH setting: ") + potValue); + tremolo.depth(potValue); + } + + // Use POT3 (centre) to control the volume setting + if (controls.checkPotValue(volumeHandle, potValue)) { + // Pot has changed + Serial.println(String("New VOLUME setting: ") + potValue); + tremolo.volume(potValue); + } + + // Use the 'u' and 'd' keys to adjust volume across ten levels. + if (Serial) { + if (Serial.available() > 0) { + while (Serial.available()) { + char key = Serial.read(); + if (key == 'u') { + headphoneVolume = (headphoneVolume + 1) % MAX_HEADPHONE_VOL; + Serial.println(String("Increasing HEADPHONE volume to ") + headphoneVolume); + } + else if (key == 'd') { + headphoneVolume = (headphoneVolume - 1) % MAX_HEADPHONE_VOL; + Serial.println(String("Decreasing HEADPHONE volume to ") + headphoneVolume); + } + codec.setHeadphoneVolume(static_cast(headphoneVolume) / static_cast(MAX_HEADPHONE_VOL)); + } + } + } + + // Use the loopCounter to roughly measure human timescales. Every few seconds, print the CPU usage + // to the serial port. About 500,000 loops! + if (loopCount % 524288 == 0) { + Serial.print("Processor Usage, Total: "); Serial.print(AudioProcessorUsage()); + Serial.print("% "); + Serial.print(" tremolo: "); Serial.print(tremolo.processorUsage()); + Serial.println("%"); + } + loopCount++; + +} diff --git a/src/AudioEffectTremolo.h b/src/AudioEffectTremolo.h new file mode 100644 index 0000000..f01c1c9 --- /dev/null +++ b/src/AudioEffectTremolo.h @@ -0,0 +1,126 @@ +/**************************************************************************//** + * @file + * @author Steve Lascos + * @company Blackaddr Audio + * + * Tremolo is a classic volume modulate effect. + * + * @copyright This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version.* + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY__BAEFFECTS_AUDIOEFFECTDELAYEXTERNAL_H; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + *****************************************************************************/ + +#ifndef __BAEFFECTS_AUDIOEFFECTTREMOLO_H +#define __BAEFFECTS_AUDIOEFFECTTREMOLO_H + +#include +#include "LibBasicFunctions.h" + +namespace BAEffects { + +/**************************************************************************//** + * AudioEffectTremolo + *****************************************************************************/ +class AudioEffectTremolo : public AudioStream { +public: + + ///< List of AudioEffectTremolo MIDI controllable parameters + enum { + BYPASS = 0, ///< controls effect bypass + RATE, ///< controls the rate of the modulation + DEPTH, ///< controls the depth of the modulation + WAVEFORM, ///< select the modulation waveform + VOLUME, ///< controls the output volume level + NUM_CONTROLS ///< this can be used as an alias for the number of MIDI controls + }; + + // *** CONSTRUCTORS *** + AudioEffectTremolo(); + + virtual ~AudioEffectTremolo(); ///< Destructor + + // *** PARAMETERS *** + void rate(float rateValue) { m_rate = rateValue; } + + void depth(float depthValue) { m_depth = depthValue; } + + void setWaveform(BALibrary::Waveform waveform); + + + /// Bypass the effect. + /// @param byp when true, bypass wil disable the effect, when false, effect is enabled. + /// Note that audio still passes through when bypass is enabled. + void bypass(bool byp) { m_bypass = byp; } + + /// Get if the effect is bypassed + /// @returns true if bypassed, false if not bypassed + bool isBypass() { return m_bypass; } + + /// Toggle the bypass effect + void toggleBypass() { m_bypass = !m_bypass; } + + /// Set the output volume. This affect both the wet and dry signals. + /// @details The default is 1.0. + /// @param vol Sets the output volume between -1.0 and +1.0 + void volume(float vol) {m_volume = vol; } + + // ** ENABLE / DISABLE ** + + /// Enables audio processing. Note: when not enabled, CPU load is nearly zero. + void enable() { m_enable = true; } + + /// Disables audio process. When disabled, CPU load is nearly zero. + void disable() { m_enable = false; } + + // ** MIDI ** + + /// Sets whether MIDI OMNI channel is processig on or off. When on, + /// all midi channels are used for matching CCs. + /// @param isOmni when true, all channels are processed, when false, channel + /// must match configured value. + void setMidiOmni(bool isOmni) { m_isOmni = isOmni; } + + /// Configure an effect parameter to be controlled by a MIDI CC + /// number on a particular channel. + /// @param parameter one of the parameter names in the class enum + /// @param midiCC the CC number from 0 to 127 + /// @param midiChannel the effect will only response to the CC on this channel + /// when OMNI mode is off. + void mapMidiControl(int parameter, int midiCC, int midiChannel = 0); + + /// process a MIDI Continous-Controller (CC) message + /// @param channel the MIDI channel from 0 to 15) + /// @param midiCC the CC number from 0 to 127 + /// @param value the CC value from 0 to 127 + void processMidi(int channel, int midiCC, int value); + + + virtual void update(void); ///< update automatically called by the Teesny Audio Library + +private: + audio_block_t *m_inputQueueArray[1]; + BALibrary::LowFrequencyOscillator *m_osc = nullptr; + int m_midiConfig[NUM_CONTROLS][2]; // stores the midi parameter mapping + bool m_isOmni = false; + bool m_bypass = true; + bool m_enable = false; + + float m_rate = 0.0f; + float m_depth = 0.0f; + BALibrary::Waveform m_waveform = BALibrary::Waveform::SINE; + float m_volume = 1.0f; + +}; + +} + +#endif /* __BAEFFECTS_AUDIOEFFECTTREMOLO_H */ diff --git a/src/BAEffects.h b/src/BAEffects.h index 4b906a4..50b92b0 100644 --- a/src/BAEffects.h +++ b/src/BAEffects.h @@ -25,5 +25,6 @@ #include "BAAudioEffectDelayExternal.h" #include "AudioEffectAnalogDelay.h" #include "AudioEffectSOS.h" +#include "AudioEffectTremolo.h" #endif /* __BAEFFECTS_H */ diff --git a/src/LibBasicFunctions.h b/src/LibBasicFunctions.h index 25439c2..c1f8fdf 100644 --- a/src/LibBasicFunctions.h +++ b/src/LibBasicFunctions.h @@ -396,6 +396,61 @@ private: bool m_running = false; }; +/// Supported LFO waveforms +enum class Waveform : unsigned { + SINE, ///< sinewave + TRIANGLE, ///< triangle wave + SQUARE, ///< square wave + SAWTOOTH, ///< sawtooth wave + RANDOM, ///< a non-repeating random waveform + NUM_WAVEFORMS, ///< the number of defined waveforms +}; + + +/**************************************************************************//** + * The LFO is commonly used on modulation effects where some parameter (delay, + * volume, etc.) is modulated via waveform at a frequency below 20 Hz. Waveforms + * vary between -1.0f and +1.0f. + *****************************************************************************/ +template +class LowFrequencyOscillator { +public: + +// /// Supported waveform precisions +// enum class Precision { +// FLOAT, ///< single-precision floating point +// DOUBLE, ///< double-precision floating point +// INT16, ///< Q15 integer precision +// INT32, ///< Q31 integer precision +// }; + + // TODO: permit changing the mode/rate without destruction + LowFrequencyOscillator() = delete; + LowFrequencyOscillator(Waveform mode, unsigned frequencyHz); + ~LowFrequencyOscillator(); + + /// Reset the waveform back to initial phase + void reset(); + + /// Get the next waveform value + /// @returns the next value as a float + T getNext(); + + /// Get a vector of the next AUDIO_BLOCK_SAMPLES waveform samples as + /// q15, a signed fixed point number form -1 to +0.999.. + T getVector(T *targetVector); + +private: + void updatePhase(); + Waveform m_mode; + T *m_waveformLut = nullptr; + size_t m_periodSamples = 0; + float m_radiansPerSample = 0.0f; + float m_phase = 0.0f; + float m_volume = 1.0f; + +}; + } // BALibrary diff --git a/src/common/LowFrequencyOscillator.cpp b/src/common/LowFrequencyOscillator.cpp new file mode 100644 index 0000000..2cf8501 --- /dev/null +++ b/src/common/LowFrequencyOscillator.cpp @@ -0,0 +1,98 @@ +/* + * LowFrequencyOscillator.cpp + * + * Created on: October 12, 2018 + * Author: Steve Lascos + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version.* + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . +*/ + +#include +#include "Audio.h" +#include "LibBasicFunctions.h" + +namespace BALibrary { + +constexpr float TWO_PI_F = 2.0f*3.1415927; + +template +LowFrequencyOscillator::LowFrequencyOscillator(Waveform mode, unsigned frequencyHz) +{ + // Given the fixed sample rate, determine how many samples are in the waveform. + m_periodSamples = AUDIO_SAMPLE_RATE_EXACT / frequencyHz; + m_radiansPerSample = (float)TWO_PI_F / (float)m_periodSamples; + m_mode = mode; + + switch(mode) { + case Waveform::SINE : + break; + case Waveform::SQUARE : + break; + case Waveform::TRIANGLE : + break; + case Waveform::RANDOM : + break; + default : + assert(0); // This occurs if a Waveform type is missing from the switch statement + } +} + +template +LowFrequencyOscillator::~LowFrequencyOscillator() +{ + +} + +template +void LowFrequencyOscillator::reset() +{ + m_phase = 0; +} + +template +inline void LowFrequencyOscillator::updatePhase() +{ + //if (m_phase < m_periodSamples-1) { m_phase++; } + //else { m_phase = 0; } + m_phase += m_radiansPerSample; + //if (m_phase < (TWO_PI_F-m_radiansPerSample)) { m_phase += m_radiansPerSample; } + //else { m_phase = 0.0f; } +} + +template +T LowFrequencyOscillator::getNext() +{ + T value = 0.0f; + updatePhase(); + switch(m_mode) { + case Waveform::SINE : + value = sin(m_phase); + break; + case Waveform::SQUARE : + break; + case Waveform::TRIANGLE : + break; + case Waveform::RANDOM : + break; + default : + assert(0); // This occurs if a Waveform type is missing from the switch statement + } + + return value; +} + +template class LowFrequencyOscillator; + +} // namespace BALibrary + diff --git a/src/effects/BAAudioEffectDelayExternal.cpp b/src/effects/AudioEffectDelayExternal.cpp similarity index 100% rename from src/effects/BAAudioEffectDelayExternal.cpp rename to src/effects/AudioEffectDelayExternal.cpp diff --git a/src/effects/AudioEffectTremolo.cpp b/src/effects/AudioEffectTremolo.cpp new file mode 100644 index 0000000..b0fcdf0 --- /dev/null +++ b/src/effects/AudioEffectTremolo.cpp @@ -0,0 +1,141 @@ +/* + * AudioEffectTremolo.cpp + * + * Created on: Jan 7, 2018 + * Author: slascos + */ +#include "AudioEffectTremolo.h" + +using namespace BALibrary; + +namespace BAEffects { + +constexpr int MIDI_CHANNEL = 0; +constexpr int MIDI_CONTROL = 1; + +AudioEffectTremolo::AudioEffectTremolo() +: AudioStream(1, m_inputQueueArray) +{ + m_osc = new LowFrequencyOscillator(Waveform::SINE, 4*128); +} + +AudioEffectTremolo::~AudioEffectTremolo() +{ +} + +void AudioEffectTremolo::update(void) +{ + audio_block_t *inputAudioBlock = receiveWritable(); // get the next block of input samples + + // Check is block is disabled + if (m_enable == false) { + // do not transmit or process any audio, return as quickly as possible. + if (inputAudioBlock) release(inputAudioBlock); + return; + } + + // Check is block is bypassed, if so either transmit input directly or create silence + if (m_bypass == true) { + // transmit the input directly + if (!inputAudioBlock) { + // create silence + inputAudioBlock = allocate(); + if (!inputAudioBlock) { return; } // failed to allocate + else { + clearAudioBlock(inputAudioBlock); + } + } + transmit(inputAudioBlock, 0); + release(inputAudioBlock); + return; + } + + // DO PROCESSING + // apply modulation wave + float mod = (m_osc->getNext()+1.0f)/2.0f; // value between -1.0 and +1.0f + float modVolume = (1.0f - m_depth) + mod*m_depth; // value between 0 to depth + float finalVolume = m_volume * modVolume; + + // Set the output volume + gainAdjust(inputAudioBlock, inputAudioBlock, finalVolume, 1); + + transmit(inputAudioBlock); + release(inputAudioBlock); +} + +void AudioEffectTremolo::setWaveform(Waveform waveform) +{ + m_waveform = waveform; +} + +void AudioEffectTremolo::processMidi(int channel, int control, int value) +{ + + float val = (float)value / 127.0f; + + if ((m_midiConfig[BYPASS][MIDI_CHANNEL] == channel) && + (m_midiConfig[BYPASS][MIDI_CONTROL] == control)) { + // Bypass + if (value >= 65) { bypass(false); Serial.println(String("AudioEffectTremolo::not bypassed -> ON") + value); } + else { bypass(true); Serial.println(String("AudioEffectTremolo::bypassed -> OFF") + value); } + return; + } + + if ((m_midiConfig[RATE][MIDI_CHANNEL] == channel) && + (m_midiConfig[RATE][MIDI_CONTROL] == control)) { + // Rate + rate(val); + Serial.println(String("AudioEffectTremolo::rate: ") + m_rate); + return; + } + + if ((m_midiConfig[DEPTH][MIDI_CHANNEL] == channel) && + (m_midiConfig[DEPTH][MIDI_CONTROL] == control)) { + // Depth + depth(val); + Serial.println(String("AudioEffectTremolo::depth: ") + m_depth); + return; + } + + if ((m_midiConfig[WAVEFORM][MIDI_CHANNEL] == channel) && + (m_midiConfig[WAVEFORM][MIDI_CONTROL] == control)) { + // Waveform + if (value < 16) { + m_waveform = Waveform::SINE; + } else if (value < 32) { + m_waveform = Waveform::TRIANGLE; + } else if (value < 48) { + m_waveform = Waveform::SQUARE; + } else if (value < 64) { + m_waveform = Waveform::SAWTOOTH; + } else if (value < 80) { + m_waveform = Waveform::RANDOM; + } + + Serial.println(String("AudioEffectTremolo::waveform: ") + static_cast(m_waveform)); + return; + } + + if ((m_midiConfig[VOLUME][MIDI_CHANNEL] == channel) && + (m_midiConfig[VOLUME][MIDI_CONTROL] == control)) { + // Volume + Serial.println(String("AudioEffectTremolo::volume: ") + 100*val + String("%")); + volume(val); + return; + } + +} + +void AudioEffectTremolo::mapMidiControl(int parameter, int midiCC, int midiChannel) +{ + if (parameter >= NUM_CONTROLS) { + return ; // Invalid midi parameter + } + m_midiConfig[parameter][MIDI_CHANNEL] = midiChannel; + m_midiConfig[parameter][MIDI_CONTROL] = midiCC; +} + +} + + +