-
Notifications
You must be signed in to change notification settings - Fork 0
/
audio.c
130 lines (111 loc) · 2.61 KB
/
audio.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 <pulse/simple.h>
#include <pulse/error.h>
#define BUFSIZE 32
#define RATE 1000
#define AUDIO_DELAY 4000
// How fast is dropoff?
#define START_SLANT 0.001
// How fast is max dropoff?
#define MAX_SLANT 0.05
// How fast should we ramp up?
#define MAX_ACCEL 0.08
// What minimum floor should we ignore?
#define NOISE_FLOOR 0.15
// For outputting peak levels instead of exact current amplitude
#define PEAK true
// Audio buffer tracking
int16_t buffer[BUFSIZE];
static pa_simple *s = NULL;
int pulseaudio_standby(int sfreq, void *dummy) {
return 0;
}
int pulseaudio_begin(char *arg) {
int error;
static const pa_sample_spec ss = {
.format = PA_SAMPLE_S16LE,
.rate = RATE,
.channels = 1
};
if (!(s = pa_simple_new(NULL, "Boguspath", PA_STREAM_RECORD, NULL, "record", &ss, NULL, NULL, &error))) {
printf("Error: pulseaudio: pa_simple_new() failed: %s\n", pa_strerror(error));
return 1;
}
return 0;
}
int pulseaudio_end() {
if (s != NULL) {
pa_simple_free(s);
s = NULL;
}
return 0;
}
int pulseaudio_read (int16_t *buf, int sampnum) {
int error;
int cnt, bufsize;
bufsize = sampnum * sizeof(int16_t);
if (bufsize > BUFSIZE) bufsize = BUFSIZE;
if (pa_simple_read(s, buf, bufsize, &error) < 0) {
printf("Error: pa_simple_read() failed: %s\n", pa_strerror(error));
}
cnt = bufsize / sizeof(int16_t);
return (cnt);
}
/* Ended up not needing to do this? */
/*
int flush() {
int error;
pa_simple_flush(s, &error);
}
*/
void* amplitude(void* arg) {
double result = 0.0;
int time_since_peak = 0;
double peak = 0.0;
double slant = 0.0;
double remaining = 0.0;
while(1) {
pulseaudio_read(buffer, 32);
result = 0;
for(int i = 0; i < 32; i++) {
result += abs(buffer[i]);
}
result /= BUFSIZE;
result = log(result);
result /= 4.5;
result -= 1.0;
#ifdef PEAK
if (result >= peak && result >= NOISE_FLOOR) {
if (peak + MAX_ACCEL > result) {
peak += MAX_ACCEL;
remaining = result - MAX_ACCEL;
} else {
peak = result;
}
time_since_peak = 0;
} else if (remaining > 0.0) {
peak += MAX_ACCEL;
remaining -= MAX_ACCEL;
} else {
time_since_peak += 1;
if (peak < 0.0) {
peak = 0.0;
} else {
slant = peak * START_SLANT * time_since_peak;
if (slant >= MAX_SLANT) {
slant = MAX_SLANT;
}
peak -= slant;
}
}
printf("u_amp,%f\n", peak);
#else
printf("u_amp,%f\n", result);
#endif
usleep(AUDIO_DELAY);
}
}