annotate core/ReceiveAudioThread.cpp @ 117:ada68d50e56a scope-refactoring

ReceiveAudioThread hs been ported to BBB. The scope project now is sending audio locally and receiving it at the same time
author Giulio Moro <giuliomoro@yahoo.it>
date Thu, 20 Aug 2015 16:37:15 +0100
parents
children c692827083e1
rev   line source
giuliomoro@117 1 #include "ReceiveAudioThread.h"
giuliomoro@117 2 //initialise static members
giuliomoro@117 3 AuxiliaryTask ReceiveAudioThread::receiveDataTask=NULL;
giuliomoro@117 4
giuliomoro@117 5 void ReceiveAudioThread::dealloc(){
giuliomoro@117 6 free(buffer);
giuliomoro@117 7 buffer=NULL;
giuliomoro@117 8 free(stackBuffer);
giuliomoro@117 9 stackBuffer=NULL;
giuliomoro@117 10 }
giuliomoro@117 11 void ReceiveAudioThread::wrapWritePointer(){
giuliomoro@117 12 //this is not quite a simple wrapping as you wold in a circular buffer,
giuliomoro@117 13 //as there is no guarantee the buffer will be full at all times, given that there must alwas be enough space at the end of it
giuliomoro@117 14 //to hold a full payload
giuliomoro@117 15 // lastValidPointer indicates the last pointer in the buffer containing valid data
giuliomoro@117 16 //
giuliomoro@117 17 if(writePointer+payloadLength+headerLength>bufferLength){ //if we are going to exceed the length of the buffer with the next reading
giuliomoro@117 18 // lastValidPointer=writePointer+headerLength; //remember where the last valid data are
giuliomoro@117 19 // for(int n=headerLength;n<lastValidPointer; n++){
giuliomoro@117 20 // fprintf(fd2, "%f\n",buffer[n]); //DEBUG
giuliomoro@117 21 // }
giuliomoro@117 22 writePointer=0; //and reset to beginning of the buffer
giuliomoro@117 23 }
giuliomoro@117 24 }
giuliomoro@117 25 void ReceiveAudioThread::pushPayload(int startIndex){ //backup the payload samples that will be overwritten by the new header
giuliomoro@117 26 for(int n=0; n<headerLength; n++){
giuliomoro@117 27 stackBuffer[n]=buffer[startIndex+n];
giuliomoro@117 28 }
giuliomoro@117 29 }
giuliomoro@117 30 void ReceiveAudioThread::popPayload(int startIndex){
giuliomoro@117 31 for(int n=0; n<headerLength; n++){
giuliomoro@117 32 buffer[startIndex+n]=stackBuffer[n];
giuliomoro@117 33 }
giuliomoro@117 34 }
giuliomoro@117 35
giuliomoro@117 36 int ReceiveAudioThread::readUdpToBuffer(){
giuliomoro@117 37 if(listening==false || bufferReady==false)
giuliomoro@117 38 return 0;
giuliomoro@117 39 if(writePointer<0)
giuliomoro@117 40 return 0;
giuliomoro@117 41 if(1){ //TODO: implement waitUntilReady for UdpServer
giuliomoro@117 42 //JUCE if(socket.waitUntilReady(true, waitForSocketTime)){ // waitForSocketTime could have been set to -1 (wait forever),
giuliomoro@117 43 // but it would have made it more difficult for the thread to be killed
giuliomoro@117 44 pushPayload(writePointer); //backup headerLength samples. This could be skipped if writePointer==0
giuliomoro@117 45 //read header+payload
giuliomoro@117 46 //JUCE int numBytes=socket.read(buffer+writePointer, bytesToRead,1);
giuliomoro@117 47 int numBytes=socket.read(buffer+writePointer, bytesToRead);
giuliomoro@117 48 //TODO: do something with the data in the header (e.g.: check that timestamp is sequential,
giuliomoro@117 49 // check the channel number)
giuliomoro@117 50 //TODO: (if using variable-length payload) validate the actual numBytes read against the size declared in the header
giuliomoro@117 51 if(numBytes<0){
giuliomoro@117 52 printf("error numBytes1\n");
giuliomoro@117 53 return -3; //TODO: something went wrong, you have to discard the rest of the packet!
giuliomoro@117 54 }
giuliomoro@117 55 if(numBytes==0){//TODO: when inplementing waitUntilReady, this should not happen unless you actually receive a packate of size zero (is it at all possible?)
giuliomoro@117 56 // printf("received 0 bytes\n");
giuliomoro@117 57 return 0;
giuliomoro@117 58 }
giuliomoro@117 59 if(numBytes != bytesToRead){ //this is equivalent to (numBytes<numBytes)
giuliomoro@117 60 printf("error numBytes2: %d\n", numBytes);
giuliomoro@117 61 return -4; //TODO: something went wrong, less bytes than expected in the payload.
giuliomoro@117 62 }
giuliomoro@117 63 if(buffer[writePointer]!=0)
giuliomoro@117 64 return 0; //wrong channel
giuliomoro@117 65 // printf("Received a message of length %d, it was on channel %d and timestamp %d\n", numBytes, (int)buffer[writePointer], (int)buffer[writePointer+1]);
giuliomoro@117 66 popPayload(writePointer); //restore headerLength payload samples. This could be skipped if writePointer==0
giuliomoro@117 67
giuliomoro@117 68 //even though we just wrote (payloadLength+headerLength) samples in the buffer,
giuliomoro@117 69 //we only increment by payloadLength. This way, next time a socket.read is performed, we will
giuliomoro@117 70 //backup the last headerLength samples that we just wrote and we will overwrite them with
giuliomoro@117 71 //the header from the new read. After parsing the header we will then restore the backed up samples.
giuliomoro@117 72 //This way we guarantee that, apart from the first headerLength samples, buffer is a circular buffer!
giuliomoro@117 73 printf("writepointer:%d\n", writePointer);
giuliomoro@117 74 writePointer+=payloadLength;
giuliomoro@117 75
giuliomoro@117 76 if(writePointer>lastValidPointer){
giuliomoro@117 77 // lastValidPointer=writePointer+headerLength;
giuliomoro@117 78 }
giuliomoro@117 79 wrapWritePointer();
giuliomoro@117 80 return numBytes;
giuliomoro@117 81 }
giuliomoro@117 82 return 0; //timeout occurred
giuliomoro@117 83 }
giuliomoro@117 84 ReceiveAudioThread::ReceiveAudioThread() :
giuliomoro@117 85 //JUCE Thread(threadName),
giuliomoro@117 86 socket(0),
giuliomoro@117 87 listening(false),
giuliomoro@117 88 bufferReady(false),
giuliomoro@117 89 threadIsExiting(false),
giuliomoro@117 90 buffer(NULL),
giuliomoro@117 91 stackBuffer(NULL),
giuliomoro@117 92 bufferLength(0),
giuliomoro@117 93 lastValidPointer(0),
giuliomoro@117 94 sleepTime(2000),
giuliomoro@117 95 waitForSocketTime(100),
giuliomoro@117 96 threadPriority(95)
giuliomoro@117 97 {};
giuliomoro@117 98 ReceiveAudioThread::~ReceiveAudioThread(){
giuliomoro@117 99 //JUCE stopThread(1000);
giuliomoro@117 100 while(threadRunning){
giuliomoro@117 101 sleep(sleepTime*2); //wait for thread to stop
giuliomoro@117 102 std::cout<< "Waiting for receiveAudioTask to stop" << std::endl;
giuliomoro@117 103 }
giuliomoro@117 104 //TODO: check if thread stopped, otherwise kill it before dealloc
giuliomoro@117 105 dealloc();
giuliomoro@117 106 }
giuliomoro@117 107 ReceiveAudioThread *gRAT;
giuliomoro@117 108 void receiveData(){
giuliomoro@117 109 gRAT->run();
giuliomoro@117 110 }
giuliomoro@117 111 void ReceiveAudioThread::init(int aSamplesPerBlock){
giuliomoro@117 112 dealloc();
giuliomoro@117 113 // fd=fopen("output.m","w"); //DEBUG
giuliomoro@117 114 // fprintf(fd,"var=["); //DEBUG
giuliomoro@117 115 gRAT=this;
giuliomoro@117 116 headerLength=2;
giuliomoro@117 117 payloadLength=300; //TODO: make sure that payloadLength and headerLength are the same as the client is sending.
giuliomoro@117 118 bufferLength=std::max(headerLength+(payloadLength*4), headerLength+(aSamplesPerBlock*4)); //there are many considerations that can be done here ...
giuliomoro@117 119 //We keep a headerLength padding at the beginning of the array to allow full reads from the socket
giuliomoro@117 120 buffer=(float*)malloc(sizeof(float)*bufferLength);
giuliomoro@117 121 if(buffer==NULL) // something wrong
giuliomoro@117 122 return;
giuliomoro@117 123 bufferReady=true;
giuliomoro@117 124 lastValidPointer=headerLength+ ((bufferLength-headerLength)/payloadLength)*payloadLength;
giuliomoro@117 125 memset(buffer,0,bufferLength*sizeof(float));
giuliomoro@117 126 stackBuffer=(float*)malloc(sizeof(float)*headerLength);
giuliomoro@117 127 bytesToRead=sizeof(float)*(payloadLength + headerLength);
giuliomoro@117 128 writePointer=-1;
giuliomoro@117 129 readPointer=0; //TODO: this *4 is sortof a security margin
giuliomoro@117 130 sleepTime=payloadLength/(float)44100 /4.0; //set sleepTime so that you do not check too often or too infrequently
giuliomoro@117 131 receiveDataTask=BeagleRT_createAuxiliaryTask( receiveData, threadPriority, "receiveDataTask");
giuliomoro@117 132 //JUCE startThread(threadPriority);
giuliomoro@117 133 }
giuliomoro@117 134
giuliomoro@117 135 void ReceiveAudioThread::bindToPort(int aPort){
giuliomoro@117 136 listening=socket.bindToPort(aPort);
giuliomoro@117 137 }
giuliomoro@117 138 bool ReceiveAudioThread::isListening(){
giuliomoro@117 139 return listening;
giuliomoro@117 140 }
giuliomoro@117 141 float* ReceiveAudioThread::getCurrentBuffer(int length){ // NOTE: this cannot work all the time unless samplesPerBuffer and payloadLength are multiples
giuliomoro@117 142 //TODO: make it return the number of samples actually available at the specified location
giuliomoro@117 143 if(isListening()==false || length>bufferLength)
giuliomoro@117 144 return NULL;
giuliomoro@117 145 readPointer+=length;
giuliomoro@117 146 if(readPointer>lastValidPointer){
giuliomoro@117 147 readPointer=headerLength;
giuliomoro@117 148 }
giuliomoro@117 149 return buffer+(int)readPointer;
giuliomoro@117 150 };
giuliomoro@117 151 int ReceiveAudioThread::getSamplesSrc(float *destination, int length, float samplingRateRatio){//TODO: add interleaved version
giuliomoro@117 152 if (!(samplingRateRatio>0 && samplingRateRatio<=2))
giuliomoro@117 153 return -2;
giuliomoro@117 154 if(isListening()==false)
giuliomoro@117 155 return -1;
giuliomoro@117 156 if(writePointer<0){ //if writePointer has not been initalized yet ...
giuliomoro@117 157 writePointer=2*length; // do it, so that it starts writing at a safety margin from where we write.
giuliomoro@117 158 // This will help keeping them in sync.
giuliomoro@117 159 //TODO: handle what happens when the remote stream is interrupted and then restarted
giuliomoro@117 160 }
giuliomoro@117 161 if(length>lastValidPointer) {
giuliomoro@117 162 //not enough samples available, we fill the buffer with what is available, but the destination buffer will not be filled completely
giuliomoro@117 163 //at this very moment the other thread might be writing at most one payload into the buffer.
giuliomoro@117 164 //To avoid a race condition, we need to let alone the buffer where we are currently writing
giuliomoro@117 165 //as writing the payload also temporarily overwrites the previous headerLength samples, we need to account for them as well
giuliomoro@117 166 //TODO: This assumes that the writePointer and readPointer do not drift. When doing clock synchronization we will find out that it is not true!
giuliomoro@117 167 length=lastValidPointer-payloadLength-headerLength;
giuliomoro@117 168 if(length<0) //no samples available at all!
giuliomoro@117 169 return 0;
giuliomoro@117 170 }
giuliomoro@117 171 for(int n=0; n<length; n++){
giuliomoro@117 172 destination[n]=buffer[(int)(0.5+readPointer)];//simple ZOH non-interpolation (nearest neighbour)
giuliomoro@117 173 // fprintf(fd,"%f, %d, %f;\n",readPointer,writePointer,destination[n]); //DEBUG
giuliomoro@117 174 readPointer+=samplingRateRatio;
giuliomoro@117 175 if((int)(0.5+readPointer)>=lastValidPointer){
giuliomoro@117 176 readPointer=readPointer-lastValidPointer+headerLength;
giuliomoro@117 177 }
giuliomoro@117 178 }
giuliomoro@117 179 return readPointer;
giuliomoro@117 180 }
giuliomoro@117 181
giuliomoro@117 182 bool ReceiveAudioThread::isBufferReady(){
giuliomoro@117 183 return bufferReady;
giuliomoro@117 184 }
giuliomoro@117 185 void ReceiveAudioThread::startThread(){
giuliomoro@117 186 BeagleRT_scheduleAuxiliaryTask(receiveDataTask);
giuliomoro@117 187 }
giuliomoro@117 188 void ReceiveAudioThread::stopThread(){
giuliomoro@117 189 threadIsExiting=true;
giuliomoro@117 190 }
giuliomoro@117 191 bool ReceiveAudioThread::threadShouldExit(){
giuliomoro@117 192 return(gShouldStop || threadIsExiting );
giuliomoro@117 193 }
giuliomoro@117 194 void ReceiveAudioThread::run(){
giuliomoro@117 195 // fd2=fopen("buffer.m","w"); //DEBUG
giuliomoro@117 196 // fprintf(fd2, "buf=["); //DEBUG
giuliomoro@117 197 threadRunning=true;
giuliomoro@117 198 while(!threadShouldExit()){ //TODO: check that the socket buffer is empty before starting
giuliomoro@117 199 readUdpToBuffer(); // read into the oldBuffer
giuliomoro@117 200 usleep(sleepTime);
giuliomoro@117 201 }
giuliomoro@117 202 threadRunning=false;
giuliomoro@117 203 // fprintf(fd,"];readPointer,writePointer,lastValidPointer,destination]=deal(var(:,1), var(:,2), var(:,3), var(:,4));"); //DEBUG
giuliomoro@117 204 // fclose(fd);//DEBUG
giuliomoro@117 205 // fprintf(fd2,"];");//DEBUG
giuliomoro@117 206 // fclose(fd2); //DEBUG
giuliomoro@117 207 }