summaryrefslogtreecommitdiff
path: root/csid.cpp
blob: 217eb189e6e2931525e027479fab491b833dbeb7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <iconv.h>
#include "sidplay/sidplay2.h"
#include "sidplay/builders/resid.h"
extern "C" {
#include "codec.h"
#include "playlist.h"
#include "csid.h"
#include "md5.h"
#include "common.h"
}

static sidplay2 *sidplay;
static ReSIDBuilder *resid;
static SidTune *tune;
extern int sdl_player_freq; // hack!
// SLDB support costs ~1M!!!
// current hvsc sldb size is ~35k songs
#define SLDB_MAX_SONGS 40000
// ~50k subsongs in current sldb
#define SLDB_POOL_SIZE 55000
static uint8_t sldb_digests[SLDB_MAX_SONGS][16];
static int16_t sldb_pool[SLDB_POOL_SIZE];
static int sldb_poolmark;
static int16_t *sldb_lengths[SLDB_MAX_SONGS];
static int sldb_size;
static int sldb_loaded;
static const char *sldb_fname = "/home/waker/hvsc/C64Music/DOCUMENTS/Songlengths.txt";

static void sldb_load(const char *fname)
{
    if (sldb_loaded) {
        return;
    }
    sldb_loaded = 1;
    FILE *fp = fopen (fname, "r");
    if (!fp) {
        return;
    }
    char str[1024];

    int line = 1;
    if (fgets (str, 1024, fp) != str) {
        goto fail; // eof
    }
    if (strncmp (str, "[Database]", 10)) {
        goto fail; // bad format
    }

    while (fgets (str, 1024, fp) == str) {
        if (sldb_size >= SLDB_MAX_SONGS) {
            printf ("sldb loader ran out of memory.\n");
            break;
        }
        line++;
        if (str[0] == ';') {
//            printf ("reading songlength for %s", str);
            continue; // comment
        }
        // read/validate md5
        const char *p = str;
        uint8_t digest[16];
        int sz = 0;
        char byte[3];
        while (*p && sz < 16) {
            byte[0] = tolower (*p);
            if (!((byte[0] >= '0' && byte[0] <= '9') || (byte[0] >= 'a' && byte[0] <= 'f'))) {
                printf ("invalid byte 0 in md5: %c\n", byte[0]);
                break;
            }
            p++;
            if (!(*p)) {
                break;
            }
            byte[1] = tolower (*p);
            if (!((byte[1] >= '0' && byte[1] <= '9') || (byte[1] >= 'a' && byte[1] <= 'f'))) {
                printf ("invalid byte 1 in md5: %c\n", byte[1]);
                break;
            }
            byte[2] = 0;
            p++;

            // convert from ascii hex to uint8_t
            if (byte[1] < 'a') {
                digest[sz] = byte[1] - '0';
            }
            else {
                digest[sz] = byte[1] - 'a' + 10;
            }
            if (byte[0] < 'a') {
                digest[sz] |= (byte[0] - '0') << 4;
            }
            else {
                digest[sz] |= (byte[0] - 'a' + 10) << 4;
            }
            sz++;
        }
        if (sz < 16) {
            printf ("bad md5 (sz=%d, line=%d)\n", sz, line);
            continue; // bad song md5
        }
//        else {
//            printf ("digest: ");
//            for (int j = 0; j < 16; j++) {
//                printf ("%02x", (int)digest[j]);
//            }
//            printf ("\n");
//            exit (0);
//        }
        memcpy (sldb_digests[sldb_size], digest, 16);
        sldb_lengths[sldb_size] = &sldb_pool[sldb_poolmark];
        sldb_size++;
        // check '=' sign
        if (*p != '=') {
            continue; // no '=' sign
        }
        p++;
        if (!(*p)) {
            continue; // unexpected eol
        }
        int subsong = 0;
        while (*p >= ' ') {
            // read subsong lengths until eol
            char timestamp[7]; // up to MMM:SS
            sz = 0;
            while (*p > ' ' && *p != '(' && sz < 7) {
                timestamp[sz++] = *p;
                p++;
            }
            if (sz < 4 || sz == 6 && *p > ' ' && *p != '(') {
                break; // bad timestamp
            }
            timestamp[sz] = 0;
            // check for unknown time
            int16_t time = -1;
            if (!strcmp (timestamp, "-:--")) {
                time = -1;
            }
            else {
                // parse timestamp
                const char *colon = strchr (timestamp, ':');
                if (!colon) {
                    break; // bad timestamp
                }
                // minute
                char minute[4];
                strncpy (minute, timestamp, colon-timestamp);
                minute[colon-timestamp] = 0;
                // second
                char second[3];
                strncpy (second, colon+1, 3);
                //printf ("subsong %d, time %s:%s\n", subsong, minute, second);
                time = atoi (minute) * 60 + atoi (second);
            }
            if (sldb_poolmark >= SLDB_POOL_SIZE) {
                printf ("sldb ran out of memory\n");
                goto fail;
            }
            
            sldb_lengths[sldb_size-1][subsong] = time;
            sldb_poolmark++;
            subsong++;

            // prepare for next timestamp
            if (*p == '(') {
                // skip until next whitespace
                while (*p > ' ') {
                    p++;
                }
            }
            if (*p < ' ') {
                break; // eol
            }
            // skip white spaces
            while (*p == ' ') {
                p++;
            }
            if (*p < ' ') {
                break; // eol
            }
        }
    }

fail:
    fclose (fp);
    printf ("HVSC sldb loaded %d songs, %d subsongs total\n", sldb_size, sldb_poolmark);
}

