-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.c
More file actions
487 lines (415 loc) · 13.6 KB
/
main.c
File metadata and controls
487 lines (415 loc) · 13.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
/*
* BeatTracker main driver
* To be used for DARwIn Dance Synthesis Project.
* Code originally by David Grunberg (spring 2012)
* Revised by Mark Koh (winter 2014)
*
* Description:
* This program reads an input signal from the line in port on DARwIn (hopefully this
* will be extended to microphone as well) and tracks the beats in it. When the porgram
* recieves a beat, it sends a UDP packet to localhost at port 9930, where the
* DanceSynth application will recieve it.
*
* Currently, the DanceSynth program will spawn a process of this application so that
* they do not need to be run separately. This application may be run standalone, however.
*
* **PortAudio**
* This program uses the PortAudio Portable Audio Library.
* For more information see: http://www.portaudio.com
* Copyright (c) 1999-2000 Ross Bencina and Phil Burk
*
*/
//MATLAB BEAT TRACKER
// Standard Libraries
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <time.h>
#include <stdbool.h>
// Our libraries
#include "portaudio.h"
#include "BeatTrackerMath.h"
#include "BeatTracker.h"
#include "InitializeBeatVariables.h"
// UDP settings
#define BUFLEN 70
#define NPACK 1000
#define PORT 9930
#define SRV_IP "127.0.0.1"
// Useful definitions
#define PI (3.14159265)
//PortAudio definitions
#define SAMPLE_RATE (44100)
#define FRAMES_PER_BUFFER (512)
#define NUM_CHANNELS (2)
/* #define DITHER_FLAG (paDitherOff) */
#define DITHER_FLAG (0) /**/
// Input and output devices. This may change to a reference instead of a macro
// THIS IS SOMEHOW THE ISSUE
#define INPUT_DEVICE (Pa_GetDefaultInputDevice())
//#define INPUT_DEVICE (1)
#define OUTPUT_DEVICE (Pa_GetDefaultOutputDevice())
//Change these values if you want to use a short input/output instead of a float
#define USE_FLOAT_INPUT (1)
#define USE_FLOAT_OUTPUT (1)
#if USE_FLOAT_INPUT
#define INPUT_FORMAT paFloat32
typedef float INPUT_SAMPLE;
#else
#define INPUT_FORMAT paInt16
typedef short INPUT_SAMPLE;
#endif
#if USE_FLOAT_OUTPUT
#define OUTPUT_FORMAT paFloat32
typedef float OUTPUT_SAMPLE;
#else
#define OUTPUT_FORMAT paInt16
typedef short OUTPUT_SAMPLE;
#endif
#define PA_SAMPLE_TYPE paFloat32
typedef float SAMPLE;
#define SAMPLE_SILENCE (0.0f)
#define PRINTF_S_FORMAT "%.8f"
#define NUM_SECONDS (5)
// Macro functions (used for wire callback. Way faster than function poiters)
#define CONVERT_IN_TO_OUT(in) ((OUTPUT_SAMPLE) ((in) * gInOutScaler))
// Declare our global variables
int beatHere;
int lastBeatLocation[2];
int beatDifferences;
int beatDifferencesO;
int beatDifferencesx[3];
int beatSend;
double TimeVar;
//Set up a scaling variable
double gInOutScaler = 1.0;
struct sockaddr_in si_other;
int s, slen=sizeof(si_other);
char buf[BUFLEN];
char buf3[2];
int myIndex;
int GesBuf[700]; //changed from 300 size to 700 sizei
int GesBuf2[30000];
struct timeval currentTime;
// Function prototypes
static PaError TestConfiguration();
static int wireCallback( const void *inputBuffer,
void *outputBuffer,
unsigned long framesPerBuffer,
const PaStreamCallbackTimeInfo* timeInfo,
PaStreamCallbackFlags statusFlags,
void *userData );
int SoundIsDone();
int ErrorOccurred(PaError err);
void initBeatTracker();
void printStreamParameters(const PaStreamParameters _params);
void printDeviceInfo(const PaDeviceInfo *device);
/***********************************************************************************************/
/* Main Program Execution */
/***********************************************************************************************/
// Our main function
int main(int argc, char** argv) {
printf("Sanity check...\n");
PaError err = paNoError;
//Initialize BeatTracker data
initBeatTracker();
s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
memset((char *) &si_other, 0, sizeof(si_other));
si_other.sin_family = AF_INET;
si_other.sin_port = htons(PORT);
if (inet_aton(SRV_IP, &si_other.sin_addr)==0) {
fprintf(stderr, "inet_aton() failed\n");
exit(1);
}
//We can use this when trying to change input devices
printf("Default input device: %d, Output: %d\n",(int) INPUT_DEVICE, (int) OUTPUT_DEVICE);
err = TestConfiguration();
//If we've made it here, then we're done tracking and everything is healthy
err = paNoError;
//Terminate PortAudio and exit
Pa_Terminate();
printf("Done tracking.\n");
fflush(stdout);
return 0;
}
/*
* This is the big function of the program. This function will be called
* whenever PortAudio need audio. The BeatTracker then adds the current
* sample and checks if it's a beat. If it is, then a packet is sent to the
* server.
*/
typedef struct
{
int frameIndex; /* Index into sample array. */
int maxFrameIndex;
SAMPLE *recordedSamples;
}
paTestData;
static int wireCallback( const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags, void *userData ) {
paTestData *data = (paTestData*)userData;
INPUT_SAMPLE *in;
//const SAMPLE *rptr = (const SAMPLE*)inputBuffer;
// SAMPLE *wptr = &data->recordedSamples[data->frameIndex * NUM_CHANNELS];
long framesToCalc;
long i;
int finished;
unsigned long framesLeft = data->maxFrameIndex - data->frameIndex;
int inStride;
int inChannel = 0;
time_t tStart = clock();
(void) outputBuffer; /* Prevent unused variable warnings. */
(void) timeInfo;
(void) statusFlags;
(void) userData;
in = (INPUT_SAMPLE*)inputBuffer;
inStride = 1;
BeatTrackFrame(in, beatHere);
//Check if we have a beat (the set some stuff)
if (beatPing==1){
//Put a click in the frame
in[0]=1;
lastBeatLocation[0] = lastBeatLocation[1];
lastBeatLocation[1] = fNum;
beatDifferences = lastBeatLocation[1]-lastBeatLocation[0];
beatDifferencesx[0] = beatDifferences;
beatDifferencesx[1] = beatDifferences*2;
beatDifferencesx[2] = beatDifferences*3;
}
//If we're 200 frames in (make sure we don't start too early)
if (fNum>200)
{
// Make sure this is a frame where we want to start the robot gesture (start halfway between beats)
if ((fNum==lastBeatLocation[1]+beatDifferencesx[0]/2)) //&& beatDifferences>40 && beatDifferences<60 && fNum-lastBeatLocation[1]>=61)
{
if (beatDifferences<24)
{
// beatDifferences=beatDifferences*2;
}
//Get beat difference in terms of second (change 1024 to frames per buffer?)
beatDifferencesO = round((double) (beatDifferences-4)*1024.0/44100.0*100.0);
buf[0]=255;
buf[1]=103;
buf[2]=114;
buf[3]=beatDifferencesO;
if (beatDifferences>=17 && fNum-beatSend>15)
{
buf[4] = GesBuf2[myIndex];
myIndex=myIndex+1;
buf3[0] = 255;
buf3[1] = 116;
//This may be a flag which is always on
if (buf[4]>1)
{
sendto(s, buf3, 2, 0, (struct sockaddr *)&si_other, slen);
beatSend = fNum;
//printf("Sent UDP packet.\n\n");
}
//printf("Time Diff: %f\n", (double)Pa_GetStreamTime());
//tStart=clock();
}
}
}
finished = paContinue;
printf("Dancing");
return finished;
}
//Initialize the BeatTracker data. This function needs a lot of revision
void initBeatTracker(){
//Some general initialization stuff
InitializeBeatVariables();
lastBeatLocation[0] = 0;
lastBeatLocation[1] = 0;
beatDifferences = 0;
beatSend = 0;
//Not sure what the hell this is.
//Try removing this (once beatTracker is working)
GesBuf[0]=47;
GesBuf[1]=47;
GesBuf[2]=47;
GesBuf[3]=47;
GesBuf[4]=47;
GesBuf[5]=47;
GesBuf[6]=47;
GesBuf[7]=47;
GesBuf[8]=47;
GesBuf[9]=47;
GesBuf[10]=48;
GesBuf[11]=48;
GesBuf[12]=48;
GesBuf[13]=48;
GesBuf[14]=48;
GesBuf[15]=48;
GesBuf[16]=48;
GesBuf[17]=48;
GesBuf[18]=49;
GesBuf[19]=50;
GesBuf[20]=49;
GesBuf[21]=50;
GesBuf[22]=49;
GesBuf[23]=50;
GesBuf[24]=49;
GesBuf[25]=50;
GesBuf[26]=47;
GesBuf[27]=47;
GesBuf[28]=47;
GesBuf[29]=47;
GesBuf[30]=47;
GesBuf[31]=47;
GesBuf[32]=47;
GesBuf[33]=47;
GesBuf[34]=47;
GesBuf[35]=47;
GesBuf[36]=47;
GesBuf[37]=47;
GesBuf[38]=47;
GesBuf[39]=48;
GesBuf[40]=48;
GesBuf[41]=48;
GesBuf[42]=48;
GesBuf[43]=48;
GesBuf[44]=48;
GesBuf[45]=48;
GesBuf[46]=48;
GesBuf[47]=49;
GesBuf[48]=50;
GesBuf[49]=49;
GesBuf[50]=50;
GesBuf[51]=49;
GesBuf[52]=50;
GesBuf[53]=49;
GesBuf[54]=50;
myIndex=0;
//Erm, fill this one in too?
for (myIndex=0;myIndex<30000;myIndex++) {
if (fmod(myIndex,2)==0)
{
GesBuf2[myIndex]=51;
}
else
{
GesBuf2[myIndex]=52;
}
}
myIndex=0;
}
static PaError TestConfiguration( )
{
int c;
PaError err = paNoError;
PaStream* stream;
PaStreamParameters inputParameters, outputParameters;
paTestData data;
int i;
int totalFrames;
int numSamples;
int numBytes;
SAMPLE max, val;
double average;
// Print info for all available devices
data.maxFrameIndex = totalFrames = NUM_SECONDS * SAMPLE_RATE; /* Record for a few seconds. */
data.frameIndex = 0;
numSamples = totalFrames * NUM_CHANNELS;
numBytes = numSamples * sizeof(SAMPLE);
data.recordedSamples = (SAMPLE *) malloc( numBytes ); /* From now on, recordedSamples is initialised. */
if( data.recordedSamples == NULL )
{
printf("Could not allocate record array.\n");
}
for( i=0; i<numSamples; i++ ) data.recordedSamples[i] = 0;
err = Pa_Initialize();
int deviceCount = Pa_GetDeviceCount();
printf("Number of devices: %d\n", deviceCount);
//Errors with the audio input
inputParameters.device = Pa_GetDefaultInputDevice(); /* default input device */
//inputParameters.device = 1;
/*printf("Default Device: %d\n", Pa_GetDefaultInputDevice());
*/
if (inputParameters.device == paNoDevice) {
fprintf(stderr,"Error: No default input device.\n");
return err;
}
inputParameters.channelCount = 2; /* stereo input */
inputParameters.sampleFormat = PA_SAMPLE_TYPE;
inputParameters.suggestedLatency = Pa_GetDeviceInfo( inputParameters.device )->defaultLowInputLatency;
inputParameters.hostApiSpecificStreamInfo = NULL;
// Issue somewhere here too
printStreamParameters(inputParameters);
//printStreamParameters(outputParameters);
//Errors with the stream
err = Pa_OpenStream(
&stream,
&inputParameters,
NULL,
SAMPLE_RATE,
FRAMES_PER_BUFFER, /* frames per buffer */
paClipOff,
wireCallback,
&data );
if( err != paNoError ) {
printf("Error opening stream\n");
return err;
}
printf("Stream open\n");
//Can't open the stream
err = Pa_StartStream( stream );
if( err != paNoError ) {
printf("Error starting stream\n");
return err;
}
printf("Stream started\n");
//Wait for a character from the command line. If it's enter, this will return.
c = getchar();
//Can't close the stream
printf("Closing stream.\n");
err = Pa_CloseStream( stream );
if( err != paNoError )
return err;
//If the enter key's pressed, return and stop tracking
if( c == 'q' ) return 1;
}
void printStreamParameters(const PaStreamParameters _params) {
printf("\n");
printf("device = %s\n", Pa_GetDeviceInfo(_params.device)->name);
printf("channelCount = %d\n", _params.channelCount);
printf("sampleFormat = ");
bool flagTrue = false;
bool lastTrue = false;
flagTrue = _params.sampleFormat & paFloat32;
printf("%s", flagTrue ? "paFloat32" : "\b\b\b ");
lastTrue = flagTrue;
flagTrue = _params.sampleFormat & paInt32;
printf("%s%s", lastTrue ? " | " : "", flagTrue ? "paInt32" : "");
lastTrue = flagTrue;
flagTrue = _params.sampleFormat & paInt24;
printf("%s%s", lastTrue ? " | " : "", flagTrue ? "paInt24" : "");
lastTrue = flagTrue;
flagTrue = _params.sampleFormat & paInt16;
printf("%s%s", lastTrue ? " | " : "", flagTrue ? "paInt16" : "");
lastTrue = flagTrue;
flagTrue = _params.sampleFormat & paInt8;
printf("%s%s", lastTrue ? " | " : "", flagTrue ? "paInt8" : "");
lastTrue = flagTrue;
flagTrue = _params.sampleFormat & paCustomFormat;
printf("%s%s", lastTrue ? " | " : "", flagTrue ? "paCustomFormat" : "");
lastTrue = flagTrue;
flagTrue = _params.sampleFormat & paNonInterleaved;
printf("%s%s", lastTrue ? " | " : "", flagTrue ? "paNonInterleaved" : "");
printf("\n");
printf("suggestedLatency = %f\n", _params.suggestedLatency);
printf("\n");
}
void printDeviceInfo(const PaDeviceInfo *device) {
printf( "Name = %s\n", device->name);
printf( "Host API = %s\n", Pa_GetHostApiInfo(device->hostApi)->name);
printf( "Max inputs = %d\n", device->maxInputChannels);
printf( "Max outputs = %d\n", device->maxOutputChannels);
printf( "Default low input latency = %8.4f\n", device->defaultLowInputLatency);
printf( "Default low output latency = %8.4f\n", device->defaultLowOutputLatency);
printf( "Default high input latency = %8.4f\n", device->defaultHighInputLatency);
printf( "Default high output latency = %8.4f\n", device->defaultHighOutputLatency);
}