GmeDecoderPlugin.cxx 7.8 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
#include "tag/TagHandler.hxx"
27
#include "tag/TagBuilder.hxx"
28
#include "fs/Path.hxx"
29
#include "fs/AllocatedPath.hxx"
30
#include "util/ScopeExit.hxx"
31
#include "util/FormatString.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
#include <stdio.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
static void
109
gme_file_decode(DecoderClient &client, Path path_fs)
110
{
111
	const auto container = ParseContainerPath(path_fs);
112

113 114
	Music_Emu *emu;
	const char *gme_err =
115
		gme_open_file(container.path.c_str(), &emu, GME_SAMPLE_RATE);
116
	if (gme_err != nullptr) {
117
		LogWarning(gme_domain, gme_err);
118 119
		return;
	}
120

121 122
	AtScopeExit(emu) { gme_delete(emu); };

123 124 125
	FormatDebug(gme_domain, "emulator type '%s'\n",
		    gme_type_system(gme_type(emu)));

126 127 128 129 130
#if GME_VERSION >= 0x000600
	if (gme_accuracy >= 0)
		gme_enable_accuracy(emu, gme_accuracy);
#endif

131
	gme_info_t *ti;
132
	gme_err = gme_track_info(emu, &ti, container.track);
133
	if (gme_err != nullptr) {
134
		LogWarning(gme_domain, gme_err);
135 136 137
		return;
	}

138
	const int length = ti->play_length;
139 140 141 142
	gme_free_info(ti);

	const SignedSongTime song_len = length > 0
		? SignedSongTime::FromMS(length)
143
		: SignedSongTime::Negative();
144 145 146

	/* initialize the MPD decoder */

147 148 149
	const auto audio_format = CheckAudioFormat(GME_SAMPLE_RATE,
						   SampleFormat::S16,
						   GME_CHANNELS);
150

151
	client.Ready(audio_format, true, song_len);
152

153
	gme_err = gme_start_track(emu, container.track);
154
	if (gme_err != nullptr)
155
		LogWarning(gme_domain, gme_err);
156

157 158
	if (length > 0)
		gme_set_fade(emu, length);
159

160
	/* play */
161
	DecoderCommand cmd;
162
	do {
163
		short buf[GME_BUFFER_SAMPLES];
164
		gme_err = gme_play(emu, GME_BUFFER_SAMPLES, buf);
165
		if (gme_err != nullptr) {
166
			LogWarning(gme_domain, gme_err);
167 168 169
			return;
		}

170
		cmd = client.SubmitData(nullptr, buf, sizeof(buf), 0);
171
		if (cmd == DecoderCommand::SEEK) {
172
			unsigned where = client.GetSeekTime().ToMS();
173
			gme_err = gme_seek(emu, where);
174
			if (gme_err != nullptr) {
175
				LogWarning(gme_domain, gme_err);
176
				client.SeekError();
177
			} else
178
				client.CommandFinished();
179 180
		}

181
		if (gme_track_ended(emu))
182
			break;
183
	} while (cmd != DecoderCommand::STOP);
184 185
}

186
static void
187
ScanGmeInfo(const gme_info_t &info, unsigned song_num, int track_count,
188
	    const TagHandler &handler, void *handler_ctx)
189
{
Max Kellermann's avatar
Max Kellermann committed
190
	if (info.play_length > 0)
191
		tag_handler_invoke_duration(handler, handler_ctx,
Max Kellermann's avatar
Max Kellermann committed
192
					    SongTime::FromMS(info.play_length));
193

194 195 196 197 198 199
	if (track_count > 1) {
		char track[16];
		sprintf(track, "%u", song_num + 1);
		tag_handler_invoke_tag(handler, handler_ctx, TAG_TRACK, track);
	}

200 201 202 203 204
	if (info.song != nullptr) {
		if (track_count > 1) {
			/* start numbering subtunes from 1 */
			char tag_title[1024];
			snprintf(tag_title, sizeof(tag_title),
205
				 "%s (%u/%d)",
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
				 info.song, song_num + 1,
				 track_count);
			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);
}

232
static bool
233
ScanMusicEmu(Music_Emu *emu, unsigned song_num,
234
	     const TagHandler &handler, void *handler_ctx)
235 236 237 238 239 240 241 242 243 244
{
	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);

245 246
	AtScopeExit(ti) { gme_free_info(ti); };

247 248 249 250 251
	ScanGmeInfo(*ti, song_num, gme_track_count(emu),
		    handler, handler_ctx);
	return true;
}

252
static bool
253
gme_scan_file(Path path_fs,
254
	      const TagHandler &handler, void *handler_ctx)
255
{
256
	const auto container = ParseContainerPath(path_fs);
257

258 259
	Music_Emu *emu;
	const char *gme_err =
260
		gme_open_file(container.path.c_str(), &emu, GME_SAMPLE_RATE);
261
	if (gme_err != nullptr) {
262
		LogWarning(gme_domain, gme_err);
263
		return false;
264
	}
265

266
	AtScopeExit(emu) { gme_delete(emu); };
267

268
	return ScanMusicEmu(emu, container.track, handler, handler_ctx);
269 270
}

271
static std::forward_list<DetachedSong>
272 273
gme_container_scan(Path path_fs)
{
274
	std::forward_list<DetachedSong> list;
275 276 277 278 279 280 281 282 283

	Music_Emu *emu;
	const char *gme_err = gme_open_file(path_fs.c_str(), &emu,
					    GME_SAMPLE_RATE);
	if (gme_err != nullptr) {
		LogWarning(gme_domain, gme_err);
		return list;
	}

284 285
	AtScopeExit(emu) { gme_delete(emu); };

286 287 288 289 290 291 292
	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());

293 294
	TagBuilder tag_builder;

295 296
	auto tail = list.before_begin();
	for (unsigned i = 1; i <= num_songs; ++i) {
297 298 299
		ScanMusicEmu(emu, i,
			     add_tag_handler, &tag_builder);

300 301 302
		char track_name[64];
		snprintf(track_name, sizeof(track_name),
			 SUBTUNE_PREFIX "%03u.%s", i, subtune_suffix);
303 304
		tail = list.emplace_after(tail, track_name,
					  tag_builder.Commit());
305 306 307 308 309
	}

	return list;
}

310 311 312
static const char *const gme_suffixes[] = {
	"ay", "gbs", "gym", "hes", "kss", "nsf",
	"nsfe", "sap", "spc", "vgm", "vgz",
313
	nullptr
314 315
};

316
const struct DecoderPlugin gme_decoder_plugin = {
317
	"gme",
318
	gme_plugin_init,
319 320 321 322 323 324 325 326
	nullptr,
	nullptr,
	gme_file_decode,
	gme_scan_file,
	nullptr,
	gme_container_scan,
	gme_suffixes,
	nullptr,
327
};