SidplayDecoderPlugin.cxx 15.1 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2020 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
#include "lib/icu/Converter.hxx"
29
#ifdef HAVE_SIDPLAYFP
30
#include "fs/io/FileReader.hxx"
31 32
#include "util/RuntimeError.hxx"
#endif
33
#include "util/StringFormat.hxx"
34
#include "util/StringView.hxx"
35
#include "util/Domain.hxx"
36 37
#include "util/AllocatedString.hxx"
#include "util/CharUtil.hxx"
38
#include "util/ByteOrder.hxx"
39
#include "util/RuntimeError.hxx"
40
#include "Log.hxx"
41

42 43 44 45 46 47 48 49 50 51
#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
52 53
#include <sidplay/sidplay2.h>
#include <sidplay/builders/resid.h>
54
#include <sidplay/utils/SidTuneMod.h>
55
#include <sidplay/utils/SidDatabase.h>
56
#endif
57

58
#include <iterator>
59
#include <memory>
60

61 62
#include <string.h>

63 64 65 66
#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
67 68
#define SUBTUNE_PREFIX "tune_"

69 70
static constexpr Domain sidplay_domain("sidplay");

71
struct SidplayGlobal {
72
	std::unique_ptr<SidDatabase> songlength_database;
Mike Dawson's avatar
Mike Dawson committed
73

74 75 76
	bool all_files_are_containers;
	unsigned default_songlength;
	std::string default_genre;
Mike Dawson's avatar
Mike Dawson committed
77

78 79 80
	bool filter_setting;

#ifdef HAVE_SIDPLAYFP
81
	std::unique_ptr<uint8_t[]> kernal, basic;
82 83 84 85 86 87
#endif

	explicit SidplayGlobal(const ConfigBlock &block);
};

static SidplayGlobal *sidplay_global;
88

89 90 91 92 93 94 95 96 97 98 99 100 101 102
#ifdef HAVE_SIDPLAYFP
static constexpr unsigned rom_size = 8192;

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

103 104 105
/**
 * Throws on error.
 */
106
static std::unique_ptr<SidDatabase>
107
sidplay_load_songlength_db(const Path path)
108
{
109
	auto db = std::make_unique<SidDatabase>();
110 111 112 113 114
#ifdef HAVE_SIDPLAYFP
	bool error = !db->open(path.c_str());
#else
	bool error = db->open(path.c_str()) < 0;
#endif
115 116 117
	if (error)
		throw FormatRuntimeError("unable to read songlengths file %s: %s",
					 path.c_str(), db->error());
118 119 120 121

	return db;
}

