aboutsummaryrefslogtreecommitdiffstats
path: root/src/decoder/sidplay_decoder_plugin.cxx
blob: 486dd816f8b89c07d5a9e198c51edd39b9ce3356 (plain) (blame)
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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
/*
 * Copyright (C) 2003-2011 The Music Player Daemon Project
 * http://www.musicpd.org
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "config.h"
#include "../DecoderAPI.hxx"
#include "tag/TagHandler.hxx"
#include "util/Domain.hxx"
#include "Log.hxx"

#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <glib.h>

#include <sidplay/sidplay2.h>
#include <sidplay/builders/resid.h>
#include <sidplay/utils/SidTuneMod.h>

#define SUBTUNE_PREFIX "tune_"

static constexpr Domain sidplay_domain("sidplay");

static GPatternSpec *path_with_subtune;
static const char *songlength_file;
static GKeyFile *songlength_database;

static bool all_files_are_containers;
static unsigned default_songlength;

static bool filter_setting;

static GKeyFile *
sidplay_load_songlength_db(const char *path)
{
	GError *error = NULL;
	gchar *data;
	gsize size;

	if (!g_file_get_contents(path, &data, &size, &error)) {
		FormatError(sidplay_domain,
			    "unable to read songlengths file %s: %s",
			    path, error->message);
		g_error_free(error);
		return NULL;
	}

	/* replace any ; comment characters with # */
	for (gsize i = 0; i < size; i++)
		if (data[i] == ';')
			data[i] = '#';

	GKeyFile *db = g_key_file_new();
	bool success = g_key_file_load_from_data(db, data, size,
						 G_KEY_FILE_NONE, &error);
	g_free(data);
	if (!success) {
		FormatError(sidplay_domain,
			    "unable to parse songlengths file %s: %s",
			    path, error->message);
		g_error_free(error);
		g_key_file_free(db);
		return NULL;
	}

	g_key_file_set_list_separator(db, ' ');
	return db;
}

static bool
sidplay_init(const config_param &param)
{
	/* read the songlengths database file */
	songlength_file = param.GetBlockValue("songlength_database");
	if (songlength_file != NULL)
		songlength_database = sidplay_load_songlength_db(songlength_file);

	default_songlength = param.GetBlockValue("default_songlength", 0u);

	all_files_are_containers =
		param.GetBlockValue("all_files_are_containers", true);

	path_with_subtune=g_pattern_spec_new(
			"*/" SUBTUNE_PREFIX "???.sid");

	filter_setting = param.GetBlockValue("filter", true);

	return true;
}

static void
sidplay_finish()
{
	g_pattern_spec_free(path_with_subtune);

	if(songlength_database)
		g_key_file_free(songlength_database);
}

/**
 * returns the file path stripped of any /tune_xxx.sid subtune
 * suffix
 */
static char *
get_container_name(const char *path_fs)
{
	char *path_container=g_strdup(path_fs);

	if(!g_pattern_match(path_with_subtune,
		strlen(path_container), path_container, NULL))
		return path_container;

	char *ptr=g_strrstr(path_container, "/" SUBTUNE_PREFIX);
	if(ptr) *ptr='\0';

	return path_container;
}

/**
 * returns tune number from file.sid/tune_xxx.sid style path or 1 if
 * no subtune is appended
 */
static unsigned
get_song_num(const char *path_fs)
{
	if(g_pattern_match(path_with_subtune,
		strlen(path_fs), path_fs, NULL)) {
		char *sub=g_strrstr(path_fs, "/" SUBTUNE_PREFIX);
		if(!sub) return 1;

		sub+=strlen("/" SUBTUNE_PREFIX);
		int song_num=strtol(sub, NULL, 10);

		if (errno == EINVAL)
			return 1;
		else
			return song_num;
	} else
		return 1;
}

/* get the song length in seconds */
static int
get_song_length(const char *path_fs)
{
	if (songlength_database == NULL)
		return -1;

	gchar *sid_file=get_container_name(path_fs);
	SidTuneMod tune(sid_file);
	g_free(sid_file);
	if(!tune) {
		LogWarning(sidplay_domain,
			   "failed to load file for calculating md5 sum");
		return -1;
	}
	char md5sum[SIDTUNE_MD5_LENGTH+1];
	tune.createMD5(md5sum);

	const unsigned song_num = get_song_num(path_fs);

	gsize num_items;
	gchar **values=g_key_file_get_string_list(songlength_database,
		"Database", md5sum, &num_items, NULL);
	if(!values || song_num>num_items) {
		g_strfreev(values);
		return -1;
	}

	int minutes=strtol(values[song_num-1], NULL, 10);
	if(errno==EINVAL) minutes=0;

	int seconds;
	char *ptr=strchr(values[song_num-1], ':');
	if(ptr) {
		seconds=strtol(ptr+1, NULL, 10);
		if(errno==EINVAL) seconds=0;
	} else
		seconds=0;

	g_strfreev(values);

	return (minutes*60)+seconds;
}

