SidplayDecoderPlugin.cxx 13.1 KB
Newer Older
1
/*
2
 * Copyright 2003-2018 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 24
#include "tag/Handler.hxx"
#include "tag/Builder.hxx"
25
#include "song/DetachedSong.hxx"
26
#include "fs/Path.hxx"
27
#include "fs/AllocatedPath.hxx"
28
#ifdef HAVE_SIDPLAYFP
29
#include "fs/io/FileReader.hxx"
30 31
#include "util/RuntimeError.hxx"
#endif
32
#include "util/Macros.hxx"
33
#include "util/StringFormat.hxx"
34
#include "util/Domain.hxx"
35
#include "util/ByteOrder.hxx"
36
#include "Log.hxx"
37

38 39 40 41 42 43 44 45 46 47
#ifdef HAVE_SIDPLAYFP
#include <sidplayfp/sidplayfp.h>
#include <sidplayfp/SidInfo.h>
#include <sidplayfp/SidConfig.h>
#include <sidplayfp/SidTune.h>
#include <sidplayfp/SidTuneInfo.h>
#include <sidplayfp/builders/resid.h>
#include <sidplayfp/builders/residfp.h>
#include <sidplayfp/SidDatabase.h>
#else
48 49
#include <sidplay/sidplay2.h>
#include <sidplay/builders/resid.h>
50
#include <sidplay/utils/SidTuneMod.h>
51
#include <sidplay/utils/SidDatabase.h>
52
#endif
53

54 55 56
#include <string.h>
#include <stdio.h>

57 58 59 60
#ifdef HAVE_SIDPLAYFP
#define LIBSIDPLAYFP_VERSION GCC_MAKE_VERSION(LIBSIDPLAYFP_VERSION_MAJ, LIBSIDPLAYFP_VERSION_MIN, LIBSIDPLAYFP_VERSION_LEV)
#endif

Mike Dawson's avatar
Mike Dawson committed
61 62
#define SUBTUNE_PREFIX "tune_"

63 64
static constexpr Domain sidplay_domain("sidplay");

65
static SidDatabase *songlength_database;
Mike Dawson's avatar
Mike Dawson committed
66 67

static bool all_files_are_containers;
68
static unsigned default_songlength;
Mike Dawson's avatar
Mike Dawson committed
69

70 71
static bool filter_setting;

72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
#ifdef HAVE_SIDPLAYFP
static constexpr unsigned rom_size = 8192;
static uint8_t *kernal, *basic = nullptr;

static void loadRom(const Path rom_path, uint8_t *dump)
{
	FileReader romDump(rom_path);
	if (romDump.Read(dump, rom_size) != rom_size)
	{
		throw FormatRuntimeError
			("Could not load rom dump '%s'", rom_path.c_str());
	}
}
#endif

87
static SidDatabase *
88
sidplay_load_songlength_db(const Path path)
89
{
90
	SidDatabase *db = new SidDatabase();
91 92 93 94 95 96
#ifdef HAVE_SIDPLAYFP
	bool error = !db->open(path.c_str());
#else
	bool error = db->open(path.c_str()) < 0;
#endif
	if (error) {
97 98
		FormatError(sidplay_domain,
			    "unable to read songlengths file %s: %s",
99 100
			    path.c_str(), db->error());
		delete db;
101
		return nullptr;
102 103 104 105 106
	}

	return db;
}

Mike Dawson's avatar
Mike Dawson committed
107
static bool
108
sidplay_init(const ConfigBlock &block)
Mike Dawson's avatar
Mike Dawson committed
109
{
110
	/* read the songlengths database file */
111
	const auto database_path = block.GetPath("songlength_database");
112 113
	if (!database_path.IsNull())
		songlength_database = sidplay_load_songlength_db(database_path);
114

115
	default_songlength = block.GetPositiveValue("default_songlength", 0u);
116

117
	all_files_are_containers =
118
		block.GetBlockValue("all_files_are_containers", true);
Mike Dawson's avatar
Mike Dawson committed
119

120
	filter_setting = block.GetBlockValue("filter", true);
121

122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
#ifdef HAVE_SIDPLAYFP
	/* read kernal rom dump file */
	const auto kernal_path = block.GetPath("kernal");
	if (!kernal_path.IsNull())
	{
		kernal = new uint8_t[rom_size];
		loadRom(kernal_path, kernal);
	}

	/* read basic rom dump file */
	const auto basic_path = block.GetPath("basic");
	if (!basic_path.IsNull())
	{
		basic = new uint8_t[rom_size];
		loadRom(basic_path, basic);
	}
#endif

Mike Dawson's avatar
Mike Dawson committed
140 141 142
	return true;
}

