Mercurial > hg > beaglert
changeset 1:24fc8026ae8e
_new sample playback example
author | Victor Zappi <victor.zappi@qmul.ac.uk> |
---|---|
date | Thu, 06 Nov 2014 14:23:26 +0000 |
parents | 8a575ba3ab52 |
children | 021ac8a1a4f9 |
files | .cproject .project projects/samples/SampleData.h projects/samples/main.cpp projects/samples/render.cpp projects/samples/sample.wav |
diffstat | 6 files changed, 354 insertions(+), 3 deletions(-) [+] |
line wrap: on
line diff
--- a/.cproject Fri Oct 31 19:10:17 2014 +0100 +++ b/.cproject Thu Nov 06 14:23:26 2014 +0000 @@ -1,5 +1,7 @@ <?xml version="1.0" encoding="UTF-8" standalone="no"?> -<?fileVersion 4.0.0?><cproject storage_type_id="org.eclipse.cdt.core.XmlProjectDescriptionStorage"> +<?fileVersion 4.0.0?> + +<cproject storage_type_id="org.eclipse.cdt.core.XmlProjectDescriptionStorage"> <storageModule moduleId="org.eclipse.cdt.core.settings"> <cconfiguration id="cdt.managedbuild.config.gnu.exe.debug.528876549"> <storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="cdt.managedbuild.config.gnu.exe.debug.528876549" moduleId="org.eclipse.cdt.core.settings" name="Debug"> @@ -58,6 +60,7 @@ <listOptionValue builtIn="false" value="rt"/> <listOptionValue builtIn="false" value="native"/> <listOptionValue builtIn="false" value="xenomai"/> + <listOptionValue builtIn="false" value="sndfile"/> </option> <option id="gnu.cpp.link.option.flags.2096887116" name="Linker flags" superClass="gnu.cpp.link.option.flags" value="-pthread -rdynamics" valueType="string"/> <option id="gnu.cpp.link.option.userobjs.537608578" name="Other objects" superClass="gnu.cpp.link.option.userobjs" valueType="userObjs"> @@ -81,7 +84,7 @@ <sourceEntries> <entry excluding="audio_routines_old.S" flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="core"/> <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="include"/> - <entry excluding="d-box|basic_sensor|basic|basic_analog_output" flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="projects"/> + <entry excluding="oscillator_bank|d-box|basic_sensor|basic|basic_analog_output" flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="projects"/> </sourceEntries> </configuration> </storageModule> @@ -154,7 +157,7 @@ <sourceEntries> <entry excluding="audio_routines_old.S" flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="core"/> <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="include"/> - <entry excluding="d-box|basic_sensor|basic|basic_analog_output" flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="projects"/> + <entry excluding="oscillator_bank|d-box|basic_sensor|basic|basic_analog_output" flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="projects"/> </sourceEntries> </configuration> </storageModule>
--- a/.project Fri Oct 31 19:10:17 2014 +0100 +++ b/.project Thu Nov 06 14:23:26 2014 +0000 @@ -10,6 +10,10 @@ <triggers>clean,full,incremental,</triggers> <arguments> <dictionary> + <key>?children?</key> + <value>?name?=outputEntries\|?children?=?name?=entry\\\\\\\|\\\|?name?=entry\\\\\\\|\\\|\||</value> + </dictionary> + <dictionary> <key>?name?</key> <value></value> </dictionary>
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/projects/samples/SampleData.h Thu Nov 06 14:23:26 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/samples/main.cpp Thu Nov 06 14:23:26 2014 +0000 @@ -0,0 +1,192 @@ +/* + * 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 <native/task.h> // to kill sample trigger task +#include "SampleData.h" + +using namespace std; + +//extern AuxiliaryTask gTriggerSamplesTask; + +// 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"; +} + +int main(int argc, char *argv[]) +{ + int periodSize = 8; // Period size in sensor frames + int verbose = 0; // Verbose printing level + 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 '?': + default: + usage(basename(argv[0])); + exit(1); + } + } + + if(fileName.empty()){ + fileName = "samples/sample.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/samples/render.cpp Thu Nov 06 14:23:26 2014 +0000 @@ -0,0 +1,133 @@ +/* + * 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; + +// Task for handling the update of the frequencies using the matrix +AuxiliaryTask gTriggerSamplesTask; + +bool initialise_trigger(); +void trigger_samples(); + +// 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 auxiliary tasks + if(!initialise_trigger()) + 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 out = 0; + + // If triggered... + if(gReadPtr != -1) + out += gSampleData.samples[gReadPtr++]; // ...read each sample... + + if(gReadPtr >= gSampleData.sampleLen) + gReadPtr = -1; + + 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 task run at next opportunity + scheduleAuxiliaryTask(gTriggerSamplesTask); +} + +// Initialise the auxiliary task +// and print info + +bool initialise_trigger() +{ + if((gTriggerSamplesTask = createAuxiliaryTaskLoop(&trigger_samples, 50, "beaglert-trigger-samples")) == 0) + return false; + + rt_printf("Press 'a' to trigger sample, 's' to stop\n"); + rt_printf("Press 'q' to quit\n"); + + return true; +} + +// 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 trigger_samples() +{ + // 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 '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; +}