]> git.sesse.net Git - c64tapwav/blob - decode.cpp
Add support for filtering the waveform before detection.
[c64tapwav] / decode.cpp
1 #include <stdio.h>
2 #include <string.h>
3 #include <math.h>
4 #include <assert.h>
5 #include <limits.h>
6 #include <getopt.h>
7 #include <vector>
8 #include <algorithm>
9
10 #include "audioreader.h"
11 #include "interpolate.h"
12 #include "tap.h"
13
14 #define BUFSIZE 4096
15 #define C64_FREQUENCY 985248
16 #define SYNC_PULSE_START 1000
17 #define SYNC_PULSE_END 20000
18 #define SYNC_PULSE_LENGTH 378.0
19 #define SYNC_TEST_TOLERANCE 1.10
20
21 #define NUM_FILTER_COEFF 32
22
23 static float hysteresis_limit = 3000.0 / 32768.0;
24 static bool do_calibrate = true;
25 static bool output_cycles_plot = false;
26 static bool use_filter = false;
27 static float filter_coeff[NUM_FILTER_COEFF] = { 1.0f };  // The rest is filled with 0.
28 static bool output_filtered = false;
29
30 // between [x,x+1]
31 double find_zerocrossing(const std::vector<float> &pcm, int x)
32 {
33         if (pcm[x] == 0) {
34                 return x;
35         }
36         if (pcm[x + 1] == 0) {
37                 return x + 1;
38         }
39
40         assert(pcm[x + 1] < 0);
41         assert(pcm[x] > 0);
42
43         double upper = x;
44         double lower = x + 1;
45         while (lower - upper > 1e-3) {
46                 double mid = 0.5f * (upper + lower);
47                 if (lanczos_interpolate(pcm, mid) > 0) {
48                         upper = mid;
49                 } else {
50                         lower = mid;
51                 }
52         }
53
54         return 0.5f * (upper + lower);
55 }
56
57 struct pulse {
58         double time;  // in seconds from start
59         double len;   // in seconds
60 };
61
62 // Calibrate on the first ~25k pulses (skip a few, just to be sure).
63 double calibrate(const std::vector<pulse> &pulses) {
64         if (pulses.size() < SYNC_PULSE_END) {
65                 fprintf(stderr, "Too few pulses, not calibrating!\n");
66                 return 1.0;
67         }
68
69         int sync_pulse_end = -1;
70         double sync_pulse_stddev = -1.0;
71
72         // Compute the standard deviation (to check for uneven speeds).
73         // If it suddenly skyrockets, we assume that sync ended earlier
74         // than we thought (it should be 25000 cycles), and that we should
75         // calibrate on fewer cycles.
76         for (int try_end : { 2000, 4000, 5000, 7500, 10000, 15000, SYNC_PULSE_END }) {
77                 double sum2 = 0.0;
78                 for (int i = SYNC_PULSE_START; i < try_end; ++i) {
79                         double cycles = pulses[i].len * C64_FREQUENCY;
80                         sum2 += (cycles - SYNC_PULSE_LENGTH) * (cycles - SYNC_PULSE_LENGTH);
81                 }
82                 double stddev = sqrt(sum2 / (try_end - SYNC_PULSE_START - 1));
83                 if (sync_pulse_end != -1 && stddev > 5.0 && stddev / sync_pulse_stddev > 1.3) {
84                         fprintf(stderr, "Stopping at %d sync pulses because standard deviation would be too big (%.2f cycles); shorter-than-usual trailer?\n",
85                                 sync_pulse_end, stddev);
86                         break;
87                 }
88                 sync_pulse_end = try_end;
89                 sync_pulse_stddev = stddev;
90         }
91         fprintf(stderr, "Sync pulse length standard deviation: %.2f cycles\n",
92                 sync_pulse_stddev);
93
94         double sum = 0.0;
95         for (int i = SYNC_PULSE_START; i < sync_pulse_end; ++i) {
96                 sum += pulses[i].len;
97         }
98         double mean_length = C64_FREQUENCY * sum / (sync_pulse_end - SYNC_PULSE_START);
99         double calibration_factor = SYNC_PULSE_LENGTH / mean_length;
100         fprintf(stderr, "Calibrated sync pulse length: %.2f -> %.2f (change %+.2f%%)\n",
101                 mean_length, SYNC_PULSE_LENGTH, 100.0 * (calibration_factor - 1.0));
102
103         // Check for pulses outside +/- 10% (sign of misdetection).
104         for (int i = SYNC_PULSE_START; i < sync_pulse_end; ++i) {
105                 double cycles = pulses[i].len * calibration_factor * C64_FREQUENCY;
106                 if (cycles < SYNC_PULSE_LENGTH / SYNC_TEST_TOLERANCE || cycles > SYNC_PULSE_LENGTH * SYNC_TEST_TOLERANCE) {
107                         fprintf(stderr, "Sync cycle with downflank at %.6f was detected at %.0f cycles; misdetect?\n",
108                                 pulses[i].time, cycles);
109                 }
110         }
111
112         return calibration_factor;
113 }
114
115 void output_tap(const std::vector<pulse>& pulses, double calibration_factor)
116 {
117         std::vector<char> tap_data;
118         for (unsigned i = 0; i < pulses.size(); ++i) {
119                 double cycles = pulses[i].len * calibration_factor * C64_FREQUENCY;
120                 int len = lrintf(cycles / TAP_RESOLUTION);
121                 if (i > SYNC_PULSE_END && (cycles < 100 || cycles > 800)) {
122                         fprintf(stderr, "Cycle with downflank at %.6f was detected at %.0f cycles; misdetect?\n",
123                                         pulses[i].time, cycles);
124                 }
125                 if (len <= 255) {
126                         tap_data.push_back(len);
127                 } else {
128                         int overflow_len = lrintf(cycles);
129                         tap_data.push_back(0);
130                         tap_data.push_back(overflow_len & 0xff);
131                         tap_data.push_back((overflow_len >> 8) & 0xff);
132                         tap_data.push_back(overflow_len >> 16);
133                 }
134         }
135
136         tap_header hdr;
137         memcpy(hdr.identifier, "C64-TAPE-RAW", 12);
138         hdr.version = 1;
139         hdr.reserved[0] = hdr.reserved[1] = hdr.reserved[2] = 0;
140         hdr.data_len = tap_data.size();
141
142         fwrite(&hdr, sizeof(hdr), 1, stdout);
143         fwrite(tap_data.data(), tap_data.size(), 1, stdout);
144 }
145
146 static struct option long_options[] = {
147         {"no-calibrate",     0,                 0, 's' },
148         {"plot-cycles",      0,                 0, 'p' },
149         {"hysteresis-limit", required_argument, 0, 'l' },
150         {"filter",           required_argument, 0, 'f' },
151         {"output-filtered",  0,                 0, 'F' },
152         {"help",             0,                 0, 'h' },
153         {0,                  0,                 0, 0   }
154 };
155
156 void help()
157 {
158         fprintf(stderr, "decode [OPTIONS] AUDIO-FILE > TAP-FILE\n");
159         fprintf(stderr, "\n");
160         fprintf(stderr, "  -s, --no-calibrate           do not try to calibrate on sync pulse length\n");
161         fprintf(stderr, "  -p, --plot-cycles            output debugging info to cycles.plot\n");
162         fprintf(stderr, "  -l, --hysteresis-limit VAL   change amplitude threshold for ignoring pulses (0..32768)\n");
163         fprintf(stderr, "  -f, --filter C1:C2:C3:...    specify FIR filter (up to %d coefficients)\n", NUM_FILTER_COEFF);
164         fprintf(stderr, "  -F, --output-filtered        output filtered waveform to filtered.raw\n");
165         fprintf(stderr, "  -h, --help                   display this help, then exit\n");
166         exit(1);
167 }
168
169 void parse_options(int argc, char **argv)
170 {
171         for ( ;; ) {
172                 int option_index = 0;
173                 int c = getopt_long(argc, argv, "spl:f:Fh", long_options, &option_index);
174                 if (c == -1)
175                         break;
176
177                 switch (c) {
178                 case 's':
179                         do_calibrate = false;
180                         break;
181
182                 case 'p':
183                         output_cycles_plot = true;
184                         break;
185                 case 'l':
186                         hysteresis_limit = atof(optarg) / 32768.0;
187                         break;
188
189                 case 'f': {
190                         const char *coeffstr = strtok(optarg, ":");
191                         int coeff_index = 0;
192                         while (coeff_index < NUM_FILTER_COEFF && coeffstr != NULL) {
193                                 filter_coeff[coeff_index++] = atof(coeffstr);
194                                 coeffstr = strtok(NULL, ":");
195                         }
196                         use_filter = true;
197                         break;
198                 }
199
200                 case 'F':
201                         output_filtered = true;
202                         break;
203
204                 case 'h':
205                 default:
206                         help();
207                         exit(1);
208                 }
209         }
210 }
211
212 // TODO: Support AVX here.
213 std::vector<float> do_filter(const std::vector<float>& pcm, const float* filter)
214 {
215         std::vector<float> filtered_pcm;
216         filtered_pcm.reserve(pcm.size());
217         for (unsigned i = NUM_FILTER_COEFF; i < pcm.size(); ++i) {
218                 float s = 0.0f;
219                 for (int j = 0; j < NUM_FILTER_COEFF; ++j) {
220                         s += filter[j] * pcm[i - j];
221                 }
222                 filtered_pcm.push_back(s);
223         }
224
225         if (output_filtered) {
226                 FILE *fp = fopen("filtered.raw", "wb");
227                 fwrite(filtered_pcm.data(), filtered_pcm.size() * sizeof(filtered_pcm[0]), 1, fp);
228                 fclose(fp);
229         }
230
231         return filtered_pcm;
232 }
233
234 int main(int argc, char **argv)
235 {
236         parse_options(argc, argv);
237
238         make_lanczos_weight_table();
239         std::vector<float> pcm;
240         int sample_rate;
241         if (!read_audio_file(argv[optind], &pcm, &sample_rate)) {
242                 exit(1);
243         }
244
245         if (use_filter) {
246                 pcm = do_filter(pcm, filter_coeff);
247         }
248
249 #if 0
250         for (int i = 0; i < LEN; ++i) {
251                 in[i] += rand() % 10000;
252         }
253 #endif
254
255 #if 0
256         for (int i = 0; i < LEN; ++i) {
257                 printf("%d\n", in[i]);
258         }
259 #endif
260
261         std::vector<pulse> pulses;  // in seconds
262
263         // Find the flanks.
264         int last_bit = -1;
265         double last_downflank = -1;
266         for (unsigned i = 0; i < pcm.size(); ++i) {
267                 int bit = (pcm[i] > 0) ? 1 : 0;
268                 if (bit == 0 && last_bit == 1) {
269                         // Check if we ever go up above <hysteresis_limit> before we dip down again.
270                         bool true_pulse = false;
271                         unsigned j;
272                         int min_level_after = 32767;
273                         for (j = i; j < pcm.size(); ++j) {
274                                 min_level_after = std::min<int>(min_level_after, pcm[j]);
275                                 if (pcm[j] > 0) break;
276                                 if (pcm[j] < -hysteresis_limit) {
277                                         true_pulse = true;
278                                         break;
279                                 }
280                         }
281
282                         if (!true_pulse) {
283 #if 0
284                                 fprintf(stderr, "Ignored down-flank at %.6f seconds due to hysteresis (%d < %d).\n",
285                                         double(i) / sample_rate, -min_level_after, hysteresis_limit);
286 #endif
287                                 i = j;
288                                 continue;
289                         } 
290
291                         // down-flank!
292                         double t = find_zerocrossing(pcm, i - 1) * (1.0 / sample_rate);
293                         if (last_downflank > 0) {
294                                 pulse p;
295                                 p.time = t;
296                                 p.len = t - last_downflank;
297                                 pulses.push_back(p);
298                         }
299                         last_downflank = t;
300                 }
301                 last_bit = bit;
302         }
303
304         double calibration_factor = 1.0;
305         if (do_calibrate) {
306                 calibration_factor = calibrate(pulses);
307         }
308
309         if (output_cycles_plot) {
310                 FILE *fp = fopen("cycles.plot", "w");
311                 for (unsigned i = 0; i < pulses.size(); ++i) {
312                         double cycles = pulses[i].len * calibration_factor * C64_FREQUENCY;
313                         fprintf(fp, "%f %f\n", pulses[i].time, cycles);
314                 }
315                 fclose(fp);
316         }
317
318         output_tap(pulses, calibration_factor);
319 }