143
static void
144
sidplay_finish() noexcept
Mike Dawson's avatar
Mike Dawson committed
145
{
146
	delete songlength_database;
147 148 149 150 151

#ifdef HAVE_SIDPLAYFP
	delete[] basic;
	delete[] kernal;
#endif
Mike Dawson's avatar
Mike Dawson committed
152 153
}

154 155 156 157 158 159 160
struct SidplayContainerPath {
	AllocatedPath path;
	unsigned track;
};

gcc_pure
static unsigned
161
ParseSubtuneName(const char *base) noexcept
Mike Dawson's avatar
Mike Dawson committed
162
{
163 164
	if (memcmp(base, SUBTUNE_PREFIX, sizeof(SUBTUNE_PREFIX) - 1) != 0)
		return 0;
Mike Dawson's avatar
Mike Dawson committed
165

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

168 169 170 171
	char *endptr;
	auto track = strtoul(base, &endptr, 10);
	if (endptr == base || *endptr != '.')
		return 0;
Mike Dawson's avatar
Mike Dawson committed
172

173
	return track;
Mike Dawson's avatar
Mike Dawson committed
174 175 176
}

/**
177 178
 * 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
179
 */
180 181
static SidplayContainerPath
ParseContainerPath(Path path_fs)
Mike Dawson's avatar
Mike Dawson committed
182
{
183 184 185 186 187 188 189
	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
190 191
}

192 193 194 195 196
/**
 * This is a template, because libsidplay requires SidTuneMod while
 * libsidplayfp requires just a plain Sidtune.
 */
template<typename T>
197
static SignedSongTime
198
get_song_length(T &tune)
199
{
200 201
	assert(tune.getStatus());

202 203 204 205 206 207 208 209 210 211
	if (songlength_database == nullptr)
		return SignedSongTime::Negative();

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

	return SignedSongTime::FromS(length);
}

