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