GmeDecoderPlugin.cxx 8.2 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2017 The Music Player Daemon Project
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
 * 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.
 */

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

37 38
#include <gme/gme.h>

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

43 44
#define SUBTUNE_PREFIX "tune_"

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

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

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

58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
#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;
}

75 76
gcc_pure
static unsigned
77
ParseSubtuneName(const char *base) noexcept
78 79 80 81 82 83 84 85 86 87 88 89 90 91
{
	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;
}

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

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

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

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

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

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

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

129 130 131 132 133 134 135 136
    /*
     * 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());
	}
137 138 139 140 141 142 143 144 145 146 147
	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) {
148 149
		return;
	}
150

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

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

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

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

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

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

	/* initialize the MPD decoder */

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

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

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

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

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

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

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

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

224 225 226
	if (track_count > 1)
		tag_handler_invoke_tag(handler, handler_ctx, TAG_TRACK,
				       StringFormat<16>("%u", song_num + 1));
227

228 229 230
	if (info.song != nullptr) {
		if (track_count > 1) {
			/* start numbering subtunes from 1 */
231 232 233 234
			const auto tag_title =
				StringFormat<1024>("%s (%u/%d)",
						   info.song, song_num + 1,
						   track_count);
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
			tag_handler_invoke_tag(handler, handler_ctx,
					       TAG_TITLE, tag_title);
		} else
			tag_handler_invoke_tag(handler, handler_ctx,
					       TAG_TITLE, info.song);
	}

	if (info.author != nullptr)
		tag_handler_invoke_tag(handler, handler_ctx,
				       TAG_ARTIST, info.author);

	if (info.game != nullptr)
		tag_handler_invoke_tag(handler, handler_ctx,
				       TAG_ALBUM, info.game);

	if (info.comment != nullptr)
		tag_handler_invoke_tag(handler, handler_ctx,
				       TAG_COMMENT, info.comment);

	if (info.copyright != nullptr)
		tag_handler_invoke_tag(handler, handler_ctx,
				       TAG_DATE, info.copyright);
}

259
static bool
260
ScanMusicEmu(Music_Emu *emu, unsigned song_num,
261
	     const TagHandler &handler, void *handler_ctx)
262 263 264 265 266 267 268 269 270 271
{
	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);

272 273
	AtScopeExit(ti) { gme_free_info(ti); };

274 275 276 277 278
	ScanGmeInfo(*ti, song_num, gme_track_count(emu),
		    handler, handler_ctx);
	return true;
}

279
static bool
280
gme_scan_file(Path path_fs,
281
	      const TagHandler &handler, void *handler_ctx) noexcept
282
{
283
	const auto container = ParseContainerPath(path_fs);
284

285 286
	Music_Emu *emu = LoadGmeAndM3u(container);
	if(emu == nullptr) {
287
		return false;
288
	}
289

290
	AtScopeExit(emu) { gme_delete(emu); };
291

292
	return ScanMusicEmu(emu, container.track, handler, handler_ctx);
293 294
}

295
static std::forward_list<DetachedSong>
296 297
gme_container_scan(Path path_fs)
{
298
	std::forward_list<DetachedSong> list;
299
	const auto container = ParseContainerPath(path_fs);
300

301 302
	Music_Emu *emu = LoadGmeAndM3u(container);
	if(emu == nullptr) {
303 304 305
		return list;
	}

306 307
	AtScopeExit(emu) { gme_delete(emu); };

308 309 310 311 312 313 314
	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());

315 316
	TagBuilder tag_builder;

317
	auto tail = list.before_begin();
318
	for (unsigned i = 0; i < num_songs; ++i) {
319 320 321
		ScanMusicEmu(emu, i,
			     add_tag_handler, &tag_builder);

322 323 324
		const auto track_name =
			StringFormat<64>(SUBTUNE_PREFIX "%03u.%s", i+1,
					 subtune_suffix);
325 326
		tail = list.emplace_after(tail, track_name,
					  tag_builder.Commit());
327 328 329 330 331
	}

	return list;
}

332 333 334
static const char *const gme_suffixes[] = {
	"ay", "gbs", "gym", "hes", "kss", "nsf",
	"nsfe", "sap", "spc", "vgm", "vgz",
335
	nullptr
336 337
};

338
const struct DecoderPlugin gme_decoder_plugin = {
339
	"gme",
340
	gme_plugin_init,
341 342 343 344 345 346 347 348
	nullptr,
	nullptr,
	gme_file_decode,
	gme_scan_file,
	nullptr,
	gme_container_scan,
	gme_suffixes,
	nullptr,
349
};