SidplayDecoderPlugin.cxx 9.98 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright (C) 2003-2014 The Music Player Daemon Project
3 4 5 6 7 8 9 10 11 12 13
 * 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.
14 15 16 17
 *
 * 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.
18 19
 */

20
#include "config.h"
21
#include "SidplayDecoderPlugin.hxx"
22
#include "../DecoderAPI.hxx"
23
#include "tag/TagHandler.hxx"
24
#include "fs/Path.hxx"
25
#include "util/FormatString.hxx"
26
#include "util/Domain.hxx"
27
#include "system/ByteOrder.hxx"
28
#include "Log.hxx"
29

Mike Dawson's avatar
Mike Dawson committed
30 31
#include <errno.h>
#include <stdlib.h>
Max Kellermann's avatar
Max Kellermann committed
32
#include <string.h>
33 34 35 36
#include <glib.h>

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

Mike Dawson's avatar
Mike Dawson committed
39 40
#define SUBTUNE_PREFIX "tune_"

41 42
static constexpr Domain sidplay_domain("sidplay");

Mike Dawson's avatar
Mike Dawson committed
43
static GPatternSpec *path_with_subtune;
44 45
static const char *songlength_file;
static GKeyFile *songlength_database;
Mike Dawson's avatar
Mike Dawson committed
46 47

static bool all_files_are_containers;
48
static unsigned default_songlength;
Mike Dawson's avatar
Mike Dawson committed
49

50 51
static bool filter_setting;

