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