212
static void
213
sidplay_file_decode(DecoderClient &client, Path path_fs)
214
{
215
	int channels;
216 217 218

	/* load the tune */

219
	const auto container = ParseContainerPath(path_fs);
220 221 222
#ifdef HAVE_SIDPLAYFP
	SidTune tune(container.path.c_str());
#else
223
	SidTuneMod tune(container.path.c_str());
224
#endif
225
	if (!tune.getStatus()) {
226 227 228 229 230
#ifdef HAVE_SIDPLAYFP
		const char *error = tune.statusString();
#else
		const char *error = tune.getInfo().statusString;
#endif
231
		FormatWarning(sidplay_domain, "failed to load file: %s",
232
			      error);
233 234 235
		return;
	}

236
	const int song_num = container.track;
Mike Dawson's avatar
Mike Dawson committed
237
	tune.selectSong(song_num);
238

239
	auto duration = get_song_length(tune);
240 241
	if (duration.IsNegative() && default_songlength > 0)
		duration = SongTime::FromS(default_songlength);
242

243 244
	/* initialize the player */

245 246
#ifdef HAVE_SIDPLAYFP
	sidplayfp player;
247 248

	player.setRoms(kernal, basic, nullptr);
249
#else
250
	sidplay2 player;
251 252 253 254 255 256 257
#endif
#ifdef HAVE_SIDPLAYFP
	bool error = !player.load(&tune);
#else
	bool error = player.load(&tune) < 0;
#endif
	if (error) {
258 259
		FormatWarning(sidplay_domain,
			      "sidplay2.load() failed: %s", player.error());
260 261 262 263 264
		return;
	}

	/* initialize the builder */

265 266 267 268 269 270
#ifdef HAVE_SIDPLAYFP
	ReSIDfpBuilder builder("ReSID");
	if (!builder.getStatus()) {
		FormatWarning(sidplay_domain,
			      "failed to initialize ReSIDfpBuilder: %s",
			      builder.error());
271 272 273
		return;
	}

274 275 276 277 278 279 280 281
	builder.create(player.info().maxsids());
	if (!builder.getStatus()) {
		FormatWarning(sidplay_domain,
			      "ReSIDfpBuilder.create() failed: %s",
			      builder.error());
		return;
	}
#else
282 283 284
	ReSIDBuilder builder("ReSID");
	builder.create(player.info().maxsids);
	if (!builder) {
285 286
		FormatWarning(sidplay_domain, "ReSIDBuilder.create() failed: %s",
			      builder.error());
287 288
		return;
	}
289
#endif
290

291
	builder.filter(filter_setting);
292 293 294 295 296 297 298 299
#ifdef HAVE_SIDPLAYFP
	if (!builder.getStatus()) {
		FormatWarning(sidplay_domain,
			      "ReSIDfpBuilder.filter() failed: %s",
			      builder.error());
		return;
	}
#else
300
	if (!builder) {
301 302
		FormatWarning(sidplay_domain, "ReSIDBuilder.filter() failed: %s",
			      builder.error());
303 304
		return;
	}
305
#endif
306 307 308

	/* configure the player */

309
	auto config = player.config();
310

311
#ifndef HAVE_SIDPLAYFP
312 313 314
	config.clockDefault = SID2_CLOCK_PAL;
	config.clockForced = true;
	config.clockSpeed = SID2_CLOCK_CORRECT;
315
#endif
316
	config.frequency = 48000;
317
#ifndef HAVE_SIDPLAYFP
318
	config.optimisation = SID2_DEFAULT_OPTIMISATION;
319

320 321
	config.precision = 16;
	config.sidDefault = SID2_MOS6581;
322
#endif
323
	config.sidEmulation = &builder;
324 325 326 327
#ifdef HAVE_SIDPLAYFP
	config.samplingMethod = SidConfig::INTERPOLATE;
	config.fastSampling = false;
#else
328 329
	config.sidModel = SID2_MODEL_CORRECT;
	config.sidSamples = true;
330 331 332
	config.sampleFormat = IsLittleEndian()
		? SID2_LITTLE_SIGNED
		: SID2_BIG_SIGNED;
333 334 335
#endif

#ifdef HAVE_SIDPLAYFP
336
#if LIBSIDPLAYFP_VERSION >= GCC_MAKE_VERSION(1,8,0)
337
	const bool stereo = tune.getInfo()->sidChips() >= 2;
338 339 340
#else
	const bool stereo = tune.getInfo()->isStereo();
#endif
341 342 343 344 345 346 347 348
#else
	const bool stereo = tune.isStereo();
#endif

	if (stereo) {
#ifdef HAVE_SIDPLAYFP
		config.playback = SidConfig::STEREO;
#else
349
		config.playback = sid2_stereo;
350
#endif
351 352
		channels = 2;
	} else {
353 354 355
#ifdef HAVE_SIDPLAYFP
		config.playback = SidConfig::MONO;
#else
356
		config.playback = sid2_mono;
357
#endif
358 359
		channels = 1;
	}
360

361 362 363 364 365 366
#ifdef HAVE_SIDPLAYFP
	error = !player.config(config);
#else
	error = player.config(config) < 0;
#endif
	if (error) {
367 368
		FormatWarning(sidplay_domain,
			      "sidplay2.config() failed: %s", player.error());
369 370 371 372 373
		return;
	}

	/* initialize the MPD decoder */

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

377
	client.Ready(audio_format, true, duration);
378 379 380

	/* .. and play */

381 382 383
#ifdef HAVE_SIDPLAYFP
	constexpr unsigned timebase = 1;
#else
384
	const unsigned timebase = player.timebase();
385
#endif
386 387 388
	const unsigned end = duration.IsNegative()
		? 0u
		: duration.ToScale<uint64_t>(timebase);
389

390
	DecoderCommand cmd;
391
	do {
392
		short buffer[4096];
393

394 395
		const auto result = player.play(buffer, ARRAY_SIZE(buffer));
		if (result <= 0)
396 397
			break;

398 399 400 401 402 403 404 405
#ifdef HAVE_SIDPLAYFP
		/* libsidplayfp returns the number of samples */
		const size_t nbytes = result * sizeof(buffer[0]);
#else
		/* libsidplay2 returns the number of bytes */
		const size_t nbytes = result;
#endif

406
		client.SubmitTimestamp(FloatDuration(player.time()) / timebase);
407

408
		cmd = client.SubmitData(nullptr, buffer, nbytes, 0);
409

410
		if (cmd == DecoderCommand::SEEK) {
411
			unsigned data_time = player.time();
412
			unsigned target_time =
413
				client.GetSeekTime().ToScale(timebase);
414 415 416 417 418 419 420 421

			/* 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 */
422 423
			while (data_time < target_time &&
			       player.play(buffer, ARRAY_SIZE(buffer)) > 0)
424
				data_time = player.time();
425

426
			client.CommandFinished();
427 428
		}

429
		if (end > 0 && player.time() >= end)
430 431
			break;

432
	} while (cmd != DecoderCommand::STOP);
433 434
}

435 436
gcc_pure
static const char *
437
GetInfoString(const SidTuneInfo &info, unsigned i) noexcept
438
{
439 440 441 442 443
#ifdef HAVE_SIDPLAYFP
	return info.numberOfInfoStrings() > i
		? info.infoString(i)
		: nullptr;
#else
444 445 446
	return info.numberOfInfoStrings > i
		? info.infoString[i]
		: nullptr;
447
#endif
448 449
}

450 451
static void
ScanSidTuneInfo(const SidTuneInfo &info, unsigned track, unsigned n_tracks,
452
		TagHandler &handler) noexcept
