SidplayDecoderPlugin.cxx 8.77 KB
Newer Older
1
/*
2
 * Copyright 2003-2016 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 "fs/AllocatedPath.hxx"
26
#include "util/FormatString.hxx"
27
#include "util/Domain.hxx"
28
#include "util/Error.hxx"
29
#include "system/ByteOrder.hxx"
30
#include "system/FatalError.hxx"
31
#include "Log.hxx"
32

Max Kellermann's avatar
Max Kellermann committed
33
#include <string.h>
34 35 36

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

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

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

44
static SidDatabase *songlength_database;
Mike Dawson's avatar
Mike Dawson committed
45 46

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

49 50
static bool filter_setting;

51
static SidDatabase *
52
sidplay_load_songlength_db(const Path path)
53
{
54 55
	SidDatabase *db = new SidDatabase();
	if (db->open(path.c_str()) < 0) {
56 57
		FormatError(sidplay_domain,
			    "unable to read songlengths file %s: %s",
58 59
			    path.c_str(), db->error());
		delete db;
60
		return nullptr;
61 62 63 64 65
	}

	return db;
}

Mike Dawson's avatar
Mike Dawson committed
66
static bool
67
sidplay_init(const ConfigBlock &block)
Mike Dawson's avatar
Mike Dawson committed
68
{
69
	/* read the songlengths database file */
70
	Error error;
71
	const auto database_path = block.GetBlockPath("songlength_database", error);
72 73 74 75
	if (!database_path.IsNull())
		songlength_database = sidplay_load_songlength_db(database_path);
	else if (error.IsDefined())
		FatalError(error);
76

77
	default_songlength = block.GetBlockValue("default_songlength", 0u);
78

79
	all_files_are_containers =
80
		block.GetBlockValue("all_files_are_containers", true);
Mike Dawson's avatar
Mike Dawson committed
81

82
	filter_setting = block.GetBlockValue("filter", true);
83

Mike Dawson's avatar
Mike Dawson committed
84 85 86
	return true;
}

87
static void
Mike Dawson's avatar
Mike Dawson committed
88 89
sidplay_finish()
{
90
	delete songlength_database;
Mike Dawson's avatar
Mike Dawson committed
91 92
}

93 94 95 96 97 98 99 100
struct SidplayContainerPath {
	AllocatedPath path;
	unsigned track;
};

gcc_pure
static unsigned
ParseSubtuneName(const char *base)
Mike Dawson's avatar
Mike Dawson committed
101
{
102 103
	if (memcmp(base, SUBTUNE_PREFIX, sizeof(SUBTUNE_PREFIX) - 1) != 0)
		return 0;
Mike Dawson's avatar
Mike Dawson committed
104

105
	base += sizeof(SUBTUNE_PREFIX) - 1;
Mike Dawson's avatar
Mike Dawson committed
106

107 108 109 110
	char *endptr;
	auto track = strtoul(base, &endptr, 10);
	if (endptr == base || *endptr != '.')
		return 0;
Mike Dawson's avatar
Mike Dawson committed
111

112
	return track;
Mike Dawson's avatar
Mike Dawson committed
113 114 115
}

/**
116 117
 * returns the file path stripped of any /tune_xxx.* subtune suffix
 * and the track number (or 1 if no "tune_xxx" suffix is present).
Mike Dawson's avatar
Mike Dawson committed
118
 */
119 120
static SidplayContainerPath
ParseContainerPath(Path path_fs)
Mike Dawson's avatar
Mike Dawson committed
121
{
122 123 124 125 126 127 128
	const Path base = path_fs.GetBase();
	unsigned track;
	if (base.IsNull() ||
	    (track = ParseSubtuneName(base.c_str())) < 1)
		return { AllocatedPath(path_fs), 1 };

	return { path_fs.GetDirectoryName(), track };
Mike Dawson's avatar
Mike Dawson committed
129 130
}

