andrewm@0: /* andrewm@0: * RTAudio.cpp andrewm@0: * andrewm@0: * Central control code for hard real-time audio on BeagleBone Black andrewm@0: * using PRU and Xenomai Linux extensions. This code began as part andrewm@0: * of the Hackable Instruments project (EPSRC) at Queen Mary University andrewm@0: * of London, 2013-14. andrewm@0: * andrewm@0: * (c) 2014 Victor Zappi and Andrew McPherson andrewm@0: * Queen Mary University of London andrewm@0: */ andrewm@0: andrewm@0: andrewm@0: #include andrewm@0: #include andrewm@0: #include andrewm@0: #include andrewm@0: #include andrewm@0: #include andrewm@0: #include andrewm@0: #include andrewm@0: andrewm@0: // Xenomai-specific includes andrewm@0: #include andrewm@0: #include andrewm@0: #include andrewm@0: #include andrewm@0: andrewm@0: #include "../include/RTAudio.h" andrewm@0: #include "../include/PRU.h" andrewm@0: #include "../include/I2c_Codec.h" andrewm@0: #include "../include/render.h" andrewm@0: #include "../include/GPIOcontrol.h" andrewm@0: andrewm@0: using namespace std; andrewm@0: andrewm@0: // Data structure to keep track of auxiliary tasks we andrewm@0: // can schedule andrewm@0: typedef struct { andrewm@0: RT_TASK task; andrewm@0: void (*function)(void); andrewm@0: char *name; andrewm@0: int priority; andrewm@0: } InternalAuxiliaryTask; andrewm@0: andrewm@0: const char gRTAudioThreadName[] = "beaglert-audio"; andrewm@0: andrewm@0: // Real-time tasks and objects andrewm@0: RT_TASK gRTAudioThread; andrewm@0: PRU *gPRU = 0; andrewm@0: I2c_Codec *gAudioCodec = 0; andrewm@0: andrewm@0: vector gAuxTasks; andrewm@0: andrewm@0: // Flag which tells the audio task to stop andrewm@0: bool gShouldStop = false; andrewm@0: andrewm@0: // general settings giuliomoro@16: char *gPRUFilename;//[256] = "pru_rtaudio.bin"; // path to PRU binary file andrewm@0: int gRTAudioVerbose = 0; // Verbosity level for debugging andrewm@0: int gAmplifierMutePin = -1; andrewm@5: int gAmplifierShouldBeginMuted = 0; andrewm@0: andrewm@13: // Number of audio and matrix channels, globally accessible giuliomoro@16: // At least gNumMatrixChannels and gNumMatrixGpioChannels need to be global to be used giuliomoro@16: // by the analogRead() and analogWrite() and the digital macros without creating andrewm@13: // extra confusion in their use cases by passing this argument andrewm@13: int gNumAudioChannels = 0; andrewm@13: int gNumMatrixChannels = 0; giuliomoro@16: int gNumMatrixGpioChannels = 0; andrewm@0: andrewm@0: // initAudio() prepares the infrastructure for running PRU-based real-time andrewm@0: // audio, but does not actually start the calculations. andrewm@0: // periodSize indicates the number of _sensor_ frames per period: the audio period size andrewm@0: // is twice this value. In total, the audio latency in frames will be 4*periodSize, andrewm@0: // plus any latency inherent in the ADCs and DACs themselves. andrewm@12: // useMatrix indicates whether to enable the ADC and DAC or just use the audio codec. andrewm@12: // numMatrixChannels indicates how many ADC and DAC channels to use. andrewm@0: // userData is an opaque pointer which will be passed through to the initialise_render() andrewm@0: // function for application-specific use andrewm@0: // andrewm@0: // Returns 0 on success. andrewm@0: andrewm@5: int BeagleRT_initAudio(RTAudioSettings *settings, void *userData) andrewm@0: { andrewm@0: rt_print_auto_init(1); andrewm@5: setVerboseLevel(settings->verbose); giuliomoro@16: gPRUFilename=settings->pruFilename; andrewm@0: if(gRTAudioVerbose == 1) andrewm@0: rt_printf("Running with Xenomai\n"); andrewm@0: andrewm@5: if(gRTAudioVerbose) { andrewm@5: cout << "Starting with period size " << settings->periodSize << "; "; andrewm@5: if(settings->useMatrix) andrewm@5: cout << "matrix enabled\n"; andrewm@5: else andrewm@5: cout << "matrix disabled\n"; andrewm@5: cout << "DAC level " << settings->dacLevel << "dB; ADC level " << settings->adcLevel; andrewm@5: cout << "dB; headphone level " << settings->headphoneLevel << "dB\n"; andrewm@5: if(settings->beginMuted) andrewm@5: cout << "Beginning with speaker muted\n"; andrewm@5: } andrewm@0: andrewm@0: // Prepare GPIO pins for amplifier mute and status LED andrewm@5: if(settings->ampMutePin >= 0) { andrewm@5: gAmplifierMutePin = settings->ampMutePin; andrewm@5: gAmplifierShouldBeginMuted = settings->beginMuted; andrewm@0: andrewm@5: if(gpio_export(settings->ampMutePin)) { andrewm@0: if(gRTAudioVerbose) giuliomoro@16: cout << "Warning: couldn't export amplifier mute pin " << settings-> ampMutePin << "\n"; andrewm@0: } andrewm@5: if(gpio_set_dir(settings->ampMutePin, OUTPUT_PIN)) { andrewm@0: if(gRTAudioVerbose) andrewm@0: cout << "Couldn't set direction on amplifier mute pin\n"; andrewm@0: return -1; andrewm@0: } andrewm@5: if(gpio_set_value(settings->ampMutePin, LOW)) { andrewm@0: if(gRTAudioVerbose) andrewm@0: cout << "Couldn't set value on amplifier mute pin\n"; andrewm@0: return -1; andrewm@0: } andrewm@0: } andrewm@0: andrewm@12: // Limit the matrix channels to sane values andrewm@12: if(settings->numMatrixChannels >= 8) andrewm@12: settings->numMatrixChannels = 8; andrewm@12: else if(settings->numMatrixChannels >= 4) andrewm@12: settings->numMatrixChannels = 4; andrewm@12: else andrewm@12: settings->numMatrixChannels = 2; andrewm@12: andrewm@12: // Sanity check the combination of channels and period size andrewm@12: if(settings->numMatrixChannels <= 4 && settings->periodSize < 2) { andrewm@12: cout << "Error: " << settings->numMatrixChannels << " channels and period size of " << settings->periodSize << " not supported.\n"; andrewm@12: return 1; andrewm@12: } andrewm@12: if(settings->numMatrixChannels <= 2 && settings->periodSize < 4) { andrewm@12: cout << "Error: " << settings->numMatrixChannels << " channels and period size of " << settings->periodSize << " not supported.\n"; andrewm@12: return 1; andrewm@12: } andrewm@12: andrewm@0: // Use PRU for audio andrewm@0: gPRU = new PRU(); andrewm@0: gAudioCodec = new I2c_Codec(); andrewm@0: giuliomoro@16: gNumMatrixGpioChannels = settings->useMatrixGpio ? settings->numMatrixGpioChannels : 0; //this is called here to make sure prepareGPIO initializes the appropriate GPIO pins giuliomoro@16: if(gPRU->prepareGPIO(settings->useMatrix, settings->useMatrixGpio, 1, 1)) { andrewm@0: cout << "Error: unable to prepare GPIO for PRU audio\n"; andrewm@0: return 1; andrewm@0: } andrewm@12: if(gPRU->initialise(0, settings->periodSize, settings->numMatrixChannels, true)) { andrewm@0: cout << "Error: unable to initialise PRU\n"; andrewm@0: return 1; andrewm@0: } andrewm@5: if(gAudioCodec->initI2C_RW(2, settings->codecI2CAddress, -1)) { andrewm@0: cout << "Unable to open codec I2C\n"; andrewm@0: return 1; andrewm@0: } andrewm@0: if(gAudioCodec->initCodec()) { andrewm@0: cout << "Error: unable to initialise audio codec\n"; andrewm@0: return 1; andrewm@0: } andrewm@0: andrewm@5: // Set default volume levels andrewm@5: BeagleRT_setDACLevel(settings->dacLevel); andrewm@5: BeagleRT_setADCLevel(settings->adcLevel); andrewm@5: BeagleRT_setHeadphoneLevel(settings->headphoneLevel); andrewm@5: andrewm@12: // Initialise the rendering environment: pass the number of audio and matrix andrewm@12: // channels, the period size for matrix and audio, and the sample rates andrewm@12: andrewm@12: int audioPeriodSize = settings->periodSize * 2; andrewm@12: float audioSampleRate = 44100.0; andrewm@12: float matrixSampleRate = 22050.0; andrewm@12: if(settings->useMatrix) { andrewm@12: audioPeriodSize = settings->periodSize * settings->numMatrixChannels / 4; andrewm@12: matrixSampleRate = audioSampleRate * 4.0 / (float)settings->numMatrixChannels; andrewm@12: } andrewm@12: andrewm@13: gNumAudioChannels = 2; andrewm@13: gNumMatrixChannels = settings->useMatrix ? settings->numMatrixChannels : 0; giuliomoro@16: if(!initialise_render(gNumMatrixChannels, gNumMatrixGpioChannels, gNumAudioChannels, andrewm@12: settings->useMatrix ? settings->periodSize : 0, /* matrix period size */ andrewm@12: audioPeriodSize, andrewm@12: matrixSampleRate, audioSampleRate, andrewm@12: userData)) { andrewm@0: cout << "Couldn't initialise audio rendering\n"; andrewm@0: return 1; andrewm@0: } andrewm@0: andrewm@0: return 0; andrewm@0: } andrewm@0: andrewm@0: // audioLoop() is the main function which starts the PRU audio code andrewm@0: // and then transfers control to the PRU object. The PRU object in andrewm@0: // turn will call the audio render() callback function every time andrewm@0: // there is new data to process. andrewm@0: andrewm@0: void audioLoop(void *) andrewm@0: { andrewm@0: if(gRTAudioVerbose==1) andrewm@0: rt_printf("_________________Audio Thread!\n"); andrewm@0: andrewm@0: // PRU audio andrewm@0: assert(gAudioCodec != 0 && gPRU != 0); andrewm@0: andrewm@0: if(gAudioCodec->startAudio(0)) { andrewm@0: rt_printf("Error: unable to start I2C audio codec\n"); andrewm@0: gShouldStop = 1; andrewm@0: } andrewm@0: else { giuliomoro@16: if(gPRU->start(gPRUFilename)) { giuliomoro@16: rt_printf("Error: unable to start PRU from file %s\n", gPRUFilename); andrewm@0: gShouldStop = 1; andrewm@0: } andrewm@0: else { andrewm@0: // All systems go. Run the loop; it will end when gShouldStop is set to 1 andrewm@5: andrewm@5: if(!gAmplifierShouldBeginMuted) { andrewm@5: // First unmute the amplifier andrewm@5: if(BeagleRT_muteSpeakers(0)) { andrewm@5: if(gRTAudioVerbose) andrewm@5: rt_printf("Warning: couldn't set value (high) on amplifier mute pin\n"); andrewm@5: } andrewm@0: } andrewm@0: andrewm@0: gPRU->loop(); andrewm@0: andrewm@0: // Now clean up andrewm@0: // gPRU->waitForFinish(); andrewm@0: gPRU->disable(); andrewm@0: gAudioCodec->stopAudio(); andrewm@0: gPRU->cleanupGPIO(); andrewm@0: } andrewm@0: } andrewm@0: andrewm@0: if(gRTAudioVerbose == 1) andrewm@0: rt_printf("audio thread ended\n"); andrewm@0: } andrewm@0: andrewm@0: // Create a calculation loop which can run independently of the audio, at a different andrewm@0: // (equal or lower) priority. Audio priority is 99; priority should be generally be less than this. andrewm@0: // Returns an (opaque) pointer to the created task on success; 0 on failure andrewm@0: AuxiliaryTask createAuxiliaryTaskLoop(void (*functionToCall)(void), int priority, const char *name) andrewm@0: { andrewm@0: InternalAuxiliaryTask *newTask = (InternalAuxiliaryTask*)malloc(sizeof(InternalAuxiliaryTask)); andrewm@0: andrewm@0: // Attempt to create the task andrewm@0: if(rt_task_create(&(newTask->task), name, 0, priority, T_JOINABLE | T_FPU)) { andrewm@0: cout << "Error: unable to create auxiliary task " << name << endl; andrewm@0: free(newTask); andrewm@0: return 0; andrewm@0: } andrewm@0: andrewm@0: // Populate the rest of the data structure and store it in the vector andrewm@0: newTask->function = functionToCall; andrewm@0: newTask->name = strdup(name); andrewm@0: newTask->priority = priority; andrewm@0: andrewm@0: gAuxTasks.push_back(newTask); andrewm@0: andrewm@0: return (AuxiliaryTask)newTask; andrewm@0: } andrewm@0: andrewm@0: // Schedule a previously created auxiliary task. It will run when the priority rules next andrewm@0: // allow it to be scheduled. andrewm@0: void scheduleAuxiliaryTask(AuxiliaryTask task) andrewm@0: { andrewm@0: InternalAuxiliaryTask *taskToSchedule = (InternalAuxiliaryTask *)task; andrewm@0: andrewm@0: rt_task_resume(&taskToSchedule->task); andrewm@0: } andrewm@0: andrewm@0: // Calculation loop that can be used for other tasks running at a lower andrewm@0: // priority than the audio thread. Simple wrapper for Xenomai calls. andrewm@0: // Treat the argument as containing the task structure andrewm@0: void auxiliaryTaskLoop(void *taskStruct) andrewm@0: { andrewm@0: // Get function to call from the argument andrewm@0: void (*auxiliary_function)(void) = ((InternalAuxiliaryTask *)taskStruct)->function; andrewm@0: const char *name = ((InternalAuxiliaryTask *)taskStruct)->name; andrewm@0: andrewm@0: // Wait for a notification andrewm@0: rt_task_suspend(NULL); andrewm@0: andrewm@0: while(!gShouldStop) { andrewm@0: // Then run the calculations andrewm@0: auxiliary_function(); andrewm@0: andrewm@0: // Wait for a notification andrewm@0: rt_task_suspend(NULL); andrewm@0: } andrewm@0: andrewm@0: if(gRTAudioVerbose == 1) andrewm@0: rt_printf("auxiliary task %s ended\n", name); andrewm@0: } andrewm@0: andrewm@0: // startAudio() should be called only after initAudio() successfully completes. andrewm@0: // It launches the real-time Xenomai task which runs the audio loop. Returns 0 andrewm@0: // on success. andrewm@0: andrewm@5: int BeagleRT_startAudio() andrewm@0: { andrewm@0: // Create audio thread with the highest priority andrewm@0: if(rt_task_create(&gRTAudioThread, gRTAudioThreadName, 0, 99, T_JOINABLE | T_FPU)) { andrewm@0: cout << "Error: unable to create Xenomai audio thread" << endl; andrewm@0: return -1; andrewm@0: } andrewm@0: andrewm@0: // Start all RT threads andrewm@0: if(rt_task_start(&gRTAudioThread, &audioLoop, 0)) { andrewm@0: cout << "Error: unable to start Xenomai audio thread" << endl; andrewm@0: return -1; andrewm@0: } andrewm@0: andrewm@0: // The user may have created other tasks. Start those also. andrewm@0: vector::iterator it; andrewm@0: for(it = gAuxTasks.begin(); it != gAuxTasks.end(); it++) { andrewm@0: InternalAuxiliaryTask *taskStruct = *it; andrewm@0: andrewm@0: if(rt_task_start(&(taskStruct->task), &auxiliaryTaskLoop, taskStruct)) { andrewm@0: cerr << "Error: unable to start Xenomai task " << taskStruct->name << endl; andrewm@0: return -1; andrewm@0: } andrewm@0: } andrewm@0: andrewm@0: return 0; andrewm@0: } andrewm@0: andrewm@0: // Stop the PRU-based audio from running and wait andrewm@0: // for the tasks to complete before returning. andrewm@0: andrewm@5: void BeagleRT_stopAudio() andrewm@0: { andrewm@0: // Tell audio thread to stop (if this hasn't been done already) andrewm@0: gShouldStop = true; andrewm@0: andrewm@5: if(gRTAudioVerbose) andrewm@5: cout << "Stopping audio...\n"; andrewm@5: andrewm@0: // Now wait for threads to respond and actually stop... andrewm@0: rt_task_join(&gRTAudioThread); andrewm@0: andrewm@0: // Stop all the auxiliary threads too andrewm@0: vector::iterator it; andrewm@0: for(it = gAuxTasks.begin(); it != gAuxTasks.end(); it++) { andrewm@0: InternalAuxiliaryTask *taskStruct = *it; andrewm@0: andrewm@0: // Wake up each thread and join it andrewm@0: rt_task_resume(&(taskStruct->task)); andrewm@0: rt_task_join(&(taskStruct->task)); andrewm@0: } andrewm@0: } andrewm@0: andrewm@0: // Free any resources associated with PRU real-time audio andrewm@5: void BeagleRT_cleanupAudio() andrewm@0: { andrewm@0: cleanup_render(); andrewm@0: andrewm@0: // Clean up the auxiliary tasks andrewm@0: vector::iterator it; andrewm@0: for(it = gAuxTasks.begin(); it != gAuxTasks.end(); it++) { andrewm@0: InternalAuxiliaryTask *taskStruct = *it; andrewm@0: andrewm@0: // Free the name string and the struct itself andrewm@0: free(taskStruct->name); andrewm@0: free(taskStruct); andrewm@0: } andrewm@0: gAuxTasks.clear(); andrewm@0: andrewm@0: if(gPRU != 0) andrewm@0: delete gPRU; andrewm@0: if(gAudioCodec != 0) andrewm@0: delete gAudioCodec; andrewm@0: andrewm@0: if(gAmplifierMutePin >= 0) andrewm@0: gpio_unexport(gAmplifierMutePin); andrewm@0: gAmplifierMutePin = -1; andrewm@0: } andrewm@0: andrewm@5: // Set the level of the DAC; affects all outputs (headphone, line, speaker) andrewm@5: // 0dB is the maximum, -63.5dB is the minimum; 0.5dB steps andrewm@5: int BeagleRT_setDACLevel(float decibels) andrewm@5: { andrewm@5: if(gAudioCodec == 0) andrewm@5: return -1; andrewm@5: return gAudioCodec->setDACVolume((int)floorf(decibels * 2.0 + 0.5)); andrewm@5: } andrewm@5: andrewm@5: // Set the level of the ADC andrewm@5: // 0dB is the maximum, -12dB is the minimum; 1.5dB steps andrewm@5: int BeagleRT_setADCLevel(float decibels) andrewm@5: { andrewm@5: if(gAudioCodec == 0) andrewm@5: return -1; andrewm@5: return gAudioCodec->setADCVolume((int)floorf(decibels * 2.0 + 0.5)); andrewm@5: } andrewm@5: andrewm@5: // Set the level of the onboard headphone amplifier; affects headphone andrewm@5: // output only (not line out or speaker) andrewm@5: // 0dB is the maximum, -63.5dB is the minimum; 0.5dB steps andrewm@5: int BeagleRT_setHeadphoneLevel(float decibels) andrewm@5: { andrewm@5: if(gAudioCodec == 0) andrewm@5: return -1; andrewm@5: return gAudioCodec->setHPVolume((int)floorf(decibels * 2.0 + 0.5)); andrewm@5: } andrewm@5: andrewm@5: // Mute or unmute the onboard speaker amplifiers andrewm@5: // mute == 0 means unmute; otherwise mute andrewm@5: // Returns 0 on success andrewm@5: int BeagleRT_muteSpeakers(int mute) andrewm@5: { andrewm@5: int pinValue = mute ? LOW : HIGH; andrewm@5: andrewm@5: // Check that we have an enabled pin for controlling the mute andrewm@5: if(gAmplifierMutePin < 0) andrewm@5: return -1; andrewm@5: andrewm@5: return gpio_set_value(gAmplifierMutePin, pinValue); andrewm@5: } andrewm@5: andrewm@0: // Set the verbosity level andrewm@0: void setVerboseLevel(int level) andrewm@0: { andrewm@0: gRTAudioVerbose = level; andrewm@0: }