Add some heuristics to deal with shorter initial sync periods.
[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 <vector>
7 #include <algorithm>
8
9 #include "audioreader.h"
10 #include "interpolate.h"
11 #include "tap.h"
12
13 #define BUFSIZE 4096
14 #define HYSTERESIS_LIMIT 3000
15 #define C64_FREQUENCY 985248
16
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 // between [x,x+1]
23 double find_zerocrossing(const std::vector<short> &pcm, int x)
24 {
25         if (pcm[x] == 0) {
26                 return x;
27         }
28         if (pcm[x + 1] == 0) {
29                 return x + 1;
30         }
31
32         assert(pcm[x + 1] < 0);
33         assert(pcm[x] > 0);
34
35         double upper = x;
36         double lower = x + 1;
37         while (lower - upper > 1e-3) {
38                 double mid = 0.5f * (upper + lower);
39                 if (lanczos_interpolate(pcm, mid) > 0) {
40                         upper = mid;
41                 } else {
42                         lower = mid;
43                 }
44         }
45
46         return 0.5f * (upper + lower);
47 }
48
49 struct pulse {
50         double time;  // in seconds from start
51         double len;   // in seconds
52 };
53
54 // Calibrate on the first ~25k pulses (skip a few, just to be sure).
55 double calibrate(const std::vector<pulse> &pulses) {
56         if (pulses.size() < SYNC_PULSE_END) {
57                 fprintf(stderr, "Too few pulses, not calibrating!\n");
58                 return 1.0;
59         }
60
61         int sync_pulse_end = -1;
62         double sync_pulse_stddev = -1.0;
63
64         // Compute the standard deviation (to check for uneven speeds).
65         // If it suddenly skyrockets, we assume that sync ended earlier
66         // than we thought (it should be 25000 cycles), and that we should
67         // calibrate on fewer cycles.
68         for (int try_end : { 2000, 4000, 5000, 7500, 10000, 15000, SYNC_PULSE_END }) {
69                 double sum2 = 0.0;
70                 for (int i = SYNC_PULSE_START; i < try_end; ++i) {
71                         double cycles = pulses[i].len * C64_FREQUENCY;
72                         sum2 += (cycles - SYNC_PULSE_LENGTH) * (cycles - SYNC_PULSE_LENGTH);
73                 }
74                 double stddev = sqrt(sum2 / (try_end - SYNC_PULSE_START - 1));
75                 if (sync_pulse_end != -1 && stddev > 5.0 && stddev / sync_pulse_stddev > 1.3) {
76                         fprintf(stderr, "Stopping at %d sync pulses because standard deviation would be too big (%.2f cycles); shorter-than-usual trailer?\n",
77                                 sync_pulse_end, stddev);
78                         break;
79                 }
80                 sync_pulse_end = try_end;
81                 sync_pulse_stddev = stddev;
82         }
83         fprintf(stderr, "Sync pulse length standard deviation: %.2f cycles\n",
84                 sync_pulse_stddev);
85
86         double sum = 0.0;
87         for (int i = SYNC_PULSE_START; i < sync_pulse_end; ++i) {
88                 sum += pulses[i].len;
89         }
90         double mean_length = C64_FREQUENCY * sum / (sync_pulse_end - SYNC_PULSE_START);
91         double calibration_factor = SYNC_PULSE_LENGTH / mean_length;
92         fprintf(stderr, "Calibrated sync pulse length: %.2f -> %.2f (change %+.2f%%)\n",
93                 mean_length, SYNC_PULSE_LENGTH, 100.0 * (calibration_factor - 1.0));
94
95         // Check for pulses outside +/- 10% (sign of misdetection).
96         for (int i = SYNC_PULSE_START; i < sync_pulse_end; ++i) {
97                 double cycles = pulses[i].len * calibration_factor * C64_FREQUENCY;
98                 if (cycles < SYNC_PULSE_LENGTH / SYNC_TEST_TOLERANCE || cycles > SYNC_PULSE_LENGTH * SYNC_TEST_TOLERANCE) {
99                         fprintf(stderr, "Sync cycle with downflank at %.6f was detected at %.0f cycles; misdetect?\n",
100                                 pulses[i].time, cycles);
101                 }
102         }
103
104         return calibration_factor;
105 }
106         
107 int main(int argc, char **argv)
108 {
109         make_lanczos_weight_table();
110         std::vector<short> pcm;
111         int sample_rate;
112         if (!read_audio_file(argv[1], &pcm, &sample_rate)) {
113                 exit(1);
114         }
115
116 #if 0
117         for (int i = 0; i < LEN; ++i) {
118                 in[i] += rand() % 10000;
119         }
120 #endif
121
122 #if 0
123         for (int i = 0; i < LEN; ++i) {
124                 printf("%d\n", in[i]);
125         }
126 #endif
127
128         std::vector<pulse> pulses;  // in seconds
129
130         // Find the flanks.
131         int last_bit = -1;
132         double last_downflank = -1;
133         for (unsigned i = 0; i < pcm.size(); ++i) {
134                 int bit = (pcm[i] > 0) ? 1 : 0;
135                 if (bit == 0 && last_bit == 1) {
136                         // Check if we ever go up above HYSTERESIS_LIMIT before we dip down again.
137                         bool true_pulse = false;
138                         unsigned j;
139                         int min_level_after = 32767;
140                         for (j = i; j < pcm.size(); ++j) {
141                                 min_level_after = std::min<int>(min_level_after, pcm[j]);
142                                 if (pcm[j] > 0) break;
143                                 if (pcm[j] < -HYSTERESIS_LIMIT) {
144                                         true_pulse = true;
145                                         break;
146                                 }
147                         }
148
149                         if (!true_pulse) {
150 #if 0
151                                 fprintf(stderr, "Ignored down-flank at %.6f seconds due to hysteresis (%d < %d).\n",
152                                         double(i) / sample_rate, -min_level_after, HYSTERESIS_LIMIT);
153 #endif
154                                 i = j;
155                                 continue;
156                         } 
157
158                         // down-flank!
159                         double t = find_zerocrossing(pcm, i - 1) * (1.0 / sample_rate);
160                         if (last_downflank > 0) {
161                                 pulse p;
162                                 p.time = t;
163                                 p.len = t - last_downflank;
164                                 pulses.push_back(p);
165                         }
166                         last_downflank = t;
167                 }
168                 last_bit = bit;
169         }
170
171         double calibration_factor = calibrate(pulses);
172
173         FILE *fp = fopen("cycles.plot", "w");
174         std::vector<char> tap_data;
175         for (unsigned i = 0; i < pulses.size(); ++i) {
176                 double cycles = pulses[i].len * calibration_factor * C64_FREQUENCY;
177                 fprintf(fp, "%f %f\n", pulses[i].time, cycles);
178                 int len = lrintf(cycles / TAP_RESOLUTION);
179                 if (i > SYNC_PULSE_END && (cycles < 100 || cycles > 800)) {
180                         fprintf(stderr, "Cycle with downflank at %.6f was detected at %.0f cycles; misdetect?\n",
181                                         pulses[i].time, cycles);
182                 }
183                 if (len <= 255) {
184                         tap_data.push_back(len);
185                 } else {
186                         int overflow_len = lrintf(cycles);
187                         tap_data.push_back(0);
188                         tap_data.push_back(overflow_len & 0xff);
189                         tap_data.push_back((overflow_len >> 8) & 0xff);
190                         tap_data.push_back(overflow_len >> 16);
191                 }
192         }
193         fclose(fp);
194
195         tap_header hdr;
196         memcpy(hdr.identifier, "C64-TAPE-RAW", 12);
197         hdr.version = 1;
198         hdr.reserved[0] = hdr.reserved[1] = hdr.reserved[2] = 0;
199         hdr.data_len = tap_data.size();
200
201         fwrite(&hdr, sizeof(hdr), 1, stdout);
202         fwrite(tap_data.data(), tap_data.size(), 1, stdout);
203
204         // Output a debug raw file with pulse detection points.
205         fp = fopen("debug.raw", "wb");
206         short one = 32767;
207         short zero = 0;
208         unsigned pulsenum = 0;
209         for (unsigned i = 0; i < pcm.size(); ++i) {
210                 unsigned next_pulse = (pulsenum >= pulses.size()) ? INT_MAX : int(pulses[pulsenum].time * sample_rate);
211                 if (i >= next_pulse) {
212                         fwrite(&one, sizeof(one), 1, fp);
213                         ++pulsenum;
214                 } else {
215                         fwrite(&zero, sizeof(zero), 1, fp);
216                 }
217         }
218         fclose(fp);
219 }