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