]> git.sesse.net Git - c64tapwav/blob - decode.cpp
Add some quasi-useful options.
[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 static float hysteresis_limit = 3000.0 / 32768.0;
22 static bool do_calibrate = true;
23 static bool output_cycles_plot = false;
24
25 // between [x,x+1]
26 double find_zerocrossing(const std::vector<float> &pcm, int x)
27 {
28         if (pcm[x] == 0) {
29                 return x;
30         }
31         if (pcm[x + 1] == 0) {
32                 return x + 1;
33         }
34
35         assert(pcm[x + 1] < 0);
36         assert(pcm[x] > 0);
37
38         double upper = x;
39         double lower = x + 1;
40         while (lower - upper > 1e-3) {
41                 double mid = 0.5f * (upper + lower);
42                 if (lanczos_interpolate(pcm, mid) > 0) {
43                         upper = mid;
44                 } else {
45                         lower = mid;
46                 }
47         }
48
49         return 0.5f * (upper + lower);
50 }
51
52 struct pulse {
53         double time;  // in seconds from start
54         double len;   // in seconds
55 };
56
57 // Calibrate on the first ~25k pulses (skip a few, just to be sure).
58 double calibrate(const std::vector<pulse> &pulses) {
59         if (pulses.size() < SYNC_PULSE_END) {
60                 fprintf(stderr, "Too few pulses, not calibrating!\n");
61                 return 1.0;
62         }
63
64         int sync_pulse_end = -1;
65         double sync_pulse_stddev = -1.0;
66
67         // Compute the standard deviation (to check for uneven speeds).
68         // If it suddenly skyrockets, we assume that sync ended earlier
69         // than we thought (it should be 25000 cycles), and that we should
70         // calibrate on fewer cycles.
71         for (int try_end : { 2000, 4000, 5000, 7500, 10000, 15000, SYNC_PULSE_END }) {
72                 double sum2 = 0.0;
73                 for (int i = SYNC_PULSE_START; i < try_end; ++i) {
74                         double cycles = pulses[i].len * C64_FREQUENCY;
75                         sum2 += (cycles - SYNC_PULSE_LENGTH) * (cycles - SYNC_PULSE_LENGTH);
76                 }
77                 double stddev = sqrt(sum2 / (try_end - SYNC_PULSE_START - 1));
78                 if (sync_pulse_end != -1 && stddev > 5.0 && stddev / sync_pulse_stddev > 1.3) {
79                         fprintf(stderr, "Stopping at %d sync pulses because standard deviation would be too big (%.2f cycles); shorter-than-usual trailer?\n",
80                                 sync_pulse_end, stddev);
81                         break;
82                 }
83                 sync_pulse_end = try_end;
84                 sync_pulse_stddev = stddev;
85         }
86         fprintf(stderr, "Sync pulse length standard deviation: %.2f cycles\n",
87                 sync_pulse_stddev);
88
89         double sum = 0.0;
90         for (int i = SYNC_PULSE_START; i < sync_pulse_end; ++i) {
91                 sum += pulses[i].len;
92         }
93         double mean_length = C64_FREQUENCY * sum / (sync_pulse_end - SYNC_PULSE_START);
94         double calibration_factor = SYNC_PULSE_LENGTH / mean_length;
95         fprintf(stderr, "Calibrated sync pulse length: %.2f -> %.2f (change %+.2f%%)\n",
96                 mean_length, SYNC_PULSE_LENGTH, 100.0 * (calibration_factor - 1.0));
97
98         // Check for pulses outside +/- 10% (sign of misdetection).
99         for (int i = SYNC_PULSE_START; i < sync_pulse_end; ++i) {
100                 double cycles = pulses[i].len * calibration_factor * C64_FREQUENCY;
101                 if (cycles < SYNC_PULSE_LENGTH / SYNC_TEST_TOLERANCE || cycles > SYNC_PULSE_LENGTH * SYNC_TEST_TOLERANCE) {
102                         fprintf(stderr, "Sync cycle with downflank at %.6f was detected at %.0f cycles; misdetect?\n",
103                                 pulses[i].time, cycles);
104                 }
105         }
106
107         return calibration_factor;
108 }
109
110 void output_tap(const std::vector<pulse>& pulses, double calibration_factor)
111 {
112         std::vector<char> tap_data;
113         for (unsigned i = 0; i < pulses.size(); ++i) {
114                 double cycles = pulses[i].len * calibration_factor * C64_FREQUENCY;
115                 int len = lrintf(cycles / TAP_RESOLUTION);
116                 if (i > SYNC_PULSE_END && (cycles < 100 || cycles > 800)) {
117                         fprintf(stderr, "Cycle with downflank at %.6f was detected at %.0f cycles; misdetect?\n",
118                                         pulses[i].time, cycles);
119                 }
120                 if (len <= 255) {
121                         tap_data.push_back(len);
122                 } else {
123                         int overflow_len = lrintf(cycles);
124                         tap_data.push_back(0);
125                         tap_data.push_back(overflow_len & 0xff);
126                         tap_data.push_back((overflow_len >> 8) & 0xff);
127                         tap_data.push_back(overflow_len >> 16);
128                 }
129         }
130
131         tap_header hdr;
132         memcpy(hdr.identifier, "C64-TAPE-RAW", 12);
133         hdr.version = 1;
134         hdr.reserved[0] = hdr.reserved[1] = hdr.reserved[2] = 0;
135         hdr.data_len = tap_data.size();
136
137         fwrite(&hdr, sizeof(hdr), 1, stdout);
138         fwrite(tap_data.data(), tap_data.size(), 1, stdout);
139 }
140
141 static struct option long_options[] = {
142         {"no-calibrate",     0,                 0, 's' },
143         {"plot-cycles",      0,                 0, 'p' },
144         {"hysteresis-limit", required_argument, 0, 'l' },
145         {"help",             0,                 0, 'h' },
146         {0,                  0,                 0, 0   }
147 };
148
149 void help()
150 {
151         fprintf(stderr, "decode [OPTIONS] AUDIO-FILE > TAP-FILE\n");
152         fprintf(stderr, "\n");
153         fprintf(stderr, "  -s, --no-calibrate           do not try to calibrate on sync pulse length\n");
154         fprintf(stderr, "  -p, --plot-cycles            output debugging info to cycles.plot\n");
155         fprintf(stderr, "  -l, --hysteresis-limit VAL   change amplitude threshold for ignoring pulses (0..32768)\n");
156         fprintf(stderr, "  -h, --help                   display this help, then exit\n");
157         exit(1);
158 }
159
160 void parse_options(int argc, char **argv)
161 {
162         for ( ;; ) {
163                 int option_index = 0;
164                 int c = getopt_long(argc, argv, "spl:h", long_options, &option_index);
165                 if (c == -1)
166                         break;
167
168                 switch (c) {
169                 case 's':
170                         do_calibrate = false;
171                         break;
172
173                 case 'p':
174                         output_cycles_plot = true;
175                         break;
176                 case 'l':
177                         hysteresis_limit = atof(optarg) / 32768.0;
178                         break;
179
180                 case 'h':
181                 default:
182                         help();
183                         exit(1);
184                 }
185         }
186 }
187
188 int main(int argc, char **argv)
189 {
190         parse_options(argc, argv);
191
192         make_lanczos_weight_table();
193         std::vector<float> pcm;
194         int sample_rate;
195         if (!read_audio_file(argv[optind], &pcm, &sample_rate)) {
196                 exit(1);
197         }
198
199 #if 0
200         for (int i = 0; i < LEN; ++i) {
201                 in[i] += rand() % 10000;
202         }
203 #endif
204
205 #if 0
206         for (int i = 0; i < LEN; ++i) {
207                 printf("%d\n", in[i]);
208         }
209 #endif
210
211         std::vector<pulse> pulses;  // in seconds
212
213         // Find the flanks.
214         int last_bit = -1;
215         double last_downflank = -1;
216         for (unsigned i = 0; i < pcm.size(); ++i) {
217                 int bit = (pcm[i] > 0) ? 1 : 0;
218                 if (bit == 0 && last_bit == 1) {
219                         // Check if we ever go up above <hysteresis_limit> before we dip down again.
220                         bool true_pulse = false;
221                         unsigned j;
222                         int min_level_after = 32767;
223                         for (j = i; j < pcm.size(); ++j) {
224                                 min_level_after = std::min<int>(min_level_after, pcm[j]);
225                                 if (pcm[j] > 0) break;
226                                 if (pcm[j] < -hysteresis_limit) {
227                                         true_pulse = true;
228                                         break;
229                                 }
230                         }
231
232                         if (!true_pulse) {
233 #if 0
234                                 fprintf(stderr, "Ignored down-flank at %.6f seconds due to hysteresis (%d < %d).\n",
235                                         double(i) / sample_rate, -min_level_after, hysteresis_limit);
236 #endif
237                                 i = j;
238                                 continue;
239                         } 
240
241                         // down-flank!
242                         double t = find_zerocrossing(pcm, i - 1) * (1.0 / sample_rate);
243                         if (last_downflank > 0) {
244                                 pulse p;
245                                 p.time = t;
246                                 p.len = t - last_downflank;
247                                 pulses.push_back(p);
248                         }
249                         last_downflank = t;
250                 }
251                 last_bit = bit;
252         }
253
254         double calibration_factor = 1.0;
255         if (do_calibrate) {
256                 calibration_factor = calibrate(pulses);
257         }
258
259         if (output_cycles_plot) {
260                 FILE *fp = fopen("cycles.plot", "w");
261                 for (unsigned i = 0; i < pulses.size(); ++i) {
262                         double cycles = pulses[i].len * calibration_factor * C64_FREQUENCY;
263                         fprintf(fp, "%f %f\n", pulses[i].time, cycles);
264                 }
265                 fclose(fp);
266         }
267
268         output_tap(pulses, calibration_factor);
269 }