SidplayDecoderPlugin.cxx 15.2 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2021 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 "SidplayDecoderPlugin.hxx"
21
#include "decoder/Features.h"
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>

Mike Dawson's avatar
Mike Dawson committed
63 64
#define SUBTUNE_PREFIX "tune_"

65 66
static constexpr Domain sidplay_domain("sidplay");

67
struct SidplayGlobal {
68
	std::unique_ptr<SidDatabase> songlength_database;
Mike Dawson's avatar
Mike Dawson committed
69

70 71 72
	bool all_files_are_containers;
	unsigned default_songlength;
	std::string default_genre;
Mike Dawson's avatar
Mike Dawson committed
73

74 75 76
	bool filter_setting;

#ifdef HAVE_SIDPLAYFP
77
	std::unique_ptr<uint8_t[]> kernal, basic;
78 79 80 81 82 83
#endif

	explicit SidplayGlobal(const ConfigBlock &block);
};

static SidplayGlobal *sidplay_global;
84

85 86 87 88 89 90 91 92 93 94 95 96 97 98
#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

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

	return db;
}

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

126
	default_songlength = block.GetPositiveValue("default_songlength", 0U);
127

128 129
	default_genre = block.GetBlockValue("default_genre", "");

130
	all_files_are_containers =
131
		block.GetBlockValue("all_files_are_containers", true);
Mike Dawson's avatar
Mike Dawson committed
132

133
	filter_setting = block.GetBlockValue("filter", true);
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())
	{
140 141
		kernal.reset(new uint8_t[rom_size]);
		loadRom(kernal_path, kernal.get());
142 143 144 145 146 147
	}

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

154 155 156 157
static bool
sidplay_init(const ConfigBlock &block)
{
	sidplay_global = new SidplayGlobal(block);
Mike Dawson's avatar
Mike Dawson committed
158 159 160
	return true;
}

161
static void
162
sidplay_finish() noexcept
Mike Dawson's avatar
Mike Dawson committed
163
{
164
	delete sidplay_global;
Mike Dawson's avatar
Mike Dawson committed
165 166
}

167 168 169 170 171 172 173
struct SidplayContainerPath {
	AllocatedPath path;
	unsigned track;
};

gcc_pure
static unsigned
174
ParseSubtuneName(const char *base) noexcept
Mike Dawson's avatar
Mike Dawson committed
175
{
176 177
	if (memcmp(base, SUBTUNE_PREFIX, sizeof(SUBTUNE_PREFIX) - 1) != 0)
		return 0;
Mike Dawson's avatar
Mike Dawson committed
178

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

181 182 183 184
	char *endptr;
	auto track = strtoul(base, &endptr, 10);
	if (endptr == base || *endptr != '.')
		return 0;
Mike Dawson's avatar
Mike Dawson committed
185

186
	return track;
Mike Dawson's avatar
Mike Dawson committed
187 188 189
}

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

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

215
	if (sidplay_global->songlength_database == nullptr)
216 217
		return SignedSongTime::Negative();

218 219 220 221 222 223 224 225 226 227 228 229
#if LIBSIDPLAYFP_VERSION_MAJ >= 2
	const auto lengthms =
		sidplay_global->songlength_database->lengthMs(tune);
	/* check for new song length format since HVSC#68 or later */
	if (lengthms < 0)
	{
#endif
		/* old song lenghth format */
		const auto length =
			sidplay_global->songlength_database->length(tune);
		if (length >= 0)
			return SignedSongTime::FromS(length);
230 231
		return SignedSongTime::Negative();

232 233 234 235
#if LIBSIDPLAYFP_VERSION_MAJ >= 2
	}
	return SignedSongTime::FromMS(lengthms);
#endif
236 237
}

