GmeDecoderPlugin.cxx 8.04 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
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 "fs/NarrowPath.hxx"
31
#include "util/ScopeExit.hxx"
32
#include "util/StringCompare.hxx"
33
#include "util/StringFormat.hxx"
34 35
#include "util/Domain.hxx"
#include "Log.hxx"
36

37 38
#include <gme/gme.h>

39
#include <assert.h>
40
#include <stdlib.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
	base = StringAfterPrefix(base, SUBTUNE_PREFIX);
	if (base == nullptr)
80 81 82 83 84 85 86 87 88 89
		return 0;

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

	return track;
}

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

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

106 107 108 109 110 111 112 113 114 115 116 117 118
static AllocatedPath
ReplaceSuffix(Path src,
	      const PathTraitsFS::const_pointer_type new_suffix) noexcept
{
	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));
}

119 120 121
static Music_Emu*
LoadGmeAndM3u(GmeContainerPath container) {

122 123
	Music_Emu *emu;
	const char *gme_err =
124
		gme_open_file(NarrowPath(container.path), &emu, GME_SAMPLE_RATE);
125
	if (gme_err != nullptr) {
126
		LogWarning(gme_domain, gme_err);
127 128 129
		return nullptr;
	}

130 131
	const auto m3u_path = ReplaceSuffix(container.path,
					    PATH_LITERAL("m3u"));
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.
     */
137
	if (!m3u_path.IsNull() && FileExists(m3u_path))
138
		gme_load_m3u(emu, NarrowPath(m3u_path));
139

140 141 142 143 144 145 146 147 148 149 150
	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) {
151 152
		return;
	}
153

154 155
	AtScopeExit(emu) { gme_delete(emu); };

156 157 158
	FormatDebug(gme_domain, "emulator type '%s'\n",
		    gme_type_system(gme_type(emu)));

159 160 161 162 163
#if GME_VERSION >= 0x000600
	if (gme_accuracy >= 0)
		gme_enable_accuracy(emu, gme_accuracy);
#endif

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

171
	const int length = ti->play_length;
172 173 174 175
	gme_free_info(ti);

	const SignedSongTime song_len = length > 0
		? SignedSongTime::FromMS(length)
176
		: SignedSongTime::Negative();
177 178 179

	/* initialize the MPD decoder */

180 181 182
	const auto audio_format = CheckAudioFormat(GME_SAMPLE_RATE,
						   SampleFormat::S16,
						   GME_CHANNELS);
183

184
	client.Ready(audio_format, true, song_len);
185

186
	gme_err = gme_start_track(emu, container.track);
187
	if (gme_err != nullptr)
188
		LogWarning(gme_domain, gme_err);
189

190
	if (length > 0)
191 192 193 194 195
		gme_set_fade(emu, length
#if GME_VERSION >= 0x000700
			     , 8000
#endif
			     );
196

197
	/* play */
198
	DecoderCommand cmd;
199
	do {
200
		short buf[GME_BUFFER_SAMPLES];
201
		gme_err = gme_play(emu, GME_BUFFER_SAMPLES, buf);
202
		if (gme_err != nullptr) {
203
			LogWarning(gme_domain, gme_err);
204 205 206
			return;
		}

207
		cmd = client.SubmitData(nullptr, buf, sizeof(buf), 0);
208
		if (cmd == DecoderCommand::SEEK) {
209
			unsigned where = client.GetSeekTime().ToMS();
210
			gme_err = gme_seek(emu, where);
211
			if (gme_err != nullptr) {
212
				LogWarning(gme_domain, gme_err);
213
				client.SeekError();
214
			} else
215
				client.CommandFinished();
216 217
		}

218
		if (gme_track_ended(emu))
219
			break;
220
	} while (cmd != DecoderCommand::STOP);
221 222
}

223
static void
224
ScanGmeInfo(const gme_info_t &info, unsigned song_num, int track_count,
225
	    TagHandler &handler) noexcept
226
{
Max Kellermann's avatar
Max Kellermann committed
227
	if (info.play_length > 0)
228
		handler.OnDuration(SongTime::FromMS(info.play_length));
229

230
	if (track_count > 1)
231
		handler.OnTag(TAG_TRACK, StringFormat<16>("%u", song_num + 1));
232

233
	if (!StringIsEmpty(info.song)) {
234 235
		if (track_count > 1) {
			/* start numbering subtunes from 1 */
236 237 238 239
			const auto tag_title =
				StringFormat<1024>("%s (%u/%d)",
						   info.song, song_num + 1,
						   track_count);
240
			handler.OnTag(TAG_TITLE, tag_title);
241
		} else
242
			handler.OnTag(TAG_TITLE, info.song);
243 244
	}

245
	if (!StringIsEmpty(info.author))
246
		handler.OnTag(TAG_ARTIST, info.author);
247

248
	if (!StringIsEmpty(info.game))
249
		handler.OnTag(TAG_ALBUM, info.game);
250

251
	if (!StringIsEmpty(info.comment))
252
		handler.OnTag(TAG_COMMENT, info.comment);
253

254
	if (!StringIsEmpty(info.copyright))
255
		handler.OnTag(TAG_DATE, info.copyright);
256 257
}

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

270 271
	AtScopeExit(ti) { gme_free_info(ti); };

272
	ScanGmeInfo(*ti, song_num, gme_track_count(emu), handler);
273 274 275
	return true;
}

276
static bool
277
gme_scan_file(Path path_fs, TagHandler &handler) noexcept
278
{
279
	const auto container = ParseContainerPath(path_fs);
280

281 282
	Music_Emu *emu = LoadGmeAndM3u(container);
	if(emu == nullptr) {
283
		return false;
284
	}
285

286
	AtScopeExit(emu) { gme_delete(emu); };
287

288
	return ScanMusicEmu(emu, container.track, handler);
289 290
}

291
static std::forward_list<DetachedSong>
292 293
gme_container_scan(Path path_fs)
{
294
	std::forward_list<DetachedSong> list;
295
	const auto container = ParseContainerPath(path_fs);
296

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

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

304 305 306 307 308
	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;

309
	const auto *subtune_suffix = path_fs.GetSuffix();
310

311 312
	TagBuilder tag_builder;

313
	auto tail = list.before_begin();
314
	for (unsigned i = 0; i < num_songs; ++i) {
315 316
		AddTagHandler h(tag_builder);
		ScanMusicEmu(emu, i, h);
317

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

	return list;
}

328 329 330
static const char *const gme_suffixes[] = {
	"ay", "gbs", "gym", "hes", "kss", "nsf",
	"nsfe", "sap", "spc", "vgm", "vgz",
331
	nullptr
332 333
};

334
const struct DecoderPlugin gme_decoder_plugin = {
335
	"gme",
336
	gme_plugin_init,
337 338 339 340 341 342 343 344
	nullptr,
	nullptr,
	gme_file_decode,
	gme_scan_file,
	nullptr,
	gme_container_scan,
	gme_suffixes,
	nullptr,
345
};