]> git.sesse.net Git - c64tapwav/blob - decode.cpp
49be647ea2cc67442718f2765e66ff508cd91064
[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 "interpolate.h"
10 #include "tap.h"
11
12 #define BUFSIZE 4096
13 #define HYSTERESIS_LIMIT 3000
14 #define SAMPLE_RATE 44100
15 #define C64_FREQUENCY 985248
16
17 #define SYNC_PULSE_START 1000
18 #define SYNC_PULSE_END 15000
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 int main(int argc, char **argv)
55 {
56         make_lanczos_weight_table();
57         std::vector<short> pcm;
58
59         while (!feof(stdin)) {
60                 short buf[BUFSIZE];
61                 ssize_t ret = fread(buf, 2, BUFSIZE, stdin);
62                 if (ret >= 0) {
63                         pcm.insert(pcm.end(), buf, buf + ret);
64                 }
65         }       
66
67 #if 0
68         for (int i = 0; i < LEN; ++i) {
69                 in[i] += rand() % 10000;
70         }
71 #endif
72
73 #if 0
74         for (int i = 0; i < LEN; ++i) {
75                 printf("%d\n", in[i]);
76         }
77 #endif
78
79         std::vector<pulse> pulses;  // in seconds
80
81         // Find the flanks.
82         int last_bit = -1;
83         double last_downflank = -1;
84         for (unsigned i = 0; i < pcm.size(); ++i) {
85                 int bit = (pcm[i] > 0) ? 1 : 0;
86                 if (bit == 0 && last_bit == 1) {
87                         // Check if we ever go up above HYSTERESIS_LIMIT before we dip down again.
88                         bool true_pulse = false;
89                         unsigned j;
90                         int min_level_after = 32767;
91                         for (j = i; j < pcm.size(); ++j) {
92                                 min_level_after = std::min<int>(min_level_after, pcm[j]);
93                                 if (pcm[j] > 0) break;
94                                 if (pcm[j] < -HYSTERESIS_LIMIT) {
95                                         true_pulse = true;
96                                         break;
97                                 }
98                         }
99
100                         if (!true_pulse) {
101 #if 0
102                                 fprintf(stderr, "Ignored down-flank at %.6f seconds due to hysteresis (%d < %d).\n",
103                                         double(i) / SAMPLE_RATE, -min_level_after, HYSTERESIS_LIMIT);
104 #endif
105                                 i = j;
106                                 continue;
107                         } 
108
109                         // down-flank!
110                         double t = find_zerocrossing(pcm, i - 1) * (1.0 / SAMPLE_RATE);
111                         if (last_downflank > 0) {
112                                 pulse p;
113                                 p.time = t;
114                                 p.len = t - last_downflank;
115                                 pulses.push_back(p);
116                         }
117                         last_downflank = t;
118                 }
119                 last_bit = bit;
120         }
121
122         // Calibrate on the first ~25k pulses (skip a few, just to be sure).
123         double calibration_factor = 1.0f;
124         if (pulses.size() < SYNC_PULSE_END) {
125                 fprintf(stderr, "Too few pulses, not calibrating!\n");
126         } else {
127                 double sum = 0.0;
128                 for (int i = SYNC_PULSE_START; i < SYNC_PULSE_END; ++i) {
129                         sum += pulses[i].len;
130                 }
131                 double mean_length = C64_FREQUENCY * sum / (SYNC_PULSE_END - SYNC_PULSE_START);
132                 calibration_factor = SYNC_PULSE_LENGTH / mean_length;
133                 fprintf(stderr, "Calibrated sync pulse length: %.2f -> %.2f (change %+.2f%%)\n",
134                         mean_length, SYNC_PULSE_LENGTH, 100.0 * (calibration_factor - 1.0));
135
136                 // Check for pulses outside +/- 10% (sign of misdetection).
137                 for (int i = SYNC_PULSE_START; i < SYNC_PULSE_END; ++i) {
138                         double cycles = pulses[i].len * calibration_factor * C64_FREQUENCY;
139                         if (cycles < SYNC_PULSE_LENGTH / SYNC_TEST_TOLERANCE || cycles > SYNC_PULSE_LENGTH * SYNC_TEST_TOLERANCE) {
140                                 fprintf(stderr, "Sync cycle with downflank at %.6f was detected at %.0f cycles; misdetect?\n",
141                                         pulses[i].time, cycles);
142                         }
143                 }
144
145                 // Compute the standard deviation (to check for uneven speeds).
146                 double sum2 = 0.0;
147                 for (int i = SYNC_PULSE_START; i < SYNC_PULSE_END; ++i) {
148                         double cycles = pulses[i].len * calibration_factor * C64_FREQUENCY;
149                         sum2 += (cycles - SYNC_PULSE_LENGTH) * (cycles - SYNC_PULSE_LENGTH);
150                 }
151                 double stddev = sqrt(sum2 / (SYNC_PULSE_END - SYNC_PULSE_START - 1));
152                 fprintf(stderr, "Sync pulse length standard deviation: %.2f cycles\n",
153                         stddev);
154         }
155
156         FILE *fp = fopen("cycles.plot", "w");
157         std::vector<char> tap_data;
158         for (unsigned i = 0; i < pulses.size(); ++i) {
159                 double cycles = pulses[i].len * calibration_factor * C64_FREQUENCY;
160                 fprintf(fp, "%f %f\n", pulses[i].time, cycles);
161                 int len = lrintf(cycles / TAP_RESOLUTION);
162                 if (i > SYNC_PULSE_END && (cycles < 100 || cycles > 800)) {
163                         fprintf(stderr, "Cycle with downflank at %.6f was detected at %.0f cycles; misdetect?\n",
164                                         pulses[i].time, cycles);
165                 }
166                 if (len <= 255) {
167                         tap_data.push_back(len);
168                 } else {
169                         int overflow_len = lrintf(cycles);
170                         tap_data.push_back(0);
171                         tap_data.push_back(overflow_len & 0xff);
172                         tap_data.push_back((overflow_len >> 8) & 0xff);
173                         tap_data.push_back(overflow_len >> 16);
174                 }
175         }
176         fclose(fp);
177
178         tap_header hdr;
179         memcpy(hdr.identifier, "C64-TAPE-RAW", 12);
180         hdr.version = 1;
181         hdr.reserved[0] = hdr.reserved[1] = hdr.reserved[2] = 0;
182         hdr.data_len = tap_data.size();
183
184         fwrite(&hdr, sizeof(hdr), 1, stdout);
185         fwrite(tap_data.data(), tap_data.size(), 1, stdout);
186
187         // Output a debug raw file with pulse detection points.
188         fp = fopen("debug.raw", "wb");
189         short one = 32767;
190         short zero = 0;
191         unsigned pulsenum = 0;
192         for (unsigned i = 0; i < pcm.size(); ++i) {
193                 unsigned next_pulse = (pulsenum >= pulses.size()) ? INT_MAX : int(pulses[pulsenum].time * SAMPLE_RATE);
194                 if (i >= next_pulse) {
195                         fwrite(&one, sizeof(one), 1, fp);
196                         ++pulsenum;
197                 } else {
198                         fwrite(&zero, sizeof(zero), 1, fp);
199                 }
200         }
201         fclose(fp);
202 }