More output to stderr.
[c64tapwav] / decode.cpp
1 // Copyright Steinar H. Gunderson <sgunderson@bigfoot.com>
2 // Licensed under the GPL, v2. (See the file COPYING.)
3
4 #include <stdio.h>
5 #include <string.h>
6 #include <math.h>
7 #include <assert.h>
8 #include <limits.h>
9 #include <getopt.h>
10 #include <vector>
11 #include <algorithm>
12
13 #include "audioreader.h"
14 #include "interpolate.h"
15 #include "level.h"
16 #include "tap.h"
17 #include "filter.h"
18
19 #define BUFSIZE 4096
20 #define C64_FREQUENCY 985248
21 #define SYNC_PULSE_START 1000
22 #define SYNC_PULSE_END 20000
23 #define SYNC_PULSE_LENGTH 378.0
24 #define SYNC_TEST_TOLERANCE 1.10
25
26 // SPSA options
27 #define NUM_FILTER_COEFF 32
28 #define NUM_SPSA_VALS (NUM_FILTER_COEFF + 2)
29 #define NUM_ITER 5000
30 #define A NUM_ITER/10  // approx
31 #define INITIAL_A 0.005 // A bit of trial and error...
32 #define INITIAL_C 0.02  // This too.
33 #define GAMMA 0.166
34 #define ALPHA 1.0
35
36 static float hysteresis_upper_limit = 0.1;
37 static float hysteresis_lower_limit = -0.1;
38 static bool do_calibrate = true;
39 static bool output_cycles_plot = false;
40 static bool do_crop = false;
41 static float crop_start = 0.0f, crop_end = HUGE_VAL;
42
43 static bool use_fir_filter = false;
44 static float filter_coeff[NUM_FILTER_COEFF] = { 1.0f };  // The rest is filled with 0.
45 static bool use_rc_filter = false;
46 static float rc_filter_freq;
47 static bool output_filtered = false;
48
49 static bool quiet = false;
50 static bool do_auto_level = false;
51 static bool output_leveled = false;
52 static std::vector<float> train_snap_points;
53 static bool do_train = false;
54
55 // The frequency to filter on (for do_auto_level), in Hertz.
56 // Larger values makes the compressor react faster, but if it is too large,
57 // you'll ruin the waveforms themselves.
58 static float auto_level_freq = 200.0;
59
60 // The minimum estimated sound level (for do_auto_level) at any given point.
61 // If you decrease this, you'll be able to amplify really silent signals
62 // by more, but you'll also increase the level of silent (ie. noise-only) segments,
63 // possibly caused misdetected pulses in these segments.
64 static float min_level = 0.05f;
65
66 // search for the value <limit> between [x,x+1]
67 double find_crossing(const std::vector<float> &pcm, int x, float limit)
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) > limit) {
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         {"auto-level-freq",  required_argument, 0, 'b' },
179         {"output-leveled",   0,                 0, 'A' },
180         {"min-level",        required_argument, 0, 'm' },
181         {"no-calibrate",     0,                 0, 's' },
182         {"plot-cycles",      0,                 0, 'p' },
183         {"hysteresis-limit", required_argument, 0, 'l' },
184         {"filter",           required_argument, 0, 'f' },
185         {"rc-filter",        required_argument, 0, 'r' },
186         {"output-filtered",  0,                 0, 'F' },
187         {"crop",             required_argument, 0, 'c' },
188         {"quiet",            0,                 0, 'q' },
189         {"help",             0,                 0, 'h' },
190         {0,                  0,                 0, 0   }
191 };
192
193 void help()
194 {
195         fprintf(stderr, "decode [OPTIONS] AUDIO-FILE > TAP-FILE\n");
196         fprintf(stderr, "\n");
197         fprintf(stderr, "  -a, --auto-level             automatically adjust amplitude levels throughout the file\n");
198         fprintf(stderr, "  -b, --auto-level-freq        minimum frequency in Hertz of corrected level changes (default 200 Hz)\n");
199         fprintf(stderr, "  -A, --output-leveled         output leveled waveform to leveled.raw\n");
200         fprintf(stderr, "  -m, --min-level              minimum estimated sound level (0..1) for --auto-level\n");
201         fprintf(stderr, "  -s, --no-calibrate           do not try to calibrate on sync pulse length\n");
202         fprintf(stderr, "  -p, --plot-cycles            output debugging info to cycles.plot\n");
203         fprintf(stderr, "  -l, --hysteresis-limit U[:L] change amplitude threshold for ignoring pulses (-1..1)\n");
204         fprintf(stderr, "  -f, --filter C1:C2:C3:...    specify FIR filter (up to %d coefficients)\n", NUM_FILTER_COEFF);
205         fprintf(stderr, "  -r, --rc-filter FREQ         send signal through a highpass RC filter with given frequency (in Hertz)\n");
206         fprintf(stderr, "  -F, --output-filtered        output filtered waveform to filtered.raw\n");
207         fprintf(stderr, "  -c, --crop START[:END]       use only the given part of the file\n");
208         fprintf(stderr, "  -t, --train LEN1:LEN2:...    train a filter for detecting any of the given number of cycles\n");
209         fprintf(stderr, "                               (implies --no-calibrate and --quiet unless overridden)\n");
210         fprintf(stderr, "  -q, --quiet                  suppress some informational messages\n");
211         fprintf(stderr, "  -h, --help                   display this help, then exit\n");
212         exit(1);
213 }
214
215 void parse_options(int argc, char **argv)
216 {
217         for ( ;; ) {
218                 int option_index = 0;
219                 int c = getopt_long(argc, argv, "ab:Am:spl:f:r:Fc:t:qh", long_options, &option_index);
220                 if (c == -1)
221                         break;
222
223                 switch (c) {
224                 case 'a':
225                         do_auto_level = true;
226                         break;
227
228                 case 'b':
229                         auto_level_freq = atof(optarg);
230                         break;
231
232                 case 'A':
233                         output_leveled = true;
234                         break;
235
236                 case 'm':
237                         min_level = atof(optarg);
238                         break;
239
240                 case 's':
241                         do_calibrate = false;
242                         break;
243
244                 case 'p':
245                         output_cycles_plot = true;
246                         break;
247
248                 case 'l': {
249                         const char *hyststr = strtok(optarg, ": ");
250                         hysteresis_upper_limit = atof(hyststr);
251                         hyststr = strtok(NULL, ": ");
252                         if (hyststr == NULL) {
253                                 hysteresis_lower_limit = -hysteresis_upper_limit;
254                         } else {
255                                 hysteresis_lower_limit = atof(hyststr);
256                         }
257                         break;
258                 }
259
260                 case 'f': {
261                         const char *coeffstr = strtok(optarg, ": ");
262                         int coeff_index = 0;
263                         while (coeff_index < NUM_FILTER_COEFF && coeffstr != NULL) {
264                                 filter_coeff[coeff_index++] = atof(coeffstr);
265                                 coeffstr = strtok(NULL, ": ");
266                         }
267                         use_fir_filter = true;
268                         break;
269                 }
270
271                 case 'r':
272                         use_rc_filter = true;
273                         rc_filter_freq = atof(optarg);
274                         break;
275
276                 case 'F':
277                         output_filtered = true;
278                         break;
279
280                 case 'c': {
281                         const char *cropstr = strtok(optarg, ":");
282                         crop_start = atof(cropstr);
283                         cropstr = strtok(NULL, ":");
284                         if (cropstr == NULL) {
285                                 crop_end = HUGE_VAL;
286                         } else {
287                                 crop_end = atof(cropstr);
288                         }
289                         do_crop = true;
290                         break;
291                 }
292
293                 case 't': {
294                         const char *cyclestr = strtok(optarg, ":");
295                         while (cyclestr != NULL) {
296                                 train_snap_points.push_back(atof(cyclestr));
297                                 cyclestr = strtok(NULL, ":");
298                         }
299                         do_train = true;
300
301                         // Set reasonable defaults (can be overridden later on the command line).
302                         do_calibrate = false;
303                         quiet = true;
304                         break;
305                 }
306
307                 case 'q':
308                         quiet = true;
309                         break;
310
311                 case 'h':
312                 default:
313                         help();
314                         exit(1);
315                 }
316         }
317 }
318
319 std::vector<float> crop(const std::vector<float>& pcm, float crop_start, float crop_end, int sample_rate)
320 {
321         size_t start_sample, end_sample;
322         if (crop_start >= 0.0f) {
323                 start_sample = std::min<size_t>(lrintf(crop_start * sample_rate), pcm.size());
324         }
325         if (crop_end >= 0.0f) {
326                 end_sample = std::min<size_t>(lrintf(crop_end * sample_rate), pcm.size());
327         }
328         return std::vector<float>(pcm.begin() + start_sample, pcm.begin() + end_sample);
329 }
330
331 // TODO: Support AVX here.
332 std::vector<float> do_fir_filter(const std::vector<float>& pcm, const float* filter)
333 {
334         std::vector<float> filtered_pcm;
335         filtered_pcm.reserve(pcm.size());
336         for (unsigned i = NUM_FILTER_COEFF; i < pcm.size(); ++i) {
337                 float s = 0.0f;
338                 for (int j = 0; j < NUM_FILTER_COEFF; ++j) {
339                         s += filter[j] * pcm[i - j];
340                 }
341                 filtered_pcm.push_back(s);
342         }
343
344         if (output_filtered) {
345                 FILE *fp = fopen("filtered.raw", "wb");
346                 fwrite(filtered_pcm.data(), filtered_pcm.size() * sizeof(filtered_pcm[0]), 1, fp);
347                 fclose(fp);
348         }
349
350         return filtered_pcm;
351 }
352
353 std::vector<float> do_rc_filter(const std::vector<float>& pcm, float freq, int sample_rate)
354 {
355         // This is only a 6 dB/oct filter, which seemingly works better
356         // than the Filter class, which is a standard biquad (12 dB/oct).
357         // The b/c calculations come from libnyquist (atone.c);
358         // I haven't checked, but I suppose they fall out of the bilinear
359         // transform of the transfer function H(s) = s/(s + w).
360         std::vector<float> filtered_pcm;
361         filtered_pcm.resize(pcm.size());
362         const float b = 2.0f - cos(2.0 * M_PI * freq / sample_rate);
363         const float c = b - sqrt(b * b - 1.0f);
364         float prev_in = 0.0f;
365         float prev_out = 0.0f;
366         for (unsigned i = 0; i < pcm.size(); ++i) {
367                 float in = pcm[i];
368                 float out = c * (prev_out + in - prev_in);
369                 filtered_pcm[i] = out;
370                 prev_in = in;
371                 prev_out = out;
372         }
373
374         if (output_filtered) {
375                 FILE *fp = fopen("filtered.raw", "wb");
376                 fwrite(filtered_pcm.data(), filtered_pcm.size() * sizeof(filtered_pcm[0]), 1, fp);
377                 fclose(fp);
378         }
379
380         return filtered_pcm;
381 }
382
383 std::vector<pulse> detect_pulses(const std::vector<float> &pcm, float hysteresis_upper_limit, float hysteresis_lower_limit, int sample_rate)
384 {
385         std::vector<pulse> pulses;
386
387         // Find the flanks.
388         enum State { START, ABOVE, BELOW } state = START;
389         double last_downflank = -1;
390         for (unsigned i = 0; i < pcm.size(); ++i) {
391                 if (pcm[i] > hysteresis_upper_limit) {
392                         state = ABOVE;
393                 } else if (pcm[i] < hysteresis_lower_limit) {
394                         if (state == ABOVE) {
395                                 // down-flank!
396                                 double t = find_crossing(pcm, i - 1, hysteresis_lower_limit) * (1.0 / sample_rate) + crop_start;
397                                 if (last_downflank > 0) {
398                                         pulse p;
399                                         p.time = t;
400                                         p.len = t - last_downflank;
401                                         pulses.push_back(p);
402                                 }
403                                 last_downflank = t;
404                         }
405                         state = BELOW;
406                 }
407         }
408         return pulses;
409 }
410
411 void output_cycle_plot(const std::vector<pulse> &pulses, double calibration_factor)
412 {
413         FILE *fp = fopen("cycles.plot", "w");
414         for (unsigned i = 0; i < pulses.size(); ++i) {
415                 double cycles = pulses[i].len * calibration_factor * C64_FREQUENCY;
416                 fprintf(fp, "%f %f\n", pulses[i].time, cycles);
417         }
418         fclose(fp);
419 }
420
421 std::pair<int, double> find_closest_point(double x, const std::vector<float> &points)
422 {
423         int best_point = 0;
424         double best_dist = (x - points[0]) * (x - points[0]);
425         for (unsigned j = 1; j < train_snap_points.size(); ++j) {
426                 double dist = (x - points[j]) * (x - points[j]);
427                 if (dist < best_dist) {
428                         best_point = j;
429                         best_dist = dist;
430                 }
431         }
432         return std::make_pair(best_point, best_dist);
433 }
434
435 float eval_badness(const std::vector<pulse>& pulses, double calibration_factor)
436 {
437         double sum_badness = 0.0;
438         for (unsigned i = 0; i < pulses.size(); ++i) {
439                 double cycles = pulses[i].len * calibration_factor * C64_FREQUENCY;
440                 if (cycles > 2000.0) cycles = 2000.0;  // Don't make pauses arbitrarily bad.
441                 std::pair<int, double> selected_point_and_sq_dist = find_closest_point(cycles, train_snap_points);
442                 sum_badness += selected_point_and_sq_dist.second;
443         }
444         return sqrt(sum_badness / (pulses.size() - 1));
445 }
446
447 void find_kmeans(const std::vector<pulse> &pulses, double calibration_factor, const std::vector<float> &initial_centers)
448 {
449         std::vector<float> last_centers = initial_centers;
450         std::vector<float> sums;
451         std::vector<float> num;
452         sums.resize(initial_centers.size());
453         num.resize(initial_centers.size());
454         for ( ;; ) {
455                 for (unsigned i = 0; i < initial_centers.size(); ++i) {
456                         sums[i] = 0.0f;
457                         num[i] = 0;
458                 }
459                 for (unsigned i = 0; i < pulses.size(); ++i) {
460                         double cycles = pulses[i].len * calibration_factor * C64_FREQUENCY;
461                         // Ignore heavy outliers, which are almost always long pauses.
462                         if (cycles > 2000.0) {
463                                 continue;
464                         }
465                         std::pair<int, double> selected_point_and_sq_dist = find_closest_point(cycles, last_centers);
466                         int p = selected_point_and_sq_dist.first;
467                         sums[p] += cycles;
468                         ++num[p];
469                 }
470                 bool any_moved = false;
471                 for (unsigned i = 0; i < initial_centers.size(); ++i) {
472                         if (num[i] == 0) {
473                                 fprintf(stderr, "K-means broke down, can't output new reference training points\n");
474                                 return;
475                         }
476                         float new_center = sums[i] / num[i];
477                         if (fabs(new_center - last_centers[i]) > 1e-3) {
478                                 any_moved = true;
479                         }
480                         last_centers[i] = new_center;
481                 }
482                 if (!any_moved) {
483                         break;
484                 }
485         }
486         fprintf(stderr, "New reference training points:");
487         for (unsigned i = 0; i < last_centers.size(); ++i) {
488                 fprintf(stderr, " %.3f", last_centers[i]);
489         }
490         fprintf(stderr, "\n");
491 }
492
493 void spsa_train(const std::vector<float> &pcm, int sample_rate)
494 {
495         float vals[NUM_SPSA_VALS] = { hysteresis_upper_limit, hysteresis_lower_limit, 1.0f };  // The rest is filled with 0.
496
497         float start_c = INITIAL_C;
498         double best_badness = HUGE_VAL;
499
500         for (int n = 1; n < NUM_ITER; ++n) {
501                 float a = INITIAL_A * pow(n + A, -ALPHA);
502                 float c = start_c * pow(n, -GAMMA);
503
504                 // find a random perturbation
505                 float p[NUM_SPSA_VALS];
506                 float vals1[NUM_SPSA_VALS], vals2[NUM_SPSA_VALS];
507                 for (int i = 0; i < NUM_SPSA_VALS; ++i) {
508                         p[i] = (rand() % 2) ? 1.0 : -1.0;
509                         vals1[i] = std::max(std::min(vals[i] - c * p[i], 1.0f), -1.0f);
510                         vals2[i] = std::max(std::min(vals[i] + c * p[i], 1.0f), -1.0f);
511                 }
512
513                 std::vector<pulse> pulses1 = detect_pulses(do_fir_filter(pcm, vals1 + 2), vals1[0], vals1[1], sample_rate);
514                 std::vector<pulse> pulses2 = detect_pulses(do_fir_filter(pcm, vals2 + 2), vals2[0], vals2[1], sample_rate);
515                 float badness1 = eval_badness(pulses1, 1.0);
516                 float badness2 = eval_badness(pulses2, 1.0);
517
518                 // Find the gradient estimator
519                 float g[NUM_SPSA_VALS];
520                 for (int i = 0; i < NUM_SPSA_VALS; ++i) {
521                         g[i] = (badness2 - badness1) / (2.0 * c * p[i]);
522                         vals[i] -= a * g[i];
523                         vals[i] = std::max(std::min(vals[i], 1.0f), -1.0f);
524                 }
525                 if (badness2 < badness1) {
526                         std::swap(badness1, badness2);
527                         std::swap(vals1, vals2);
528                         std::swap(pulses1, pulses2);
529                 }
530                 if (badness1 < best_badness) {
531                         fprintf(stderr, "\nNew best filter (badness=%f):", badness1);
532                         for (int i = 0; i < NUM_FILTER_COEFF; ++i) {
533                                 fprintf(stderr, " %.5f", vals1[i + 2]);
534                         }
535                         fprintf(stderr, ", hysteresis limits = %f %f\n", vals1[0], vals1[1]);
536                         best_badness = badness1;
537
538                         find_kmeans(pulses1, 1.0, train_snap_points);
539
540                         if (output_cycles_plot) {
541                                 output_cycle_plot(pulses1, 1.0);
542                         }
543                 }
544                 fprintf(stderr, "%d ", n);
545                 fflush(stderr);
546         }
547 }
548
549 int main(int argc, char **argv)
550 {
551         parse_options(argc, argv);
552
553         make_lanczos_weight_table();
554         std::vector<float> pcm;
555         int sample_rate;
556         if (!read_audio_file(argv[optind], &pcm, &sample_rate)) {
557                 exit(1);
558         }
559
560         if (do_crop) {
561                 pcm = crop(pcm, crop_start, crop_end, sample_rate);
562         }
563
564         if (use_fir_filter) {
565                 pcm = do_fir_filter(pcm, filter_coeff);
566         }
567
568         if (use_rc_filter) {
569                 pcm = do_rc_filter(pcm, rc_filter_freq, sample_rate);
570         }
571
572         if (do_auto_level) {
573                 pcm = level_samples(pcm, min_level, auto_level_freq, sample_rate);
574                 if (output_leveled) {
575                         FILE *fp = fopen("leveled.raw", "wb");
576                         fwrite(pcm.data(), pcm.size() * sizeof(pcm[0]), 1, fp);
577                         fclose(fp);
578                 }
579         }
580
581 #if 0
582         for (int i = 0; i < LEN; ++i) {
583                 in[i] += rand() % 10000;
584         }
585 #endif
586
587 #if 0
588         for (int i = 0; i < LEN; ++i) {
589                 printf("%d\n", in[i]);
590         }
591 #endif
592
593         if (do_train) {
594                 spsa_train(pcm, sample_rate);
595                 exit(0);
596         }
597
598         std::vector<pulse> pulses = detect_pulses(pcm, hysteresis_upper_limit, hysteresis_lower_limit, sample_rate);
599
600         double calibration_factor = 1.0;
601         if (do_calibrate) {
602                 calibration_factor = calibrate(pulses);
603         }
604
605         if (output_cycles_plot) {
606                 output_cycle_plot(pulses, calibration_factor);
607         }
608
609         output_tap(pulses, calibration_factor);
610 }