GmeDecoderPlugin.cxx 7.75 KB
Newer Older
1
/*
2
 * Copyright 2003-2018 The Music Player Daemon Project
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
 * 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.
 */

#include "GmeDecoderPlugin.hxx"
21
#include "../DecoderAPI.hxx"
22
#include "config/Block.hxx"
23
#include "CheckAudioFormat.hxx"
24
#include "song/DetachedSong.hxx"
25 26
#include "tag/Handler.hxx"
#include "tag/Builder.hxx"
27
#include "fs/Path.hxx"
28
#include "fs/AllocatedPath.hxx"
29
#include "fs/FileSystem.hxx"
30
#include "util/ScopeExit.hxx"
31
#include "util/StringFormat.hxx"
Max Kellermann's avatar
Max Kellermann committed
32
#include "util/UriUtil.hxx"
33 34
#include "util/Domain.hxx"
#include "Log.hxx"
35

36 37
#include <gme/gme.h>

38
#include <assert.h>
39 40
#include <stdlib.h>
#include <string.h>
41

42 43
#define SUBTUNE_PREFIX "tune_"

44 45
static constexpr Domain gme_domain("gme");

46 47 48 49 50
static constexpr unsigned GME_SAMPLE_RATE = 44100;
static constexpr unsigned GME_CHANNELS = 2;
static constexpr unsigned GME_BUFFER_FRAMES = 2048;
static constexpr unsigned GME_BUFFER_SAMPLES =
	GME_BUFFER_FRAMES * GME_CHANNELS;
51

52
struct GmeContainerPath {
53
	AllocatedPath path;
54 55 56
	unsigned track;
};

57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
#if GME_VERSION >= 0x000600
static int gme_accuracy;
#endif

static bool
gme_plugin_init(gcc_unused const ConfigBlock &block)
{
#if GME_VERSION >= 0x000600
	auto accuracy = block.GetBlockParam("accuracy");
	gme_accuracy = accuracy != nullptr
		? (int)accuracy->GetBoolValue()
		: -1;
#endif

	return true;
}

74 75
gcc_pure
static unsigned
76
ParseSubtuneName(const char *base) noexcept
77 78 79 80 81 82 83 84 85 86 87 88 89 90
{
	if (memcmp(base, SUBTUNE_PREFIX, sizeof(SUBTUNE_PREFIX) - 1) != 0)
		return 0;

	base += sizeof(SUBTUNE_PREFIX) - 1;

	char *endptr;
	auto track = strtoul(base, &endptr, 10);
	if (endptr == base || *endptr != '.')
		return 0;

	return track;
}

91
/**
92 93
 * returns the file path stripped of any /tune_xxx.* subtune suffix
 * and the track number (or 0 if no "tune_xxx" suffix is present).
94
 */
95 96
static GmeContainerPath
ParseContainerPath(Path path_fs)
97
{
98 99 100 101 102
	const Path base = path_fs.GetBase();
	unsigned track;
	if (base.IsNull() ||
	    (track = ParseSubtuneName(base.c_str())) < 1)
		return { AllocatedPath(path_fs), 0 };
103

104
	return { path_fs.GetDirectoryName(), track - 1 };
105 106
}

107 108 109 110 111
static Music_Emu*
LoadGmeAndM3u(GmeContainerPath container) {

	const char *path = container.path.c_str();
	const char *suffix = uri_get_suffix(path);
112

113 114
	Music_Emu *emu;
	const char *gme_err =
115
		gme_open_file(path, &emu, GME_SAMPLE_RATE);
116
	if (gme_err != nullptr) {
117
		LogWarning(gme_domain, gme_err);
118 119 120 121 122 123 124 125 126 127
		return nullptr;
	}

	if(suffix == nullptr) {
		return emu;
	}

	std::string m3u_path(path,suffix);
	m3u_path += "m3u";

128 129 130 131 132 133 134 135
    /*
     * Some GME formats lose metadata if you attempt to
     * load a non-existant M3U file, so check that one
     * exists before loading.
     */
	if(FileExists(Path::FromFS(m3u_path.c_str()))) {
		gme_load_m3u(emu,m3u_path.c_str());
	}
136 137 138 139 140 141 142 143 144 145 146
	return emu;
}


static void
gme_file_decode(DecoderClient &client, Path path_fs)
{
	const auto container = ParseContainerPath(path_fs);

	Music_Emu *emu = LoadGmeAndM3u(container);
	if(emu == nullptr) {
147 148
		return;
	}
149

150 151
	AtScopeExit(emu) { gme_delete(emu); };

152 153 154
	FormatDebug(gme_domain, "emulator type '%s'\n",
		    gme_type_system(gme_type(emu)));

155 156 157 158 159
#if GME_VERSION >= 0x000600
	if (gme_accuracy >= 0)
		gme_enable_accuracy(emu, gme_accuracy);
#endif

160
	gme_info_t *ti;
161
	const char *gme_err = gme_track_info(emu, &ti, container.track);
162
	if (gme_err != nullptr) {
163
		LogWarning(gme_domain, gme_err);
164 165 166
		return;
	}

167
	const int length = ti->play_length;
168 169 170 171
	gme_free_info(ti);

	const SignedSongTime song_len = length > 0
		? SignedSongTime::FromMS(length)
172
		: SignedSongTime::Negative();
173 174 175

	/* initialize the MPD decoder */

176 177 178
	const auto audio_format = CheckAudioFormat(GME_SAMPLE_RATE,
						   SampleFormat::S16,
						   GME_CHANNELS);
179

180
	client.Ready(audio_format, true, song_len);
181

182
	gme_err = gme_start_track(emu, container.track);
183
	if (gme_err != nullptr)
184
		LogWarning(gme_domain, gme_err);
185

186 187
	if (length > 0)
		gme_set_fade(emu, length);
188

189
	/* play */
190
	DecoderCommand cmd;
191
	do {
192
		short buf[GME_BUFFER_SAMPLES];
193
		gme_err = gme_play(emu, GME_BUFFER_SAMPLES, buf);
194
		if (gme_err != nullptr) {
195
			LogWarning(gme_domain, gme_err);
196 197 198
			return;
		}

199
		cmd = client.SubmitData(nullptr, buf, sizeof(buf), 0);
200
		if (cmd == DecoderCommand::SEEK) {
201
			unsigned where = client.GetSeekTime().ToMS();
202
			gme_err = gme_seek(emu, where);
203
			if (gme_err != nullptr) {
204
				LogWarning(gme_domain, gme_err);
205
				client.SeekError();
206
			} else
207
				client.CommandFinished();
208 209
		}

210
		if (gme_track_ended(emu))
211
			break;
212
	} while (cmd != DecoderCommand::STOP);
213 214
}