static int
sldb_find (const uint8_t *digest) {
    for (int i = 0; i < sldb_size; i++) {
        if (!memcmp (digest, sldb_digests[i], 16)) {
            return i;
        }
    }
    return -1;
}

extern "C" int
csid_init (const char *fname, int track, float start, float end) {
    sidplay = new sidplay2;
    resid = new ReSIDBuilder ("wtf");
    resid->create (sidplay->info ().maxsids);
    resid->filter (true);
    resid->sampling (sdl_player_freq);
    tune = new SidTune (fname);
    // calc md5
    uint8_t sig[16];
    md5_t md5;
    md5_init (&md5);
    md5_process (&md5, (const char *)tune->cache.get () + tune->fileOffset, tune->getInfo ().c64dataLen);
    uint16_t tmp;
    tmp = tune->getInfo ().initAddr;
    md5_process (&md5, &tmp, 2);
    tmp = tune->getInfo ().playAddr;
    md5_process (&md5, &tmp, 2);
    tmp = tune->getInfo ().songs;
    md5_process (&md5, &tmp, 2);
    for (int s = 1; s <= tune->getInfo ().songs; s++)
    {
        tune->selectSong (s);
        md5_process (&md5, &tune->getInfo ().songSpeed, sizeof (tune->getInfo ().songSpeed));
    }
    if (tune->getInfo ().clockSpeed == SIDTUNE_CLOCK_NTSC) {
        md5_process (&md5, &tune->getInfo ().clockSpeed, sizeof (tune->getInfo ().clockSpeed));
    }
    md5_finish (&md5, sig);

    tune->selectSong (track+1);
    csid.info.channels = tune->isStereo () ? 2 : 1;
    sid2_config_t conf;
    conf = sidplay->config ();
    conf.frequency = sdl_player_freq;
    conf.precision = 16;
    conf.playback = csid.info.channels == 2 ? sid2_stereo : sid2_mono;
    conf.sidEmulation = resid;
    conf.optimisation = 0;
    sidplay->config (conf);
    sidplay->load (tune);
    csid.info.bitsPerSample = 16;
    csid.info.samplesPerSecond = sdl_player_freq;
    csid.info.position = 0;
    float length = 120;
    sldb_load(sldb_fname);
    if (sldb_loaded) {
        int song = sldb_find (sig);
        if (song >= 0 && sldb_lengths[song][track] >= 0) {
            length = sldb_lengths[song][track];
        }
//        if (song < 0) {
//            printf ("song %s not found in db, md5: ", fname);
//            for (int j = 0; j < 16; j++) {
//                printf ("%02x", (int)sig[j]);
//            }
//            printf ("\n");
//        }
    }
    csid.info.duration = length;

    return 0;
}

