GmeDecoderPlugin.cxx 8.56 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 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 "pcm/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 "fs/NarrowPath.hxx"
31
#include "util/ScopeExit.hxx"
32
#include "util/StringCompare.hxx"
33
#include "util/StringFormat.hxx"
34
#include "util/StringView.hxx"
35 36
#include "util/Domain.hxx"
#include "Log.hxx"
37

38 39
#include <gme/gme.h>

40 41
#include <cassert>

42
#include <stdlib.h>
43

44 45
#define SUBTUNE_PREFIX "tune_"

46 47
static constexpr Domain gme_domain("gme");

48 49 50 51 52
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;
53

54
struct GmeContainerPath {
55
	AllocatedPath path;
56 57 58
	unsigned track;
};

59 60 61
#if GME_VERSION >= 0x000600
static int gme_accuracy;
#endif
62
static unsigned gme_default_fade;
63 64

static bool
Rosen Penev's avatar
Rosen Penev committed
65
gme_plugin_init([[maybe_unused]] const ConfigBlock &block)
66 67 68 69 70 71 72
{
#if GME_VERSION >= 0x000600
	auto accuracy = block.GetBlockParam("accuracy");
	gme_accuracy = accuracy != nullptr
		? (int)accuracy->GetBoolValue()
		: -1;
#endif
73 74 75 76
	auto fade = block.GetBlockParam("default_fade");
	gme_default_fade = fade != nullptr
		? fade->GetUnsignedValue() * 1000
		: 8000;
77 78 79 80

	return true;
}

81 82
gcc_pure
static unsigned
83
ParseSubtuneName(const char *base) noexcept
84
{
85 86
	base = StringAfterPrefix(base, SUBTUNE_PREFIX);
	if (base == nullptr)
87 88 89 90 91 92 93 94 95 96
		return 0;

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

	return track;
}

97
/**
98 99
 * returns the file path stripped of any /tune_xxx.* subtune suffix
 * and the track number (or 0 if no "tune_xxx" suffix is present).
100
 */
101 102
static GmeContainerPath
ParseContainerPath(Path path_fs)
103
{
104 105 106
	const Path base = path_fs.GetBase();
	unsigned track;
	if (base.IsNull() ||
107
	    (track = ParseSubtuneName(NarrowPath(base))) < 1)
108
		return { AllocatedPath(path_fs), 0 };
109

110
	return { path_fs.GetDirectoryName(), track - 1 };
111 112
}

113 114
static AllocatedPath
ReplaceSuffix(Path src,
Max Kellermann's avatar
Max Kellermann committed
115
	      const PathTraitsFS::const_pointer new_suffix) noexcept
116 117 118 119 120 121 122 123 124 125
{
	const auto *old_suffix = src.GetSuffix();
	if (old_suffix == nullptr)
		return nullptr;

	PathTraitsFS::string s(src.c_str(), old_suffix);
	s += new_suffix;
	return AllocatedPath::FromFS(std::move(s));
}

126
static Music_Emu*
127
LoadGmeAndM3u(const GmeContainerPath& container) {
128

129 130
	Music_Emu *emu;
	const char *gme_err =
131
		gme_open_file(NarrowPath(container.path), &emu, GME_SAMPLE_RATE);
132
	if (gme_err != nullptr) {
133
		LogWarning(gme_domain, gme_err);
134 135 136
		return nullptr;
	}

137 138
	const auto m3u_path = ReplaceSuffix(container.path,
					    PATH_LITERAL("m3u"));
139 140 141 142 143
    /*
     * Some GME formats lose metadata if you attempt to
     * load a non-existant M3U file, so check that one
     * exists before loading.
     */
144
	if (!m3u_path.IsNull() && FileExists(m3u_path))
145
		gme_load_m3u(emu, NarrowPath(m3u_path));
146

147 148 149 150 151 152 153 154 155 156 157
	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) {
158 159
		return;
	}
160

161 162
	AtScopeExit(emu) { gme_delete(emu); };

163 164 165
	FormatDebug(gme_domain, "emulator type '%s'\n",
		    gme_type_system(gme_type(emu)));

166 167 168 169 170
#if GME_VERSION >= 0x000600
	if (gme_accuracy >= 0)
		gme_enable_accuracy(emu, gme_accuracy);
#endif

171
	gme_info_t *ti;
172
	const char *gme_err = gme_track_info(emu, &ti, container.track);
173
	if (gme_err != nullptr) {
174
		LogWarning(gme_domain, gme_err);
175 176 177
		return;
	}

178
	const int length = ti->play_length;
179 180 181 182 183
#if GME_VERSION >= 0x000700
	const int fade   = ti->fade_length;
#else
	const int fade   = -1;
#endif
184 185 186
	gme_free_info(ti);

	const SignedSongTime song_len = length > 0
187 188
		? SignedSongTime::FromMS(length +
			(fade == -1 ? gme_default_fade : fade))
189
		: SignedSongTime::Negative();
190 191 192

	/* initialize the MPD decoder */

193 194 195
	const auto audio_format = CheckAudioFormat(GME_SAMPLE_RATE,
						   SampleFormat::S16,
						   GME_CHANNELS);
196

197
	client.Ready(audio_format, true, song_len);
198

199
	gme_err = gme_start_track(emu, container.track);