122 123
inline
SidplayGlobal::SidplayGlobal(const ConfigBlock &block)
Mike Dawson's avatar
Mike Dawson committed
124
{
125
	/* read the songlengths database file */
126
	const auto database_path = block.GetPath("songlength_database");
127 128
	if (!database_path.IsNull())
		songlength_database = sidplay_load_songlength_db(database_path);
129

130
	default_songlength = block.GetPositiveValue("default_songlength", 0u);
131

132 133
	default_genre = block.GetBlockValue("default_genre", "");

134
	all_files_are_containers =
135
		block.GetBlockValue("all_files_are_containers", true);
Mike Dawson's avatar
Mike Dawson committed
136

137
	filter_setting = block.GetBlockValue("filter", true);
138

139 140 141 142 143
#ifdef HAVE_SIDPLAYFP
	/* read kernal rom dump file */
	const auto kernal_path = block.GetPath("kernal");
	if (!kernal_path.IsNull())
	{
144 145
		kernal.reset(new uint8_t[rom_size]);
		loadRom(kernal_path, kernal.get());
146 147 148 149 150 151
	}

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

158 159 160 161
static bool
sidplay_init(const ConfigBlock &block)
{
	sidplay_global = new SidplayGlobal(block);
Mike Dawson's avatar
Mike Dawson committed
162 163 164
	return true;
}

165
static void
166
sidplay_finish() noexcept
Mike Dawson's avatar
Mike Dawson committed
167
{
168
	delete sidplay_global;
Mike Dawson's avatar
Mike Dawson committed
169 170
}

171 172 173 174 175 176 177
struct SidplayContainerPath {
	AllocatedPath path;
	unsigned track;
};

gcc_pure
static unsigned
178
ParseSubtuneName(const char *base) noexcept
Mike Dawson's avatar
Mike Dawson committed
179
{
180 181
	if (memcmp(base, SUBTUNE_PREFIX, sizeof(SUBTUNE_PREFIX) - 1) != 0)
		return 0;
Mike Dawson's avatar
Mike Dawson committed
182

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

185 186 187 188
	char *endptr;
	auto track = strtoul(base, &endptr, 10);
	if (endptr == base || *endptr != '.')
		return 0;
Mike Dawson's avatar
Mike Dawson committed
189

190
	return track;
Mike Dawson's avatar
Mike Dawson committed
191 192 193
}

/**
194 195
 * 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
196
 */
197
static SidplayContainerPath
198
ParseContainerPath(Path path_fs) noexcept
Mike Dawson's avatar
Mike Dawson committed
199
{
200 201 202 203 204 205 206
	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
207 208
}

209 210 211 212 213
/**
 * This is a template, because libsidplay requires SidTuneMod while
 * libsidplayfp requires just a plain Sidtune.
 */
template<typename T>
214
static SignedSongTime
215
get_song_length(T &tune) noexcept
216
{
217 218
	assert(tune.getStatus());

219
	if (sidplay_global->songlength_database == nullptr)
220 221
		return SignedSongTime::Negative();

222
	const auto length = sidplay_global->songlength_database->length(tune);
223 224 225 226 227 228
	if (length < 0)
		return SignedSongTime::Negative();

	return SignedSongTime::FromS(length);
}

229
static void
230
sidplay_file_decode(DecoderClient &client, Path path_fs)
231
{
232
	int channels;
233 234 235

	/* load the tune */

236
	const auto container = ParseContainerPath(path_fs);
237 238 239
#ifdef HAVE_SIDPLAYFP
	SidTune tune(container.path.c_str());
#else
240
	SidTuneMod tune(container.path.c_str());
241
#endif
242
	if (!tune.getStatus()) {
243 244 245 246 247
#ifdef HAVE_SIDPLAYFP
		const char *error = tune.statusString();
#else
		const char *error = tune.getInfo().statusString;
#endif
248
		FormatWarning(sidplay_domain, "failed to load file: %s",
249
			      error);
250 251 252
		return;
	}

253
	const int song_num = container.track;
Mike Dawson's avatar
Mike Dawson committed
254
	tune.selectSong(song_num);
255

256
	auto duration = get_song_length(tune);
257 258
	if (duration.IsNegative() && sidplay_global->default_songlength > 0)
		duration = SongTime::FromS(sidplay_global->default_songlength);
259

260 261
	/* initialize the player */

262 263
#ifdef HAVE_SIDPLAYFP
	sidplayfp player;
264

265 266 267
	player.setRoms(sidplay_global->kernal.get(),
		       sidplay_global->basic.get(),
		       nullptr);
268
#else
269
	sidplay2 player;
270 271 272 273 274 275 276
#endif
#ifdef HAVE_SIDPLAYFP
	bool error = !player.load(&tune);
#else
	bool error = player.load(&tune) < 0;
#endif
	if (error) {
277 278
		FormatWarning(sidplay_domain,
			      "sidplay2.load() failed: %s", player.error());
279 280 281 282 283
		return;
	}

	/* initialize the builder */

284 285 286 287 288 289
#ifdef HAVE_SIDPLAYFP
	ReSIDfpBuilder builder("ReSID");
	if (!builder.getStatus()) {
		FormatWarning(sidplay_domain,
			      "failed to initialize ReSIDfpBuilder: %s",
			      builder.error());
290 291 292
		return;
	}

293 294 295 296 297 298 299 300
	builder.create(player.info().maxsids());
	if (!builder.getStatus()) {
		FormatWarning(sidplay_domain,
			      "ReSIDfpBuilder.create() failed: %s",
			      builder.error());
		return;
	}
#else
301 302 303
	ReSIDBuilder builder("ReSID");
	builder.create(player.info().maxsids);
	if (!builder) {
304 305
		FormatWarning(sidplay_domain, "ReSIDBuilder.create() failed: %s",
			      builder.error());
306 307
		return;
	}
308
#endif
309

310
	builder.filter(sidplay_global->filter_setting);
311 312 313 314 315 316 317 318
#ifdef HAVE_SIDPLAYFP
	if (!builder.getStatus()) {
		FormatWarning(sidplay_domain,
			      "ReSIDfpBuilder.filter() failed: %s",
			      builder.error());
		return;
	}
#else
319
	if (!builder) {
320 321
		FormatWarning(sidplay_domain, "ReSIDBuilder.filter() failed: %s",
			      builder.error());
322 323
		return;
	}
324
#endif
325 326 327

	/* configure the player */

328
	auto config = player.config();
329

330
#ifndef HAVE_SIDPLAYFP
331 332 333
	config.clockDefault = SID2_CLOCK_PAL;
	config.clockForced = true;
	config.clockSpeed = SID2_CLOCK_CORRECT;
334
#endif
335
	config.frequency = 48000;
336
#ifndef HAVE_SIDPLAYFP
337
	config.optimisation = SID2_DEFAULT_OPTIMISATION;
338

339 340
	config.precision = 16;
	config.sidDefault = SID2_MOS6581;
341
#endif
342
	config.sidEmulation = &builder;
343 344 345 346
#ifdef HAVE_SIDPLAYFP
	config.samplingMethod = SidConfig::INTERPOLATE;
	config.fastSampling = false;
#else
347 348
	config.sidModel = SID2_MODEL_CORRECT;
	config.sidSamples = true;
349 350 351
	config.sampleFormat = IsLittleEndian()
		? SID2_LITTLE_SIGNED
		: SID2_BIG_SIGNED;
352 353 354
#endif

#ifdef HAVE_SIDPLAYFP
355
#if LIBSIDPLAYFP_VERSION >= GCC_MAKE_VERSION(1,8,0)
356
	const bool stereo = tune.getInfo()->sidChips() >= 2;
357 358 359
#else
	const bool stereo = tune.getInfo()->isStereo();
#endif
360 361 362 363 364 365 366 367
#else
	const bool stereo = tune.isStereo();
#endif

	if (stereo) {
#ifdef HAVE_SIDPLAYFP
		config.playback = SidConfig::STEREO;
#else
368
		config.playback = sid2_stereo;
369
#endif
370 371
		channels = 2;
	} else {
372 373 374
#ifdef HAVE_SIDPLAYFP
		config.playback = SidConfig::MONO;
#else
375
		config.playback = sid2_mono;
376
#endif
377 378
		channels = 1;
	}
379

380 381 382 383 384 385
#ifdef HAVE_SIDPLAYFP
	error = !player.config(config);
#else
	error = player.config(config) < 0;
#endif
	if (error) {
386 387
		FormatWarning(sidplay_domain,
			      "sidplay2.config() failed: %s", player.error());
388 389 390 391 392
		return;
	}

	/* initialize the MPD decoder */

393 394
	const AudioFormat audio_format(48000, SampleFormat::S16, channels);
	assert(audio_format.IsValid());
395

396
	client.Ready(audio_format, true, duration);
397 398 399

	/* .. and play */

400 401 402
#ifdef HAVE_SIDPLAYFP
	constexpr unsigned timebase = 1;
#else
403
	const unsigned timebase = player.timebase();
404
#endif
405 406 407
	const unsigned end = duration.IsNegative()
		? 0u
		: duration.ToScale<uint64_t>(timebase);
408

409
	DecoderCommand cmd;
410
	do {
411
		short buffer[4096];
412

413
		const auto result = player.play(buffer, std::size(buffer));
414
		if (result <= 0)
415 416
			break;

417 418 419 420 421 422 423 424
#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

425
		client.SubmitTimestamp(FloatDuration(player.time()) / timebase);
426

427
		cmd = client.SubmitData(nullptr, buffer, nbytes, 0);
428

429
		if (cmd == DecoderCommand::SEEK) {
430
			unsigned data_time = player.time();
431
			unsigned target_time =
432
				client.GetSeekTime().ToScale(timebase);
433 434 435 436 437 438 439 440

			/* 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 */
441
			while (data_time < target_time &&
442
			       player.play(buffer, std::size(buffer)) > 0)
443
				data_time = player.time();
444

445
			client.CommandFinished();
446 447
		}

448
		if (end > 0 && player.time() >= end)
449 450
			break;

451
	} while (cmd != DecoderCommand::STOP);
452 453
}

454 455 456 457 458
static AllocatedString<char>
Windows1252ToUTF8(const char *s) noexcept
{
#ifdef HAVE_ICU_CONVERTER
	try {
459
		return IcuConverter::Create("windows-1252")->ToUTF8(s);
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
	} catch (...) { }
#endif

	/*
	 * Fallback to not transcoding windows-1252 to utf-8, that may result
	 * in invalid utf-8 unless nonprintable characters are replaced.
	 */
	auto t = AllocatedString<char>::Duplicate(s);

	for (size_t i = 0; t[i] != AllocatedString<char>::SENTINEL; i++)
		if (!IsPrintableASCII(t[i]))
			t[i] = '?';

	return t;
}

476
gcc_pure
477
static AllocatedString<char>
478
GetInfoString(const SidTuneInfo &info, unsigned i) noexcept
479
{
480
#ifdef HAVE_SIDPLAYFP
481
	const char *s = info.numberOfInfoStrings() > i
482
		? info.infoString(i)
483
		: "";
484
#else
485
	const char *s = info.numberOfInfoStrings > i
486
		? info.infoString[i]
487
		: "";
488
#endif
489 490

	return Windows1252ToUTF8(s);
491 492
}

493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
gcc_pure
static AllocatedString<char>
GetDateString(const SidTuneInfo &info) noexcept
{
	/*
	 * Field 2 is called <released>, previously used as <copyright>.
	 * It is formatted <year><space><company or author or group>,
	 * where <year> may be <YYYY>, <YYY?>, <YY??> or <YYYY-YY>, for
	 * example "1987", "199?", "19??" or "1985-87". The <company or
	 * author or group> may be for example Rob Hubbard. A full field
	 * may be for example "1987 Rob Hubbard".
	 */
	AllocatedString<char> release = GetInfoString(info, 2);

	/* Keep the <year> part only for the date. */
	for (size_t i = 0; release[i] != AllocatedString<char>::SENTINEL; i++)
		if (std::isspace(release[i])) {
			release[i] = AllocatedString<char>::SENTINEL;
			break;
		}

	return release;
515 516
}

517 518
static void
ScanSidTuneInfo(const SidTuneInfo &info, unsigned track, unsigned n_tracks,
519
		TagHandler &handler) noexcept
520
{
521 522 523 524
	/* album */
	const auto album = GetInfoString(info, 0);

	handler.OnTag(TAG_ALBUM, album.c_str());
Mike Dawson's avatar
Mike Dawson committed
525

526
	if (n_tracks > 1) {
527 528
		const auto tag_title =
			StringFormat<1024>("%s (%u/%u)",
529
					   album.c_str(), track, n_tracks);
530
		handler.OnTag(TAG_TITLE, tag_title.c_str());
Mike Dawson's avatar
Mike Dawson committed
531
	} else
532
		handler.OnTag(TAG_TITLE, album.c_str());
Mike Dawson's avatar
Mike Dawson committed
533 534

	/* artist */
535 536 537
	const auto artist = GetInfoString(info, 1);
	if (!artist.empty())
		handler.OnTag(TAG_ARTIST, artist.c_str());
538

539
	/* genre */
540 541 542
	if (!sidplay_global->default_genre.empty())
		handler.OnTag(TAG_GENRE,
			      sidplay_global->default_genre.c_str());
543

544
	/* date */
545
	const auto date = GetDateString(info);
546 547
	if (!date.empty())
		handler.OnTag(TAG_DATE, date.c_str());
548

Mike Dawson's avatar
Mike Dawson committed
549
	/* track */
550
	handler.OnTag(TAG_TRACK, StringFormat<16>("%u", track).c_str());
551 552 553
}

static bool
554
sidplay_scan_file(Path path_fs, TagHandler &handler) noexcept
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
{
	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

577
	ScanSidTuneInfo(info, song_num, n_tracks, handler);
Mike Dawson's avatar
Mike Dawson committed
578

579
	/* time */
580
	const auto duration = get_song_length(tune);
581
	if (!duration.IsNegative())
582
		handler.OnDuration(SongTime(duration));
583

584
	return true;
585 586
}

587
static std::forward_list<DetachedSong>
588
sidplay_container_scan(Path path_fs)
Mike Dawson's avatar
Mike Dawson committed
589
{
590
	std::forward_list<DetachedSong> list;
591

592 593 594 595 596
#ifdef HAVE_SIDPLAYFP
	SidTune tune(path_fs.c_str());
#else
	SidTuneMod tune(path_fs.c_str());
#endif
597
	if (!tune.getStatus())
598
		return list;
Mike Dawson's avatar
Mike Dawson committed
599

600 601 602 603 604 605 606
#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
607 608 609

	/* Don't treat sids containing a single tune
		as containers */
610
	if (!sidplay_global->all_files_are_containers && n_tracks < 2)
611 612
		return list;

613 614
	TagBuilder tag_builder;

615
	auto tail = list.before_begin();
616
	for (unsigned i = 1; i <= n_tracks; ++i) {
617 618
		tune.selectSong(i);

619 620
		AddTagHandler h(tag_builder);
		ScanSidTuneInfo(info, i, n_tracks, h);
621

622 623 624 625
		const SignedSongTime duration = get_song_length(tune);
		if (!duration.IsNegative())
			h.OnDuration(SongTime(duration));

626 627
		/* Construct container/tune path names, eg.
		   Delta.sid/tune_001.sid */
628 629
		tail = list.emplace_after(tail,
					  StringFormat<32>(SUBTUNE_PREFIX "%03u.sid", i),
630
					  tag_builder.Commit());
631
	}
Mike Dawson's avatar
Mike Dawson committed
632

633
	return list;
Mike Dawson's avatar
Mike Dawson committed
634 635
}

636 637
static const char *const sidplay_suffixes[] = {
	"sid",
638 639 640 641
	"mus",
	"str",
	"prg",
	"P00",
642
	nullptr
643 644
};

645 646 647 648 649
constexpr DecoderPlugin sidplay_decoder_plugin =
	DecoderPlugin("sidplay", sidplay_file_decode, sidplay_scan_file)
	.WithInit(sidplay_init, sidplay_finish)
	.WithContainer(sidplay_container_scan)
	.WithSuffixes(sidplay_suffixes);