Mercurial > hg > beaglert
changeset 3:6810f166482f
_new IIR filter example
author | Victor Zappi <victor.zappi@qmul.ac.uk> |
---|---|
date | Thu, 06 Nov 2014 17:55:05 +0000 |
parents | 021ac8a1a4f9 |
children | f34c63568523 |
files | .cproject projects/filter_IIR/SampleData.h projects/filter_IIR/longsample.wav projects/filter_IIR/main.cpp projects/filter_IIR/render.cpp |
diffstat | 5 files changed, 443 insertions(+), 2 deletions(-) [+] |
line wrap: on
line diff
--- a/.cproject Thu Nov 06 15:59:16 2014 +0000 +++ b/.cproject Thu Nov 06 17:55:05 2014 +0000 @@ -83,8 +83,8 @@ </folderInfo> <sourceEntries> <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="include"/> - <entry excluding="oscillator_bank|samples|basic_sensor|d-box|basic_analog_output|basic" flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="projects"/> <entry excluding="audio_routines_old.S" flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="core"/> + <entry excluding="filter_FIR|oscillator_bank|samples|basic_sensor|d-box|basic_analog_output|basic" flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="projects"/> </sourceEntries> </configuration> </storageModule> @@ -155,9 +155,9 @@ </toolChain> </folderInfo> <sourceEntries> - <entry excluding="oscillator_bank|samples|basic_sensor|d-box|basic_analog_output|basic" flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="projects"/> <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="include"/> <entry excluding="audio_routines_old.S" flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="core"/> + <entry excluding="filter_FIR|oscillator_bank|samples|basic_sensor|d-box|basic_analog_output|basic" flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="projects"/> </sourceEntries> </configuration> </storageModule>
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/projects/filter_IIR/SampleData.h Thu Nov 06 17:55:05 2014 +0000 @@ -0,0 +1,19 @@ +/* + * SampleData.h + * + * Created on: Nov 5, 2014 + * Author: Victor Zappi + */ + +#ifndef SAMPLEDATA_H_ +#define SAMPLEDATA_H_ + +// User defined structure to pass between main and rendere complex data retrieved from file +struct SampleData { + float *samples; // Samples in file + int sampleLen; // Total nume of samples +}; + + + +#endif /* SAMPLEDATA_H_ */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/projects/filter_IIR/main.cpp Thu Nov 06 17:55:05 2014 +0000 @@ -0,0 +1,195 @@ +/* + * main.cpp + * + * Created on: Oct 24, 2014 + * Author: Andrew McPherson and Victor Zappi + */ + +#include <iostream> +#include <cstdlib> +#include <libgen.h> +#include <signal.h> +#include <string> +#include <sndfile.h> // to load audio files +#include "../../include/RTAudio.h" +#include "SampleData.h" + +using namespace std; + +float gCutFreq = 100; + +// Load samples from file +int initFile(string file, SampleData *smp)//float *& smp) +{ + SNDFILE *sndfile ; + SF_INFO sfinfo ; + + if (!(sndfile = sf_open (file.c_str(), SFM_READ, &sfinfo))) { + cout << "Couldn't open file " << file << endl; + return 1; + } + + int numChan = sfinfo.channels; + if(numChan != 1) + { + cout << "Error: " << file << " is not a mono file" << endl; + return 1; + } + + smp->sampleLen = sfinfo.frames * numChan; + smp->samples = new float[smp->sampleLen]; + if(smp == NULL){ + cout << "Could not allocate buffer" << endl; + return 1; + } + + int subformat = sfinfo.format & SF_FORMAT_SUBMASK; + int readcount = sf_read_float(sndfile, smp->samples, smp->sampleLen); + + // Pad with zeros in case we couldn't read whole file + for(int k = readcount; k <smp->sampleLen; k++) + smp->samples[k] = 0; + + if (subformat == SF_FORMAT_FLOAT || subformat == SF_FORMAT_DOUBLE) { + double scale ; + int m ; + + sf_command (sndfile, SFC_CALC_SIGNAL_MAX, &scale, sizeof (scale)) ; + if (scale < 1e-10) + scale = 1.0 ; + else + scale = 32700.0 / scale ; + cout << "File samples scale = " << scale << endl; + + for (m = 0; m < smp->sampleLen; m++) + smp->samples[m] *= scale; + } + + sf_close(sndfile); + + return 0; +} + + +// Handle Ctrl-C by requesting that the audio rendering stop +void interrupt_handler(int var) +{ + //rt_task_delete ((RT_TASK *) &gTriggerSamplesTask); + gShouldStop = true; +} + +// Print usage information +void usage(const char * processName) +{ + cerr << "Usage: " << processName << " [-h] [-v] [-p period] [-f frequency]" << endl; + cerr << " -h: Print this menu\n"; + cerr << " -v: Enable verbose messages\n"; + cerr << " -p period: Set the period (hardware buffer) size in sensor frames\n"; + cerr << " -m: Enable the matrix (ADC and DAC) as well as audio\n"; + cerr << " -f filename: Name of the file to load (default is \"sample.wav\")\n"; + cerr << " -c freq: Set the cut off frequency of the filter in Hz\n"; +} + +int main(int argc, char *argv[]) +{ + int verbose = 0; // Verbose printing level + int periodSize = 8; // Period size in sensor frames + int useMatrix = 0; // Whether to use the matrix or just audio + string fileName; // Name of the sample to load + + SampleData sampleData; // User define structure to pass data retrieved from file to render function + sampleData.samples = 0; + sampleData.sampleLen = -1; + + // Parse command-line arguments + while (1) { + int c; + if ((c = getopt(argc, argv, "hp:vms:")) < 0) + break; + switch (c) { + case 'h': + usage(basename(argv[0])); + exit(0); + case 'p': + periodSize = atoi(optarg); + if(periodSize < 1) + periodSize = 1; + break; + case 'v': + verbose = 1; + break; + case 'm': + useMatrix = 1; + break; + case 'f': + fileName = string((char *)optarg); + break; + case 'c': + gCutFreq = atof(optarg); + break; + case '?': + default: + usage(basename(argv[0])); + exit(1); + } + } + + if(fileName.empty()){ + fileName = "filter/longsample.wav"; + } + + // Set verbose logging information (optional by using value > 0; default is 0) + setVerboseLevel(verbose); + + if(verbose) { + cout << "Starting with period size " << periodSize << endl; + if(useMatrix) + cout << "Matrix enabled\n"; + else + cout << "Matrix disabled\n"; + cout << "Loading file " << fileName << endl; + } + + // Load file + if(initFile(fileName, &sampleData) != 0) + { + cout << "Error: unable to load samples " << endl; + return -1; + } + + if(verbose) + cout << "File contains " << sampleData.sampleLen << " samples" << endl; + + // Initialise the PRU audio device + if(initAudio(periodSize, useMatrix, &sampleData) != 0) { + cout << "Error: unable to initialise audio" << endl; + return -1; + } + + // Start the audio device running + if(startAudio()) { + cout << "Error: unable to start real-time audio" << endl; + return -1; + } + + // Set up interrupt handler to catch Control-C + signal(SIGINT, interrupt_handler); + + // Run until told to stop + while(!gShouldStop) { + usleep(100000); + } + + // Stop the audio device + stopAudio(); + + if(verbose) { + cout << "Cleaning up..." << endl; + } + + // Clean up any resources allocated for audio + cleanupAudio(); + + // All done! + return 0; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/projects/filter_IIR/render.cpp Thu Nov 06 17:55:05 2014 +0000 @@ -0,0 +1,227 @@ +/* + * render.cpp + * + * Created on: Oct 24, 2014 + * Author: Andrew McPherson and Victor Zappi + */ + + +#include "../../include/render.h" +#include "../../include/RTAudio.h" // to schedule lower prio parallel process +#include <rtdk.h> +#include <cmath> +#include <stdio.h> +#include "SampleData.h" + +SampleData gSampleData; // User defined structure to get complex data from main +int gReadPtr; // Position of last read sample from file +int gNumChannels; + +// filter vars +float gLastX[2]; +float gLastY[2]; +double lb0, lb1, lb2, la1, la2 = 0.0; + +// communication vars between the 2 auxiliary tasks +int gChangeCoeff = 0; +int gFreqDelta = 0; + +void initialise_filter(float freq); + +void calculate_coeff(float cutFreq); + +bool initialise_aux_tasks(); + +// Task for handling the update of the frequencies using the matrix +AuxiliaryTask gChangeCoeffTask; + +void check_coeff(); + +// Task for handling the update of the frequencies using the matrix +AuxiliaryTask gInputTask; + +void read_input(); + + +extern float gCutFreq; + + +// initialise_render() is called once before the audio rendering starts. +// Use it to perform any initialisation and allocation which is dependent +// on the period size or sample rate. +// +// userData holds an opaque pointer to a data structure that was passed +// in from the call to initAudio(). +// +// Return true on success; returning false halts the program. + +bool initialise_render(int numChannels, int numMatrixFramesPerPeriod, + int numAudioFramesPerPeriod, float matrixSampleRate, + float audioSampleRate, void *userData) +{ + + // Retrieve a parameter passed in from the initAudio() call + gSampleData = *(SampleData *)userData; + + gReadPtr = -1; + gNumChannels = numChannels; + + initialise_filter(200); + + // Initialise auxiliary tasks + if(!initialise_aux_tasks()) + return false; + + return true; +} + +// render() is called regularly at the highest priority by the audio engine. +// Input and output are given from the audio hardware and the other +// ADCs and DACs (if available). If only audio is available, numMatrixFrames +// will be 0. + +void render(int numMatrixFrames, int numAudioFrames, float *audioIn, float *audioOut, + uint16_t *matrixIn, uint16_t *matrixOut) +{ + for(int n = 0; n < numAudioFrames; n++) { + float sample = 0; + float out = 0; + + // If triggered... + if(gReadPtr != -1) + sample += gSampleData.samples[gReadPtr++]; // ...read each sample... + + if(gReadPtr >= gSampleData.sampleLen) + gReadPtr = -1; + + out = lb0*sample+lb1*gLastX[0]+lb2*gLastX[1]-la1*gLastY[0]-la2*gLastY[1]; + + gLastX[1] = gLastX[0]; + gLastX[0] = out; + gLastY[1] = gLastY[0]; + gLastY[0] = out; + + for(int channel = 0; channel < gNumChannels; channel++) + audioOut[n * gNumChannels + channel] = out; // ...and put it in both left and right channel + + } + + // Request that the lower-priority tasks run at next opportunity + scheduleAuxiliaryTask(gChangeCoeffTask); + scheduleAuxiliaryTask(gInputTask); +} + +// First calculation of coefficients + +void initialise_filter(float freq) +{ + calculate_coeff(freq); +} + + +// Calculate the filter coefficients +// second order low pass butterworth filter + +void calculate_coeff(float cutFreq) +{ + // Initialise any previous state (clearing buffers etc.) + // to prepare for calls to render() + float sampleRate = 44100; + double f = 2*M_PI*cutFreq/sampleRate; + double denom = 4+2*sqrt(2)*f+f*f; + lb0 = f*f/denom; + lb1 = 2*lb0; + lb2 = lb0; + la1 = (2*f*f-8)/denom; + la2 = (f*f+4-2*sqrt(2)*f)/denom; + gLastX[0] = gLastX [1] = 0; + gLastY[0] = gLastY[1] = 0; + +} + + +// Initialise the auxiliary tasks +// and print info + +bool initialise_aux_tasks() +{ + if((gChangeCoeffTask = createAuxiliaryTaskLoop(&check_coeff, 90, "beaglert-check-coeff")) == 0) + return false; + + if((gInputTask = createAuxiliaryTaskLoop(&read_input, 50, "beaglert-read-input")) == 0) + return false; + + rt_printf("Press 'a' to trigger sample, 's' to stop\n"); + rt_printf("Press 'z' to low down cut-off freq of 100 Hz, 'x' to raise it up\n"); + rt_printf("Press 'q' to quit\n"); + + return true; +} + +// Check if cut-off freq has been changed +// and new coefficients are needed + +void check_coeff() +{ + if(gChangeCoeff == 1) + { + gCutFreq += gFreqDelta; + gCutFreq = gCutFreq < 0 ? 0 : gCutFreq; + gCutFreq = gCutFreq > 22050 ? 22050 : gCutFreq; + + rt_printf("Cut-off frequency: %f\n", gCutFreq); + + calculate_coeff(gCutFreq); + gChangeCoeff = 0; + } +} + +// This is a lower-priority call to periodically read keyboard input +// and trigger samples. By placing it at a lower priority, +// it has minimal effect on the audio performance but it will take longer to +// complete if the system is under heavy audio load. + +void read_input() +{ + // This is not a real-time task! + // Cos getchar is a system call, not handled by Xenomai. + // This task will be automatically down graded. + + char keyStroke = '.'; + + keyStroke = getchar(); + while(getchar()!='\n'); // to read the first stroke + + switch (keyStroke) + { + case 'a': + gReadPtr = 0; + break; + case 's': + gReadPtr = -1; + break; + case 'z': + gChangeCoeff = 1; + gFreqDelta = -100; + break; + case 'x': + gChangeCoeff = 1; + gFreqDelta = 100; + break; + case 'q': + gShouldStop = true; + break; + default: + break; + } +} + + + +// cleanup_render() is called once at the end, after the audio has stopped. +// Release any resources that were allocated in initialise_render(). + +void cleanup_render() +{ + delete[] gSampleData.samples; +}