SidplayDecoderPlugin.cxx 8.82 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/AllocatedString.hxx"
28
#include "util/Domain.hxx"
29
#include "util/Error.hxx"
30
#include "system/ByteOrder.hxx"
31
#include "system/FatalError.hxx"
32
#include "Log.hxx"
33

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

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

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

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

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

	return db;
}

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

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

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

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

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

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

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

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

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

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

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

/**
117 118
 * 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
119
 */
120 121
static SidplayContainerPath
ParseContainerPath(Path path_fs)
Mike Dawson's avatar
Mike Dawson committed
122
{
123 124 125 126 127 128 129
	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
130 131
}

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

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

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

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

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

	/* load the tune */

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

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

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

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

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

	/* initialize the builder */

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

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

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

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

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

	/* initialize the MPD decoder */

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

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

	/* .. and play */

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

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

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

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

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

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

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

			decoder_command_finished(decoder);
		}

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

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

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

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

299 300
	tune.selectSong(song_num);

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

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

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

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

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

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

336
	return true;
337 338
}

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

	const SidTuneInfo &info=tune.getInfo();

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

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

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

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