1 /*
2  * Copyright 2003-2021 The Music Player Daemon Project
3  * http://www.musicpd.org
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18  */
19 
20 #include "GmeDecoderPlugin.hxx"
21 #include "../DecoderAPI.hxx"
22 #include "config/Block.hxx"
23 #include "pcm/CheckAudioFormat.hxx"
24 #include "song/DetachedSong.hxx"
25 #include "tag/Handler.hxx"
26 #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 #include "util/Domain.hxx"
36 #include "Log.hxx"
37 
38 #include <gme/gme.h>
39 
40 #include <cassert>
41 
42 #include <stdlib.h>
43 
44 #define SUBTUNE_PREFIX "tune_"
45 
46 static constexpr Domain gme_domain("gme");
47 
48 static constexpr unsigned GME_SAMPLE_RATE = 44100;
49 static constexpr unsigned GME_CHANNELS = 2;
50 static constexpr unsigned GME_BUFFER_FRAMES = 2048;
51 static constexpr unsigned GME_BUFFER_SAMPLES =
52 	GME_BUFFER_FRAMES * GME_CHANNELS;
53 
54 struct GmeContainerPath {
55 	AllocatedPath path;
56 	unsigned track;
57 };
58 
59 #if GME_VERSION >= 0x000600
60 static int gme_accuracy;
61 #endif
62 static unsigned gme_default_fade;
63 
64 static bool
gme_plugin_init(const ConfigBlock & block)65 gme_plugin_init([[maybe_unused]] const ConfigBlock &block)
66 {
67 #if GME_VERSION >= 0x000600
68 	auto accuracy = block.GetBlockParam("accuracy");
69 	gme_accuracy = accuracy != nullptr
70 		? (int)accuracy->GetBoolValue()
71 		: -1;
72 #endif
73 	auto fade = block.GetBlockParam("default_fade");
74 	gme_default_fade = fade != nullptr
75 		? fade->GetUnsignedValue() * 1000
76 		: 8000;
77 
78 	return true;
79 }
80 
81 gcc_pure
82 static unsigned
ParseSubtuneName(const char * base)83 ParseSubtuneName(const char *base) noexcept
84 {
85 	base = StringAfterPrefix(base, SUBTUNE_PREFIX);
86 	if (base == nullptr)
87 		return 0;
88 
89 	char *endptr;
90 	auto track = strtoul(base, &endptr, 10);
91 	if (endptr == base || *endptr != '.')
92 		return 0;
93 
94 	return track;
95 }
96 
97 /**
98  * returns the file path stripped of any /tune_xxx.* subtune suffix
99  * and the track number (or 0 if no "tune_xxx" suffix is present).
100  */
101 static GmeContainerPath
ParseContainerPath(Path path_fs)102 ParseContainerPath(Path path_fs)
103 {
104 	const Path base = path_fs.GetBase();
105 	unsigned track;
106 	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 static AllocatedPath
ReplaceSuffix(Path src,const PathTraitsFS::const_pointer new_suffix)114 ReplaceSuffix(Path src,
115 	      const PathTraitsFS::const_pointer new_suffix) noexcept
116 {
117 	const auto *old_suffix = src.GetSuffix();
118 	if (old_suffix == nullptr)
119 		return nullptr;
120 
121 	PathTraitsFS::string s(src.c_str(), old_suffix);
122 	s += new_suffix;
123 	return AllocatedPath::FromFS(std::move(s));
124 }
125 
126 static Music_Emu*
LoadGmeAndM3u(const GmeContainerPath & container)127 LoadGmeAndM3u(const GmeContainerPath& container) {
128 
129 	Music_Emu *emu;
130 	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 		return nullptr;
135 	}
136 
137 	const auto m3u_path = ReplaceSuffix(container.path,
138 					    PATH_LITERAL("m3u"));
139     /*
140      * Some GME formats lose metadata if you attempt to
141      * load a non-existant M3U file, so check that one
142      * exists before loading.
143      */
144 	if (!m3u_path.IsNull() && FileExists(m3u_path))
145 		gme_load_m3u(emu, NarrowPath(m3u_path));
146 
147 	return emu;
148 }
149 
150 
151 static void
gme_file_decode(DecoderClient & client,Path path_fs)152 gme_file_decode(DecoderClient &client, Path path_fs)
153 {
154 	const auto container = ParseContainerPath(path_fs);
155 
156 	Music_Emu *emu = LoadGmeAndM3u(container);
157 	if(emu == nullptr) {
158 		return;
159 	}
160 
161 	AtScopeExit(emu) { gme_delete(emu); };
162 
163 	FmtDebug(gme_domain, "emulator type '{}'",
164 		 gme_type_system(gme_type(emu)));
165 
166 #if GME_VERSION >= 0x000600
167 	if (gme_accuracy >= 0)
168 		gme_enable_accuracy(emu, gme_accuracy);
169 #endif
170 
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 		return;
176 	}
177 
178 	const int length = ti->play_length;
179 #if GME_VERSION >= 0x000700
180 	const int fade   = ti->fade_length;
181 #else
182 	const int fade   = -1;
183 #endif
184 	gme_free_info(ti);
185 
186 	const SignedSongTime song_len = length > 0
187 		? SignedSongTime::FromMS(length +
188 			(fade == -1 ? gme_default_fade : fade))
189 		: SignedSongTime::Negative();
190 
191 	/* initialize the MPD decoder */
192 
193 	const auto audio_format = CheckAudioFormat(GME_SAMPLE_RATE,
194 						   SampleFormat::S16,
195 						   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 		gme_set_fade(emu, length
205 #if GME_VERSION >= 0x000700
206 			     , fade == -1 ? gme_default_fade : fade
207 #endif
208 			     );
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 			return;
218 		}
219 
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
ScanGmeInfo(const gme_info_t & info,unsigned song_num,int track_count,TagHandler & handler)237 ScanGmeInfo(const gme_info_t &info, unsigned song_num, int track_count,
238 	    TagHandler &handler) noexcept
239 {
240 	if (info.play_length > 0)
241 		handler.OnDuration(SongTime::FromMS(info.play_length
242 #if GME_VERSION >= 0x000700
243 			+ (info.fade_length == -1 ? gme_default_fade : info.fade_length)
244 #endif
245 			));
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 		if (track_count > 1) {
252 			/* start numbering subtunes from 1 */
253 			const auto tag_title =
254 				StringFormat<1024>("%s (%u/%d)",
255 						   info.song, song_num + 1,
256 						   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
ScanMusicEmu(Music_Emu * emu,unsigned song_num,TagHandler & handler)276 ScanMusicEmu(Music_Emu *emu, unsigned song_num, TagHandler &handler) noexcept
277 {
278 	gme_info_t *ti;
279 	const char *gme_err = gme_track_info(emu, &ti, song_num);
280 	if (gme_err != nullptr) {
281 		LogWarning(gme_domain, gme_err);
282 		return false;
283 	}
284 
285 	assert(ti != nullptr);
286 
287 	AtScopeExit(ti) { gme_free_info(ti); };
288 
289 	ScanGmeInfo(*ti, song_num, gme_track_count(emu), handler);
290 	return true;
291 }
292 
293 static bool
gme_scan_file(Path path_fs,TagHandler & handler)294 gme_scan_file(Path path_fs, TagHandler &handler) noexcept
295 {
296 	const auto container = ParseContainerPath(path_fs);
297 
298 	Music_Emu *emu = LoadGmeAndM3u(container);
299 	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>
gme_container_scan(Path path_fs)309 gme_container_scan(Path path_fs)
310 {
311 	std::forward_list<DetachedSong> list;
312 	const auto container = ParseContainerPath(path_fs);
313 
314 	Music_Emu *emu = LoadGmeAndM3u(container);
315 	if(emu == nullptr) {
316 		return list;
317 	}
318 
319 	AtScopeExit(emu) { gme_delete(emu); };
320 
321 	const unsigned num_songs = gme_track_count(emu);
322 	/* if it only contains a single tune, don't treat as container */
323 	if (num_songs < 2)
324 		return list;
325 
326 	const auto *subtune_suffix = path_fs.GetSuffix();
327 
328 	TagBuilder tag_builder;
329 
330 	auto tail = list.before_begin();
331 	for (unsigned i = 0; i < num_songs; ++i) {
332 		AddTagHandler h(tag_builder);
333 		ScanMusicEmu(emu, i, h);
334 
335 		const auto track_name =
336 			StringFormat<64>(SUBTUNE_PREFIX "%03u.%s", i+1,
337 					 subtune_suffix);
338 		tail = list.emplace_after(tail, track_name,
339 					  tag_builder.Commit());
340 	}
341 
342 	return list;
343 }
344 
345 static const char *const gme_suffixes[] = {
346 	"ay", "gbs", "gym", "hes", "kss", "nsf",
347 	"nsfe", "rsn", "sap", "spc", "vgm", "vgz",
348 	nullptr
349 };
350 
351 constexpr DecoderPlugin gme_decoder_plugin =
352 	DecoderPlugin("gme", gme_file_decode, gme_scan_file)
353 	.WithInit(gme_plugin_init)
354 	.WithContainer(gme_container_scan)
355 	.WithSuffixes(gme_suffixes);
356