-
Notifications
You must be signed in to change notification settings - Fork 3
/
buffer_operations.hpp
99 lines (86 loc) · 2.48 KB
/
buffer_operations.hpp
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
//
// Created by e on 6/18/20.
//
#ifndef WTTOOL_BUFFER_OPERATIONS_HPP
#define WTTOOL_BUFFER_OPERATIONS_HPP
#include "headers.hpp"
#include "interpolate.hpp"
namespace wttool {
vector<float> resample(const vector<float> &inBuf, int outputFrames,
const InterpFunc &interpFunc) {
vector<float> outBuf(outputFrames);
// double ratio = static_cast<double>(inBuf.size()) / static_cast<double>(outputFrames);
// ? hm.
double ratio = static_cast<double>(inBuf.size()-1) / static_cast<double>(outputFrames-1);
for (size_t outFrame = 0; outFrame < outputFrames; ++outFrame) {
outBuf[outFrame] = interpFunc(inBuf, outFrame, ratio);
}
std::cout << "resampled " << inBuf[inBuf.size()-1] << " to " << outBuf[outputFrames-1] << "\n";
return outBuf;
}
// convert float vector to position-delta format, returning new vector of 2x size
vector<float> convertToScWavetable(vector<float> in) {
size_t framesIn = in.size();
size_t framesOut = framesIn * 2;
vector<float> out(framesOut);
const float *src = in.data();
float *dst = out.data();
for (size_t i = 0; i < framesIn; ++i) {
float a = src[i];
float b = src[(i+1) % framesIn];
*dst++ = 2.f * a - b;
*dst++ = b - a;
}
// hm.. no difference, as expected
// (this is how it's written in SC sources)
// int imax = framesIn - 1;
// float val1, val2;
// int i;
// dst -= 1;
// for (i = 0; i < imax; ++i) {
// val1 = in[i];
// val2 = in[i + 1];
// *++dst = 2.f * val1 - val2;
// *++dst = val2 - val1;
// }
// val1 = in[imax];
// val2 = in[0];
// *++dst = 2.f * val1 - val2;
// *++dst = val2 - val1;
return out;
}
size_t nextPowerOfTwo(size_t x) {
size_t y = x;
while ((y & (y - 1)) != 0) {
++y;
}
return y;
}
// helper
bool isNearZero(float x) {
return std::fabs(x) <= (std::numeric_limits<float>::epsilon() * 2);
}
// trim beginning and end of float vector to first occurrence of "near zero"
// returns a new vector
vector<float> trimToZeros(const vector<float> &inBuf) {
size_t start = 0;
size_t end = inBuf.size() - 1;
while (!isNearZero(inBuf[start])) {
++start;
}
while (!isNearZero(inBuf[end])) {
--end;
}
size_t len = end - start;
if (len < 1) {
return inBuf;
}
auto outBuf = vector<float>(len);
int i = 0;
for (int frame = start; frame < end; ++frame) {
outBuf[i] = inBuf[frame];
}
return outBuf;
}
}
#endif // WTTOOL_BUFFER_OPERATIONS_HPP