238
static void
239
sidplay_file_decode(DecoderClient &client, Path path_fs)
240
{
241
	int channels;
242 243 244

	/* load the tune */

245
	const auto container = ParseContainerPath(path_fs);
246 247 248
#ifdef HAVE_SIDPLAYFP
	SidTune tune(container.path.c_str());
#else
249
	SidTuneMod tune(container.path.c_str());
250
#endif
251
	if (!tune.getStatus()) {
252 253 254 255 256
#ifdef HAVE_SIDPLAYFP
		const char *error = tune.statusString();
#else
		const char *error = tune.getInfo().statusString;
#endif
257
		FormatWarning(sidplay_domain, "failed to load file: %s",
258
			      error);
259 260 261
		return;
	}

262
	const int song_num = container.track;
Mike Dawson's avatar
Mike Dawson committed
263
	tune.selectSong(song_num);
264

265
	auto duration = get_song_length(tune);
266 267
	if (duration.IsNegative() && sidplay_global->default_songlength > 0)
		duration = SongTime::FromS(sidplay_global->default_songlength);
268

269 270
	/* initialize the player */

271 272
#ifdef HAVE_SIDPLAYFP
	sidplayfp player;
273

274 275 276
	player.setRoms(sidplay_global->kernal.get(),
		       sidplay_global->basic.get(),
		       nullptr);
277
#else
278
	sidplay2 player;
279 280 281 282 283 284 285
#endif
#ifdef HAVE_SIDPLAYFP
	bool error = !player.load(&tune);
#else
	bool error = player.load(&tune) < 0;
#endif
	if (error) {
286 287
		FormatWarning(sidplay_domain,
			      "sidplay2.load() failed: %s", player.error());
288 289 290 291 292
		return;
	}

	/* initialize the builder */

293 294 295 296 297 298
#ifdef HAVE_SIDPLAYFP
	ReSIDfpBuilder builder("ReSID");
	if (!builder.getStatus()) {
		FormatWarning(sidplay_domain,
			      "failed to initialize ReSIDfpBuilder: %s",
			      builder.error());
299 300 301
		return;
	}

302 303 304 305 306 307 308 309
	builder.create(player.info().maxsids());
	if (!builder.getStatus()) {
		FormatWarning(sidplay_domain,
			      "ReSIDfpBuilder.create() failed: %s",
			      builder.error());
		return;
	}
#else
310 311 312
	ReSIDBuilder builder("ReSID");
	builder.create(player.info().maxsids);
	if (!builder) {
313 314
		FormatWarning(sidplay_domain, "ReSIDBuilder.create() failed: %s",
			      builder.error());
315 316
		return;
	}
317
#endif
318

319
	builder.filter(sidplay_global->filter_setting);
320 321 322 323 324 325 326 327
#ifdef HAVE_SIDPLAYFP
	if (!builder.getStatus()) {
		FormatWarning(sidplay_domain,
			      "ReSIDfpBuilder.filter() failed: %s",
			      builder.error());
		return;
	}
#else
328
	if (!builder) {
329 330
		FormatWarning(sidplay_domain, "ReSIDBuilder.filter() failed: %s",
			      builder.error());
331 332
		return;
	}
333
#endif
334 335 336

	/* configure the player */

337
	auto config = player.config();
338

339
#ifndef HAVE_SIDPLAYFP
340 341 342
	config.clockDefault = SID2_CLOCK_PAL;
	config.clockForced = true;
	config.clockSpeed = SID2_CLOCK_CORRECT;
343
#endif
344
	config.frequency = 48000;
345
#ifndef HAVE_SIDPLAYFP
346
	config.optimisation = SID2_DEFAULT_OPTIMISATION;
347

348 349
	config.precision = 16;
	config.sidDefault = SID2_MOS6581;
350
#endif
351
	config.sidEmulation = &builder;
352 353 354 355
#ifdef HAVE_SIDPLAYFP
	config.samplingMethod = SidConfig::INTERPOLATE;
	config.fastSampling = false;
#else
356 357
	config.sidModel = SID2_MODEL_CORRECT;
	config.sidSamples = true;
358 359 360
	config.sampleFormat = IsLittleEndian()
		? SID2_LITTLE_SIGNED
		: SID2_BIG_SIGNED;
361 362 363 364 365 366 367 368 369 370 371 372
#endif

#ifdef HAVE_SIDPLAYFP
	const bool stereo = tune.getInfo()->sidChips() >= 2;
#else
	const bool stereo = tune.isStereo();
#endif

	if (stereo) {
#ifdef HAVE_SIDPLAYFP
		config.playback = SidConfig::STEREO;
#else
373
		config.playback = sid2_stereo;
374
#endif
375 376
		channels = 2;
	} else {
377 378 379
#ifdef HAVE_SIDPLAYFP
		config.playback = SidConfig::MONO;
#else
380
		config.playback = sid2_mono;
381
#endif
382 383
		channels = 1;
	}
384

385 386 387 388 389 390
#ifdef HAVE_SIDPLAYFP
	error = !player.config(config);
#else
	error = player.config(config) < 0;
#endif
	if (error) {
391 392
		FormatWarning(sidplay_domain,
			      "sidplay2.config() failed: %s", player.error());
393 394 395 396 397
		return;
	}

	/* initialize the MPD decoder */

398 399
	const AudioFormat audio_format(48000, SampleFormat::S16, channels);
	assert(audio_format.IsValid());
400

401
	client.Ready(audio_format, true, duration);
402 403 404

	/* .. and play */

405 406 407
#ifdef HAVE_SIDPLAYFP
	constexpr unsigned timebase = 1;
#else
408
	const unsigned timebase = player.timebase();
409
#endif
410
	const unsigned end = duration.IsNegative()
411
		? 0U
412
		: duration.ToScale<uint64_t>(timebase);
413

414
	DecoderCommand cmd;
415
	do {
416
		short buffer[4096];
417

418
		const auto result = player.play(buffer, std::size(buffer));
419
		if (result <= 0)
420 421
			break;

422 423 424 425 426 427 428 429
#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

430
		client.SubmitTimestamp(FloatDuration(player.time()) / timebase);
431

432
		cmd = client.SubmitData(nullptr, buffer, nbytes, 0);
433

434
		if (cmd == DecoderCommand::SEEK) {
435
			unsigned data_time = player.time();
436
			unsigned target_time =
437
				client.GetSeekTime().ToScale(timebase);
438 439 440 441 442 443 444 445

			/* 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 */
446
			while (data_time < target_time &&
447
			       player.play(buffer, std::size(buffer)) > 0)
448
				data_time = player.time();
449

450
			client.CommandFinished();
451 452
		}

453
		if (end > 0 && player.time() >= end)
454 455
			break;

456
	} while (cmd != DecoderCommand::STOP);
457 458
}

