annotate core/RTAudio.cpp @ 41:4255ecbb9bec ultra-staging

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