131
/* get the song length in seconds */
132
static SignedSongTime
133
get_song_length(SidTuneMod &tune)
134
{
135
	assert(tune);
136

137
	if (songlength_database == nullptr)
138
		return SignedSongTime::Negative();
139

140
	const auto length = songlength_database->length(tune);
141
	if (length < 0)
142
		return SignedSongTime::Negative();
143

144
	return SignedSongTime::FromS(length);
145 146
}

147
static void
148
sidplay_file_decode(Decoder &decoder, Path path_fs)
149
{
150
	int channels;
151 152 153

	/* load the tune */

154
	const auto container = ParseContainerPath(path_fs);
155
	SidTuneMod tune(container.path.c_str());
156
	if (!tune) {
157
		LogWarning(sidplay_domain, "failed to load file");
158 159 160
		return;
	}

161
	const int song_num = container.track;
Mike Dawson's avatar
Mike Dawson committed
162
	tune.selectSong(song_num);
163

164
	auto duration = get_song_length(tune);
165 166
	if (duration.IsNegative() && default_songlength > 0)
		duration = SongTime::FromS(default_songlength);
167

168 169 170 171 172
	/* initialize the player */

	sidplay2 player;
	int iret = player.load(&tune);
	if (iret != 0) {
173 174
		FormatWarning(sidplay_domain,
			      "sidplay2.load() failed: %s", player.error());
175 176 177 178 179 180 181
		return;
	}

	/* initialize the builder */

	ReSIDBuilder builder("ReSID");
	if (!builder) {
182 183
		LogWarning(sidplay_domain,
			   "failed to initialize ReSIDBuilder");
184 185 186 187 188
		return;
	}

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

193
	builder.filter(filter_setting);
194
	if (!builder) {
195
		LogWarning(sidplay_domain, "ReSIDBuilder.filter() failed");
196 197 198 199 200 201 202 203 204 205 206 207
		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;
208

209 210 211 212 213
	config.precision = 16;
	config.sidDefault = SID2_MOS6581;
	config.sidEmulation = &builder;
	config.sidModel = SID2_MODEL_CORRECT;
	config.sidSamples = true;
214 215 216
	config.sampleFormat = IsLittleEndian()
		? SID2_LITTLE_SIGNED
		: SID2_BIG_SIGNED;
217 218 219 220 221 222 223
	if (tune.isStereo()) {
		config.playback = sid2_stereo;
		channels = 2;
	} else {
		config.playback = sid2_mono;
		channels = 1;
	}
224 225 226

	iret = player.config(config);
	if (iret != 0) {
227 228
		FormatWarning(sidplay_domain,
			      "sidplay2.config() failed: %s", player.error());
229 230 231 232 233
		return;
	}

	/* initialize the MPD decoder */

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

237
	decoder_initialized(decoder, audio_format, true, duration);
238 239 240

	/* .. and play */

241
	const unsigned timebase = player.timebase();
242 243 244
	const unsigned end = duration.IsNegative()
		? 0u
		: duration.ToScale<uint64_t>(timebase);
245

246
	DecoderCommand cmd;
247 248 249 250 251 252 253 254
	do {
		char buffer[4096];
		size_t nbytes;

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

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

257
		cmd = decoder_data(decoder, nullptr, buffer, nbytes, 0);
258

259
		if (cmd == DecoderCommand::SEEK) {
260
			unsigned data_time = player.time();
261 262
			unsigned target_time =
				decoder_seek_time(decoder).ToScale(timebase);
263 264 265 266 267 268 269 270 271 272 273 274

			/* 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;
275
				data_time = player.time();
276 277 278 279 280
			}

			decoder_command_finished(decoder);
		}

281
		if (end > 0 && player.time() >= end)
282 283
			break;

284
	} while (cmd != DecoderCommand::STOP);
285 286
}

287
static bool
288
sidplay_scan_file(Path path_fs,
289
		  const TagHandler &handler, void *handler_ctx)
290
{
291 292
	const auto container = ParseContainerPath(path_fs);
	const unsigned song_num = container.track;
Mike Dawson's avatar
Mike Dawson committed
293

294
	SidTuneMod tune(container.path.c_str());
295
	if (!tune)
296
		return false;
297

298 299
	tune.selectSong(song_num);

300 301
	const SidTuneInfo &info = tune.getInfo();

Mike Dawson's avatar
Mike Dawson committed
302 303
	/* title */
	const char *title;
304
	if (info.numberOfInfoStrings > 0 && info.infoString[0] != nullptr)
Mike Dawson's avatar
Mike Dawson committed
305 306 307 308 309
		title=info.infoString[0];
	else
		title="";

	if(info.songs>1) {
310 311 312 313
		char tag_title[1024];
		snprintf(tag_title, sizeof(tag_title),
			 "%s (%d/%d)",
			 title, song_num, info.songs);
314 315
		tag_handler_invoke_tag(handler, handler_ctx,
				       TAG_TITLE, tag_title);
Mike Dawson's avatar
Mike Dawson committed
316
	} else
317
		tag_handler_invoke_tag(handler, handler_ctx, TAG_TITLE, title);
Mike Dawson's avatar
Mike Dawson committed
318 319

	/* artist */
320
	if (info.numberOfInfoStrings > 1 && info.infoString[1] != nullptr)
321 322
		tag_handler_invoke_tag(handler, handler_ctx, TAG_ARTIST,
				       info.infoString[1]);
323

Mike Dawson's avatar
Mike Dawson committed
324
	/* track */
325 326
	char track[16];
	sprintf(track, "%d", song_num);
327
	tag_handler_invoke_tag(handler, handler_ctx, TAG_TRACK, track);
Mike Dawson's avatar
Mike Dawson committed
328

329
	/* time */
330
	const auto duration = get_song_length(tune);
331 332
	if (!duration.IsNegative())
		tag_handler_invoke_duration(handler, handler_ctx,
333
					    SongTime(duration));
334

335
	return true;
336 337
}

Mike Dawson's avatar
Mike Dawson committed
338
static char *
339
sidplay_container_scan(Path path_fs, const unsigned int tnum)
Mike Dawson's avatar
Mike Dawson committed
340
{
341
	SidTune tune(path_fs.c_str(), nullptr, true);
Mike Dawson's avatar
Mike Dawson committed
342
	if (!tune)
343
		return nullptr;
Mike Dawson's avatar
Mike Dawson committed
344 345 346 347 348 349

	const SidTuneInfo &info=tune.getInfo();

	/* Don't treat sids containing a single tune
		as containers */
	if(!all_files_are_containers && info.songs<2)
350
		return nullptr;
Mike Dawson's avatar
Mike Dawson committed
351 352 353 354

	/* Construct container/tune path names, eg.
		Delta.sid/tune_001.sid */
	if(tnum<=info.songs) {
355
		return FormatNew(SUBTUNE_PREFIX "%03u.sid", tnum);
Mike Dawson's avatar
Mike Dawson committed
356
	} else
357
		return nullptr;
Mike Dawson's avatar
Mike Dawson committed
358 359
}

360 361
static const char *const sidplay_suffixes[] = {
	"sid",
362 363 364 365
	"mus",
	"str",
	"prg",
	"P00",
366
	nullptr
367 368
};

369 370
extern const struct DecoderPlugin sidplay_decoder_plugin;
const struct DecoderPlugin sidplay_decoder_plugin = {
371
	"sidplay",
Mike Dawson's avatar
Mike Dawson committed
372 373
	sidplay_init,
	sidplay_finish,
374
	nullptr, /* stream_decode() */
375
	sidplay_file_decode,
376
	sidplay_scan_file,
377
	nullptr, /* stream_tag() */
Mike Dawson's avatar
Mike Dawson committed
378
	sidplay_container_scan,
379
	sidplay_suffixes,
380
	nullptr, /* mime_types */
381
};