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