215
static void
216
ScanGmeInfo(const gme_info_t &info, unsigned song_num, int track_count,
217
	    TagHandler &handler) noexcept
218
{
Max Kellermann's avatar
Max Kellermann committed
219
	if (info.play_length > 0)
220
		handler.OnDuration(SongTime::FromMS(info.play_length));
221

222
	if (track_count > 1)
223
		handler.OnTag(TAG_TRACK, StringFormat<16>("%u", song_num + 1));
224

225 226 227
	if (info.song != nullptr) {
		if (track_count > 1) {
			/* start numbering subtunes from 1 */
228 229 230 231
			const auto tag_title =
				StringFormat<1024>("%s (%u/%d)",
						   info.song, song_num + 1,
						   track_count);
232
			handler.OnTag(TAG_TITLE, tag_title);
233
		} else
234
			handler.OnTag(TAG_TITLE, info.song);
235 236 237
	}

	if (info.author != nullptr)
238
		handler.OnTag(TAG_ARTIST, info.author);
239 240

	if (info.game != nullptr)
241
		handler.OnTag(TAG_ALBUM, info.game);
242 243

	if (info.comment != nullptr)
244
		handler.OnTag(TAG_COMMENT, info.comment);
245 246

	if (info.copyright != nullptr)
247
		handler.OnTag(TAG_DATE, info.copyright);
248 249
}

250
static bool
251
ScanMusicEmu(Music_Emu *emu, unsigned song_num, TagHandler &handler) noexcept
252 253 254 255 256 257 258 259 260 261
{
	gme_info_t *ti;
	const char *gme_err = gme_track_info(emu, &ti, song_num);
	if (gme_err != nullptr) {
		LogWarning(gme_domain, gme_err);
		return false;
	}

	assert(ti != nullptr);

262 263
	AtScopeExit(ti) { gme_free_info(ti); };

264
	ScanGmeInfo(*ti, song_num, gme_track_count(emu), handler);
265 266 267
	return true;
}

268
static bool
269
gme_scan_file(Path path_fs, TagHandler &handler) noexcept
270
{
271
	const auto container = ParseContainerPath(path_fs);
272

273 274
	Music_Emu *emu = LoadGmeAndM3u(container);
	if(emu == nullptr) {
275
		return false;
276
	}
277

278
	AtScopeExit(emu) { gme_delete(emu); };
279

280
	return ScanMusicEmu(emu, container.track, handler);
281 282
}

283
static std::forward_list<DetachedSong>
284 285
gme_container_scan(Path path_fs)
{
286
	std::forward_list<DetachedSong> list;
287
	const auto container = ParseContainerPath(path_fs);
288

289 290
	Music_Emu *emu = LoadGmeAndM3u(container);
	if(emu == nullptr) {
291 292 293
		return list;
	}

294 295
	AtScopeExit(emu) { gme_delete(emu); };

296 297 298 299 300 301 302
	const unsigned num_songs = gme_track_count(emu);
	/* if it only contains a single tune, don't treat as container */
	if (num_songs < 2)
		return list;

	const char *subtune_suffix = uri_get_suffix(path_fs.c_str());

303 304
	TagBuilder tag_builder;

305
	auto tail = list.before_begin();
306
	for (unsigned i = 0; i < num_songs; ++i) {
307 308
		AddTagHandler h(tag_builder);
		ScanMusicEmu(emu, i, h);
309

310 311 312
		const auto track_name =
			StringFormat<64>(SUBTUNE_PREFIX "%03u.%s", i+1,
					 subtune_suffix);
313 314
		tail = list.emplace_after(tail, track_name,
					  tag_builder.Commit());
315 316 317 318 319
	}

	return list;
}

320 321 322
static const char *const gme_suffixes[] = {
	"ay", "gbs", "gym", "hes", "kss", "nsf",
	"nsfe", "sap", "spc", "vgm", "vgz",
323
	nullptr
324 325
};

326
const struct DecoderPlugin gme_decoder_plugin = {
327
	"gme",
328
	gme_plugin_init,
329 330 331 332 333 334 335 336
	nullptr,
	nullptr,
	gme_file_decode,
	gme_scan_file,
	nullptr,
	gme_container_scan,
	gme_suffixes,
	nullptr,
337
};