comparison core/ReceiveAudioThread.cpp @ 235:3d41a6fa1830

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