]> git.sesse.net Git - c64tapwav/blob - decode.cpp
Add a program to sync up two stereo channels.
[c64tapwav] / decode.cpp
1 #include <stdio.h>
2 #include <string.h>
3 #include <math.h>
4 #include <unistd.h>
5 #include <assert.h>
6 #include <vector>
7 #include <algorithm>
8
9 #define LANCZOS_RADIUS 30
10 #define BUFSIZE 4096
11 #define HYSTERESIS_LIMIT 3000
12 #define SAMPLE_RATE 44100
13 #define C64_FREQUENCY 985248
14 #define TAP_RESOLUTION 8
15
16 #define SYNC_PULSE_START 1000
17 #define SYNC_PULSE_END 15000
18 #define SYNC_PULSE_LENGTH 380.0
19 #define SYNC_TEST_TOLERANCE 1.10
20
21 struct tap_header {
22         char identifier[12];
23         char version;
24         char reserved[3];
25         unsigned int data_len;
26 };
27
28 double sinc(double x)
29 {
30         if (fabs(x) < 1e-6) {
31                 return 1.0f - fabs(x);
32         } else {
33                 return sin(x) / x;
34         }
35 }
36
37 #if 0
38 double weight(double x)
39 {
40         if (fabs(x) > LANCZOS_RADIUS) {
41                 return 0.0f;
42         }
43         return sinc(M_PI * x) * sinc(M_PI * x / LANCZOS_RADIUS);
44 }
45 #else
46 double weight(double x)
47 {
48         if (fabs(x) > 1.0f) {
49                 return 0.0f;
50         }
51         return 1.0f - fabs(x);
52 }
53 #endif
54
55 double interpolate(const std::vector<short> &pcm, double i)
56 {
57         int lower = std::max<int>(ceil(i - LANCZOS_RADIUS), 0);
58         int upper = std::min<int>(floor(i + LANCZOS_RADIUS), pcm.size() - 1);
59         double sum = 0.0f;
60
61         for (int x = lower; x <= upper; ++x) {
62                 sum += pcm[x] * weight(i - x);
63         }
64         return sum;
65 }
66         
67 // between [x,x+1]
68 double find_zerocrossing(const std::vector<short> &pcm, int x)
69 {
70         if (pcm[x] == 0) {
71                 return x;
72         }
73         if (pcm[x + 1] == 0) {
74                 return x + 1;
75         }
76
77         assert(pcm[x + 1] > 0);
78         assert(pcm[x] < 0);
79
80         double lower = x;
81         double upper = x + 1;
82         while (upper - lower > 1e-6) {
83                 double mid = 0.5f * (upper + lower);
84                 if (interpolate(pcm, mid) > 0) {
85                         upper = mid;
86                 } else {
87                         lower = mid;
88                 }
89         }
90
91         return 0.5f * (upper + lower);
92 }
93
94 struct pulse {
95         double time;  // in seconds from start
96         double len;   // in seconds
97 };
98         
99 int main(int argc, char **argv)
100 {
101         std::vector<short> pcm;
102
103         while (!feof(stdin)) {
104                 short buf[BUFSIZE];
105                 ssize_t ret = fread(buf, 2, BUFSIZE, stdin);
106                 if (ret >= 0) {
107                         pcm.insert(pcm.end(), buf, buf + ret);
108                 }
109         }       
110
111 #if 0
112         for (int i = 0; i < LEN; ++i) {
113                 in[i] += rand() % 10000;
114         }
115 #endif
116
117 #if 0
118         for (int i = 0; i < LEN; ++i) {
119                 printf("%d\n", in[i]);
120         }
121 #endif
122
123         std::vector<pulse> pulses;  // in seconds
124
125         // Find the flanks.
126         int last_bit = -1;
127         double last_upflank = -1;
128         for (unsigned i = 0; i < pcm.size(); ++i) {
129                 int bit = (pcm[i] > 0) ? 1 : 0;
130                 if (bit == 1 && last_bit == 0) {
131                         // Check if we ever go up above HYSTERESIS_LIMIT before we dip down again.
132                         bool true_pulse = false;
133                         unsigned j;
134                         int max_level_after = -32768;
135                         for (j = i; j < pcm.size(); ++j) {
136                                 max_level_after = std::max<int>(max_level_after, pcm[j]);
137                                 if (pcm[j] < 0) break;
138                                 if (pcm[j] > HYSTERESIS_LIMIT) {
139                                         true_pulse = true;
140                                         break;
141                                 }
142                         }
143
144                         if (!true_pulse) {
145 #if 0
146                                 fprintf(stderr, "Ignored up-flank at %.6f seconds due to hysteresis (%d < %d).\n",
147                                         double(i) / SAMPLE_RATE, max_level_after, HYSTERESIS_LIMIT);
148 #endif
149                                 i = j;
150                                 continue;
151                         } 
152
153                         // up-flank!
154                         double t = find_zerocrossing(pcm, i - 1) * (1.0 / SAMPLE_RATE);
155                         if (last_upflank > 0) {
156                                 pulse p;
157                                 p.time = t;
158                                 p.len = t - last_upflank;
159                                 pulses.push_back(p);
160                         }
161                         last_upflank = t;
162                 }
163                 last_bit = bit;
164         }
165
166         // Calibrate on the first ~25k pulses (skip a few, just to be sure).
167         double calibration_factor = 1.0f;
168         if (pulses.size() < SYNC_PULSE_END) {
169                 fprintf(stderr, "Too few pulses, not calibrating!\n");
170         } else {
171                 double sum = 0.0;
172                 for (int i = SYNC_PULSE_START; i < SYNC_PULSE_END; ++i) {
173                         sum += pulses[i].len;
174                 }
175                 double mean_length = C64_FREQUENCY * sum / (SYNC_PULSE_END - SYNC_PULSE_START);
176                 calibration_factor = SYNC_PULSE_LENGTH / mean_length;
177                 fprintf(stderr, "Calibrated sync pulse length: %.2f -> 380.0 (change %+.2f%%)\n",
178                         mean_length, 100.0 * (calibration_factor - 1.0));
179
180                 // Check for pulses outside +/- 10% (sign of misdetection).
181                 for (int i = SYNC_PULSE_START; i < SYNC_PULSE_END; ++i) {
182                         double cycles = pulses[i].len * calibration_factor * C64_FREQUENCY;
183                         if (cycles < SYNC_PULSE_LENGTH / SYNC_TEST_TOLERANCE || cycles > SYNC_PULSE_LENGTH * SYNC_TEST_TOLERANCE) {
184                                 fprintf(stderr, "Sync cycle with upflank at %.6f was detected at %.0f cycles; misdetect?\n",
185                                         pulses[i].time, cycles);
186                         }
187                 }
188
189                 // Compute the standard deviation (to check for uneven speeds).
190                 double sum2 = 0.0;
191                 for (int i = SYNC_PULSE_START; i < SYNC_PULSE_END; ++i) {
192                         double cycles = pulses[i].len * calibration_factor * C64_FREQUENCY;
193                         sum2 += (cycles - SYNC_PULSE_LENGTH) * (cycles - SYNC_PULSE_LENGTH);
194                 }
195                 double stddev = sqrt(sum2 / (SYNC_PULSE_END - SYNC_PULSE_START - 1));
196                 fprintf(stderr, "Sync pulse length standard deviation: %.2f cycles\n",
197                         stddev);
198         }
199
200         FILE *fp = fopen("cycles.plot", "w");
201         std::vector<char> tap_data;
202         for (unsigned i = 0; i < pulses.size(); ++i) {
203                 double cycles = pulses[i].len * calibration_factor * C64_FREQUENCY;
204                 fprintf(fp, "%f %f\n", pulses[i].time, cycles);
205                 int len = lrintf(cycles / TAP_RESOLUTION);
206                 if (i > SYNC_PULSE_END && (cycles < 100 || cycles > 800)) {
207                         fprintf(stderr, "Cycle with upflank at %.6f was detected at %.0f cycles; misdetect?\n",
208                                         pulses[i].time, cycles);
209                 }
210                 if (len <= 255) {
211                         tap_data.push_back(len);
212                 } else {
213                         int overflow_len = lrintf(cycles);
214                         tap_data.push_back(0);
215                         tap_data.push_back(overflow_len & 0xff);
216                         tap_data.push_back((overflow_len >> 8) & 0xff);
217                         tap_data.push_back(overflow_len >> 16);
218                 }
219         }
220         fclose(fp);
221
222         tap_header hdr;
223         memcpy(hdr.identifier, "C64-TAPE-RAW", 12);
224         hdr.version = 1;
225         hdr.reserved[0] = hdr.reserved[1] = hdr.reserved[2] = 0;
226         hdr.data_len = tap_data.size();
227
228         fwrite(&hdr, sizeof(hdr), 1, stdout);
229         fwrite(tap_data.data(), tap_data.size(), 1, stdout);
230 }