annotate core/ReceiveAudioThread.cpp @ 217:c42a6b4dc2d4 mergingClockSync

Recovered some files from ClockSync
author Giulio Moro <giuliomoro@yahoo.it>
date Sat, 13 Feb 2016 04:09:12 +0000
parents
children 6a23c07d0fbb
rev   line source
giuliomoro@217 1 #include "ReceiveAudioThread.h"
giuliomoro@217 2
giuliomoro@217 3 #ifdef USE_JUCE
giuliomoro@217 4 #else
giuliomoro@217 5 //initialise static members
giuliomoro@217 6 bool ReceiveAudioThread::staticConstructed=false;
giuliomoro@217 7 AuxiliaryTask ReceiveAudioThread::receiveDataTask=NULL;
giuliomoro@217 8 std::vector<ReceiveAudioThread *> ReceiveAudioThread::objAddrs(0);
giuliomoro@217 9 bool ReceiveAudioThread::threadRunning;
giuliomoro@217 10 bool ReceiveAudioThread::threadIsExiting;
giuliomoro@217 11 int ReceiveAudioThread::sleepTime;
giuliomoro@217 12
giuliomoro@217 13 void receiveData(){
giuliomoro@217 14 ReceiveAudioThread::run();
giuliomoro@217 15 }
giuliomoro@217 16 void ReceiveAudioThread::staticConstructor(){
giuliomoro@217 17 if(staticConstructed==true)
giuliomoro@217 18 return;
giuliomoro@217 19 staticConstructed=true;
giuliomoro@217 20 threadIsExiting=false;
giuliomoro@217 21 receiveDataTask=BeagleRT_createAuxiliaryTask(receiveData, 90, "receiveDataTask"); //TODO: allow different priorities
giuliomoro@217 22 }
giuliomoro@217 23 #endif /* USE_JUCE */
giuliomoro@217 24
giuliomoro@217 25 void ReceiveAudioThread::dealloc(){
giuliomoro@217 26 free(buffer);
giuliomoro@217 27 buffer=NULL;
giuliomoro@217 28 free(stackBuffer);
giuliomoro@217 29 stackBuffer=NULL;
giuliomoro@217 30 }
giuliomoro@217 31 void ReceiveAudioThread::wrapWritePointer(){
giuliomoro@217 32 //this is not quite a simple wrapping as you would do in a circular buffer,
giuliomoro@217 33 //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@217 34 //to hold a full payload
giuliomoro@217 35 // lastValidPointer indicates the last pointer in the buffer containing valid data
giuliomoro@217 36 //
giuliomoro@217 37 if(writePointer+payloadLength+headerLength>bufferLength){ //if we are going to exceed the length of the buffer with the next reading
giuliomoro@217 38 // lastValidPointer=writePointer+headerLength; //remember where the last valid data are
giuliomoro@217 39 // for(int n=headerLength;n<lastValidPointer; n++){
giuliomoro@217 40 // fprintf(fd2, "%f\n",buffer[n]); //DEBUG
giuliomoro@217 41 // }
giuliomoro@217 42 writePointer=0; //and reset to beginning of the buffer
giuliomoro@217 43 }
giuliomoro@217 44 }
giuliomoro@217 45 void ReceiveAudioThread::pushPayload(int startIndex){ //backup the payload samples that will be overwritten by the new header
giuliomoro@217 46 for(int n=0; n<headerLength; n++){
giuliomoro@217 47 stackBuffer[n]=buffer[startIndex+n];
giuliomoro@217 48 }
giuliomoro@217 49 }
giuliomoro@217 50 void ReceiveAudioThread::popPayload(int startIndex){
giuliomoro@217 51 for(int n=0; n<headerLength; n++){
giuliomoro@217 52 buffer[startIndex+n]=stackBuffer[n];
giuliomoro@217 53 }
giuliomoro@217 54 }
giuliomoro@217 55
giuliomoro@217 56 int ReceiveAudioThread::readUdpToBuffer(){
giuliomoro@217 57 if(listening==false || bufferReady==false)
giuliomoro@217 58 return 0;
giuliomoro@217 59 if(writePointer<0)
giuliomoro@217 60 return 0;
giuliomoro@217 61 if(socket.waitUntilReady(true, waitForSocketTime)){// TODO: if waitForSocketTime here is >>5, the
giuliomoro@217 62 #ifdef USE_JUCE
giuliomoro@217 63 #else
giuliomoro@217 64 lastTime=rt_timer_read();
giuliomoro@217 65 // rt_printf("lastTimeread= %llu\n", lastTime);
giuliomoro@217 66 #endif /* USE_JUCE */
giuliomoro@217 67 // destructor (always or sometimes) never actually gets called, despite run() returns ...see issue #1381
giuliomoro@217 68 pushPayload(writePointer); //backup headerLength samples. This could be skipped if writePointer==0
giuliomoro@217 69 //read header+payload
giuliomoro@217 70 int numBytes=socket.read(buffer+writePointer, bytesToRead, true); //read without waiting.
giuliomoro@217 71 //TODO: (if using variable-length payload) validate the actual numBytes read against the size declared in the header
giuliomoro@217 72 if(numBytes<0){
giuliomoro@217 73 printf("error numBytes1\n");
giuliomoro@217 74 return -3; //TODO: something went wrong, you have to discard the rest of the packet!
giuliomoro@217 75 }
giuliomoro@217 76 if(numBytes==0){//TODO: this should not happen unless you actually receive a packet of size zero (is it at all possible?)
giuliomoro@217 77 // printf("received 0 bytes\n");
giuliomoro@217 78 return 0;
giuliomoro@217 79 }
giuliomoro@217 80 if(numBytes != bytesToRead){ //this is equivalent to (numBytes<bytesToRead)
giuliomoro@217 81 printf("error numBytes2: %d\n", numBytes);
giuliomoro@217 82 return -4; //TODO: something went wrong, less bytes than expected in the payload.
giuliomoro@217 83 }
giuliomoro@217 84 if(channel!=(int)buffer[writePointer]){
giuliomoro@217 85 // printf("I am channel %d, but I received data for channel %d\n", channel, (int)buffer[writePointer]);
giuliomoro@217 86 return -5;
giuliomoro@217 87 }
giuliomoro@217 88 if(buffer[writePointer+1]!=timestamp+1)
giuliomoro@217 89 printf("missing a timestamp: %d\n",timestamp+1);
giuliomoro@217 90 timestamp=buffer[writePointer+1];
giuliomoro@217 91 // rt_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@217 92
giuliomoro@217 93 popPayload(writePointer); //restore headerLength payload samples. This could be skipped if writePointer==0
giuliomoro@217 94 //even though we just wrote (payloadLength+headerLength) samples in the buffer,
giuliomoro@217 95 //we only increment by payloadLength. This way, next time a socket.read is performed, we will
giuliomoro@217 96 //backup the last headerLength samples that we just wrote and we will overwrite them with
giuliomoro@217 97 //the header from the new read. After parsing the header we will then restore the backed up samples.
giuliomoro@217 98 //This way we guarantee that, apart from the first headerLength samples, buffer is a circular buffer!
giuliomoro@217 99 writePointer+=payloadLength;
giuliomoro@217 100 wrapWritePointer();
giuliomoro@217 101 return numBytes;
giuliomoro@217 102 }
giuliomoro@217 103 return 0; //timeout occurred
giuliomoro@217 104 }
giuliomoro@217 105 //USE_JUCE Thread(threadName),
giuliomoro@217 106 #ifdef USE_JUCE
giuliomoro@217 107 ReceiveAudioThread::ReceiveAudioThread(const String &threadName) :
giuliomoro@217 108 Thread(threadName),
giuliomoro@217 109 #else
giuliomoro@217 110 ReceiveAudioThread::ReceiveAudioThread() :
giuliomoro@217 111 #endif /* USE_JUCE */
giuliomoro@217 112 socket(0),
giuliomoro@217 113 listening(false),
giuliomoro@217 114 bufferReady(false),
giuliomoro@217 115 buffer(NULL),
giuliomoro@217 116 stackBuffer(NULL),
giuliomoro@217 117 bufferLength(0),
giuliomoro@217 118 lastValidPointer(0),
giuliomoro@217 119 waitForSocketTime(5),
giuliomoro@217 120 #ifdef USE_JUCE
giuliomoro@217 121 threadPriority(5)
giuliomoro@217 122 #else
giuliomoro@217 123 threadPriority(88)
giuliomoro@217 124 #endif /* USE_JUCE */
giuliomoro@217 125 {};
giuliomoro@217 126 ReceiveAudioThread::~ReceiveAudioThread(){
giuliomoro@217 127 #ifdef USE_JUCE
giuliomoro@217 128 stopThread(1000);
giuliomoro@217 129 #else
giuliomoro@217 130 stopThread();
giuliomoro@217 131 while(threadRunning){
giuliomoro@217 132 usleep(sleepTime*2); //wait for thread to stop
giuliomoro@217 133 std::cout<< "Waiting for receiveAudioTask to stop" << std::endl;
giuliomoro@217 134 }
giuliomoro@217 135 #endif /* USE_JUCE */
giuliomoro@217 136 //TODO: check if thread stopped, otherwise kill it before dealloc
giuliomoro@217 137 dealloc();
giuliomoro@217 138 }
giuliomoro@217 139 void ReceiveAudioThread::init(int aPort, int aSamplesPerBlock, int aChannel){
giuliomoro@217 140 dealloc();
giuliomoro@217 141 #ifdef USE_JUCE
giuliomoro@217 142 #else
giuliomoro@217 143 staticConstructor();
giuliomoro@217 144 objAddrs.push_back(this);//TODO: this line should be in the constructor
giuliomoro@217 145 #endif /* USE_JUCE */
giuliomoro@217 146 bindToPort(aPort);
giuliomoro@217 147 channel=aChannel;
giuliomoro@217 148 printf("Channel %d is receiving on port %d\n",aChannel, aPort);
giuliomoro@217 149 // fd=fopen("output.m","w"); //DEBUG
giuliomoro@217 150 // fprintf(fd,"var=["); //DEBUG
giuliomoro@217 151 headerLength=2;
giuliomoro@217 152 payloadLength=300; //TODO: make sure that payloadLength and headerLength are the same as the client is sending.
giuliomoro@217 153 bufferLength=std::max(headerLength+(payloadLength*4), headerLength+(aSamplesPerBlock*4)); //there are many considerations that can be done here ...
giuliomoro@217 154 //We keep a headerLength padding at the beginning of the array to allow full reads from the socket
giuliomoro@217 155 buffer=(float*)malloc(sizeof(float)*bufferLength);
giuliomoro@217 156 if(buffer==NULL) // something wrong
giuliomoro@217 157 return;
giuliomoro@217 158 lastValidPointer=headerLength+ ((bufferLength-headerLength)/payloadLength)*payloadLength;
giuliomoro@217 159 memset(buffer,0,bufferLength*sizeof(float));
giuliomoro@217 160 stackBuffer=(float*)malloc(sizeof(float)*headerLength);
giuliomoro@217 161 if(stackBuffer==NULL) // something wrong
giuliomoro@217 162 return;
giuliomoro@217 163 bufferReady=true;
giuliomoro@217 164 bytesToRead=sizeof(float)*(payloadLength + headerLength);
giuliomoro@217 165 writePointer=-1;
giuliomoro@217 166 readPointer=0;
giuliomoro@217 167 sleepTime=payloadLength/(float)44100 /4.0; //set sleepTime so that you do not check too often or too infrequently
giuliomoro@217 168 timestamp=0;
giuliomoro@217 169 #ifdef USE_JUCE
giuliomoro@217 170 startThread(threadPriority);
giuliomoro@217 171 #else
giuliomoro@217 172 //TODO: the thread cannot be started here at the moment because init() is called in setup(), where tasks cannot be scheduled
giuliomoro@217 173 #endif /* USE_JUCE */
giuliomoro@217 174 }
giuliomoro@217 175
giuliomoro@217 176 void ReceiveAudioThread::bindToPort(int aPort){
giuliomoro@217 177 listening=socket.bindToPort(aPort);
giuliomoro@217 178 #ifdef USE_JUCE
giuliomoro@217 179 #else
giuliomoro@217 180 if(listening==false) //this condition is valid also for USE_JUCE, but we do not printf in USE_JUCE
giuliomoro@217 181 printf("Could not bind to port %d\n",aPort);
giuliomoro@217 182 #endif /* USE_JUCE */
giuliomoro@217 183 }
giuliomoro@217 184 bool ReceiveAudioThread::isListening(){
giuliomoro@217 185 return listening;
giuliomoro@217 186 }
giuliomoro@217 187 float* ReceiveAudioThread::getCurrentBuffer(int length){ // NOTE: this cannot work all the time unless samplesPerBuffer and payloadLength are multiples
giuliomoro@217 188 //TODO: make it return the number of samples actually available at the specified location
giuliomoro@217 189 if(isListening()==false || length>bufferLength)
giuliomoro@217 190 return NULL;
giuliomoro@217 191 readPointer+=length;
giuliomoro@217 192 if(readPointer>lastValidPointer){
giuliomoro@217 193 readPointer=headerLength;
giuliomoro@217 194 }
giuliomoro@217 195 return buffer+(int)readPointer;
giuliomoro@217 196 };
giuliomoro@217 197 int ReceiveAudioThread::getSamplesSrc(float *destination, int length,
giuliomoro@217 198 float samplingRateRatio, int numChannelsInDestination,
giuliomoro@217 199 int channelToWriteTo)
giuliomoro@217 200 {
giuliomoro@217 201 if (!(samplingRateRatio>0 && samplingRateRatio<=2))
giuliomoro@217 202 return -2;
giuliomoro@217 203 if(isListening()==false)
giuliomoro@217 204 return -1;
giuliomoro@217 205 static int numCalls=0;
giuliomoro@217 206 if(writePointer<0 /*|| (numCalls&16383)==0*/){ //if writePointer has not been initalized yet ...
giuliomoro@217 207 #ifdef USE_JUCE
giuliomoro@217 208 #else //debug
giuliomoro@217 209 rt_printf("reinit the writePointer, readPointer: %f;\n",readPointer);
giuliomoro@217 210 readPointer=0;
giuliomoro@217 211 #endif /* USE_JUCE */
giuliomoro@217 212 writePointer=2*length; // do it, so that it starts writing at a safety margin from where we write.
giuliomoro@217 213 // This will help keeping them in sync.
giuliomoro@217 214 //TODO: handle what happens when the remote stream is interrupted and then restarted
giuliomoro@217 215 }
giuliomoro@217 216 numCalls++;
giuliomoro@217 217 if(length>lastValidPointer) {
giuliomoro@217 218 //not enough samples available, we fill the buffer with what is available, but the destination buffer will not be filled completely
giuliomoro@217 219 //at this very moment the other thread might be writing at most one payload into the buffer.
giuliomoro@217 220 //To avoid a race condition, we need to let alone the buffer where we are currently writing
giuliomoro@217 221 //as writing the payload also temporarily overwrites the previous headerLength samples, we need to account for them as well
giuliomoro@217 222 //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@217 223 length=lastValidPointer-payloadLength-headerLength;
giuliomoro@217 224 if(length<0) //no samples available at all!
giuliomoro@217 225 return 0;
giuliomoro@217 226 }
giuliomoro@217 227 for(int n=0; n<length; n++){
giuliomoro@217 228 destination[n*numChannelsInDestination+channelToWriteTo]=buffer[(int)(0.5+readPointer)];//simple ZOH non-interpolation (nearest neighbour)
giuliomoro@217 229 // fprintf(fd,"%f, %d, %f;\n",readPointer,writePointer,destination[n]); //DEBUG
giuliomoro@217 230 readPointer+=samplingRateRatio;
giuliomoro@217 231 if((int)(0.5+readPointer)>=lastValidPointer){
giuliomoro@217 232 readPointer=readPointer-lastValidPointer+headerLength;
giuliomoro@217 233 }
giuliomoro@217 234 }
giuliomoro@217 235 return length;
giuliomoro@217 236 }
giuliomoro@217 237 int ReceiveAudioThread::getSamplesSrc(float *destination, int length, float samplingRateRatio){
giuliomoro@217 238 return getSamplesSrc(destination, length, samplingRateRatio, 1,0);
giuliomoro@217 239 // TODO: rewriting this so that it does not call the override method we can save a multiply and add
giuliomoro@217 240 // for each sample.
giuliomoro@217 241 }
giuliomoro@217 242 bool ReceiveAudioThread::isBufferReady(){
giuliomoro@217 243 return bufferReady;
giuliomoro@217 244 }
giuliomoro@217 245 #ifdef USE_JUCE
giuliomoro@217 246 #else
giuliomoro@217 247 void ReceiveAudioThread::startThread(){
giuliomoro@217 248 BeagleRT_scheduleAuxiliaryTask(receiveDataTask);
giuliomoro@217 249 }
giuliomoro@217 250 void ReceiveAudioThread::stopThread(){
giuliomoro@217 251 threadIsExiting=true;
giuliomoro@217 252 }
giuliomoro@217 253 bool ReceiveAudioThread::threadShouldExit(){
giuliomoro@217 254 return(gShouldStop || threadIsExiting );
giuliomoro@217 255 }
giuliomoro@217 256 RTIME ReceiveAudioThread::getLastTime(){
giuliomoro@217 257 return lastTime;
giuliomoro@217 258 }
giuliomoro@217 259 #endif /* USE_JUCE */
giuliomoro@217 260 int ReceiveAudioThread::getTimestamp(){
giuliomoro@217 261 return timestamp;
giuliomoro@217 262 }
giuliomoro@217 263 void ReceiveAudioThread::run(){
giuliomoro@217 264 // fd2=fopen("buffer.m","w"); //DEBUG
giuliomoro@217 265 // fprintf(fd2, "buf=["); //DEBUG
giuliomoro@217 266 threadRunning=true;
giuliomoro@217 267 int maxCount=10;
giuliomoro@217 268 int count=0;
giuliomoro@217 269 // Clean the socket from anything that is currently in it.
giuliomoro@217 270 #ifdef USE_JUCE
giuliomoro@217 271 // this is borrowed from BeagleRT's UdpServer class.
giuliomoro@217 272 int n;
giuliomoro@217 273 do {
giuliomoro@217 274 float waste;
giuliomoro@217 275 if(socket.waitUntilReady(true, 0)==0)
giuliomoro@217 276 break;
giuliomoro@217 277 n=socket.read((void*)&waste, sizeof(float), false);
giuliomoro@217 278 count++;
giuliomoro@217 279 if(n<0){
giuliomoro@217 280 printf("error\n");
giuliomoro@217 281 break;
giuliomoro@217 282 }
giuliomoro@217 283 printf("n: %d\n",n);
giuliomoro@217 284 } while (n>0 && (maxCount<=0 || count<maxCount));
giuliomoro@217 285 #else
giuliomoro@217 286 for(unsigned int n=0; n<objAddrs.size(); n++){
giuliomoro@217 287 count=objAddrs[n]->socket.empty(maxCount);
giuliomoro@217 288 }
giuliomoro@217 289 #endif /* USE_JUCE */
giuliomoro@217 290 printf("socket emptied with %d reads\n", count);
giuliomoro@217 291
giuliomoro@217 292 while(!threadShouldExit()){ //TODO: check that the socket buffer is empty before starting
giuliomoro@217 293 #ifdef USE_JUCE
giuliomoro@217 294 readUdpToBuffer(); // read into the oldBuffer
giuliomoro@217 295 sleep(sleepTime);
giuliomoro@217 296 #else
giuliomoro@217 297 for(unsigned int n=0; n<ReceiveAudioThread::objAddrs.size(); n++){
giuliomoro@217 298 // printf("%d\n", n);
giuliomoro@217 299 ReceiveAudioThread::objAddrs[n]->readUdpToBuffer();
giuliomoro@217 300 }
giuliomoro@217 301 usleep(sleepTime); //TODO: use rt_task_sleep instead
giuliomoro@217 302 #endif /* USE_JUCE */
giuliomoro@217 303 }
giuliomoro@217 304 threadRunning=false;
giuliomoro@217 305 printf("Thread is not running \n");
giuliomoro@217 306 // fprintf(fd,"];readPointer,writePointer,lastValidPointer,destination]=deal(var(:,1), var(:,2), var(:,3), var(:,4));"); //DEBUG
giuliomoro@217 307 // fclose(fd);//DEBUG
giuliomoro@217 308 // fprintf(fd2,"];");//DEBUG
giuliomoro@217 309 // fclose(fd2); //DEBUG
giuliomoro@217 310 }