8 #define LANCZOS_RADIUS 30
10 #define HYSTERESIS_LIMIT 1000
11 #define SAMPLE_RATE 44100
12 #define C64_FREQUENCY 985248
13 #define TAP_RESOLUTION 8
18 return 1.0f - fabs(x);
25 double weight(double x)
27 if (fabs(x) > LANCZOS_RADIUS) {
30 return sinc(M_PI * x) * sinc(M_PI * x / LANCZOS_RADIUS);
33 double weight(double x)
38 return 1.0f - fabs(x);
42 double interpolate(const std::vector<short> &pcm, double i)
44 int lower = std::max<int>(ceil(i - LANCZOS_RADIUS), 0);
45 int upper = std::min<int>(floor(i + LANCZOS_RADIUS), pcm.size() - 1);
48 for (int x = lower; x <= upper; ++x) {
49 sum += pcm[x] * weight(i - x);
55 double find_zerocrossing(const std::vector<short> &pcm, int x)
60 if (pcm[x + 1] == 0) {
64 assert(pcm[x + 1] > 0);
69 while (upper - lower > 1e-6) {
70 double mid = 0.5f * (upper + lower);
71 if (interpolate(pcm, mid) > 0) {
78 return 0.5f * (upper + lower);
81 int main(int argc, char **argv)
83 std::vector<short> pcm;
85 while (!feof(stdin)) {
87 ssize_t ret = fread(buf, 2, BUFSIZE, stdin);
89 pcm.insert(pcm.end(), buf, buf + ret);
94 for (int i = 0; i < LEN; ++i) {
95 in[i] += rand() % 10000;
100 for (int i = 0; i < LEN; ++i) {
101 printf("%d\n", in[i]);
105 std::vector<float> pulse_lengths; // in seconds
109 double last_upflank = -1;
110 int last_max_level = 0;
111 for (int i = 0; i < pcm.size(); ++i) {
112 int bit = (pcm[i] > 0) ? 1 : 0;
113 if (bit == 1 && last_bit == 0 && last_max_level > HYSTERESIS_LIMIT) {
115 double t = find_zerocrossing(pcm, i - 1) * (1.0 / SAMPLE_RATE);
116 if (last_upflank > 0) {
117 pulse_lengths.push_back(t - last_upflank);
122 last_max_level = std::max(last_max_level, abs(pcm[i]));
126 // Calibrate on the first ~15k pulses (skip a few, just to be sure).
127 float calibration_factor = 1.0f;
128 if (pulse_lengths.size() < 20000) {
129 fprintf(stderr, "Too few pulses, not calibrating!\n");
132 for (int i = 1000; i < 16000; ++i) {
133 sum += pulse_lengths[i];
135 double mean_length = C64_FREQUENCY * sum / 15000.0f;
136 calibration_factor = 380.0 / mean_length;
137 fprintf(stderr, "Cycle length: %.2f -> 380.0 (change %+.2f%%)\n",
138 mean_length, 100.0 * (calibration_factor - 1.0));
141 for (int i = 0; i < pulse_lengths.size(); ++i) {
142 int len = lrintf(pulse_lengths[i] * calibration_factor * C64_FREQUENCY / TAP_RESOLUTION);
143 //fprintf(stderr, "length: %f (0x%x)\n", t - last_upflank, len);
144 printf("0x%x\n", len);