extern "C" void
csid_free (void) {
    delete sidplay;
    sidplay = 0;
    delete resid;
    resid = 0;
    delete tune;
    tune = 0;
}

extern "C" int
csid_read (char *bytes, int size) {
    if (csid.info.position > csid.info.duration) {
        return 0;
    }
    int rd = sidplay->play (bytes, size/csid.info.channels);
    csid.info.position += size/csid.info.channels/2 / (float)csid.info.samplesPerSecond;
    return rd * csid.info.channels;
}

extern "C" int
csid_seek (float time) {
    float t = time;
    if (t < csid.info.position) {
        // reinit
        sidplay->load (tune);
    }
    else {
        t -= csid.info.position;
    }
    resid->filter (false);
    int samples = t * csid.info.samplesPerSecond;
    samples *= 2 * csid.info.channels;
    uint16_t buffer[4096 * csid.info.channels];
    while (samples > 0) {
        int n = min (samples, 4096) * csid.info.channels;
        int done = sidplay->play (buffer, n);
//        printf ("seek-read %d samples, done %d\n", n, done);
        if (done < n) {
//            if (sidplay->state () != sid2_stopped) {
                printf ("sid seek failure\n");
                return -1;
//            }
        }
        samples -= done;
    }
    resid->filter (true);
    csid.info.position = time;

    return 0;
}

static const char *
convstr (const char* str) {
    int sz = strlen (str);
    static char out[2048];
    const char *enc = "iso8859-1";
    iconv_t cd = iconv_open ("utf8", enc);
    if (!cd) {
        printf ("unknown encoding: %s\n", enc);
        return NULL;
    }
    else {
        size_t inbytesleft = sz;
        size_t outbytesleft = 2047;
        char *pin = (char*)str;
        char *pout = out;
        memset (out, 0, sizeof (out));
        size_t res = iconv (cd, &pin, &inbytesleft, &pout, &outbytesleft);
        iconv_close (cd);
    }
    return out;
}

extern "C" int
csid_add (const char *fname) {
    sldb_load(sldb_fname);
    SidTune *tune;
    tune = new SidTune (fname);
    int tunes = tune->getInfo ().songs;
    for (int s = 0; s < tunes; s++) {
        if (tune->selectSong (s+1)) {
            unsigned length = 120;
            playItem_t *it = (playItem_t*)malloc (sizeof (playItem_t));
            memset (it, 0, sizeof (playItem_t));
            it->codec = &csid;
            it->fname = strdup (fname);
            it->tracknum = s;
            it->timestart = 0;
            it->timeend = 0;
            SidTuneInfo sidinfo;
            tune->getInfo (sidinfo);
            int i = sidinfo.numberOfInfoStrings;
            if (i >= 1 && sidinfo.infoString[0] && sidinfo.infoString[0][0]) {
                ps_add_meta (it, sidinfo.songs > 1 ? "album" : "title", convstr (sidinfo.infoString[0]));
            }
            if (i >= 2 && sidinfo.infoString[1] && sidinfo.infoString[1][0]) {
                ps_add_meta (it, "artist", convstr (sidinfo.infoString[1]));
            }
            if (i >= 3 && sidinfo.infoString[2] && sidinfo.infoString[2][0]) {
                ps_add_meta (it, "copyright", convstr (sidinfo.infoString[2]));
            }

            for (int j = 3; j < i; j++)
            {
                if (sidinfo.infoString[j] && sidinfo.infoString[j][0]) {
                    ps_add_meta (it, "info", convstr (sidinfo.infoString[j]));
                }
            }
            char trk[10];
            snprintf (trk, 10, "%d", s+1);
            ps_add_meta (it, "track", trk);
            ps_append_item (it);
        }
    }
    delete tune;
    return 0;
}

static const char *exts[]=
{
	"sid",NULL
};

extern "C" const char **csid_getexts (void) {
    return exts;
}

codec_t csid = {
    csid_init,
    csid_free,
    csid_read,
    csid_seek,
    csid_add,
    csid_getexts
};