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