-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbeat.c
130 lines (110 loc) · 2.36 KB
/
beat.c
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
#include <stdio.h>
#include <stddef.h>
#include <unistd.h>
#include <stdlib.h>
#include <math.h>
#include <sys/time.h>
#define BEAT_DELAY 40000
// Beat tracking variables
float bpm;
float uspb;
int beat_type = 2;
void set_beat_type(int t) {
beat_type = t;
}
float calc_uspb(float b) {
return 1000000.0 / (b / 60.0);
}
void set_uspb(float u) {
uspb = u;
bpm = 1000000.0 * 60 / u;
}
void set_bpm(float b) {
bpm = b;
uspb = calc_uspb(bpm);
}
void bpm_double() {
bpm *= 2.0;
uspb = calc_uspb(bpm);
}
void bpm_halve() {
bpm *= 0.5;
uspb = calc_uspb(bpm);
}
void bpm_increase() {
bpm += 2.0;
uspb = calc_uspb(bpm);
}
void bpm_decrease() {
bpm -= 2.0;
uspb = calc_uspb(bpm);
}
void bpm_default() {
bpm = 120.0;
uspb = calc_uspb(bpm);
}
/* The main beat loop */
void* beat(void* arg) {
struct timeval beat, current, dt;
float us_passed;
float beat_value = 1.0;
float beat_progress = 0.0;
gettimeofday(&beat, NULL);
while(1) {
gettimeofday(¤t, NULL);
timersub(¤t, &beat, &dt);
us_passed = dt.tv_sec * 1000000 + dt.tv_usec;
beat_progress = us_passed / uspb;
switch(beat_type) {
case 1:
// Sawtooth down
if (beat_progress > 1.0) {
beat = current;
beat_value = 1.0;
} else {
beat_value = 1.0 - beat_progress;
}
break;
case 2:
// Sawtooth up
if (beat_progress > 1.0) {
beat = current;
beat_value = 1.0;
} else {
beat_value = beat_progress;
}
break;
case 3:
// Sine wave
if (beat_progress > 1.0) {
beat = current;
beat_value = 1.0;
} else {
// normalize a sin wave between 0.0 and 1.0 that peaks at the beat
beat_value = (cos(beat_progress * 2.0 * M_PI) + 1.0) / 2.0;
}
break;
case 4:
// Triangle
if (beat_progress > 1.0) {
beat = current;
beat_value = 1.0;
} else {
if (beat_progress > 0.5) {
beat_value = beat_progress;
} else {
beat_value = 1.0 - beat_progress;
}
beat_value -= 0.5;
beat_value *= 2.0;
}
break;
}
#if DEBUG
printf("uspb is %f\n", uspb);
#else
printf("u_beat,%f\n", beat_value);
#endif
usleep(BEAT_DELAY);
}
}