SidplayDecoderPlugin.cxx 10.2 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
/* get the song length in seconds */
162
static SignedSongTime
163
get_song_length(Path path_fs)
164
{
165
	if (songlength_database == nullptr)
166
		return SignedSongTime::Negative();
167

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
		return SignedSongTime::Negative();
175 176 177 178
	}
	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
	if(!values || song_num>num_items) {
		g_strfreev(values);
186
		return SignedSongTime::Negative();
187 188
	}

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
		if(errno==EINVAL) seconds=0;
	} else
		seconds=0;

	g_strfreev(values);

202
	return SignedSongTime::FromS((minutes * 60) + seconds);
203 204
}

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
	auto duration = get_song_length(path_fs);
	if (duration.IsNegative() && default_songlength > 0)
		duration = SongTime::FromS(default_songlength);
226

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

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

	/* initialize the builder */

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

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

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

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

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

	/* initialize the MPD decoder */

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

296
	decoder_initialized(decoder, audio_format, true, duration);
297 298 299

	/* .. and play */

300
	const unsigned timebase = player.timebase();
301 302 303
	const unsigned end = duration.IsNegative()
		? 0u
		: duration.ToScale<uint64_t>(timebase);
304

305
	DecoderCommand cmd;
306 307 308 309 310 311 312 313
	do {
		char buffer[4096];
		size_t nbytes;

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

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

316
		cmd = decoder_data(decoder, nullptr, buffer, nbytes, 0);
317

318
		if (cmd == DecoderCommand::SEEK) {
319
			unsigned data_time = player.time();
320 321
			unsigned target_time =
				decoder_seek_time(decoder).ToScale(timebase);
322 323 324 325 326 327 328 329 330 331 332 333

			/* 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;
334
				data_time = player.time();
335 336 337 338 339
			}

			decoder_command_finished(decoder);
		}

340
		if (end > 0 && player.time() >= end)
341 342
			break;

343
	} while (cmd != DecoderCommand::STOP);
344 345
}

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

353
	SidTune tune(path_container, nullptr, true);
354
	free(path_container);
355
	if (!tune)
356
		return false;
357 358 359

	const SidTuneInfo &info = tune.getInfo();

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

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

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

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

387
	/* time */
388 389 390
	const auto duration = get_song_length(path_fs);
	if (!duration.IsNegative())
		tag_handler_invoke_duration(handler, handler_ctx,
391
					    SongTime(duration));
392

393
	return true;
394 395
}

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

	const SidTuneInfo &info=tune.getInfo();

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

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

418 419
static const char *const sidplay_suffixes[] = {
	"sid",
420 421 422 423
	"mus",
	"str",
	"prg",
	"P00",
424
	nullptr
425 426
};

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