]> git.sesse.net Git - c64tapwav/blob - decode.cpp
Integrate the leveler into decode.
[c64tapwav] / decode.cpp
1 #include <stdio.h>
2 #include <string.h>
3 #include <math.h>
4 #include <assert.h>
5 #include <limits.h>
6 #include <getopt.h>
7 #include <vector>
8 #include <algorithm>
9
10 #include "audioreader.h"
11 #include "interpolate.h"
12 #include "level.h"
13 #include "tap.h"
14
15 #define BUFSIZE 4096
16 #define C64_FREQUENCY 985248
17 #define SYNC_PULSE_START 1000
18 #define SYNC_PULSE_END 20000
19 #define SYNC_PULSE_LENGTH 378.0
20 #define SYNC_TEST_TOLERANCE 1.10
21
22 #define NUM_FILTER_COEFF 32
23
24 static float hysteresis_limit = 3000.0 / 32768.0;
25 static bool do_calibrate = true;
26 static bool output_cycles_plot = false;
27 static bool use_filter = false;
28 static bool do_crop = false;
29 static float crop_start = 0.0f, crop_end = HUGE_VAL;
30 static float filter_coeff[NUM_FILTER_COEFF] = { 1.0f };  // The rest is filled with 0.
31 static bool output_filtered = false;
32 static bool quiet = false;
33 static bool do_auto_level = false;
34 static bool output_leveled = false;
35
36 // between [x,x+1]
37 double find_zerocrossing(const std::vector<float> &pcm, int x)
38 {
39         if (pcm[x] == 0) {
40                 return x;
41         }
42         if (pcm[x + 1] == 0) {
43                 return x + 1;
44         }
45
46         assert(pcm[x + 1] < 0);
47         assert(pcm[x] > 0);
48
49         double upper = x;
50         double lower = x + 1;
51         while (lower - upper > 1e-3) {
52                 double mid = 0.5f * (upper + lower);
53                 if (lanczos_interpolate(pcm, mid) > 0) {
54                         upper = mid;
55                 } else {
56                         lower = mid;
57                 }
58         }
59
60         return 0.5f * (upper + lower);
61 }
62
63 struct pulse {
64         double time;  // in seconds from start
65         double len;   // in seconds
66 };
67
68 // Calibrate on the first ~25k pulses (skip a few, just to be sure).
69 double calibrate(const std::vector<pulse> &pulses) {
70         if (pulses.size() < SYNC_PULSE_END) {
71                 fprintf(stderr, "Too few pulses, not calibrating!\n");
72                 return 1.0;
73         }
74
75         int sync_pulse_end = -1;
76         double sync_pulse_stddev = -1.0;
77
78         // Compute the standard deviation (to check for uneven speeds).
79         // If it suddenly skyrockets, we assume that sync ended earlier
80         // than we thought (it should be 25000 cycles), and that we should
81         // calibrate on fewer cycles.
82         for (int try_end : { 2000, 4000, 5000, 7500, 10000, 15000, SYNC_PULSE_END }) {
83                 double sum2 = 0.0;
84                 for (int i = SYNC_PULSE_START; i < try_end; ++i) {
85                         double cycles = pulses[i].len * C64_FREQUENCY;
86                         sum2 += (cycles - SYNC_PULSE_LENGTH) * (cycles - SYNC_PULSE_LENGTH);
87                 }
88                 double stddev = sqrt(sum2 / (try_end - SYNC_PULSE_START - 1));
89                 if (sync_pulse_end != -1 && stddev > 5.0 && stddev / sync_pulse_stddev > 1.3) {
90                         fprintf(stderr, "Stopping at %d sync pulses because standard deviation would be too big (%.2f cycles); shorter-than-usual trailer?\n",
91                                 sync_pulse_end, stddev);
92                         break;
93                 }
94                 sync_pulse_end = try_end;
95                 sync_pulse_stddev = stddev;
96         }
97         if (!quiet) {
98                 fprintf(stderr, "Sync pulse length standard deviation: %.2f cycles\n",
99                         sync_pulse_stddev);
100         }
101
102         double sum = 0.0;
103         for (int i = SYNC_PULSE_START; i < sync_pulse_end; ++i) {
104                 sum += pulses[i].len;
105         }
106         double mean_length = C64_FREQUENCY * sum / (sync_pulse_end - SYNC_PULSE_START);
107         double calibration_factor = SYNC_PULSE_LENGTH / mean_length;
108         if (!quiet) {
109                 fprintf(stderr, "Calibrated sync pulse length: %.2f -> %.2f (change %+.2f%%)\n",
110                         mean_length, SYNC_PULSE_LENGTH, 100.0 * (calibration_factor - 1.0));
111         }
112
113         // Check for pulses outside +/- 10% (sign of misdetection).
114         for (int i = SYNC_PULSE_START; i < sync_pulse_end; ++i) {
115                 double cycles = pulses[i].len * calibration_factor * C64_FREQUENCY;
116                 if (cycles < SYNC_PULSE_LENGTH / SYNC_TEST_TOLERANCE || cycles > SYNC_PULSE_LENGTH * SYNC_TEST_TOLERANCE) {
117                         fprintf(stderr, "Sync cycle with downflank at %.6f was detected at %.0f cycles; misdetect?\n",
118                                 pulses[i].time, cycles);
119                 }
120         }
121
122         return calibration_factor;
123 }
124
125 void output_tap(const std::vector<pulse>& pulses, double calibration_factor)
126 {
127         std::vector<char> tap_data;
128         for (unsigned i = 0; i < pulses.size(); ++i) {
129                 double cycles = pulses[i].len * calibration_factor * C64_FREQUENCY;
130                 int len = lrintf(cycles / TAP_RESOLUTION);
131                 if (i > SYNC_PULSE_END && (cycles < 100 || cycles > 800)) {
132                         fprintf(stderr, "Cycle with downflank at %.6f was detected at %.0f cycles; misdetect?\n",
133                                         pulses[i].time, cycles);
134                 }
135                 if (len <= 255) {
136                         tap_data.push_back(len);
137                 } else {
138                         int overflow_len = lrintf(cycles);
139                         tap_data.push_back(0);
140                         tap_data.push_back(overflow_len & 0xff);
141                         tap_data.push_back((overflow_len >> 8) & 0xff);
142                         tap_data.push_back(overflow_len >> 16);
143                 }
144         }
145
146         tap_header hdr;
147         memcpy(hdr.identifier, "C64-TAPE-RAW", 12);
148         hdr.version = 1;
149         hdr.reserved[0] = hdr.reserved[1] = hdr.reserved[2] = 0;
150         hdr.data_len = tap_data.size();
151
152         fwrite(&hdr, sizeof(hdr), 1, stdout);
153         fwrite(tap_data.data(), tap_data.size(), 1, stdout);
154 }
155
156 static struct option long_options[] = {
157         {"auto-level",       0,                 0, 'a' },
158         {"no-calibrate",     0,                 0, 's' },
159         {"plot-cycles",      0,                 0, 'p' },
160         {"hysteresis-limit", required_argument, 0, 'l' },
161         {"filter",           required_argument, 0, 'f' },
162         {"output-filtered",  0,                 0, 'F' },
163         {"crop",             required_argument, 0, 'c' },
164         {"quiet",            0,                 0, 'q' },
165         {"help",             0,                 0, 'h' },
166         {0,                  0,                 0, 0   }
167 };
168
169 void help()
170 {
171         fprintf(stderr, "decode [OPTIONS] AUDIO-FILE > TAP-FILE\n");
172         fprintf(stderr, "\n");
173         fprintf(stderr, "  -a, --auto-level             automatically adjust amplitude levels throughout the file\n");
174         fprintf(stderr, "  -A, --output-leveled         output leveled waveform to leveled.raw\n");
175         fprintf(stderr, "  -s, --no-calibrate           do not try to calibrate on sync pulse length\n");
176         fprintf(stderr, "  -p, --plot-cycles            output debugging info to cycles.plot\n");
177         fprintf(stderr, "  -l, --hysteresis-limit VAL   change amplitude threshold for ignoring pulses (0..32768)\n");
178         fprintf(stderr, "  -f, --filter C1:C2:C3:...    specify FIR filter (up to %d coefficients)\n", NUM_FILTER_COEFF);
179         fprintf(stderr, "  -F, --output-filtered        output filtered waveform to filtered.raw\n");
180         fprintf(stderr, "  -c, --crop START[:END]       use only the given part of the file\n");
181         fprintf(stderr, "  -q, --quiet                  suppress some informational messages\n");
182         fprintf(stderr, "  -h, --help                   display this help, then exit\n");
183         exit(1);
184 }
185
186 void parse_options(int argc, char **argv)
187 {
188         for ( ;; ) {
189                 int option_index = 0;
190                 int c = getopt_long(argc, argv, "aAspl:f:Fc:qh", long_options, &option_index);
191                 if (c == -1)
192                         break;
193
194                 switch (c) {
195                 case 'a':
196                         do_auto_level = true;
197                         break;
198
199                 case 'A':
200                         output_leveled = true;
201                         break;
202
203                 case 's':
204                         do_calibrate = false;
205                         break;
206
207                 case 'p':
208                         output_cycles_plot = true;
209                         break;
210
211                 case 'l':
212                         hysteresis_limit = atof(optarg) / 32768.0;
213                         break;
214
215                 case 'f': {
216                         const char *coeffstr = strtok(optarg, ":");
217                         int coeff_index = 0;
218                         while (coeff_index < NUM_FILTER_COEFF && coeffstr != NULL) {
219                                 filter_coeff[coeff_index++] = atof(coeffstr);
220                                 coeffstr = strtok(NULL, ":");
221                         }
222                         use_filter = true;
223                         break;
224                 }
225
226                 case 'F':
227                         output_filtered = true;
228                         break;
229
230                 case 'c': {
231                         const char *cropstr = strtok(optarg, ":");
232                         crop_start = atof(cropstr);
233                         cropstr = strtok(NULL, ":");
234                         if (cropstr == NULL) {
235                                 crop_end = HUGE_VAL;
236                         } else {
237                                 crop_end = atof(cropstr);
238                         }
239                         do_crop = true;
240                         break;
241                 }
242
243                 case 'q':
244                         quiet = true;
245                         break;
246
247                 case 'h':
248                 default:
249                         help();
250                         exit(1);
251                 }
252         }
253 }
254
255 std::vector<float> crop(const std::vector<float>& pcm, float crop_start, float crop_end, int sample_rate)
256 {
257         size_t start_sample, end_sample;
258         if (crop_start >= 0.0f) {
259                 start_sample = std::min<size_t>(lrintf(crop_start * sample_rate), pcm.size());
260         }
261         if (crop_end >= 0.0f) {
262                 end_sample = std::min<size_t>(lrintf(crop_end * sample_rate), pcm.size());
263         }
264         return std::vector<float>(pcm.begin() + start_sample, pcm.begin() + end_sample);
265 }
266
267 // TODO: Support AVX here.
268 std::vector<float> do_filter(const std::vector<float>& pcm, const float* filter)
269 {
270         std::vector<float> filtered_pcm;
271         filtered_pcm.reserve(pcm.size());
272         for (unsigned i = NUM_FILTER_COEFF; i < pcm.size(); ++i) {
273                 float s = 0.0f;
274                 for (int j = 0; j < NUM_FILTER_COEFF; ++j) {
275                         s += filter[j] * pcm[i - j];
276                 }
277                 filtered_pcm.push_back(s);
278         }
279
280         if (output_filtered) {
281                 FILE *fp = fopen("filtered.raw", "wb");
282                 fwrite(filtered_pcm.data(), filtered_pcm.size() * sizeof(filtered_pcm[0]), 1, fp);
283                 fclose(fp);
284         }
285
286         return filtered_pcm;
287 }
288
289 std::vector<pulse> detect_pulses(const std::vector<float> &pcm, int sample_rate)
290 {
291         std::vector<pulse> pulses;
292
293         // Find the flanks.
294         int last_bit = -1;
295         double last_downflank = -1;
296         for (unsigned i = 0; i < pcm.size(); ++i) {
297                 int bit = (pcm[i] > 0) ? 1 : 0;
298                 if (bit == 0 && last_bit == 1) {
299                         // Check if we ever go up above <hysteresis_limit> before we dip down again.
300                         bool true_pulse = false;
301                         unsigned j;
302                         int min_level_after = 32767;
303                         for (j = i; j < pcm.size(); ++j) {
304                                 min_level_after = std::min<int>(min_level_after, pcm[j]);
305                                 if (pcm[j] > 0) break;
306                                 if (pcm[j] < -hysteresis_limit) {
307                                         true_pulse = true;
308                                         break;
309                                 }
310                         }
311
312                         if (!true_pulse) {
313 #if 0
314                                 fprintf(stderr, "Ignored down-flank at %.6f seconds due to hysteresis (%d < %d).\n",
315                                         double(i) / sample_rate, -min_level_after, hysteresis_limit);
316 #endif
317                                 i = j;
318                                 continue;
319                         } 
320
321                         // down-flank!
322                         double t = find_zerocrossing(pcm, i - 1) * (1.0 / sample_rate) + crop_start;
323                         if (last_downflank > 0) {
324                                 pulse p;
325                                 p.time = t;
326                                 p.len = t - last_downflank;
327                                 pulses.push_back(p);
328                         }
329                         last_downflank = t;
330                 }
331                 last_bit = bit;
332         }
333         return pulses;
334 }
335
336 void output_cycle_plot(const std::vector<pulse> &pulses, double calibration_factor)
337 {
338         FILE *fp = fopen("cycles.plot", "w");
339         for (unsigned i = 0; i < pulses.size(); ++i) {
340                 double cycles = pulses[i].len * calibration_factor * C64_FREQUENCY;
341                 fprintf(fp, "%f %f\n", pulses[i].time, cycles);
342         }
343         fclose(fp);
344 }
345
346 int main(int argc, char **argv)
347 {
348         parse_options(argc, argv);
349
350         make_lanczos_weight_table();
351         std::vector<float> pcm;
352         int sample_rate;
353         if (!read_audio_file(argv[optind], &pcm, &sample_rate)) {
354                 exit(1);
355         }
356
357         if (do_crop) {
358                 pcm = crop(pcm, crop_start, crop_end, sample_rate);
359         }
360
361         if (use_filter) {
362                 pcm = do_filter(pcm, filter_coeff);
363         }
364
365         if (do_auto_level) {
366                 pcm = level_samples(pcm, sample_rate);
367                 if (output_leveled) {
368                         FILE *fp = fopen("leveled.raw", "wb");
369                         fwrite(pcm.data(), pcm.size() * sizeof(pcm[0]), 1, fp);
370                         fclose(fp);
371                 }
372         }
373
374 #if 0
375         for (int i = 0; i < LEN; ++i) {
376                 in[i] += rand() % 10000;
377         }
378 #endif
379
380 #if 0
381         for (int i = 0; i < LEN; ++i) {
382                 printf("%d\n", in[i]);
383         }
384 #endif
385
386         std::vector<pulse> pulses = detect_pulses(pcm, sample_rate);
387
388         double calibration_factor = 1.0;
389         if (do_calibrate) {
390                 calibration_factor = calibrate(pulses);
391         }
392
393         if (output_cycles_plot) {
394                 output_cycle_plot(pulses, calibration_factor);
395         }
396
397         output_tap(pulses, calibration_factor);
398 }