52 53 54
static GKeyFile *
sidplay_load_songlength_db(const char *path)
{
55
	GError *error = nullptr;
56 57 58 59
	gchar *data;
	gsize size;

	if (!g_file_get_contents(path, &data, &size, &error)) {
60 61 62
		FormatError(sidplay_domain,
			    "unable to read songlengths file %s: %s",
			    path, error->message);
63
		g_error_free(error);
64
		return nullptr;
65 66 67 68 69 70 71 72
	}

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

	GKeyFile *db = g_key_file_new();
73 74 75 76
	bool success = g_key_file_load_from_data(db, data, size,
						 G_KEY_FILE_NONE, &error);
	g_free(data);
	if (!success) {
77 78 79
		FormatError(sidplay_domain,
			    "unable to parse songlengths file %s: %s",
			    path, error->message);
80 81
		g_error_free(error);
		g_key_file_free(db);
82
		return nullptr;
83 84 85 86 87 88
	}

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

Mike Dawson's avatar
Mike Dawson committed
89
static bool
90
sidplay_init(const config_param &param)
Mike Dawson's avatar
Mike Dawson committed
91
{
92
	/* read the songlengths database file */
93
	songlength_file = param.GetBlockValue("songlength_database");
94
	if (songlength_file != nullptr)
95
		songlength_database = sidplay_load_songlength_db(songlength_file);
96

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

99 100
	all_files_are_containers =
		param.GetBlockValue("all_files_are_containers", true);
Mike Dawson's avatar
Mike Dawson committed
101 102 103 104

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

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

Mike Dawson's avatar
Mike Dawson committed
107 108 109
	return true;
}

110
static void
Mike Dawson's avatar
Mike Dawson committed
111 112 113
sidplay_finish()
{
	g_pattern_spec_free(path_with_subtune);
114 115 116

	if(songlength_database)
		g_key_file_free(songlength_database);
Mike Dawson's avatar
Mike Dawson committed
117 118 119 120 121 122 123
}

/**
 * returns the file path stripped of any /tune_xxx.sid subtune
 * suffix
 */
static char *
124
get_container_name(Path path_fs)
Mike Dawson's avatar
Mike Dawson committed
125
{
126
	char *path_container = strdup(path_fs.c_str());
Mike Dawson's avatar
Mike Dawson committed
127 128

	if(!g_pattern_match(path_with_subtune,
129
		strlen(path_container), path_container, nullptr))
Mike Dawson's avatar
Mike Dawson committed
130 131 132 133 134 135 136 137 138 139 140 141
		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
 */
142
static unsigned
Mike Dawson's avatar
Mike Dawson committed
143 144 145
get_song_num(const char *path_fs)
{
	if(g_pattern_match(path_with_subtune,
146
		strlen(path_fs), path_fs, nullptr)) {
Mike Dawson's avatar
Mike Dawson committed
147 148 149 150
		char *sub=g_strrstr(path_fs, "/" SUBTUNE_PREFIX);
		if(!sub) return 1;

		sub+=strlen("/" SUBTUNE_PREFIX);
151
		int song_num=strtol(sub, nullptr, 10);
Mike Dawson's avatar
Mike Dawson committed
152 153 154 155 156 157 158 159 160

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

161 162
/* get the song length in seconds */
static int
163
get_song_length(Path path_fs)
164
{
165
	if (songlength_database == nullptr)
166 167
		return -1;

168
	char *sid_file = get_container_name(path_fs);
169
	SidTuneMod tune(sid_file);
170
	free(sid_file);
171
	if(!tune) {
172 173
		LogWarning(sidplay_domain,
			   "failed to load file for calculating md5 sum");
174 175 176 177 178
		return -1;
	}
	char md5sum[SIDTUNE_MD5_LENGTH+1];
	tune.createMD5(md5sum);

179
	const unsigned song_num = get_song_num(path_fs.c_str());
180 181 182

	gsize num_items;
	gchar **values=g_key_file_get_string_list(songlength_database,
183
		"Database", md5sum, &num_items, nullptr);
184 185 186 187 188
	if(!values || song_num>num_items) {
		g_strfreev(values);
		return -1;
	}

189
	int minutes=strtol(values[song_num-1], nullptr, 10);
190 191 192 193 194
	if(errno==EINVAL) minutes=0;

	int seconds;
	char *ptr=strchr(values[song_num-1], ':');
	if(ptr) {
195
		seconds=strtol(ptr+1, nullptr, 10);
196 197 198 199 200 201 202 203 204
		if(errno==EINVAL) seconds=0;
	} else
		seconds=0;

	g_strfreev(values);

	return (minutes*60)+seconds;
}

205
static void
206
sidplay_file_decode(Decoder &decoder, Path path_fs)
207
{
208
	int channels;
209 210 211

	/* load the tune */

Mike Dawson's avatar
Mike Dawson committed
212
	char *path_container=get_container_name(path_fs);
213
	SidTune tune(path_container, nullptr, true);
214
	free(path_container);
215
	if (!tune) {
216
		LogWarning(sidplay_domain, "failed to load file");
217 218 219
		return;
	}

220
	const int song_num = get_song_num(path_fs.c_str());
Mike Dawson's avatar
Mike Dawson committed
221
	tune.selectSong(song_num);
222

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

226 227 228 229 230
	/* initialize the player */

	sidplay2 player;
	int iret = player.load(&tune);
	if (iret != 0) {
231 232
		FormatWarning(sidplay_domain,
			      "sidplay2.load() failed: %s", player.error());
233 234 235 236 237 238 239
		return;
	}

	/* initialize the builder */

	ReSIDBuilder builder("ReSID");
	if (!builder) {
240 241
		LogWarning(sidplay_domain,
			   "failed to initialize ReSIDBuilder");
242 243 244 245 246
		return;
	}

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

251
	builder.filter(filter_setting);
252
	if (!builder) {
253
		LogWarning(sidplay_domain, "ReSIDBuilder.filter() failed");
254 255 256 257 258 259 260 261 262 263 264 265
		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;
266

267 268 269 270 271
	config.precision = 16;
	config.sidDefault = SID2_MOS6581;
	config.sidEmulation = &builder;
	config.sidModel = SID2_MODEL_CORRECT;
	config.sidSamples = true;
272 273 274
	config.sampleFormat = IsLittleEndian()
		? SID2_LITTLE_SIGNED
		: SID2_BIG_SIGNED;
275 276 277 278 279 280 281
	if (tune.isStereo()) {
		config.playback = sid2_stereo;
		channels = 2;
	} else {
		config.playback = sid2_mono;
		channels = 1;
	}
282 283 284

	iret = player.config(config);
	if (iret != 0) {
285 286
		FormatWarning(sidplay_domain,
			      "sidplay2.config() failed: %s", player.error());
287 288 289 290 291
		return;
	}

	/* initialize the MPD decoder */

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

295
	decoder_initialized(decoder, audio_format, true, (float)song_len);
296 297 298

	/* .. and play */

299 300 301
	const unsigned timebase = player.timebase();
	song_len *= timebase;

302
	DecoderCommand cmd;
303 304 305 306 307 308 309 310
	do {
		char buffer[4096];
		size_t nbytes;

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

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

313
		cmd = decoder_data(decoder, nullptr, buffer, nbytes, 0);
314

315
		if (cmd == DecoderCommand::SEEK) {
316
			unsigned data_time = player.time();
317 318
			unsigned target_time = (unsigned)
				(decoder_seek_where(decoder) * timebase);
319 320 321 322 323 324 325 326 327 328 329 330

			/* 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;
331
				data_time = player.time();
332 333 334 335 336
			}

			decoder_command_finished(decoder);
		}

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

340
	} while (cmd != DecoderCommand::STOP);
341 342
}

343
static bool
344
sidplay_scan_file(Path path_fs,
345
		  const struct tag_handler *handler, void *handler_ctx)
346
{
347
	const int song_num = get_song_num(path_fs.c_str());
Mike Dawson's avatar
Mike Dawson committed
348 349
	char *path_container=get_container_name(path_fs);

350
	SidTune tune(path_container, nullptr, true);
351
	free(path_container);
352
	if (!tune)
353
		return false;
354 355 356

	const SidTuneInfo &info = tune.getInfo();

Mike Dawson's avatar
Mike Dawson committed
357 358
	/* title */
	const char *title;
359
	if (info.numberOfInfoStrings > 0 && info.infoString[0] != nullptr)
Mike Dawson's avatar
Mike Dawson committed
360 361 362 363 364
		title=info.infoString[0];
	else
		title="";

	if(info.songs>1) {
365 366 367 368
		char tag_title[1024];
		snprintf(tag_title, sizeof(tag_title),
			 "%s (%d/%d)",
			 title, song_num, info.songs);
369 370
		tag_handler_invoke_tag(handler, handler_ctx,
				       TAG_TITLE, tag_title);
Mike Dawson's avatar
Mike Dawson committed
371
	} else
372
		tag_handler_invoke_tag(handler, handler_ctx, TAG_TITLE, title);
Mike Dawson's avatar
Mike Dawson committed
373 374

	/* artist */
375
	if (info.numberOfInfoStrings > 1 && info.infoString[1] != nullptr)
376 377
		tag_handler_invoke_tag(handler, handler_ctx, TAG_ARTIST,
				       info.infoString[1]);
378

Mike Dawson's avatar
Mike Dawson committed
379
	/* track */
380 381
	char track[16];
	sprintf(track, "%d", song_num);
382
	tag_handler_invoke_tag(handler, handler_ctx, TAG_TRACK, track);
Mike Dawson's avatar
Mike Dawson committed
383

384 385
	/* time */
	int song_len=get_song_length(path_fs);
386 387
	if (song_len >= 0)
		tag_handler_invoke_duration(handler, handler_ctx, song_len);
388

389
	return true;
390 391
}

Mike Dawson's avatar
Mike Dawson committed
392
static char *
393
sidplay_container_scan(Path path_fs, const unsigned int tnum)
Mike Dawson's avatar
Mike Dawson committed
394
{
395
	SidTune tune(path_fs.c_str(), nullptr, true);
Mike Dawson's avatar
Mike Dawson committed
396
	if (!tune)
397
		return nullptr;
Mike Dawson's avatar
Mike Dawson committed
398 399 400 401 402 403

	const SidTuneInfo &info=tune.getInfo();

	/* Don't treat sids containing a single tune
		as containers */
	if(!all_files_are_containers && info.songs<2)
404
		return nullptr;
Mike Dawson's avatar
Mike Dawson committed
405 406 407 408

	/* Construct container/tune path names, eg.
		Delta.sid/tune_001.sid */
	if(tnum<=info.songs) {
409
		return FormatNew(SUBTUNE_PREFIX "%03u.sid", tnum);
Mike Dawson's avatar
Mike Dawson committed
410
	} else
411
		return nullptr;
Mike Dawson's avatar
Mike Dawson committed
412 413
}

414 415
static const char *const sidplay_suffixes[] = {
	"sid",
416 417 418 419
	"mus",
	"str",
	"prg",
	"P00",
420
	nullptr
421 422
};

423 424
extern const struct DecoderPlugin sidplay_decoder_plugin;
const struct DecoderPlugin sidplay_decoder_plugin = {
425
	"sidplay",
Mike Dawson's avatar
Mike Dawson committed
426 427
	sidplay_init,
	sidplay_finish,
428
	nullptr, /* stream_decode() */
429
	sidplay_file_decode,
430
	sidplay_scan_file,
431
	nullptr, /* stream_tag() */
Mike Dawson's avatar
Mike Dawson committed
432
	sidplay_container_scan,
433
	sidplay_suffixes,
434
	nullptr, /* mime_types */
435
};