forked from cpuimage/WebRTC_AGC
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
268 lines (241 loc) · 7.81 KB
/
main.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
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
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
//采用https://github.com/mackron/dr_libs/blob/master/dr_wav.h 解码
#define DR_WAV_IMPLEMENTATION
#include "dr_wav.h"
#include "agc.h"
#ifndef nullptr
#define nullptr 0
#endif
#ifndef MIN
#define MIN(A, B) ((A) < (B) ? (A) : (B))
#endif
//计时
#include <stdint.h>
#if defined(__APPLE__)
# include <mach/mach_time.h>
#elif defined(_WIN32)
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
#else // __linux
# include <time.h>
# ifndef CLOCK_MONOTONIC //_RAW
# define CLOCK_MONOTONIC CLOCK_REALTIME
# endif
#endif
static
uint64_t nanotimer() {
static int ever = 0;
#if defined(__APPLE__)
static mach_timebase_info_data_t frequency;
if (!ever) {
if (mach_timebase_info(&frequency) != KERN_SUCCESS) {
return 0;
}
ever = 1;
}
return 0;
#elif defined(_WIN32)
static LARGE_INTEGER frequency;
if (!ever) {
QueryPerformanceFrequency(&frequency);
ever = 1;
}
LARGE_INTEGER t;
QueryPerformanceCounter(&t);
return (t.QuadPart * (uint64_t) 1e9) / frequency.QuadPart;
#else // __linux
struct timespec t;
if (!ever) {
if (clock_gettime(CLOCK_MONOTONIC, &t) != 0) {
return 0;
}
ever = 1;
}
clock_gettime(CLOCK_MONOTONIC, &t);
return (t.tv_sec * (uint64_t)1e9) + t.tv_nsec;
#endif
}
static double now() {
static uint64_t epoch = 0;
if (!epoch) {
epoch = nanotimer();
}
return (nanotimer() - epoch) / 1e9;
};
double calcElapsed(double start, double end) {
double took = -start;
return took + end;
}
//写wav文件
void wavWrite_int16(char *filename, int16_t *buffer, size_t sampleRate, size_t totalSampleCount, unsigned int channels) {
drwav_data_format format = {};
format.container = drwav_container_riff; // <-- drwav_container_riff = normal WAV files, drwav_container_w64 = Sony Wave64.
format.format = DR_WAVE_FORMAT_PCM; // <-- Any of the DR_WAVE_FORMAT_* codes.
format.channels = channels;
format.sampleRate = (drwav_uint32) sampleRate;
format.bitsPerSample = 16;
drwav *pWav = drwav_open_file_write(filename, &format);
if (pWav) {
drwav_uint64 samplesWritten = drwav_write(pWav, totalSampleCount, buffer);
drwav_uninit(pWav);
if (samplesWritten != totalSampleCount) {
fprintf(stderr, "ERROR\n");
exit(1);
}
}
}
//读取wav文件
int16_t *wavRead_int16(char *filename, uint32_t *sampleRate, uint64_t *totalSampleCount, unsigned int* channels) {
int16_t *buffer = drwav_open_and_read_file_s16(filename, channels, sampleRate, totalSampleCount);
if (buffer == nullptr) {
printf("读取wav文件失败.");
}
return buffer;
}
//分割路径函数
void splitpath(const char *path, char *drv, char *dir, char *name, char *ext) {
const char *end;
const char *p;
const char *s;
if (path[0] && path[1] == ':') {
if (drv) {
*drv++ = *path++;
*drv++ = *path++;
*drv = '\0';
}
} else if (drv)
*drv = '\0';
for (end = path; *end && *end != ':';)
end++;
for (p = end; p > path && *--p != '\\' && *p != '/';)
if (*p == '.') {
end = p;
break;
}
if (ext)
for (s = end; (*ext = *s++);)
ext++;
for (p = end; p > path;)
if (*--p == '\\' || *p == '/') {
p++;
break;
}
if (name) {
for (s = p; s < end;)
*name++ = *s++;
*name = '\0';
}
if (dir) {
for (s = path; s < p;)
*dir++ = *s++;
*dir = '\0';
}
}
int agcProcess(int16_t *buffer, uint32_t sampleRate, size_t samplesCount, int16_t agcMode) {
if (buffer == nullptr) return -1;
if (samplesCount == 0) return -1;
WebRtcAgcConfig agcConfig;
agcConfig.compressionGaindB = 9; // default 9 dB
agcConfig.limiterEnable = 1; // default kAgcTrue (on)
agcConfig.targetLevelDbfs = 3; // default 3 (-3 dBOv)
int minLevel = 0;
int maxLevel = 255;
size_t samples = MIN(160, sampleRate / 100);
if (samples == 0) return -1;
const int maxSamples = 320;
int16_t *input = buffer;
size_t nTotal = (samplesCount / samples);
void *agcInst = WebRtcAgc_Create();
if (agcInst == NULL) return -1;
int status = WebRtcAgc_Init(agcInst, minLevel, maxLevel, agcMode, sampleRate);
if (status != 0) {
printf("WebRtcAgc_Init fail\n");
WebRtcAgc_Free(agcInst);
return -1;
}
status = WebRtcAgc_set_config(agcInst, agcConfig);
if (status != 0) {
printf("WebRtcAgc_set_config fail\n");
WebRtcAgc_Free(agcInst);
return -1;
}
size_t num_bands = 1;
int inMicLevel, outMicLevel = -1;
int16_t out_buffer[maxSamples];
int16_t *out16 = out_buffer;
uint8_t saturationWarning = 1; //是否有溢出发生,增益放大以后的最大值超过了65536
int16_t echo = 0; //增益放大是否考虑回声影响
for (int i = 0; i < nTotal; i++) {
inMicLevel = 0;
int nAgcRet = WebRtcAgc_Process(agcInst, (const int16_t *const *) &input, num_bands, samples,
(int16_t *const *) &out16, inMicLevel, &outMicLevel, echo,
&saturationWarning);
if (nAgcRet != 0) {
printf("failed in WebRtcAgc_Process\n");
WebRtcAgc_Free(agcInst);
return -1;
}
memcpy(input, out_buffer, samples * sizeof(int16_t));
input += samples;
}
const size_t remainedSamples = samplesCount - nTotal * samples;
if (remainedSamples > 0) {
if (nTotal > 0) {
input = input - samples + remainedSamples;
}
inMicLevel = 0;
int nAgcRet = WebRtcAgc_Process(agcInst, (const int16_t *const *) &input, num_bands, samples,
(int16_t *const *) &out16, inMicLevel, &outMicLevel, echo,
&saturationWarning);
if (nAgcRet != 0) {
printf("failed in WebRtcAgc_Process during filtering the last chunk\n");
WebRtcAgc_Free(agcInst);
return -1;
}
memcpy(&input[samples-remainedSamples], &out_buffer[samples-remainedSamples], remainedSamples * sizeof(int16_t));
input += samples;
}
WebRtcAgc_Free(agcInst);
return 1;
}
void auto_gain(char *in_file, char *out_file) {
//音频采样率
uint32_t sampleRate = 0;
//总音频采样数
uint64_t inSampleCount = 0;
unsigned int channels = 0;
int16_t *inBuffer = wavRead_int16(in_file, &sampleRate, &inSampleCount, &channels);
//如果加载成功
if (inBuffer != nullptr) {
// kAgcModeAdaptiveAnalog 模拟音量调节
// kAgcModeAdaptiveDigital 自适应增益
// kAgcModeFixedDigital 固定增益
double startTime = now();
agcProcess(inBuffer, sampleRate, inSampleCount, kAgcModeAdaptiveDigital);
double elapsed_time = calcElapsed(startTime, now());
printf("time: %d ms\n ", (int) (elapsed_time * 1000));
wavWrite_int16(out_file, inBuffer, sampleRate, inSampleCount, channels);
free(inBuffer);
}
}
int main(int argc, char *argv[]) {
printf("WebRTC Automatic Gain Control\n");
printf("博客:http://cpuimage.cnblogs.com/\n");
printf("音频自动增益\n");
if (argc < 2)
return -1;
char *in_file = argv[1];
char drive[3];
char dir[256];
char fname[256];
char ext[256];
char out_file[1024];
splitpath(in_file, drive, dir, fname, ext);
sprintf(out_file, "%s%s%s_out%s", drive, dir, fname, ext);
auto_gain(in_file, out_file);
printf("按任意键退出程序 \n");
getchar();
return 0;
}