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