]> git.sesse.net Git - c64tapwav/blob - decode.cpp
Fix HYSTERESIS_LIMIT being on the wrong scale.
[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/32768.0)
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<float> &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 void output_tap(const std::vector<pulse>& pulses, double calibration_factor)
108 {
109         std::vector<char> tap_data;
110         for (unsigned i = 0; i < pulses.size(); ++i) {
111                 double cycles = pulses[i].len * calibration_factor * C64_FREQUENCY;
112                 int len = lrintf(cycles / TAP_RESOLUTION);
113                 if (i > SYNC_PULSE_END && (cycles < 100 || cycles > 800)) {
114                         fprintf(stderr, "Cycle with downflank at %.6f was detected at %.0f cycles; misdetect?\n",
115                                         pulses[i].time, cycles);
116                 }
117                 if (len <= 255) {
118                         tap_data.push_back(len);
119                 } else {
120                         int overflow_len = lrintf(cycles);
121                         tap_data.push_back(0);
122                         tap_data.push_back(overflow_len & 0xff);
123                         tap_data.push_back((overflow_len >> 8) & 0xff);
124                         tap_data.push_back(overflow_len >> 16);
125                 }
126         }
127
128         tap_header hdr;
129         memcpy(hdr.identifier, "C64-TAPE-RAW", 12);
130         hdr.version = 1;
131         hdr.reserved[0] = hdr.reserved[1] = hdr.reserved[2] = 0;
132         hdr.data_len = tap_data.size();
133
134         fwrite(&hdr, sizeof(hdr), 1, stdout);
135         fwrite(tap_data.data(), tap_data.size(), 1, stdout);
136 }
137         
138 int main(int argc, char **argv)
139 {
140         make_lanczos_weight_table();
141         std::vector<float> pcm;
142         int sample_rate;
143         if (!read_audio_file(argv[1], &pcm, &sample_rate)) {
144                 exit(1);
145         }
146
147 #if 0
148         for (int i = 0; i < LEN; ++i) {
149                 in[i] += rand() % 10000;
150         }
151 #endif
152
153 #if 0
154         for (int i = 0; i < LEN; ++i) {
155                 printf("%d\n", in[i]);
156         }
157 #endif
158
159         std::vector<pulse> pulses;  // in seconds
160
161         // Find the flanks.
162         int last_bit = -1;
163         double last_downflank = -1;
164         for (unsigned i = 0; i < pcm.size(); ++i) {
165                 int bit = (pcm[i] > 0) ? 1 : 0;
166                 if (bit == 0 && last_bit == 1) {
167                         // Check if we ever go up above HYSTERESIS_LIMIT before we dip down again.
168                         bool true_pulse = false;
169                         unsigned j;
170                         int min_level_after = 32767;
171                         for (j = i; j < pcm.size(); ++j) {
172                                 min_level_after = std::min<int>(min_level_after, pcm[j]);
173                                 if (pcm[j] > 0) break;
174                                 if (pcm[j] < -HYSTERESIS_LIMIT) {
175                                         true_pulse = true;
176                                         break;
177                                 }
178                         }
179
180                         if (!true_pulse) {
181 #if 0
182                                 fprintf(stderr, "Ignored down-flank at %.6f seconds due to hysteresis (%d < %d).\n",
183                                         double(i) / sample_rate, -min_level_after, HYSTERESIS_LIMIT);
184 #endif
185                                 i = j;
186                                 continue;
187                         } 
188
189                         // down-flank!
190                         double t = find_zerocrossing(pcm, i - 1) * (1.0 / sample_rate);
191                         if (last_downflank > 0) {
192                                 pulse p;
193                                 p.time = t;
194                                 p.len = t - last_downflank;
195                                 pulses.push_back(p);
196                         }
197                         last_downflank = t;
198                 }
199                 last_bit = bit;
200         }
201
202         double calibration_factor = calibrate(pulses);
203
204         FILE *fp = fopen("cycles.plot", "w");
205         std::vector<char> tap_data;
206         for (unsigned i = 0; i < pulses.size(); ++i) {
207                 double cycles = pulses[i].len * calibration_factor * C64_FREQUENCY;
208                 fprintf(fp, "%f %f\n", pulses[i].time, cycles);
209         }
210         fclose(fp);
211
212         output_tap(pulses, calibration_factor);
213 }