Add an RC highpass filter, which seemingly does a good job of emulating the one in...
[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 "level.h"
13 #include "tap.h"
14 #include "filter.h"
15
16 #define BUFSIZE 4096
17 #define C64_FREQUENCY 985248
18 #define SYNC_PULSE_START 1000
19 #define SYNC_PULSE_END 20000
20 #define SYNC_PULSE_LENGTH 378.0
21 #define SYNC_TEST_TOLERANCE 1.10
22
23 // SPSA options
24 #define NUM_FILTER_COEFF 32
25 #define NUM_ITER 5000
26 #define A NUM_ITER/10  // approx
27 #define INITIAL_A 0.005 // A bit of trial and error...
28 #define INITIAL_C 0.02  // This too.
29 #define GAMMA 0.166
30 #define ALPHA 1.0
31
32 static float hysteresis_limit = 3000.0 / 32768.0;
33 static bool do_calibrate = true;
34 static bool output_cycles_plot = false;
35 static bool do_crop = false;
36 static float crop_start = 0.0f, crop_end = HUGE_VAL;
37
38 static bool use_fir_filter = false;
39 static float filter_coeff[NUM_FILTER_COEFF] = { 1.0f };  // The rest is filled with 0.
40 static bool use_rc_filter = false;
41 static float rc_filter_freq;
42 static bool output_filtered = false;
43
44 static bool quiet = false;
45 static bool do_auto_level = false;
46 static bool output_leveled = false;
47 static std::vector<float> train_snap_points;
48 static bool do_train = false;
49
50 // The minimum estimated sound level (for do_auto_level) at any given point.
51 // If you decrease this, you'll be able to amplify really silent signals
52 // by more, but you'll also increase the level of silent (ie. noise-only) segments,
53 // possibly caused misdetected pulses in these segments.
54 static float min_level = 0.05f;
55
56 // between [x,x+1]
57 double find_zerocrossing(const std::vector<float> &pcm, int x)
58 {
59         if (pcm[x] == 0) {
60                 return x;
61         }
62         if (pcm[x + 1] == 0) {
63                 return x + 1;
64         }
65
66         assert(pcm[x + 1] < 0);
67         assert(pcm[x] > 0);
68
69         double upper = x;
70         double lower = x + 1;
71         while (lower - upper > 1e-3) {
72                 double mid = 0.5f * (upper + lower);
73                 if (lanczos_interpolate(pcm, mid) > 0) {
74                         upper = mid;
75                 } else {
76                         lower = mid;
77                 }
78         }
79
80         return 0.5f * (upper + lower);
81 }
82
83 struct pulse {
84         double time;  // in seconds from start
85         double len;   // in seconds
86 };
87
88 // Calibrate on the first ~25k pulses (skip a few, just to be sure).
89 double calibrate(const std::vector<pulse> &pulses) {
90         if (pulses.size() < SYNC_PULSE_END) {
91                 fprintf(stderr, "Too few pulses, not calibrating!\n");
92                 return 1.0;
93         }
94
95         int sync_pulse_end = -1;
96         double sync_pulse_stddev = -1.0;
97
98         // Compute the standard deviation (to check for uneven speeds).
99         // If it suddenly skyrockets, we assume that sync ended earlier
100         // than we thought (it should be 25000 cycles), and that we should
101         // calibrate on fewer cycles.
102         for (int try_end : { 2000, 4000, 5000, 7500, 10000, 15000, SYNC_PULSE_END }) {
103                 double sum2 = 0.0;
104                 for (int i = SYNC_PULSE_START; i < try_end; ++i) {
105                         double cycles = pulses[i].len * C64_FREQUENCY;
106                         sum2 += (cycles - SYNC_PULSE_LENGTH) * (cycles - SYNC_PULSE_LENGTH);
107                 }
108                 double stddev = sqrt(sum2 / (try_end - SYNC_PULSE_START - 1));
109                 if (sync_pulse_end != -1 && stddev > 5.0 && stddev / sync_pulse_stddev > 1.3) {
110                         fprintf(stderr, "Stopping at %d sync pulses because standard deviation would be too big (%.2f cycles); shorter-than-usual trailer?\n",
111                                 sync_pulse_end, stddev);
112                         break;
113                 }
114                 sync_pulse_end = try_end;
115                 sync_pulse_stddev = stddev;
116         }
117         if (!quiet) {
118                 fprintf(stderr, "Sync pulse length standard deviation: %.2f cycles\n",
119                         sync_pulse_stddev);
120         }
121
122         double sum = 0.0;
123         for (int i = SYNC_PULSE_START; i < sync_pulse_end; ++i) {
124                 sum += pulses[i].len;
125         }
126         double mean_length = C64_FREQUENCY * sum / (sync_pulse_end - SYNC_PULSE_START);
127         double calibration_factor = SYNC_PULSE_LENGTH / mean_length;
128         if (!quiet) {
129                 fprintf(stderr, "Calibrated sync pulse length: %.2f -> %.2f (change %+.2f%%)\n",
130                         mean_length, SYNC_PULSE_LENGTH, 100.0 * (calibration_factor - 1.0));
131         }
132
133         // Check for pulses outside +/- 10% (sign of misdetection).
134         for (int i = SYNC_PULSE_START; i < sync_pulse_end; ++i) {
135                 double cycles = pulses[i].len * calibration_factor * C64_FREQUENCY;
136                 if (cycles < SYNC_PULSE_LENGTH / SYNC_TEST_TOLERANCE || cycles > SYNC_PULSE_LENGTH * SYNC_TEST_TOLERANCE) {
137                         fprintf(stderr, "Sync cycle with downflank at %.6f was detected at %.0f cycles; misdetect?\n",
138                                 pulses[i].time, cycles);
139                 }
140         }
141
142         return calibration_factor;
143 }
144
145 void output_tap(const std::vector<pulse>& pulses, double calibration_factor)
146 {
147         std::vector<char> tap_data;
148         for (unsigned i = 0; i < pulses.size(); ++i) {
149                 double cycles = pulses[i].len * calibration_factor * C64_FREQUENCY;
150                 int len = lrintf(cycles / TAP_RESOLUTION);
151                 if (i > SYNC_PULSE_END && (cycles < 100 || cycles > 800)) {
152                         fprintf(stderr, "Cycle with downflank at %.6f was detected at %.0f cycles; misdetect?\n",
153                                         pulses[i].time, cycles);
154                 }
155                 if (len <= 255) {
156                         tap_data.push_back(len);
157                 } else {
158                         int overflow_len = lrintf(cycles);
159                         tap_data.push_back(0);
160                         tap_data.push_back(overflow_len & 0xff);
161                         tap_data.push_back((overflow_len >> 8) & 0xff);
162                         tap_data.push_back(overflow_len >> 16);
163                 }
164         }
165
166         tap_header hdr;
167         memcpy(hdr.identifier, "C64-TAPE-RAW", 12);
168         hdr.version = 1;
169         hdr.reserved[0] = hdr.reserved[1] = hdr.reserved[2] = 0;
170         hdr.data_len = tap_data.size();
171
172         fwrite(&hdr, sizeof(hdr), 1, stdout);
173         fwrite(tap_data.data(), tap_data.size(), 1, stdout);
174 }
175
176 static struct option long_options[] = {
177         {"auto-level",       0,                 0, 'a' },
178         {"output-leveled",   0,                 0, 'A' },
179         {"no-calibrate",     0,                 0, 's' },
180         {"plot-cycles",      0,                 0, 'p' },
181         {"hysteresis-limit", required_argument, 0, 'l' },
182         {"filter",           required_argument, 0, 'f' },
183         {"rc-filter",        required_argument, 0, 'r' },
184         {"output-filtered",  0,                 0, 'F' },
185         {"crop",             required_argument, 0, 'c' },
186         {"quiet",            0,                 0, 'q' },
187         {"help",             0,                 0, 'h' },
188         {0,                  0,                 0, 0   }
189 };
190
191 void help()
192 {
193         fprintf(stderr, "decode [OPTIONS] AUDIO-FILE > TAP-FILE\n");
194         fprintf(stderr, "\n");
195         fprintf(stderr, "  -a, --auto-level             automatically adjust amplitude levels throughout the file\n");
196         fprintf(stderr, "  -A, --output-leveled         output leveled waveform to leveled.raw\n");
197         fprintf(stderr, "  -m, --min-level              minimum estimated sound level (0..32768) for --auto-level\n");
198         fprintf(stderr, "  -s, --no-calibrate           do not try to calibrate on sync pulse length\n");
199         fprintf(stderr, "  -p, --plot-cycles            output debugging info to cycles.plot\n");
200         fprintf(stderr, "  -l, --hysteresis-limit VAL   change amplitude threshold for ignoring pulses (0..32768)\n");
201         fprintf(stderr, "  -f, --filter C1:C2:C3:...    specify FIR filter (up to %d coefficients)\n", NUM_FILTER_COEFF);
202         fprintf(stderr, "  -r, --rc-filter FREQ         send signal through a highpass RC filter with given frequency (in Hertz)\n");
203         fprintf(stderr, "  -F, --output-filtered        output filtered waveform to filtered.raw\n");
204         fprintf(stderr, "  -c, --crop START[:END]       use only the given part of the file\n");
205         fprintf(stderr, "  -t, --train LEN1:LEN2:...    train a filter for detecting any of the given number of cycles\n");
206         fprintf(stderr, "                               (implies --no-calibrate and --quiet unless overridden)\n");
207         fprintf(stderr, "  -q, --quiet                  suppress some informational messages\n");
208         fprintf(stderr, "  -h, --help                   display this help, then exit\n");
209         exit(1);
210 }
211
212 void parse_options(int argc, char **argv)
213 {
214         for ( ;; ) {
215                 int option_index = 0;
216                 int c = getopt_long(argc, argv, "aAm:spl:f:r:Fc:t:qh", long_options, &option_index);
217                 if (c == -1)
218                         break;
219
220                 switch (c) {
221                 case 'a':
222                         do_auto_level = true;
223                         break;
224
225                 case 'A':
226                         output_leveled = true;
227                         break;
228
229                 case 'm':
230                         min_level = atof(optarg) / 32768.0;
231                         break;
232
233                 case 's':
234                         do_calibrate = false;
235                         break;
236
237                 case 'p':
238                         output_cycles_plot = true;
239                         break;
240
241                 case 'l':
242                         hysteresis_limit = atof(optarg) / 32768.0;
243                         break;
244
245                 case 'f': {
246                         const char *coeffstr = strtok(optarg, ": ");
247                         int coeff_index = 0;
248                         while (coeff_index < NUM_FILTER_COEFF && coeffstr != NULL) {
249                                 filter_coeff[coeff_index++] = atof(coeffstr);
250                                 coeffstr = strtok(NULL, ": ");
251                         }
252                         use_fir_filter = true;
253                         break;
254                 }
255
256                 case 'r':
257                         use_rc_filter = true;
258                         rc_filter_freq = atof(optarg);
259                         break;
260
261                 case 'F':
262                         output_filtered = true;
263                         break;
264
265                 case 'c': {
266                         const char *cropstr = strtok(optarg, ":");
267                         crop_start = atof(cropstr);
268                         cropstr = strtok(NULL, ":");
269                         if (cropstr == NULL) {
270                                 crop_end = HUGE_VAL;
271                         } else {
272                                 crop_end = atof(cropstr);
273                         }
274                         do_crop = true;
275                         break;
276                 }
277
278                 case 't': {
279                         const char *cyclestr = strtok(optarg, ":");
280                         while (cyclestr != NULL) {
281                                 train_snap_points.push_back(atof(cyclestr));
282                                 cyclestr = strtok(NULL, ":");
283                         }
284                         do_train = true;
285
286                         // Set reasonable defaults (can be overridden later on the command line).
287                         do_calibrate = false;
288                         quiet = true;
289                         break;
290                 }
291
292                 case 'q':
293                         quiet = true;
294                         break;
295
296                 case 'h':
297                 default:
298                         help();
299                         exit(1);
300                 }
301         }
302 }
303
304 std::vector<float> crop(const std::vector<float>& pcm, float crop_start, float crop_end, int sample_rate)
305 {
306         size_t start_sample, end_sample;
307         if (crop_start >= 0.0f) {
308                 start_sample = std::min<size_t>(lrintf(crop_start * sample_rate), pcm.size());
309         }
310         if (crop_end >= 0.0f) {
311                 end_sample = std::min<size_t>(lrintf(crop_end * sample_rate), pcm.size());
312         }
313         return std::vector<float>(pcm.begin() + start_sample, pcm.begin() + end_sample);
314 }
315
316 // TODO: Support AVX here.
317 std::vector<float> do_fir_filter(const std::vector<float>& pcm, const float* filter)
318 {
319         std::vector<float> filtered_pcm;
320         filtered_pcm.reserve(pcm.size());
321         for (unsigned i = NUM_FILTER_COEFF; i < pcm.size(); ++i) {
322                 float s = 0.0f;
323                 for (int j = 0; j < NUM_FILTER_COEFF; ++j) {
324                         s += filter[j] * pcm[i - j];
325                 }
326                 filtered_pcm.push_back(s);
327         }
328
329         if (output_filtered) {
330                 FILE *fp = fopen("filtered.raw", "wb");
331                 fwrite(filtered_pcm.data(), filtered_pcm.size() * sizeof(filtered_pcm[0]), 1, fp);
332                 fclose(fp);
333         }
334
335         return filtered_pcm;
336 }
337
338 std::vector<float> do_rc_filter(const std::vector<float>& pcm, float freq, int sample_rate)
339 {
340         std::vector<float> filtered_pcm;
341         filtered_pcm.resize(pcm.size());
342         Filter filter = Filter::hpf(M_PI * freq / sample_rate);
343         for (unsigned i = 0; i < pcm.size(); ++i) {
344                 filtered_pcm[i] = filter.update(pcm[i]);
345         }
346
347         if (output_filtered) {
348                 FILE *fp = fopen("filtered.raw", "wb");
349                 fwrite(filtered_pcm.data(), filtered_pcm.size() * sizeof(filtered_pcm[0]), 1, fp);
350                 fclose(fp);
351         }
352
353         return filtered_pcm;
354 }
355
356 std::vector<pulse> detect_pulses(const std::vector<float> &pcm, int sample_rate)
357 {
358         std::vector<pulse> pulses;
359
360         // Find the flanks.
361         int last_bit = -1;
362         double last_downflank = -1;
363         for (unsigned i = 0; i < pcm.size(); ++i) {
364                 int bit = (pcm[i] > 0) ? 1 : 0;
365                 if (bit == 0 && last_bit == 1) {
366                         // Check if we ever go up above <hysteresis_limit> before we dip down again.
367                         bool true_pulse = false;
368                         unsigned j;
369                         int min_level_after = 32767;
370                         for (j = i; j < pcm.size(); ++j) {
371                                 min_level_after = std::min<int>(min_level_after, pcm[j]);
372                                 if (pcm[j] > 0) break;
373                                 if (pcm[j] < -hysteresis_limit) {
374                                         true_pulse = true;
375                                         break;
376                                 }
377                         }
378
379                         if (!true_pulse) {
380 #if 0
381                                 fprintf(stderr, "Ignored down-flank at %.6f seconds due to hysteresis (%d < %d).\n",
382                                         double(i) / sample_rate, -min_level_after, hysteresis_limit);
383 #endif
384                                 i = j;
385                                 continue;
386                         } 
387
388                         // down-flank!
389                         double t = find_zerocrossing(pcm, i - 1) * (1.0 / sample_rate) + crop_start;
390                         if (last_downflank > 0) {
391                                 pulse p;
392                                 p.time = t;
393                                 p.len = t - last_downflank;
394                                 pulses.push_back(p);
395                         }
396                         last_downflank = t;
397                 }
398                 last_bit = bit;
399         }
400         return pulses;
401 }
402
403 void output_cycle_plot(const std::vector<pulse> &pulses, double calibration_factor)
404 {
405         FILE *fp = fopen("cycles.plot", "w");
406         for (unsigned i = 0; i < pulses.size(); ++i) {
407                 double cycles = pulses[i].len * calibration_factor * C64_FREQUENCY;
408                 fprintf(fp, "%f %f\n", pulses[i].time, cycles);
409         }
410         fclose(fp);
411 }
412
413 std::pair<int, double> find_closest_point(double x, const std::vector<float> &points)
414 {
415         int best_point = 0;
416         double best_dist = (x - points[0]) * (x - points[0]);
417         for (unsigned j = 1; j < train_snap_points.size(); ++j) {
418                 double dist = (x - points[j]) * (x - points[j]);
419                 if (dist < best_dist) {
420                         best_point = j;
421                         best_dist = dist;
422                 }
423         }
424         return std::make_pair(best_point, best_dist);
425 }
426
427 float eval_badness(const std::vector<pulse>& pulses, double calibration_factor)
428 {
429         double sum_badness = 0.0;
430         for (unsigned i = 0; i < pulses.size(); ++i) {
431                 double cycles = pulses[i].len * calibration_factor * C64_FREQUENCY;
432                 if (cycles > 2000.0) cycles = 2000.0;  // Don't make pauses arbitrarily bad.
433                 std::pair<int, double> selected_point_and_sq_dist = find_closest_point(cycles, train_snap_points);
434                 sum_badness += selected_point_and_sq_dist.second;
435         }
436         return sqrt(sum_badness / (pulses.size() - 1));
437 }
438
439 void find_kmeans(const std::vector<pulse> &pulses, double calibration_factor, const std::vector<float> &initial_centers)
440 {
441         std::vector<float> last_centers = initial_centers;
442         std::vector<float> sums;
443         std::vector<float> num;
444         sums.resize(initial_centers.size());
445         num.resize(initial_centers.size());
446         for ( ;; ) {
447                 for (unsigned i = 0; i < initial_centers.size(); ++i) {
448                         sums[i] = 0.0f;
449                         num[i] = 0;
450                 }
451                 for (unsigned i = 0; i < pulses.size(); ++i) {
452                         double cycles = pulses[i].len * calibration_factor * C64_FREQUENCY;
453                         // Ignore heavy outliers, which are almost always long pauses.
454                         if (cycles > 2000.0) {
455                                 continue;
456                         }
457                         std::pair<int, double> selected_point_and_sq_dist = find_closest_point(cycles, last_centers);
458                         int p = selected_point_and_sq_dist.first;
459                         sums[p] += cycles;
460                         ++num[p];
461                 }
462                 bool any_moved = false;
463                 for (unsigned i = 0; i < initial_centers.size(); ++i) {
464                         if (num[i] == 0) {
465                                 printf("K-means broke down, can't output new reference training points\n");
466                                 return;
467                         }
468                         float new_center = sums[i] / num[i];
469                         if (fabs(new_center - last_centers[i]) > 1e-3) {
470                                 any_moved = true;
471                         }
472                         last_centers[i] = new_center;
473                 }
474                 if (!any_moved) {
475                         break;
476                 }
477         }
478         printf("New reference training points:");
479         for (unsigned i = 0; i < last_centers.size(); ++i) {
480                 printf(" %.3f", last_centers[i]);
481         }
482         printf("\n");
483 }
484
485 void spsa_train(const std::vector<float> &pcm, int sample_rate)
486 {
487         float filter[NUM_FILTER_COEFF] = { 1.0f };  // The rest is filled with 0.
488
489         float start_c = INITIAL_C;
490         double best_badness = HUGE_VAL;
491
492         for (int n = 1; n < NUM_ITER; ++n) {
493                 float a = INITIAL_A * pow(n + A, -ALPHA);
494                 float c = start_c * pow(n, -GAMMA);
495
496                 // find a random perturbation
497                 float p[NUM_FILTER_COEFF];
498                 float filter1[NUM_FILTER_COEFF], filter2[NUM_FILTER_COEFF];
499                 for (int i = 0; i < NUM_FILTER_COEFF; ++i) {
500                         p[i] = (rand() % 2) ? 1.0 : -1.0;
501                         filter1[i] = std::max(std::min(filter[i] - c * p[i], 1.0f), -1.0f);
502                         filter2[i] = std::max(std::min(filter[i] + c * p[i], 1.0f), -1.0f);
503                 }
504
505                 std::vector<pulse> pulses1 = detect_pulses(do_fir_filter(pcm, filter1), sample_rate);
506                 std::vector<pulse> pulses2 = detect_pulses(do_fir_filter(pcm, filter2), sample_rate);
507                 float badness1 = eval_badness(pulses1, 1.0);
508                 float badness2 = eval_badness(pulses2, 1.0);
509
510                 // Find the gradient estimator
511                 float g[NUM_FILTER_COEFF];
512                 for (int i = 0; i < NUM_FILTER_COEFF; ++i) {
513                         g[i] = (badness2 - badness1) / (2.0 * c * p[i]);
514                         filter[i] -= a * g[i];
515                         filter[i] = std::max(std::min(filter[i], 1.0f), -1.0f);
516                 }
517                 if (badness2 < badness1) {
518                         std::swap(badness1, badness2);
519                         std::swap(filter1, filter2);
520                         std::swap(pulses1, pulses2);
521                 }
522                 if (badness1 < best_badness) {
523                         printf("\nNew best filter (badness=%f):", badness1);
524                         for (int i = 0; i < NUM_FILTER_COEFF; ++i) {
525                                 printf(" %.5f", filter1[i]);
526                         }
527                         best_badness = badness1;
528                         printf("\n");
529
530                         find_kmeans(pulses1, 1.0, train_snap_points);
531
532                         if (output_cycles_plot) {
533                                 output_cycle_plot(pulses1, 1.0);
534                         }
535                 }
536                 printf("%d ", n);
537                 fflush(stdout);
538         }
539 }
540
541 int main(int argc, char **argv)
542 {
543         parse_options(argc, argv);
544
545         make_lanczos_weight_table();
546         std::vector<float> pcm;
547         int sample_rate;
548         if (!read_audio_file(argv[optind], &pcm, &sample_rate)) {
549                 exit(1);
550         }
551
552         if (do_crop) {
553                 pcm = crop(pcm, crop_start, crop_end, sample_rate);
554         }
555
556         if (use_fir_filter) {
557                 pcm = do_fir_filter(pcm, filter_coeff);
558         }
559
560         if (use_rc_filter) {
561                 pcm = do_rc_filter(pcm, rc_filter_freq, sample_rate);
562         }
563
564         if (do_auto_level) {
565                 pcm = level_samples(pcm, min_level, sample_rate);
566                 if (output_leveled) {
567                         FILE *fp = fopen("leveled.raw", "wb");
568                         fwrite(pcm.data(), pcm.size() * sizeof(pcm[0]), 1, fp);
569                         fclose(fp);
570                 }
571         }
572
573 #if 0
574         for (int i = 0; i < LEN; ++i) {
575                 in[i] += rand() % 10000;
576         }
577 #endif
578
579 #if 0
580         for (int i = 0; i < LEN; ++i) {
581                 printf("%d\n", in[i]);
582         }
583 #endif
584
585         if (do_train) {
586                 spsa_train(pcm, sample_rate);
587                 exit(0);
588         }
589
590         std::vector<pulse> pulses = detect_pulses(pcm, sample_rate);
591
592         double calibration_factor = 1.0;
593         if (do_calibrate) {
594                 calibration_factor = calibrate(pulses);
595         }
596
597         if (output_cycles_plot) {
598                 output_cycle_plot(pulses, calibration_factor);
599         }
600
601         output_tap(pulses, calibration_factor);
602 }