annotate core/RTAudio.cpp @ 15:901d205d1a3c

Updated to latest PRU library; external PRU file no longer needed. Also catch SIGTERM as well as SIGINT to clean up gracefully.
author andrewm
date Sat, 07 Feb 2015 16:41:56 +0000
parents 6adb088196a7
children 670be80463a3
rev   line source
andrewm@0 1 /*
andrewm@0 2 * RTAudio.cpp
andrewm@0 3 *
andrewm@0 4 * Central control code for hard real-time audio on BeagleBone Black
andrewm@0 5 * using PRU and Xenomai Linux extensions. This code began as part
andrewm@0 6 * of the Hackable Instruments project (EPSRC) at Queen Mary University
andrewm@0 7 * of London, 2013-14.
andrewm@0 8 *
andrewm@0 9 * (c) 2014 Victor Zappi and Andrew McPherson
andrewm@0 10 * Queen Mary University of London
andrewm@0 11 */
andrewm@0 12
andrewm@0 13
andrewm@0 14 #include <stdio.h>
andrewm@0 15 #include <stdlib.h>
andrewm@0 16 #include <string.h>
andrewm@0 17 #include <strings.h>
andrewm@0 18 #include <math.h>
andrewm@0 19 #include <iostream>
andrewm@0 20 #include <assert.h>
andrewm@0 21 #include <vector>
andrewm@0 22
andrewm@0 23 // Xenomai-specific includes
andrewm@0 24 #include <sys/mman.h>
andrewm@0 25 #include <native/task.h>
andrewm@0 26 #include <native/timer.h>
andrewm@0 27 #include <rtdk.h>
andrewm@0 28
andrewm@0 29 #include "../include/RTAudio.h"
andrewm@0 30 #include "../include/PRU.h"
andrewm@0 31 #include "../include/I2c_Codec.h"
andrewm@0 32 #include "../include/render.h"
andrewm@0 33 #include "../include/GPIOcontrol.h"
andrewm@0 34
andrewm@0 35 using namespace std;
andrewm@0 36
andrewm@0 37 // Data structure to keep track of auxiliary tasks we
andrewm@0 38 // can schedule
andrewm@0 39 typedef struct {
andrewm@0 40 RT_TASK task;
andrewm@0 41 void (*function)(void);
andrewm@0 42 char *name;
andrewm@0 43 int priority;
andrewm@0 44 } InternalAuxiliaryTask;
andrewm@0 45
andrewm@0 46 const char gRTAudioThreadName[] = "beaglert-audio";
andrewm@0 47
andrewm@0 48 // Real-time tasks and objects
andrewm@0 49 RT_TASK gRTAudioThread;
andrewm@0 50 PRU *gPRU = 0;
andrewm@0 51 I2c_Codec *gAudioCodec = 0;
andrewm@0 52
andrewm@0 53 vector<InternalAuxiliaryTask*> gAuxTasks;
andrewm@0 54
andrewm@0 55 // Flag which tells the audio task to stop
andrewm@0 56 bool gShouldStop = false;
andrewm@0 57
andrewm@0 58 // general settings
andrewm@0 59 int gRTAudioVerbose = 0; // Verbosity level for debugging
andrewm@0 60 int gAmplifierMutePin = -1;
andrewm@5 61 int gAmplifierShouldBeginMuted = 0;
andrewm@0 62
andrewm@13 63 // Number of audio and matrix channels, globally accessible
andrewm@13 64 // At least gNumMatrixChannels needs to be global to be used
andrewm@13 65 // by the analogRead() and analogWrite() macros without creating
andrewm@13 66 // extra confusion in their use cases by passing this argument
andrewm@13 67 int gNumAudioChannels = 0;
andrewm@13 68 int gNumMatrixChannels = 0;
andrewm@0 69
andrewm@0 70 // initAudio() prepares the infrastructure for running PRU-based real-time
andrewm@0 71 // audio, but does not actually start the calculations.
andrewm@0 72 // periodSize indicates the number of _sensor_ frames per period: the audio period size
andrewm@0 73 // is twice this value. In total, the audio latency in frames will be 4*periodSize,
andrewm@0 74 // plus any latency inherent in the ADCs and DACs themselves.
andrewm@12 75 // useMatrix indicates whether to enable the ADC and DAC or just use the audio codec.
andrewm@12 76 // numMatrixChannels indicates how many ADC and DAC channels to use.
andrewm@0 77 // userData is an opaque pointer which will be passed through to the initialise_render()
andrewm@0 78 // function for application-specific use
andrewm@0 79 //
andrewm@0 80 // Returns 0 on success.
andrewm@0 81
andrewm@5 82 int BeagleRT_initAudio(RTAudioSettings *settings, void *userData)
andrewm@0 83 {
andrewm@0 84 rt_print_auto_init(1);
andrewm@5 85 setVerboseLevel(settings->verbose);
andrewm@5 86
andrewm@0 87 if(gRTAudioVerbose == 1)
andrewm@0 88 rt_printf("Running with Xenomai\n");
andrewm@0 89
andrewm@5 90 if(gRTAudioVerbose) {
andrewm@5 91 cout << "Starting with period size " << settings->periodSize << "; ";
andrewm@5 92 if(settings->useMatrix)
andrewm@5 93 cout << "matrix enabled\n";
andrewm@5 94 else
andrewm@5 95 cout << "matrix disabled\n";
andrewm@5 96 cout << "DAC level " << settings->dacLevel << "dB; ADC level " << settings->adcLevel;
andrewm@5 97 cout << "dB; headphone level " << settings->headphoneLevel << "dB\n";
andrewm@5 98 if(settings->beginMuted)
andrewm@5 99 cout << "Beginning with speaker muted\n";
andrewm@5 100 }
andrewm@0 101
andrewm@0 102 // Prepare GPIO pins for amplifier mute and status LED
andrewm@5 103 if(settings->ampMutePin >= 0) {
andrewm@5 104 gAmplifierMutePin = settings->ampMutePin;
andrewm@5 105 gAmplifierShouldBeginMuted = settings->beginMuted;
andrewm@0 106
andrewm@5 107 if(gpio_export(settings->ampMutePin)) {
andrewm@0 108 if(gRTAudioVerbose)
andrewm@0 109 cout << "Warning: couldn't export amplifier mute pin\n";
andrewm@0 110 }
andrewm@5 111 if(gpio_set_dir(settings->ampMutePin, OUTPUT_PIN)) {
andrewm@0 112 if(gRTAudioVerbose)
andrewm@0 113 cout << "Couldn't set direction on amplifier mute pin\n";
andrewm@0 114 return -1;
andrewm@0 115 }
andrewm@5 116 if(gpio_set_value(settings->ampMutePin, LOW)) {
andrewm@0 117 if(gRTAudioVerbose)
andrewm@0 118 cout << "Couldn't set value on amplifier mute pin\n";
andrewm@0 119 return -1;
andrewm@0 120 }
andrewm@0 121 }
andrewm@0 122
andrewm@12 123 // Limit the matrix channels to sane values
andrewm@12 124 if(settings->numMatrixChannels >= 8)
andrewm@12 125 settings->numMatrixChannels = 8;
andrewm@12 126 else if(settings->numMatrixChannels >= 4)
andrewm@12 127 settings->numMatrixChannels = 4;
andrewm@12 128 else
andrewm@12 129 settings->numMatrixChannels = 2;
andrewm@12 130
andrewm@12 131 // Sanity check the combination of channels and period size
andrewm@12 132 if(settings->numMatrixChannels <= 4 && settings->periodSize < 2) {
andrewm@12 133 cout << "Error: " << settings->numMatrixChannels << " channels and period size of " << settings->periodSize << " not supported.\n";
andrewm@12 134 return 1;
andrewm@12 135 }
andrewm@12 136 if(settings->numMatrixChannels <= 2 && settings->periodSize < 4) {
andrewm@12 137 cout << "Error: " << settings->numMatrixChannels << " channels and period size of " << settings->periodSize << " not supported.\n";
andrewm@12 138 return 1;
andrewm@12 139 }
andrewm@12 140
andrewm@0 141 // Use PRU for audio
andrewm@0 142 gPRU = new PRU();
andrewm@0 143 gAudioCodec = new I2c_Codec();
andrewm@0 144
andrewm@5 145 if(gPRU->prepareGPIO(settings->useMatrix, 1, 1)) {
andrewm@0 146 cout << "Error: unable to prepare GPIO for PRU audio\n";
andrewm@0 147 return 1;
andrewm@0 148 }
andrewm@12 149 if(gPRU->initialise(0, settings->periodSize, settings->numMatrixChannels, true)) {
andrewm@0 150 cout << "Error: unable to initialise PRU\n";
andrewm@0 151 return 1;
andrewm@0 152 }
andrewm@5 153 if(gAudioCodec->initI2C_RW(2, settings->codecI2CAddress, -1)) {
andrewm@0 154 cout << "Unable to open codec I2C\n";
andrewm@0 155 return 1;
andrewm@0 156 }
andrewm@0 157 if(gAudioCodec->initCodec()) {
andrewm@0 158 cout << "Error: unable to initialise audio codec\n";
andrewm@0 159 return 1;
andrewm@0 160 }
andrewm@0 161
andrewm@5 162 // Set default volume levels
andrewm@5 163 BeagleRT_setDACLevel(settings->dacLevel);
andrewm@5 164 BeagleRT_setADCLevel(settings->adcLevel);
andrewm@5 165 BeagleRT_setHeadphoneLevel(settings->headphoneLevel);
andrewm@5 166
andrewm@12 167 // Initialise the rendering environment: pass the number of audio and matrix
andrewm@12 168 // channels, the period size for matrix and audio, and the sample rates
andrewm@12 169
andrewm@12 170 int audioPeriodSize = settings->periodSize * 2;
andrewm@12 171 float audioSampleRate = 44100.0;
andrewm@12 172 float matrixSampleRate = 22050.0;
andrewm@12 173 if(settings->useMatrix) {
andrewm@12 174 audioPeriodSize = settings->periodSize * settings->numMatrixChannels / 4;
andrewm@12 175 matrixSampleRate = audioSampleRate * 4.0 / (float)settings->numMatrixChannels;
andrewm@12 176 }
andrewm@12 177
andrewm@13 178 gNumAudioChannels = 2;
andrewm@13 179 gNumMatrixChannels = settings->useMatrix ? settings->numMatrixChannels : 0;
andrewm@13 180
andrewm@13 181 if(!initialise_render(gNumMatrixChannels, gNumAudioChannels,
andrewm@12 182 settings->useMatrix ? settings->periodSize : 0, /* matrix period size */
andrewm@12 183 audioPeriodSize,
andrewm@12 184 matrixSampleRate, audioSampleRate,
andrewm@12 185 userData)) {
andrewm@0 186 cout << "Couldn't initialise audio rendering\n";
andrewm@0 187 return 1;
andrewm@0 188 }
andrewm@0 189
andrewm@0 190 return 0;
andrewm@0 191 }
andrewm@0 192
andrewm@0 193 // audioLoop() is the main function which starts the PRU audio code
andrewm@0 194 // and then transfers control to the PRU object. The PRU object in
andrewm@0 195 // turn will call the audio render() callback function every time
andrewm@0 196 // there is new data to process.
andrewm@0 197
andrewm@0 198 void audioLoop(void *)
andrewm@0 199 {
andrewm@0 200 if(gRTAudioVerbose==1)
andrewm@0 201 rt_printf("_________________Audio Thread!\n");
andrewm@0 202
andrewm@0 203 // PRU audio
andrewm@0 204 assert(gAudioCodec != 0 && gPRU != 0);
andrewm@0 205
andrewm@0 206 if(gAudioCodec->startAudio(0)) {
andrewm@0 207 rt_printf("Error: unable to start I2C audio codec\n");
andrewm@0 208 gShouldStop = 1;
andrewm@0 209 }
andrewm@0 210 else {
andrewm@15 211 if(gPRU->start()) {
andrewm@15 212 rt_printf("Error: unable to start PRU\n");
andrewm@0 213 gShouldStop = 1;
andrewm@0 214 }
andrewm@0 215 else {
andrewm@0 216 // All systems go. Run the loop; it will end when gShouldStop is set to 1
andrewm@5 217
andrewm@5 218 if(!gAmplifierShouldBeginMuted) {
andrewm@5 219 // First unmute the amplifier
andrewm@5 220 if(BeagleRT_muteSpeakers(0)) {
andrewm@5 221 if(gRTAudioVerbose)
andrewm@5 222 rt_printf("Warning: couldn't set value (high) on amplifier mute pin\n");
andrewm@5 223 }
andrewm@0 224 }
andrewm@0 225
andrewm@0 226 gPRU->loop();
andrewm@0 227
andrewm@0 228 // Now clean up
andrewm@0 229 // gPRU->waitForFinish();
andrewm@0 230 gPRU->disable();
andrewm@0 231 gAudioCodec->stopAudio();
andrewm@0 232 gPRU->cleanupGPIO();
andrewm@0 233 }
andrewm@0 234 }
andrewm@0 235
andrewm@0 236 if(gRTAudioVerbose == 1)
andrewm@0 237 rt_printf("audio thread ended\n");
andrewm@0 238 }
andrewm@0 239
andrewm@0 240 // Create a calculation loop which can run independently of the audio, at a different
andrewm@0 241 // (equal or lower) priority. Audio priority is 99; priority should be generally be less than this.
andrewm@0 242 // Returns an (opaque) pointer to the created task on success; 0 on failure
andrewm@0 243 AuxiliaryTask createAuxiliaryTaskLoop(void (*functionToCall)(void), int priority, const char *name)
andrewm@0 244 {
andrewm@0 245 InternalAuxiliaryTask *newTask = (InternalAuxiliaryTask*)malloc(sizeof(InternalAuxiliaryTask));
andrewm@0 246
andrewm@0 247 // Attempt to create the task
andrewm@0 248 if(rt_task_create(&(newTask->task), name, 0, priority, T_JOINABLE | T_FPU)) {
andrewm@0 249 cout << "Error: unable to create auxiliary task " << name << endl;
andrewm@0 250 free(newTask);
andrewm@0 251 return 0;
andrewm@0 252 }
andrewm@0 253
andrewm@0 254 // Populate the rest of the data structure and store it in the vector
andrewm@0 255 newTask->function = functionToCall;
andrewm@0 256 newTask->name = strdup(name);
andrewm@0 257 newTask->priority = priority;
andrewm@0 258
andrewm@0 259 gAuxTasks.push_back(newTask);
andrewm@0 260
andrewm@0 261 return (AuxiliaryTask)newTask;
andrewm@0 262 }
andrewm@0 263
andrewm@0 264 // Schedule a previously created auxiliary task. It will run when the priority rules next
andrewm@0 265 // allow it to be scheduled.
andrewm@0 266 void scheduleAuxiliaryTask(AuxiliaryTask task)
andrewm@0 267 {
andrewm@0 268 InternalAuxiliaryTask *taskToSchedule = (InternalAuxiliaryTask *)task;
andrewm@0 269
andrewm@0 270 rt_task_resume(&taskToSchedule->task);
andrewm@0 271 }
andrewm@0 272
andrewm@0 273 // Calculation loop that can be used for other tasks running at a lower
andrewm@0 274 // priority than the audio thread. Simple wrapper for Xenomai calls.
andrewm@0 275 // Treat the argument as containing the task structure
andrewm@0 276 void auxiliaryTaskLoop(void *taskStruct)
andrewm@0 277 {
andrewm@0 278 // Get function to call from the argument
andrewm@0 279 void (*auxiliary_function)(void) = ((InternalAuxiliaryTask *)taskStruct)->function;
andrewm@0 280 const char *name = ((InternalAuxiliaryTask *)taskStruct)->name;
andrewm@0 281
andrewm@0 282 // Wait for a notification
andrewm@0 283 rt_task_suspend(NULL);
andrewm@0 284
andrewm@0 285 while(!gShouldStop) {
andrewm@0 286 // Then run the calculations
andrewm@0 287 auxiliary_function();
andrewm@0 288
andrewm@0 289 // Wait for a notification
andrewm@0 290 rt_task_suspend(NULL);
andrewm@0 291 }
andrewm@0 292
andrewm@0 293 if(gRTAudioVerbose == 1)
andrewm@0 294 rt_printf("auxiliary task %s ended\n", name);
andrewm@0 295 }
andrewm@0 296
andrewm@0 297 // startAudio() should be called only after initAudio() successfully completes.
andrewm@0 298 // It launches the real-time Xenomai task which runs the audio loop. Returns 0
andrewm@0 299 // on success.
andrewm@0 300
andrewm@5 301 int BeagleRT_startAudio()
andrewm@0 302 {
andrewm@0 303 // Create audio thread with the highest priority
andrewm@0 304 if(rt_task_create(&gRTAudioThread, gRTAudioThreadName, 0, 99, T_JOINABLE | T_FPU)) {
andrewm@0 305 cout << "Error: unable to create Xenomai audio thread" << endl;
andrewm@0 306 return -1;
andrewm@0 307 }
andrewm@0 308
andrewm@0 309 // Start all RT threads
andrewm@0 310 if(rt_task_start(&gRTAudioThread, &audioLoop, 0)) {
andrewm@0 311 cout << "Error: unable to start Xenomai audio thread" << endl;
andrewm@0 312 return -1;
andrewm@0 313 }
andrewm@0 314
andrewm@0 315 // The user may have created other tasks. Start those also.
andrewm@0 316 vector<InternalAuxiliaryTask*>::iterator it;
andrewm@0 317 for(it = gAuxTasks.begin(); it != gAuxTasks.end(); it++) {
andrewm@0 318 InternalAuxiliaryTask *taskStruct = *it;
andrewm@0 319
andrewm@0 320 if(rt_task_start(&(taskStruct->task), &auxiliaryTaskLoop, taskStruct)) {
andrewm@0 321 cerr << "Error: unable to start Xenomai task " << taskStruct->name << endl;
andrewm@0 322 return -1;
andrewm@0 323 }
andrewm@0 324 }
andrewm@0 325
andrewm@0 326 return 0;
andrewm@0 327 }
andrewm@0 328
andrewm@0 329 // Stop the PRU-based audio from running and wait
andrewm@0 330 // for the tasks to complete before returning.
andrewm@0 331
andrewm@5 332 void BeagleRT_stopAudio()
andrewm@0 333 {
andrewm@0 334 // Tell audio thread to stop (if this hasn't been done already)
andrewm@0 335 gShouldStop = true;
andrewm@0 336
andrewm@5 337 if(gRTAudioVerbose)
andrewm@5 338 cout << "Stopping audio...\n";
andrewm@5 339
andrewm@0 340 // Now wait for threads to respond and actually stop...
andrewm@0 341 rt_task_join(&gRTAudioThread);
andrewm@0 342
andrewm@0 343 // Stop all the auxiliary threads too
andrewm@0 344 vector<InternalAuxiliaryTask*>::iterator it;
andrewm@0 345 for(it = gAuxTasks.begin(); it != gAuxTasks.end(); it++) {
andrewm@0 346 InternalAuxiliaryTask *taskStruct = *it;
andrewm@0 347
andrewm@0 348 // Wake up each thread and join it
andrewm@0 349 rt_task_resume(&(taskStruct->task));
andrewm@0 350 rt_task_join(&(taskStruct->task));
andrewm@0 351 }
andrewm@0 352 }
andrewm@0 353
andrewm@0 354 // Free any resources associated with PRU real-time audio
andrewm@5 355 void BeagleRT_cleanupAudio()
andrewm@0 356 {
andrewm@0 357 cleanup_render();
andrewm@0 358
andrewm@0 359 // Clean up the auxiliary tasks
andrewm@0 360 vector<InternalAuxiliaryTask*>::iterator it;
andrewm@0 361 for(it = gAuxTasks.begin(); it != gAuxTasks.end(); it++) {
andrewm@0 362 InternalAuxiliaryTask *taskStruct = *it;
andrewm@0 363
andrewm@0 364 // Free the name string and the struct itself
andrewm@0 365 free(taskStruct->name);
andrewm@0 366 free(taskStruct);
andrewm@0 367 }
andrewm@0 368 gAuxTasks.clear();
andrewm@0 369
andrewm@0 370 if(gPRU != 0)
andrewm@0 371 delete gPRU;
andrewm@0 372 if(gAudioCodec != 0)
andrewm@0 373 delete gAudioCodec;
andrewm@0 374
andrewm@0 375 if(gAmplifierMutePin >= 0)
andrewm@0 376 gpio_unexport(gAmplifierMutePin);
andrewm@0 377 gAmplifierMutePin = -1;
andrewm@0 378 }
andrewm@0 379
andrewm@5 380 // Set the level of the DAC; affects all outputs (headphone, line, speaker)
andrewm@5 381 // 0dB is the maximum, -63.5dB is the minimum; 0.5dB steps
andrewm@5 382 int BeagleRT_setDACLevel(float decibels)
andrewm@5 383 {
andrewm@5 384 if(gAudioCodec == 0)
andrewm@5 385 return -1;
andrewm@5 386 return gAudioCodec->setDACVolume((int)floorf(decibels * 2.0 + 0.5));
andrewm@5 387 }
andrewm@5 388
andrewm@5 389 // Set the level of the ADC
andrewm@5 390 // 0dB is the maximum, -12dB is the minimum; 1.5dB steps
andrewm@5 391 int BeagleRT_setADCLevel(float decibels)
andrewm@5 392 {
andrewm@5 393 if(gAudioCodec == 0)
andrewm@5 394 return -1;
andrewm@5 395 return gAudioCodec->setADCVolume((int)floorf(decibels * 2.0 + 0.5));
andrewm@5 396 }
andrewm@5 397
andrewm@5 398 // Set the level of the onboard headphone amplifier; affects headphone
andrewm@5 399 // output only (not line out or speaker)
andrewm@5 400 // 0dB is the maximum, -63.5dB is the minimum; 0.5dB steps
andrewm@5 401 int BeagleRT_setHeadphoneLevel(float decibels)
andrewm@5 402 {
andrewm@5 403 if(gAudioCodec == 0)
andrewm@5 404 return -1;
andrewm@5 405 return gAudioCodec->setHPVolume((int)floorf(decibels * 2.0 + 0.5));
andrewm@5 406 }
andrewm@5 407
andrewm@5 408 // Mute or unmute the onboard speaker amplifiers
andrewm@5 409 // mute == 0 means unmute; otherwise mute
andrewm@5 410 // Returns 0 on success
andrewm@5 411 int BeagleRT_muteSpeakers(int mute)
andrewm@5 412 {
andrewm@5 413 int pinValue = mute ? LOW : HIGH;
andrewm@5 414
andrewm@5 415 // Check that we have an enabled pin for controlling the mute
andrewm@5 416 if(gAmplifierMutePin < 0)
andrewm@5 417 return -1;
andrewm@5 418
andrewm@5 419 return gpio_set_value(gAmplifierMutePin, pinValue);
andrewm@5 420 }
andrewm@5 421
andrewm@0 422 // Set the verbosity level
andrewm@0 423 void setVerboseLevel(int level)
andrewm@0 424 {
andrewm@0 425 gRTAudioVerbose = level;
andrewm@0 426 }