accomodate possibility of random increase in time between send loops

This commit is contained in:
Stephen Birarda 2013-02-04 14:46:40 -08:00
parent 2b00a64324
commit 8035471fa4

View file

@ -21,8 +21,7 @@ const int UDP_PORT = 55443;
const int BUFFER_LENGTH_BYTES = 1024;
const int BUFFER_LENGTH_SAMPLES = BUFFER_LENGTH_BYTES / sizeof(int16_t);
const float SAMPLE_RATE = 22050.0;
const int SAMPLES_PER_PACKET = 512;
const float BUFFER_SEND_INTERVAL = (SAMPLES_PER_PACKET/SAMPLE_RATE) * 1000;
const float BUFFER_SEND_INTERVAL_USECS = (BUFFER_LENGTH_SAMPLES/SAMPLE_RATE) * 1000000;
const int MAX_SAMPLE_VALUE = std::numeric_limits<int16_t>::max();
const int MIN_SAMPLE_VALUE = std::numeric_limits<int16_t>::min();
@ -57,6 +56,10 @@ double diffclock(timeval clock1,timeval clock2)
return diffms;
}
double usecTimestamp(timeval *time, double addedUsecs = 0) {
return (time->tv_sec * 1000000.0) + time->tv_usec + addedUsecs;
}
int create_socket()
{
// Create socket
@ -139,28 +142,22 @@ void *send_buffer_thread(void *args)
int handle = buffer_args->socket_handle;
int sentBytes;
int currentSample = 1;
timeval firstSend;
timeval lastSend = {};
int currentFrame = 1;
timeval startTime;
timeval now;
int16_t *clientMix = new int16_t[BUFFER_LENGTH_SAMPLES];
int16_t *masterMix = new int16_t[BUFFER_LENGTH_SAMPLES];
gettimeofday(&firstSend, NULL);
gettimeofday(&now, NULL);
gettimeofday(&startTime, NULL);
while (true) {
while (lastSend.tv_sec != 0 && diffclock(lastSend, now) < BUFFER_SEND_INTERVAL) {
// loop here until we're allowed to send the buffer
gettimeofday(&now, NULL);
}
gettimeofday(&lastSend, NULL);
while (usecTimestamp(&startTime, (currentFrame * BUFFER_SEND_INTERVAL_USECS)) <= usecTimestamp(&now)) {
sentBytes = 0;
int sampleOffset = floor(diffclock(firstSend, now) * (SAMPLE_RATE / 1000) + 0.5);
sampleOffset = sampleOffset % whiteNoiseLength;
int sampleOffset = ((currentFrame - 1) * BUFFER_LENGTH_SAMPLES) % whiteNoiseLength;
memcpy(masterMix, whiteNoiseBuffer + sampleOffset, BUFFER_LENGTH_BYTES);
@ -195,6 +192,9 @@ void *send_buffer_thread(void *args)
}
}
currentFrame++;
}
}
pthread_exit(0);