static void
sidplay_file_decode(struct decoder *decoder, const char *path_fs)
{
	int channels;

	/* load the tune */

	char *path_container=get_container_name(path_fs);
	SidTune tune(path_container, NULL, true);
	g_free(path_container);
	if (!tune) {
		LogWarning(sidplay_domain, "failed to load file");
		return;
	}

	int song_num=get_song_num(path_fs);
	tune.selectSong(song_num);

	int song_len=get_song_length(path_fs);
	if(song_len==-1) song_len=default_songlength;

	/* initialize the player */

	sidplay2 player;
	int iret = player.load(&tune);
	if (iret != 0) {
		FormatWarning(sidplay_domain,
			      "sidplay2.load() failed: %s", player.error());
		return;
	}

	/* initialize the builder */

	ReSIDBuilder builder("ReSID");
	if (!builder) {
		LogWarning(sidplay_domain,
			   "failed to initialize ReSIDBuilder");
		return;
	}

	builder.create(player.info().maxsids);
	if (!builder) {
		LogWarning(sidplay_domain, "ReSIDBuilder.create() failed");
		return;
	}

	builder.filter(filter_setting);
	if (!builder) {
		LogWarning(sidplay_domain, "ReSIDBuilder.filter() failed");
		return;
	}

	/* configure the player */

	sid2_config_t config = player.config();

	config.clockDefault = SID2_CLOCK_PAL;
	config.clockForced = true;
	config.clockSpeed = SID2_CLOCK_CORRECT;
	config.frequency = 48000;
	config.optimisation = SID2_DEFAULT_OPTIMISATION;

	config.precision = 16;
	config.sidDefault = SID2_MOS6581;
	config.sidEmulation = &builder;
	config.sidModel = SID2_MODEL_CORRECT;
	config.sidSamples = true;
#if G_BYTE_ORDER == G_LITTLE_ENDIAN
	config.sampleFormat = SID2_LITTLE_SIGNED;
#else
	config.sampleFormat = SID2_BIG_SIGNED;
#endif
	if (tune.isStereo()) {
		config.playback = sid2_stereo;
		channels = 2;
	} else {
		config.playback = sid2_mono;
		channels = 1;
	}

	iret = player.config(config);
	if (iret != 0) {
		FormatWarning(sidplay_domain,
			      "sidplay2.config() failed: %s", player.error());
		return;
	}

	/* initialize the MPD decoder */

	const AudioFormat audio_format(48000, SampleFormat::S16, channels);
	assert(audio_format.IsValid());

	decoder_initialized(decoder, audio_format, true, (float)song_len);

	/* .. and play */

	const unsigned timebase = player.timebase();
	song_len *= timebase;

	DecoderCommand cmd;
	do {
		char buffer[4096];
		size_t nbytes;

		nbytes = player.play(buffer, sizeof(buffer));
		if (nbytes == 0)
			break;

		decoder_timestamp(decoder, (double)player.time() / timebase);

		cmd = decoder_data(decoder, NULL, buffer, nbytes, 0);

		if (cmd == DecoderCommand::SEEK) {
			unsigned data_time = player.time();
			unsigned target_time = (unsigned)
				(decoder_seek_where(decoder) * timebase);

			/* can't rewind so return to zero and seek forward */
			if(target_time<data_time) {
				player.stop();
				data_time=0;
			}

			/* ignore data until target time is reached */
			while(data_time<target_time) {
				nbytes=player.play(buffer, sizeof(buffer));
				if(nbytes==0)
					break;
				data_time = player.time();
			}

			decoder_command_finished(decoder);
		}

		if (song_len > 0 && player.time() >= (unsigned)song_len)
			break;

	} while (cmd != DecoderCommand::STOP);
}

static bool
sidplay_scan_file(const char *path_fs,
		  const struct tag_handler *handler, void *handler_ctx)
{
	int song_num=get_song_num(path_fs);
	char *path_container=get_container_name(path_fs);

	SidTune tune(path_container, NULL, true);
	g_free(path_container);
	if (!tune)
		return false;

	const SidTuneInfo &info = tune.getInfo();

	/* title */
	const char *title;
	if (info.numberOfInfoStrings > 0 && info.infoString[0] != NULL)
		title=info.infoString[0];
	else
		title="";

	if(info.songs>1) {
		char *tag_title=g_strdup_printf("%s (%d/%d)",
			title, song_num, info.songs);
		tag_handler_invoke_tag(handler, handler_ctx,
				       TAG_TITLE, tag_title);
		g_free(tag_title);
	} else
		tag_handler_invoke_tag(handler, handler_ctx, TAG_TITLE, title);

	/* artist */
	if (info.numberOfInfoStrings > 1 && info.infoString[1] != NULL)
		tag_handler_invoke_tag(handler, handler_ctx, TAG_ARTIST,
				       info.infoString[1]);

	/* track */
	char *track=g_strdup_printf("%d", song_num);
	tag_handler_invoke_tag(handler, handler_ctx, TAG_TRACK, track);
	g_free(track);

	/* time */
	int song_len=get_song_length(path_fs);
	if (song_len >= 0)
		tag_handler_invoke_duration(handler, handler_ctx, song_len);

	return true;
}

static char *
sidplay_container_scan(const char *path_fs, const unsigned int tnum)
{
	SidTune tune(path_fs, NULL, true);
	if (!tune)
		return NULL;

	const SidTuneInfo &info=tune.getInfo();

	/* Don't treat sids containing a single tune
		as containers */
	if(!all_files_are_containers && info.songs<2)
		return NULL;

	/* Construct container/tune path names, eg.
		Delta.sid/tune_001.sid */
	if(tnum<=info.songs) {
		char *subtune= g_strdup_printf(
			SUBTUNE_PREFIX "%03u.sid", tnum);
		return subtune;
	} else
		return NULL;
}

static const char *const sidplay_suffixes[] = {
	"sid",
	"mus",
	"str",
	"prg",
	"P00",
	NULL
};

extern const struct decoder_plugin sidplay_decoder_plugin;
const struct decoder_plugin sidplay_decoder_plugin = {
	"sidplay",
	sidplay_init,
	sidplay_finish,
	NULL, /* stream_decode() */
	sidplay_file_decode,
	sidplay_scan_file,
	NULL, /* stream_tag() */
	sidplay_container_scan,
	sidplay_suffixes,
	NULL, /* mime_types */
};