-
Notifications
You must be signed in to change notification settings - Fork 0
/
ir2h.cpp
93 lines (78 loc) · 2.09 KB
/
ir2h.cpp
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
// Copyright (C) 2014-2021 Theo Niessink <[email protected]>
// This work is free. You can redistribute it and/or modify it under the
// terms of the Do What The Fuck You Want To Public License, Version 2,
// as published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
#include <math.h>
#include <stdio.h>
#include "WDL/wavread.h"
int error(const char* str, int err)
{
fputs(str, stderr);
return err;
}
int main(int argc, char* argv[])
{
if (argc < 3 || argc > 4)
{
printf("Usage: %s <input WAV file> <mono/left channel output C header file>\n"
" [<right channel output C header file>]\n", argv[0]);
return 1;
}
WaveReader wav;
unsigned int len;
if (!(wav.Open(argv[1]) && (len = wav.GetLength())))
{
return error("Error: Can't open WAV file\n", 2);
}
int nch = argc > 3 ? 2 : 1;
if (nch != wav.get_nch())
{
fputs("Warning: Mono/stereo mismatch\n", stderr);
if (nch > wav.get_nch()) nch = wav.get_nch();
}
FILE* out[2];
for (int i = 0; i < nch; ++i)
{
char* fn = argv[i + 2];
printf("%s (%u samples)\n", fn, len);
out[i] = fopen(fn, "wb");
if (!out[i]) return error("Error: Can't create C header file\n", 3);
}
for (int i = 0; i < nch; ++i)
{
fprintf(out[i], "/* %u samples */\n", len);
}
float buf[2][64], * const pp[2] = { buf[0], buf[1] };
while (len > 0)
{
unsigned int n = len;
if (n > 64) n = 64;
if (wav.ReadFloatsNI((float**)pp, 0, n, nch) < n)
{
return error("Error: Can't read WAV file\n", 4);
}
for (int i = 0; i < nch; ++i)
{
for (unsigned int j = 0; j < n;)
{
const double x = (double)buf[i][j], a = fabs(x);
if (a > 0.0)
{
const double e = floor(log10(a));
fprintf(out[i], "%.8f", x / pow(10.0, e));
if (e != 0.0) fprintf(out[i], "e%+.f", e);
}
else
{
fprintf(out[i], "%.1f", x);
}
putc('f', out[i]);
if (++j < len) putc(',', out[i]);
if (!(j & 3) || j >= len) putc('\n', out[i]);
}
}
len -= n;
}
for (int i = 0; i < nch; ++i) fclose(out[i]);
return 0;
}