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