200
	if (gme_err != nullptr)
201
		LogWarning(gme_domain, gme_err);
202

203
	if (length > 0 && fade != 0)
204 205
		gme_set_fade(emu, length
#if GME_VERSION >= 0x000700
206
			     , fade == -1 ? gme_default_fade : fade
207 208
#endif
			     );
209

210
	/* play */
211
	DecoderCommand cmd;
212
	do {
213
		short buf[GME_BUFFER_SAMPLES];
214
		gme_err = gme_play(emu, GME_BUFFER_SAMPLES, buf);
215
		if (gme_err != nullptr) {
216
			LogWarning(gme_domain, gme_err);
217 218 219
			return;
		}

220
		cmd = client.SubmitData(nullptr, buf, sizeof(buf), 0);
221
		if (cmd == DecoderCommand::SEEK) {
222
			unsigned where = client.GetSeekTime().ToMS();
223
			gme_err = gme_seek(emu, where);
224
			if (gme_err != nullptr) {
225
				LogWarning(gme_domain, gme_err);
226
				client.SeekError();
227
			} else
228
				client.CommandFinished();
229 230
		}

231
		if (gme_track_ended(emu))
232
			break;
233
	} while (cmd != DecoderCommand::STOP);
234 235
}

236
static void
237
ScanGmeInfo(const gme_info_t &info, unsigned song_num, int track_count,
238
	    TagHandler &handler) noexcept
239
{
Max Kellermann's avatar
Max Kellermann committed
240
	if (info.play_length > 0)
241 242 243 244 245
		handler.OnDuration(SongTime::FromMS(info.play_length
#if GME_VERSION >= 0x000700
			+ (info.fade_length == -1 ? gme_default_fade : info.fade_length)
#endif
			));
246

247
	if (track_count > 1)
248
		handler.OnTag(TAG_TRACK, StringFormat<16>("%u", song_num + 1).c_str());
249

250
	if (!StringIsEmpty(info.song)) {
251 252
		if (track_count > 1) {
			/* start numbering subtunes from 1 */
253 254 255 256
			const auto tag_title =
				StringFormat<1024>("%s (%u/%d)",
						   info.song, song_num + 1,
						   track_count);
257
			handler.OnTag(TAG_TITLE, tag_title.c_str());
258
		} else
259
			handler.OnTag(TAG_TITLE, info.song);
260 261
	}

262
	if (!StringIsEmpty(info.author))
263
		handler.OnTag(TAG_ARTIST, info.author);
264

265
	if (!StringIsEmpty(info.game))
266
		handler.OnTag(TAG_ALBUM, info.game);
267

268
	if (!StringIsEmpty(info.comment))
269
		handler.OnTag(TAG_COMMENT, info.comment);
270

271
	if (!StringIsEmpty(info.copyright))
272
		handler.OnTag(TAG_DATE, info.copyright);
273 274
}

275
static bool
276
ScanMusicEmu(Music_Emu *emu, unsigned song_num, TagHandler &handler) noexcept
277 278 279 280 281 282 283 284 285 286
{
	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);

287 288
	AtScopeExit(ti) { gme_free_info(ti); };

289
	ScanGmeInfo(*ti, song_num, gme_track_count(emu), handler);
290 291 292
	return true;
}

293
static bool
294
gme_scan_file(Path path_fs, TagHandler &handler) noexcept
295
{
296
	const auto container = ParseContainerPath(path_fs);
297

298 299
	Music_Emu *emu = LoadGmeAndM3u(container);
	if(emu == nullptr) {
300
		return false;
301
	}
302

303
	AtScopeExit(emu) { gme_delete(emu); };
304

305
	return ScanMusicEmu(emu, container.track, handler);
306 307
}

308
static std::forward_list<DetachedSong>
309 310
gme_container_scan(Path path_fs)
{
311
	std::forward_list<DetachedSong> list;
312
	const auto container = ParseContainerPath(path_fs);
313

314 315
	Music_Emu *emu = LoadGmeAndM3u(container);
	if(emu == nullptr) {
316 317 318
		return list;
	}

319 320
	AtScopeExit(emu) { gme_delete(emu); };

321 322 323 324 325
	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;

326
	const auto *subtune_suffix = path_fs.GetSuffix();
327

328 329
	TagBuilder tag_builder;

330
	auto tail = list.before_begin();
331
	for (unsigned i = 0; i < num_songs; ++i) {
332 333
		AddTagHandler h(tag_builder);
		ScanMusicEmu(emu, i, h);
334

335 336 337
		const auto track_name =
			StringFormat<64>(SUBTUNE_PREFIX "%03u.%s", i+1,
					 subtune_suffix);
338 339
		tail = list.emplace_after(tail, track_name,
					  tag_builder.Commit());
340 341 342 343 344
	}

	return list;
}

345 346 347
static const char *const gme_suffixes[] = {
	"ay", "gbs", "gym", "hes", "kss", "nsf",
	"nsfe", "sap", "spc", "vgm", "vgz",
348
	nullptr
349 350
};

351 352 353 354 355
constexpr DecoderPlugin gme_decoder_plugin =
	DecoderPlugin("gme", gme_file_decode, gme_scan_file)
	.WithInit(gme_plugin_init)
	.WithContainer(gme_container_scan)
	.WithSuffixes(gme_suffixes);