10 #include "audioreader.h"
11 #include "interpolate.h"
17 #define C64_FREQUENCY 985248
18 #define SYNC_PULSE_START 1000
19 #define SYNC_PULSE_END 20000
20 #define SYNC_PULSE_LENGTH 378.0
21 #define SYNC_TEST_TOLERANCE 1.10
24 #define NUM_FILTER_COEFF 32
26 #define A NUM_ITER/10 // approx
27 #define INITIAL_A 0.005 // A bit of trial and error...
28 #define INITIAL_C 0.02 // This too.
32 static float hysteresis_limit = 3000.0 / 32768.0;
33 static bool do_calibrate = true;
34 static bool output_cycles_plot = false;
35 static bool do_crop = false;
36 static float crop_start = 0.0f, crop_end = HUGE_VAL;
38 static bool use_fir_filter = false;
39 static float filter_coeff[NUM_FILTER_COEFF] = { 1.0f }; // The rest is filled with 0.
40 static bool use_rc_filter = false;
41 static float rc_filter_freq;
42 static bool output_filtered = false;
44 static bool quiet = false;
45 static bool do_auto_level = false;
46 static bool output_leveled = false;
47 static std::vector<float> train_snap_points;
48 static bool do_train = false;
50 // The minimum estimated sound level (for do_auto_level) at any given point.
51 // If you decrease this, you'll be able to amplify really silent signals
52 // by more, but you'll also increase the level of silent (ie. noise-only) segments,
53 // possibly caused misdetected pulses in these segments.
54 static float min_level = 0.05f;
57 double find_zerocrossing(const std::vector<float> &pcm, int x)
62 if (pcm[x + 1] == 0) {
66 assert(pcm[x + 1] < 0);
71 while (lower - upper > 1e-3) {
72 double mid = 0.5f * (upper + lower);
73 if (lanczos_interpolate(pcm, mid) > 0) {
80 return 0.5f * (upper + lower);
84 double time; // in seconds from start
85 double len; // in seconds
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");
95 int sync_pulse_end = -1;
96 double sync_pulse_stddev = -1.0;
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 }) {
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);
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);
114 sync_pulse_end = try_end;
115 sync_pulse_stddev = stddev;
118 fprintf(stderr, "Sync pulse length standard deviation: %.2f cycles\n",
123 for (int i = SYNC_PULSE_START; i < sync_pulse_end; ++i) {
124 sum += pulses[i].len;
126 double mean_length = C64_FREQUENCY * sum / (sync_pulse_end - SYNC_PULSE_START);
127 double calibration_factor = SYNC_PULSE_LENGTH / mean_length;
129 fprintf(stderr, "Calibrated sync pulse length: %.2f -> %.2f (change %+.2f%%)\n",
130 mean_length, SYNC_PULSE_LENGTH, 100.0 * (calibration_factor - 1.0));
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);
142 return calibration_factor;
145 void output_tap(const std::vector<pulse>& pulses, double calibration_factor)
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);
156 tap_data.push_back(len);
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);
167 memcpy(hdr.identifier, "C64-TAPE-RAW", 12);
169 hdr.reserved[0] = hdr.reserved[1] = hdr.reserved[2] = 0;
170 hdr.data_len = tap_data.size();
172 fwrite(&hdr, sizeof(hdr), 1, stdout);
173 fwrite(tap_data.data(), tap_data.size(), 1, stdout);
176 static struct option long_options[] = {
177 {"auto-level", 0, 0, 'a' },
178 {"output-leveled", 0, 0, 'A' },
179 {"no-calibrate", 0, 0, 's' },
180 {"plot-cycles", 0, 0, 'p' },
181 {"hysteresis-limit", required_argument, 0, 'l' },
182 {"filter", required_argument, 0, 'f' },
183 {"rc-filter", required_argument, 0, 'r' },
184 {"output-filtered", 0, 0, 'F' },
185 {"crop", required_argument, 0, 'c' },
186 {"quiet", 0, 0, 'q' },
187 {"help", 0, 0, 'h' },
193 fprintf(stderr, "decode [OPTIONS] AUDIO-FILE > TAP-FILE\n");
194 fprintf(stderr, "\n");
195 fprintf(stderr, " -a, --auto-level automatically adjust amplitude levels throughout the file\n");
196 fprintf(stderr, " -A, --output-leveled output leveled waveform to leveled.raw\n");
197 fprintf(stderr, " -m, --min-level minimum estimated sound level (0..32768) for --auto-level\n");
198 fprintf(stderr, " -s, --no-calibrate do not try to calibrate on sync pulse length\n");
199 fprintf(stderr, " -p, --plot-cycles output debugging info to cycles.plot\n");
200 fprintf(stderr, " -l, --hysteresis-limit VAL change amplitude threshold for ignoring pulses (0..32768)\n");
201 fprintf(stderr, " -f, --filter C1:C2:C3:... specify FIR filter (up to %d coefficients)\n", NUM_FILTER_COEFF);
202 fprintf(stderr, " -r, --rc-filter FREQ send signal through a highpass RC filter with given frequency (in Hertz)\n");
203 fprintf(stderr, " -F, --output-filtered output filtered waveform to filtered.raw\n");
204 fprintf(stderr, " -c, --crop START[:END] use only the given part of the file\n");
205 fprintf(stderr, " -t, --train LEN1:LEN2:... train a filter for detecting any of the given number of cycles\n");
206 fprintf(stderr, " (implies --no-calibrate and --quiet unless overridden)\n");
207 fprintf(stderr, " -q, --quiet suppress some informational messages\n");
208 fprintf(stderr, " -h, --help display this help, then exit\n");
212 void parse_options(int argc, char **argv)
215 int option_index = 0;
216 int c = getopt_long(argc, argv, "aAm:spl:f:r:Fc:t:qh", long_options, &option_index);
222 do_auto_level = true;
226 output_leveled = true;
230 min_level = atof(optarg) / 32768.0;
234 do_calibrate = false;
238 output_cycles_plot = true;
242 hysteresis_limit = atof(optarg) / 32768.0;
246 const char *coeffstr = strtok(optarg, ": ");
248 while (coeff_index < NUM_FILTER_COEFF && coeffstr != NULL) {
249 filter_coeff[coeff_index++] = atof(coeffstr);
250 coeffstr = strtok(NULL, ": ");
252 use_fir_filter = true;
257 use_rc_filter = true;
258 rc_filter_freq = atof(optarg);
262 output_filtered = true;
266 const char *cropstr = strtok(optarg, ":");
267 crop_start = atof(cropstr);
268 cropstr = strtok(NULL, ":");
269 if (cropstr == NULL) {
272 crop_end = atof(cropstr);
279 const char *cyclestr = strtok(optarg, ":");
280 while (cyclestr != NULL) {
281 train_snap_points.push_back(atof(cyclestr));
282 cyclestr = strtok(NULL, ":");
286 // Set reasonable defaults (can be overridden later on the command line).
287 do_calibrate = false;
304 std::vector<float> crop(const std::vector<float>& pcm, float crop_start, float crop_end, int sample_rate)
306 size_t start_sample, end_sample;
307 if (crop_start >= 0.0f) {
308 start_sample = std::min<size_t>(lrintf(crop_start * sample_rate), pcm.size());
310 if (crop_end >= 0.0f) {
311 end_sample = std::min<size_t>(lrintf(crop_end * sample_rate), pcm.size());
313 return std::vector<float>(pcm.begin() + start_sample, pcm.begin() + end_sample);
316 // TODO: Support AVX here.
317 std::vector<float> do_fir_filter(const std::vector<float>& pcm, const float* filter)
319 std::vector<float> filtered_pcm;
320 filtered_pcm.reserve(pcm.size());
321 for (unsigned i = NUM_FILTER_COEFF; i < pcm.size(); ++i) {
323 for (int j = 0; j < NUM_FILTER_COEFF; ++j) {
324 s += filter[j] * pcm[i - j];
326 filtered_pcm.push_back(s);
329 if (output_filtered) {
330 FILE *fp = fopen("filtered.raw", "wb");
331 fwrite(filtered_pcm.data(), filtered_pcm.size() * sizeof(filtered_pcm[0]), 1, fp);
338 std::vector<float> do_rc_filter(const std::vector<float>& pcm, float freq, int sample_rate)
340 std::vector<float> filtered_pcm;
341 filtered_pcm.resize(pcm.size());
342 Filter filter = Filter::hpf(M_PI * freq / sample_rate);
343 for (unsigned i = 0; i < pcm.size(); ++i) {
344 filtered_pcm[i] = filter.update(pcm[i]);
347 if (output_filtered) {
348 FILE *fp = fopen("filtered.raw", "wb");
349 fwrite(filtered_pcm.data(), filtered_pcm.size() * sizeof(filtered_pcm[0]), 1, fp);
356 std::vector<pulse> detect_pulses(const std::vector<float> &pcm, int sample_rate)
358 std::vector<pulse> pulses;
362 double last_downflank = -1;
363 for (unsigned i = 0; i < pcm.size(); ++i) {
364 int bit = (pcm[i] > 0) ? 1 : 0;
365 if (bit == 0 && last_bit == 1) {
366 // Check if we ever go up above <hysteresis_limit> before we dip down again.
367 bool true_pulse = false;
369 int min_level_after = 32767;
370 for (j = i; j < pcm.size(); ++j) {
371 min_level_after = std::min<int>(min_level_after, pcm[j]);
372 if (pcm[j] > 0) break;
373 if (pcm[j] < -hysteresis_limit) {
381 fprintf(stderr, "Ignored down-flank at %.6f seconds due to hysteresis (%d < %d).\n",
382 double(i) / sample_rate, -min_level_after, hysteresis_limit);
389 double t = find_zerocrossing(pcm, i - 1) * (1.0 / sample_rate) + crop_start;
390 if (last_downflank > 0) {
393 p.len = t - last_downflank;
403 void output_cycle_plot(const std::vector<pulse> &pulses, double calibration_factor)
405 FILE *fp = fopen("cycles.plot", "w");
406 for (unsigned i = 0; i < pulses.size(); ++i) {
407 double cycles = pulses[i].len * calibration_factor * C64_FREQUENCY;
408 fprintf(fp, "%f %f\n", pulses[i].time, cycles);
413 std::pair<int, double> find_closest_point(double x, const std::vector<float> &points)
416 double best_dist = (x - points[0]) * (x - points[0]);
417 for (unsigned j = 1; j < train_snap_points.size(); ++j) {
418 double dist = (x - points[j]) * (x - points[j]);
419 if (dist < best_dist) {
424 return std::make_pair(best_point, best_dist);
427 float eval_badness(const std::vector<pulse>& pulses, double calibration_factor)
429 double sum_badness = 0.0;
430 for (unsigned i = 0; i < pulses.size(); ++i) {
431 double cycles = pulses[i].len * calibration_factor * C64_FREQUENCY;
432 if (cycles > 2000.0) cycles = 2000.0; // Don't make pauses arbitrarily bad.
433 std::pair<int, double> selected_point_and_sq_dist = find_closest_point(cycles, train_snap_points);
434 sum_badness += selected_point_and_sq_dist.second;
436 return sqrt(sum_badness / (pulses.size() - 1));
439 void find_kmeans(const std::vector<pulse> &pulses, double calibration_factor, const std::vector<float> &initial_centers)
441 std::vector<float> last_centers = initial_centers;
442 std::vector<float> sums;
443 std::vector<float> num;
444 sums.resize(initial_centers.size());
445 num.resize(initial_centers.size());
447 for (unsigned i = 0; i < initial_centers.size(); ++i) {
451 for (unsigned i = 0; i < pulses.size(); ++i) {
452 double cycles = pulses[i].len * calibration_factor * C64_FREQUENCY;
453 // Ignore heavy outliers, which are almost always long pauses.
454 if (cycles > 2000.0) {
457 std::pair<int, double> selected_point_and_sq_dist = find_closest_point(cycles, last_centers);
458 int p = selected_point_and_sq_dist.first;
462 bool any_moved = false;
463 for (unsigned i = 0; i < initial_centers.size(); ++i) {
465 printf("K-means broke down, can't output new reference training points\n");
468 float new_center = sums[i] / num[i];
469 if (fabs(new_center - last_centers[i]) > 1e-3) {
472 last_centers[i] = new_center;
478 printf("New reference training points:");
479 for (unsigned i = 0; i < last_centers.size(); ++i) {
480 printf(" %.3f", last_centers[i]);
485 void spsa_train(const std::vector<float> &pcm, int sample_rate)
487 float filter[NUM_FILTER_COEFF] = { 1.0f }; // The rest is filled with 0.
489 float start_c = INITIAL_C;
490 double best_badness = HUGE_VAL;
492 for (int n = 1; n < NUM_ITER; ++n) {
493 float a = INITIAL_A * pow(n + A, -ALPHA);
494 float c = start_c * pow(n, -GAMMA);
496 // find a random perturbation
497 float p[NUM_FILTER_COEFF];
498 float filter1[NUM_FILTER_COEFF], filter2[NUM_FILTER_COEFF];
499 for (int i = 0; i < NUM_FILTER_COEFF; ++i) {
500 p[i] = (rand() % 2) ? 1.0 : -1.0;
501 filter1[i] = std::max(std::min(filter[i] - c * p[i], 1.0f), -1.0f);
502 filter2[i] = std::max(std::min(filter[i] + c * p[i], 1.0f), -1.0f);
505 std::vector<pulse> pulses1 = detect_pulses(do_fir_filter(pcm, filter1), sample_rate);
506 std::vector<pulse> pulses2 = detect_pulses(do_fir_filter(pcm, filter2), sample_rate);
507 float badness1 = eval_badness(pulses1, 1.0);
508 float badness2 = eval_badness(pulses2, 1.0);
510 // Find the gradient estimator
511 float g[NUM_FILTER_COEFF];
512 for (int i = 0; i < NUM_FILTER_COEFF; ++i) {
513 g[i] = (badness2 - badness1) / (2.0 * c * p[i]);
514 filter[i] -= a * g[i];
515 filter[i] = std::max(std::min(filter[i], 1.0f), -1.0f);
517 if (badness2 < badness1) {
518 std::swap(badness1, badness2);
519 std::swap(filter1, filter2);
520 std::swap(pulses1, pulses2);
522 if (badness1 < best_badness) {
523 printf("\nNew best filter (badness=%f):", badness1);
524 for (int i = 0; i < NUM_FILTER_COEFF; ++i) {
525 printf(" %.5f", filter1[i]);
527 best_badness = badness1;
530 find_kmeans(pulses1, 1.0, train_snap_points);
532 if (output_cycles_plot) {
533 output_cycle_plot(pulses1, 1.0);
541 int main(int argc, char **argv)
543 parse_options(argc, argv);
545 make_lanczos_weight_table();
546 std::vector<float> pcm;
548 if (!read_audio_file(argv[optind], &pcm, &sample_rate)) {
553 pcm = crop(pcm, crop_start, crop_end, sample_rate);
556 if (use_fir_filter) {
557 pcm = do_fir_filter(pcm, filter_coeff);
561 pcm = do_rc_filter(pcm, rc_filter_freq, sample_rate);
565 pcm = level_samples(pcm, min_level, sample_rate);
566 if (output_leveled) {
567 FILE *fp = fopen("leveled.raw", "wb");
568 fwrite(pcm.data(), pcm.size() * sizeof(pcm[0]), 1, fp);
574 for (int i = 0; i < LEN; ++i) {
575 in[i] += rand() % 10000;
580 for (int i = 0; i < LEN; ++i) {
581 printf("%d\n", in[i]);
586 spsa_train(pcm, sample_rate);
590 std::vector<pulse> pulses = detect_pulses(pcm, sample_rate);
592 double calibration_factor = 1.0;
594 calibration_factor = calibrate(pulses);
597 if (output_cycles_plot) {
598 output_cycle_plot(pulses, calibration_factor);
601 output_tap(pulses, calibration_factor);