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