459 460 461 462 463
static AllocatedString<char>
Windows1252ToUTF8(const char *s) noexcept
{
#ifdef HAVE_ICU_CONVERTER
	try {
464
		return IcuConverter::Create("windows-1252")->ToUTF8(s);
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
	} 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;
}

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

	return Windows1252ToUTF8(s);
496 497
}

498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
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;
520 521
}

522 523
static void
ScanSidTuneInfo(const SidTuneInfo &info, unsigned track, unsigned n_tracks,
524
		TagHandler &handler) noexcept
525
{
526 527 528 529
	/* album */
	const auto album = GetInfoString(info, 0);

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

531
	if (n_tracks > 1) {
532 533
		const auto tag_title =
			StringFormat<1024>("%s (%u/%u)",
534
					   album.c_str(), track, n_tracks);
535
		handler.OnTag(TAG_TITLE, tag_title.c_str());
Mike Dawson's avatar
Mike Dawson committed
536
	} else
537
		handler.OnTag(TAG_TITLE, album.c_str());
Mike Dawson's avatar
Mike Dawson committed
538 539

	/* artist */
540 541 542
	const auto artist = GetInfoString(info, 1);
	if (!artist.empty())
		handler.OnTag(TAG_ARTIST, artist.c_str());
543

544
	/* genre */
545 546 547
	if (!sidplay_global->default_genre.empty())
		handler.OnTag(TAG_GENRE,
			      sidplay_global->default_genre.c_str());
548

549
	/* date */
550
	const auto date = GetDateString(info);
551 552
	if (!date.empty())
		handler.OnTag(TAG_DATE, date.c_str());
553

Mike Dawson's avatar
Mike Dawson committed
554
	/* track */
555
	handler.OnTag(TAG_TRACK, StringFormat<16>("%u", track).c_str());
556 557 558
}

static bool
559
sidplay_scan_file(Path path_fs, TagHandler &handler) noexcept
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
{
	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

582
	ScanSidTuneInfo(info, song_num, n_tracks, handler);
Mike Dawson's avatar
Mike Dawson committed
583

584
	/* time */
585
	const auto duration = get_song_length(tune);
586
	if (!duration.IsNegative())
587
		handler.OnDuration(SongTime(duration));
588

589
	return true;
590 591
}

592
static std::forward_list<DetachedSong>
593
sidplay_container_scan(Path path_fs)
Mike Dawson's avatar
Mike Dawson committed
594
{
595
	std::forward_list<DetachedSong> list;
596

597 598 599 600 601
#ifdef HAVE_SIDPLAYFP
	SidTune tune(path_fs.c_str());
#else
	SidTuneMod tune(path_fs.c_str());
#endif
602
	if (!tune.getStatus())
603
		return list;
Mike Dawson's avatar
Mike Dawson committed
604

605 606 607 608 609 610 611
#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
612 613 614

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

618 619
	TagBuilder tag_builder;

620
	auto tail = list.before_begin();
621
	for (unsigned i = 1; i <= n_tracks; ++i) {
622 623
		tune.selectSong(i);

624 625
		AddTagHandler h(tag_builder);
		ScanSidTuneInfo(info, i, n_tracks, h);
626

627 628 629 630
		const SignedSongTime duration = get_song_length(tune);
		if (!duration.IsNegative())
			h.OnDuration(SongTime(duration));

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

638
	return list;
Mike Dawson's avatar
Mike Dawson committed
639 640
}

641 642
static const char *const sidplay_suffixes[] = {
	"sid",
643 644 645 646
	"mus",
	"str",
	"prg",
	"P00",
647
	nullptr
648 649
};

650 651 652 653 654
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);