mpd/src/decoder/plugins/SidplayDecoderPlugin.cxx

655 lines
15 KiB
C++
Raw Normal View History

/*
2020-01-18 19:22:19 +01:00
* Copyright 2003-2020 The Music Player Daemon Project
* 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.
*
* 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.
*/
2013-10-20 13:05:29 +02:00
#include "SidplayDecoderPlugin.hxx"
#include "decoder/Features.h"
2013-07-28 13:18:48 +02:00
#include "../DecoderAPI.hxx"
2017-02-08 08:26:58 +01:00
#include "tag/Handler.hxx"
#include "tag/Builder.hxx"
#include "song/DetachedSong.hxx"
#include "fs/Path.hxx"
#include "fs/AllocatedPath.hxx"
#include "lib/icu/Converter.hxx"
#ifdef HAVE_SIDPLAYFP
#include "fs/io/FileReader.hxx"
#include "util/RuntimeError.hxx"
#endif
2018-01-24 12:52:43 +01:00
#include "util/StringFormat.hxx"
#include "util/StringView.hxx"
#include "util/Domain.hxx"
#include "util/AllocatedString.hxx"
#include "util/CharUtil.hxx"
2019-03-08 10:21:10 +01:00
#include "util/ByteOrder.hxx"
#include "util/RuntimeError.hxx"
#include "Log.hxx"
#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
#include <sidplay/sidplay2.h>
#include <sidplay/builders/resid.h>
#include <sidplay/utils/SidTuneMod.h>
#include <sidplay/utils/SidDatabase.h>
#endif
#include <iterator>
#include <memory>
#include <string.h>
2009-08-30 19:48:56 +02:00
#define SUBTUNE_PREFIX "tune_"
static constexpr Domain sidplay_domain("sidplay");
struct SidplayGlobal {
std::unique_ptr<SidDatabase> songlength_database;
2009-08-30 19:48:56 +02:00
bool all_files_are_containers;
unsigned default_songlength;
std::string default_genre;
2009-08-30 19:48:56 +02:00
bool filter_setting;
#ifdef HAVE_SIDPLAYFP
std::unique_ptr<uint8_t[]> kernal, basic;
#endif
explicit SidplayGlobal(const ConfigBlock &block);
};
static SidplayGlobal *sidplay_global;
#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
/**
* Throws on error.
*/
static std::unique_ptr<SidDatabase>
sidplay_load_songlength_db(const Path path)
{
auto db = std::make_unique<SidDatabase>();
#ifdef HAVE_SIDPLAYFP
bool error = !db->open(path.c_str());
#else
bool error = db->open(path.c_str()) < 0;
#endif
if (error)
throw FormatRuntimeError("unable to read songlengths file %s: %s",
path.c_str(), db->error());
return db;
}
inline
SidplayGlobal::SidplayGlobal(const ConfigBlock &block)
2009-08-30 19:48:56 +02:00
{
/* read the songlengths database file */
const auto database_path = block.GetPath("songlength_database");
if (!database_path.IsNull())
songlength_database = sidplay_load_songlength_db(database_path);
default_songlength = block.GetPositiveValue("default_songlength", 0U);
default_genre = block.GetBlockValue("default_genre", "");
all_files_are_containers =
block.GetBlockValue("all_files_are_containers", true);
2009-08-30 19:48:56 +02:00
filter_setting = block.GetBlockValue("filter", true);
#ifdef HAVE_SIDPLAYFP
/* read kernal rom dump file */
const auto kernal_path = block.GetPath("kernal");
if (!kernal_path.IsNull())
{
kernal.reset(new uint8_t[rom_size]);
loadRom(kernal_path, kernal.get());
}
/* read basic rom dump file */
const auto basic_path = block.GetPath("basic");
if (!basic_path.IsNull())
{
basic.reset(new uint8_t[rom_size]);
loadRom(basic_path, basic.get());
}
#endif
}
static bool
sidplay_init(const ConfigBlock &block)
{
sidplay_global = new SidplayGlobal(block);
2009-08-30 19:48:56 +02:00
return true;
}
static void
sidplay_finish() noexcept
2009-08-30 19:48:56 +02:00
{
delete sidplay_global;
2009-08-30 19:48:56 +02:00
}
struct SidplayContainerPath {
AllocatedPath path;
unsigned track;
};
gcc_pure
static unsigned
ParseSubtuneName(const char *base) noexcept
2009-08-30 19:48:56 +02:00
{
if (memcmp(base, SUBTUNE_PREFIX, sizeof(SUBTUNE_PREFIX) - 1) != 0)
return 0;
2009-08-30 19:48:56 +02:00
base += sizeof(SUBTUNE_PREFIX) - 1;
2009-08-30 19:48:56 +02:00
char *endptr;
auto track = strtoul(base, &endptr, 10);
if (endptr == base || *endptr != '.')
return 0;
2009-08-30 19:48:56 +02:00
return track;
2009-08-30 19:48:56 +02:00
}
/**
* returns the file path stripped of any /tune_xxx.* subtune suffix
* and the track number (or 1 if no "tune_xxx" suffix is present).
2009-08-30 19:48:56 +02:00
*/
static SidplayContainerPath
2019-08-10 12:12:52 +02:00
ParseContainerPath(Path path_fs) noexcept
2009-08-30 19:48:56 +02:00
{
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 };
2009-08-30 19:48:56 +02:00
}
/**
* This is a template, because libsidplay requires SidTuneMod while
* libsidplayfp requires just a plain Sidtune.
*/
template<typename T>
static SignedSongTime
2019-08-10 12:12:52 +02:00
get_song_length(T &tune) noexcept
{
2016-07-29 20:23:45 +02:00
assert(tune.getStatus());
if (sidplay_global->songlength_database == nullptr)
return SignedSongTime::Negative();
#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);
return SignedSongTime::Negative();
#if LIBSIDPLAYFP_VERSION_MAJ >= 2
}
return SignedSongTime::FromMS(lengthms);
#endif
}
static void
sidplay_file_decode(DecoderClient &client, Path path_fs)
{
int channels;
/* load the tune */
const auto container = ParseContainerPath(path_fs);
#ifdef HAVE_SIDPLAYFP
SidTune tune(container.path.c_str());
#else
SidTuneMod tune(container.path.c_str());
#endif
if (!tune.getStatus()) {
#ifdef HAVE_SIDPLAYFP
const char *error = tune.statusString();
#else
const char *error = tune.getInfo().statusString;
#endif
FormatWarning(sidplay_domain, "failed to load file: %s",
error);
return;
}
const int song_num = container.track;
2009-08-30 19:48:56 +02:00
tune.selectSong(song_num);
auto duration = get_song_length(tune);
if (duration.IsNegative() && sidplay_global->default_songlength > 0)
duration = SongTime::FromS(sidplay_global->default_songlength);
2009-08-30 19:49:16 +02:00
/* initialize the player */
#ifdef HAVE_SIDPLAYFP
sidplayfp player;
player.setRoms(sidplay_global->kernal.get(),
sidplay_global->basic.get(),
nullptr);
#else
sidplay2 player;
#endif
#ifdef HAVE_SIDPLAYFP
bool error = !player.load(&tune);
#else
bool error = player.load(&tune) < 0;
#endif
if (error) {
FormatWarning(sidplay_domain,
"sidplay2.load() failed: %s", player.error());
return;
}
/* initialize the builder */
#ifdef HAVE_SIDPLAYFP
ReSIDfpBuilder builder("ReSID");
if (!builder.getStatus()) {
FormatWarning(sidplay_domain,
"failed to initialize ReSIDfpBuilder: %s",
builder.error());
return;
}
builder.create(player.info().maxsids());
if (!builder.getStatus()) {
FormatWarning(sidplay_domain,
"ReSIDfpBuilder.create() failed: %s",
builder.error());
return;
}
#else
ReSIDBuilder builder("ReSID");
builder.create(player.info().maxsids);
if (!builder) {
FormatWarning(sidplay_domain, "ReSIDBuilder.create() failed: %s",
builder.error());
return;
}
#endif
builder.filter(sidplay_global->filter_setting);
#ifdef HAVE_SIDPLAYFP
if (!builder.getStatus()) {
FormatWarning(sidplay_domain,
"ReSIDfpBuilder.filter() failed: %s",
builder.error());
return;
}
#else
if (!builder) {
FormatWarning(sidplay_domain, "ReSIDBuilder.filter() failed: %s",
builder.error());
return;
}
#endif
/* configure the player */
auto config = player.config();
#ifndef HAVE_SIDPLAYFP
config.clockDefault = SID2_CLOCK_PAL;
config.clockForced = true;
config.clockSpeed = SID2_CLOCK_CORRECT;
#endif
config.frequency = 48000;
#ifndef HAVE_SIDPLAYFP
config.optimisation = SID2_DEFAULT_OPTIMISATION;
config.precision = 16;
config.sidDefault = SID2_MOS6581;
#endif
config.sidEmulation = &builder;
#ifdef HAVE_SIDPLAYFP
config.samplingMethod = SidConfig::INTERPOLATE;
config.fastSampling = false;
#else
config.sidModel = SID2_MODEL_CORRECT;
config.sidSamples = true;
config.sampleFormat = IsLittleEndian()
? SID2_LITTLE_SIGNED
: SID2_BIG_SIGNED;
#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
config.playback = sid2_stereo;
#endif
channels = 2;
} else {
#ifdef HAVE_SIDPLAYFP
config.playback = SidConfig::MONO;
#else
config.playback = sid2_mono;
#endif
channels = 1;
}
#ifdef HAVE_SIDPLAYFP
error = !player.config(config);
#else
error = player.config(config) < 0;
#endif
if (error) {
FormatWarning(sidplay_domain,
"sidplay2.config() failed: %s", player.error());
return;
}
/* initialize the MPD decoder */
2013-08-03 21:00:50 +02:00
const AudioFormat audio_format(48000, SampleFormat::S16, channels);
assert(audio_format.IsValid());
client.Ready(audio_format, true, duration);
/* .. and play */
#ifdef HAVE_SIDPLAYFP
constexpr unsigned timebase = 1;
#else
const unsigned timebase = player.timebase();
#endif
const unsigned end = duration.IsNegative()
? 0U
: duration.ToScale<uint64_t>(timebase);
DecoderCommand cmd;
do {
short buffer[4096];
const auto result = player.play(buffer, std::size(buffer));
if (result <= 0)
break;
#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
client.SubmitTimestamp(FloatDuration(player.time()) / timebase);
cmd = client.SubmitData(nullptr, buffer, nbytes, 0);
2009-08-30 19:49:16 +02:00
if (cmd == DecoderCommand::SEEK) {
unsigned data_time = player.time();
unsigned target_time =
client.GetSeekTime().ToScale(timebase);
2009-08-30 19:49:16 +02:00
/* 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 */
2016-10-27 20:25:12 +02:00
while (data_time < target_time &&
player.play(buffer, std::size(buffer)) > 0)
data_time = player.time();
2009-08-30 19:49:16 +02:00
client.CommandFinished();
2009-08-30 19:49:16 +02:00
}
if (end > 0 && player.time() >= end)
2009-08-30 19:49:16 +02:00
break;
} while (cmd != DecoderCommand::STOP);
}
static AllocatedString<char>
Windows1252ToUTF8(const char *s) noexcept
{
#ifdef HAVE_ICU_CONVERTER
try {
return IcuConverter::Create("windows-1252")->ToUTF8(s);
} 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;
}
2016-07-29 17:36:32 +02:00
gcc_pure
static AllocatedString<char>
GetInfoString(const SidTuneInfo &info, unsigned i) noexcept
2016-07-29 17:36:32 +02:00
{
#ifdef HAVE_SIDPLAYFP
const char *s = info.numberOfInfoStrings() > i
? info.infoString(i)
: "";
#else
const char *s = info.numberOfInfoStrings > i
2016-07-29 17:36:32 +02:00
? info.infoString[i]
: "";
#endif
return Windows1252ToUTF8(s);
2016-07-29 17:36:32 +02:00
}
decoder/sidplay: Fix date field to have year but not company or author Field 2 is called <released>, formerly used as <copyright>[1][2]. 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". This change splits the <released> field at the first <space>, to retain the <year> part. The 51823 SID files in High Voltage SID Collection (HVSC) version 71 have the following distribution of dates: 333 19?? 11 1990-92 6 1995-99 2 2006-08 827 198? 88 1990-93 2140 1996 530 2007 32 1982 69 1990-94 9 1996-97 15 2007-08 1 1982-83 49 1990-95 2 1996-98 2 2007-09 255 1983 3467 1991 5 1996-99 1 2007-10 677 1984 75 1991-92 1840 1997 430 2008 775 1985 65 1991-93 4 1997-98 23 2008-09 3 1985-86 10 1991-94 1276 1998 1 2008-12 10 1985-87 35 1991-97 4 1998-99 631 2009 943 1986 3320 1992 865 1999 1 2009-10 12 1986-87 26 1992-93 24 200? 645 2010 5 1986-89 59 1992-94 590 2000 1 2010-12 2083 1987 1 1992-96 4 2000-01 538 2011 31 1987-88 2996 1993 727 2001 1 2011-12 44 1987-89 42 1993-94 875 2002 651 2012 2510 1988 12 1993-95 2 2002-04 811 2013 129 1988-89 2 1993-97 844 2003 790 2014 91 1988-90 2737 1994 3 2003-05 740 2015 58 1988-91 16 1994-95 842 2004 792 2016 3466 1989 20 1994-96 2 2004-05 775 2017 95 1989-90 17 1994-97 707 2005 638 2018 150 1989-91 2271 1995 1 2005-06 284 2019 1077 199? 2 1995-96 2 2005-07 2834 1990 4 1995-97 785 2006 119 1990-91 2 1995-98 6 2006-07 References: [1] https://www.hvsc.c64.org/download/C64Music/DOCUMENTS/SID_file_format.txt [2] https://hvsc.c64.org/info
2019-08-05 10:50:47 +02:00
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;
2016-07-29 17:36:32 +02:00
}
static void
ScanSidTuneInfo(const SidTuneInfo &info, unsigned track, unsigned n_tracks,
TagHandler &handler) noexcept
{
/* album */
const auto album = GetInfoString(info, 0);
handler.OnTag(TAG_ALBUM, album.c_str());
2009-08-30 19:48:56 +02:00
if (n_tracks > 1) {
2018-01-24 12:52:43 +01:00
const auto tag_title =
StringFormat<1024>("%s (%u/%u)",
album.c_str(), track, n_tracks);
handler.OnTag(TAG_TITLE, tag_title.c_str());
2009-08-30 19:48:56 +02:00
} else
handler.OnTag(TAG_TITLE, album.c_str());
2009-08-30 19:48:56 +02:00
/* artist */
const auto artist = GetInfoString(info, 1);
if (!artist.empty())
handler.OnTag(TAG_ARTIST, artist.c_str());
/* genre */
if (!sidplay_global->default_genre.empty())
handler.OnTag(TAG_GENRE,
sidplay_global->default_genre.c_str());
2016-07-29 17:47:08 +02:00
/* date */
decoder/sidplay: Fix date field to have year but not company or author Field 2 is called <released>, formerly used as <copyright>[1][2]. 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". This change splits the <released> field at the first <space>, to retain the <year> part. The 51823 SID files in High Voltage SID Collection (HVSC) version 71 have the following distribution of dates: 333 19?? 11 1990-92 6 1995-99 2 2006-08 827 198? 88 1990-93 2140 1996 530 2007 32 1982 69 1990-94 9 1996-97 15 2007-08 1 1982-83 49 1990-95 2 1996-98 2 2007-09 255 1983 3467 1991 5 1996-99 1 2007-10 677 1984 75 1991-92 1840 1997 430 2008 775 1985 65 1991-93 4 1997-98 23 2008-09 3 1985-86 10 1991-94 1276 1998 1 2008-12 10 1985-87 35 1991-97 4 1998-99 631 2009 943 1986 3320 1992 865 1999 1 2009-10 12 1986-87 26 1992-93 24 200? 645 2010 5 1986-89 59 1992-94 590 2000 1 2010-12 2083 1987 1 1992-96 4 2000-01 538 2011 31 1987-88 2996 1993 727 2001 1 2011-12 44 1987-89 42 1993-94 875 2002 651 2012 2510 1988 12 1993-95 2 2002-04 811 2013 129 1988-89 2 1993-97 844 2003 790 2014 91 1988-90 2737 1994 3 2003-05 740 2015 58 1988-91 16 1994-95 842 2004 792 2016 3466 1989 20 1994-96 2 2004-05 775 2017 95 1989-90 17 1994-97 707 2005 638 2018 150 1989-91 2271 1995 1 2005-06 284 2019 1077 199? 2 1995-96 2 2005-07 2834 1990 4 1995-97 785 2006 119 1990-91 2 1995-98 6 2006-07 References: [1] https://www.hvsc.c64.org/download/C64Music/DOCUMENTS/SID_file_format.txt [2] https://hvsc.c64.org/info
2019-08-05 10:50:47 +02:00
const auto date = GetDateString(info);
if (!date.empty())
handler.OnTag(TAG_DATE, date.c_str());
2009-08-30 19:48:56 +02:00
/* track */
handler.OnTag(TAG_TRACK, StringFormat<16>("%u", track).c_str());
}
static bool
sidplay_scan_file(Path path_fs, TagHandler &handler) noexcept
{
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
ScanSidTuneInfo(info, song_num, n_tracks, handler);
2009-08-30 19:48:56 +02:00
/* time */
const auto duration = get_song_length(tune);
if (!duration.IsNegative())
handler.OnDuration(SongTime(duration));
return true;
}
static std::forward_list<DetachedSong>
sidplay_container_scan(Path path_fs)
2009-08-30 19:48:56 +02:00
{
std::forward_list<DetachedSong> list;
#ifdef HAVE_SIDPLAYFP
SidTune tune(path_fs.c_str());
#else
SidTuneMod tune(path_fs.c_str());
#endif
if (!tune.getStatus())
return list;
2009-08-30 19:48:56 +02:00
#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
2009-08-30 19:48:56 +02:00
/* Don't treat sids containing a single tune
as containers */
if (!sidplay_global->all_files_are_containers && n_tracks < 2)
return list;
TagBuilder tag_builder;
auto tail = list.before_begin();
for (unsigned i = 1; i <= n_tracks; ++i) {
tune.selectSong(i);
AddTagHandler h(tag_builder);
ScanSidTuneInfo(info, i, n_tracks, h);
const SignedSongTime duration = get_song_length(tune);
if (!duration.IsNegative())
h.OnDuration(SongTime(duration));
/* Construct container/tune path names, eg.
Delta.sid/tune_001.sid */
2019-08-10 12:31:31 +02:00
tail = list.emplace_after(tail,
StringFormat<32>(SUBTUNE_PREFIX "%03u.sid", i),
tag_builder.Commit());
}
2009-08-30 19:48:56 +02:00
return list;
2009-08-30 19:48:56 +02:00
}
static const char *const sidplay_suffixes[] = {
"sid",
"mus",
"str",
"prg",
"P00",
2013-10-19 18:19:03 +02:00
nullptr
};
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);