453
{
Mike Dawson's avatar
Mike Dawson committed
454
	/* title */
455 456 457
	const char *title = GetInfoString(info, 0);
	if (title == nullptr)
		title = "";
Mike Dawson's avatar
Mike Dawson committed
458

459
	if (n_tracks > 1) {
460 461 462
		const auto tag_title =
			StringFormat<1024>("%s (%u/%u)",
					   title, track, n_tracks);
463
		handler.OnTag(TAG_TITLE, tag_title);
Mike Dawson's avatar
Mike Dawson committed
464
	} else
465
		handler.OnTag(TAG_TITLE, title);
Mike Dawson's avatar
Mike Dawson committed
466 467

	/* artist */
468 469
	const char *artist = GetInfoString(info, 1);
	if (artist != nullptr)
470
		handler.OnTag(TAG_ARTIST, artist);
471

472 473 474
	/* date */
	const char *date = GetInfoString(info, 2);
	if (date != nullptr)
475
		handler.OnTag(TAG_DATE, date);
476

Mike Dawson's avatar
Mike Dawson committed
477
	/* track */
478
	handler.OnTag(TAG_TRACK, StringFormat<16>("%u", track));
479 480 481
}

static bool
482
sidplay_scan_file(Path path_fs, TagHandler &handler) noexcept
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
{
	const auto container = ParseContainerPath(path_fs);
	const unsigned song_num = container.track;

#ifdef HAVE_SIDPLAYFP
	SidTune tune(container.path.c_str());
#else
	SidTuneMod tune(container.path.c_str());
#endif
	if (!tune.getStatus())
		return false;

	tune.selectSong(song_num);

#ifdef HAVE_SIDPLAYFP
	const SidTuneInfo &info = *tune.getInfo();
	const unsigned n_tracks = info.songs();
#else
	const SidTuneInfo &info = tune.getInfo();
	const unsigned n_tracks = info.songs;
#endif

505
	ScanSidTuneInfo(info, song_num, n_tracks, handler);
Mike Dawson's avatar
Mike Dawson committed
506

507
	/* time */
508
	const auto duration = get_song_length(tune);
509
	if (!duration.IsNegative())
510
		handler.OnDuration(SongTime(duration));
511

512
	return true;
513 514
}

515
static std::forward_list<DetachedSong>
516
sidplay_container_scan(Path path_fs)
Mike Dawson's avatar
Mike Dawson committed
517
{
518
	std::forward_list<DetachedSong> list;
519

520 521 522 523 524
#ifdef HAVE_SIDPLAYFP
	SidTune tune(path_fs.c_str());
#else
	SidTuneMod tune(path_fs.c_str());
#endif
525
	if (!tune.getStatus())
526
		return list;
Mike Dawson's avatar
Mike Dawson committed
527

528 529 530 531 532 533 534
#ifdef HAVE_SIDPLAYFP
	const SidTuneInfo &info = *tune.getInfo();
	const unsigned n_tracks = info.songs();
#else
	const SidTuneInfo &info = tune.getInfo();
	const unsigned n_tracks = info.songs;
#endif
Mike Dawson's avatar
Mike Dawson committed
535 536 537

	/* Don't treat sids containing a single tune
		as containers */
538
	if(!all_files_are_containers && n_tracks < 2)
539 540
		return list;

541 542
	TagBuilder tag_builder;

543
	auto tail = list.before_begin();
544
	for (unsigned i = 1; i <= n_tracks; ++i) {
545 546
		tune.selectSong(i);

547 548
		AddTagHandler h(tag_builder);
		ScanSidTuneInfo(info, i, n_tracks, h);
549

550 551 552 553
		char track_name[32];
		/* Construct container/tune path names, eg.
		   Delta.sid/tune_001.sid */
		sprintf(track_name, SUBTUNE_PREFIX "%03u.sid", i);
554 555
		tail = list.emplace_after(tail, track_name,
					  tag_builder.Commit());
556
	}
Mike Dawson's avatar
Mike Dawson committed
557

558
	return list;
Mike Dawson's avatar
Mike Dawson committed
559 560
}

561 562
static const char *const sidplay_suffixes[] = {
	"sid",
563 564 565 566
	"mus",
	"str",
	"prg",
	"P00",
567
	nullptr
568 569
};

570 571
extern const struct DecoderPlugin sidplay_decoder_plugin;
const struct DecoderPlugin sidplay_decoder_plugin = {
572
	"sidplay",
Mike Dawson's avatar
Mike Dawson committed
573 574
	sidplay_init,
	sidplay_finish,
575
	nullptr, /* stream_decode() */
576
	sidplay_file_decode,
577
	sidplay_scan_file,
578
	nullptr, /* stream_tag() */
Mike Dawson's avatar
Mike Dawson committed
579
	sidplay_container_scan,
580
	sidplay_suffixes,
581
	nullptr, /* mime_types */
582
};