SndfileDecoderPlugin.cxx 7.47 KB
Newer Older
1
/*
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
 * 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 "SndfileDecoderPlugin.hxx"
22
#include "../DecoderAPI.hxx"
Max Kellermann's avatar
Max Kellermann committed
23
#include "input/InputStream.hxx"
24
#include "CheckAudioFormat.hxx"
25
#include "tag/Handler.hxx"
26
#include "util/Domain.hxx"
27
#include "util/ScopeExit.hxx"
28
#include "Log.hxx"
29

30
#include <exception>
31

32 33
#include <sndfile.h>

34
static constexpr Domain sndfile_domain("sndfile");
35

36
static bool
37
sndfile_init(gcc_unused const ConfigBlock &block)
38 39 40 41 42
{
       LogDebug(sndfile_domain, sf_version_string());
       return true;
}

43
struct SndfileInputStream {
44
	DecoderClient *const client;
45 46 47
	InputStream &is;

	size_t Read(void *buffer, size_t size) {
48 49
		/* libsndfile chokes on partial reads; therefore
		   always force full reads */
50
		return decoder_read_full(client, is, buffer, size)
51 52
			? size
			: 0;
53 54 55
	}
};

56 57 58
static sf_count_t
sndfile_vio_get_filelen(void *user_data)
{
59 60
	SndfileInputStream &sis = *(SndfileInputStream *)user_data;
	const InputStream &is = sis.is;
61

62 63 64
	if (!is.KnownSize())
		return -1;

65
	return is.GetSize();
66 67 68
}

static sf_count_t
69
sndfile_vio_seek(sf_count_t _offset, int whence, void *user_data)
70
{
71 72
	SndfileInputStream &sis = *(SndfileInputStream *)user_data;
	InputStream &is = sis.is;
73

74
	offset_type offset = _offset;
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
	switch (whence) {
	case SEEK_SET:
		break;

	case SEEK_CUR:
		offset += is.GetOffset();
		break;

	case SEEK_END:
		if (!is.KnownSize())
			return -1;

		offset += is.GetSize();
		break;

	default:
		return -1;
	}

94 95 96
	try {
		is.LockSeek(offset);
		return is.GetOffset();
97 98
	} catch (...) {
		LogError(std::current_exception(), "Seek failed");
99
		return -1;
100
	}
101 102 103 104 105
}

static sf_count_t
sndfile_vio_read(void *ptr, sf_count_t count, void *user_data)
{
106
	SndfileInputStream &sis = *(SndfileInputStream *)user_data;
107

108
	return sis.Read(ptr, count);
109 110 111
}

static sf_count_t
112 113 114
sndfile_vio_write(gcc_unused const void *ptr,
		  gcc_unused sf_count_t count,
		  gcc_unused void *user_data)
115 116 117 118 119 120 121 122
{
	/* no writing! */
	return -1;
}

static sf_count_t
sndfile_vio_tell(void *user_data)
{
123 124
	SndfileInputStream &sis = *(SndfileInputStream *)user_data;
	const InputStream &is = sis.is;
125

126
	return is.GetOffset();
127 128 129
}

/**
130
 * This SF_VIRTUAL_IO implementation wraps MPD's #InputStream to a
131 132
 * libsndfile stream.
 */
133
static constexpr SF_VIRTUAL_IO vio = {
134 135 136 137 138
	sndfile_vio_get_filelen,
	sndfile_vio_seek,
	sndfile_vio_read,
	sndfile_vio_write,
	sndfile_vio_tell,
139 140 141 142 143
};

/**
 * Converts a frame number to a timestamp (in seconds).
 */
144 145
static constexpr SongTime
sndfile_duration(const SF_INFO &info)
146
{
147
	return SongTime::FromScale<uint64_t>(info.frames, info.samplerate);
148 149
}

150 151
gcc_pure
static SampleFormat
152
sndfile_sample_format(const SF_INFO &info) noexcept
153
{
154 155 156 157 158 159 160 161 162 163 164 165 166
	switch (info.format & SF_FORMAT_SUBMASK) {
	case SF_FORMAT_PCM_S8:
	case SF_FORMAT_PCM_U8:
	case SF_FORMAT_PCM_16:
		return SampleFormat::S16;

	case SF_FORMAT_FLOAT:
	case SF_FORMAT_DOUBLE:
		return SampleFormat::FLOAT;

	default:
		return SampleFormat::S32;
	}
167 168
}

169 170 171 172 173 174 175 176
static AudioFormat
CheckAudioFormat(const SF_INFO &info)
{
	return CheckAudioFormat(info.samplerate,
				sndfile_sample_format(info),
				info.channels);
}

177
static sf_count_t
178 179
sndfile_read_frames(SNDFILE *sf, SampleFormat format,
		    void *buffer, sf_count_t n_frames)
180
{
181 182 183 184 185 186 187 188 189 190 191 192 193 194
	switch (format) {
	case SampleFormat::S16:
		return sf_readf_short(sf, (short *)buffer, n_frames);

	case SampleFormat::S32:
		return sf_readf_int(sf, (int *)buffer, n_frames);

	case SampleFormat::FLOAT:
		return sf_readf_float(sf, (float *)buffer, n_frames);

	default:
		assert(false);
		gcc_unreachable();
	}
195 196
}

197
static void
198
sndfile_stream_decode(DecoderClient &client, InputStream &is)
199 200 201 202 203
{
	SF_INFO info;

	info.format = 0;

204
	SndfileInputStream sis{&client, is};
205 206
	SNDFILE *const sf = sf_open_virtual(const_cast<SF_VIRTUAL_IO *>(&vio),
					    SFM_READ, &info, &sis);
207
	if (sf == nullptr) {
208 209
		FormatWarning(sndfile_domain, "sf_open_virtual() failed: %s",
			      sf_strerror(nullptr));
210 211 212
		return;
	}

213 214
	AtScopeExit(sf) { sf_close(sf); };

215
	const auto audio_format = CheckAudioFormat(info);
216

217
	client.Ready(audio_format, info.seekable, sndfile_duration(info));
218

219
	char buffer[16384];
220 221 222

	const size_t frame_size = audio_format.GetFrameSize();
	const sf_count_t read_frames = sizeof(buffer) / frame_size;
223

224
	DecoderCommand cmd;
225
	do {
226 227
		sf_count_t num_frames =
			sndfile_read_frames(sf,
228
					    audio_format.format,
229
					    buffer, read_frames);
230 231 232
		if (num_frames <= 0)
			break;

233 234 235
		cmd = client.SubmitData(is,
					buffer, num_frames * frame_size,
					0);
236
		if (cmd == DecoderCommand::SEEK) {
237
			sf_count_t c = client.GetSeekFrame();
238 239
			c = sf_seek(sf, c, SEEK_SET);
			if (c < 0)
240
				client.SeekError();
241
			else
242
				client.CommandFinished();
243
			cmd = DecoderCommand::NONE;
244
		}
245
	} while (cmd == DecoderCommand::NONE);
246 247
}

248 249
static void
sndfile_handle_tag(SNDFILE *sf, int str, TagType tag,
250
		   TagHandler &handler) noexcept
251 252 253
{
	const char *value = sf_get_string(sf, str);
	if (value != nullptr)
254
		handler.OnTag(tag, value);
255 256
}

257 258 259 260 261 262
static constexpr struct {
	int8_t str;
	TagType tag;
} sndfile_tags[] = {
	{ SF_STR_TITLE, TAG_TITLE },
	{ SF_STR_ARTIST, TAG_ARTIST },
263
	{ SF_STR_COMMENT, TAG_COMMENT },
264
	{ SF_STR_DATE, TAG_DATE },
265 266 267
	{ SF_STR_ALBUM, TAG_ALBUM },
	{ SF_STR_TRACKNUMBER, TAG_TRACK },
	{ SF_STR_GENRE, TAG_GENRE },
268 269
};

270
static bool
271
sndfile_scan_stream(InputStream &is, TagHandler &handler) noexcept
272 273 274 275 276
{
	SF_INFO info;

	info.format = 0;

277
	SndfileInputStream sis{nullptr, is};
278 279
	SNDFILE *const sf = sf_open_virtual(const_cast<SF_VIRTUAL_IO *>(&vio),
					    SFM_READ, &info, &sis);
280
	if (sf == nullptr)
281
		return false;
282

283 284
	AtScopeExit(sf) { sf_close(sf); };

285
	if (!audio_valid_sample_rate(info.samplerate)) {
286
		FormatWarning(sndfile_domain,
287
			      "Invalid sample rate in %s", is.GetURI());
288
		return false;
289 290
	}

291 292 293 294 295
	try {
		handler.OnAudioFormat(CheckAudioFormat(info));
	} catch (...) {
	}

296
	handler.OnDuration(sndfile_duration(info));
297

298
	for (auto i : sndfile_tags)
299
		sndfile_handle_tag(sf, i.str, i.tag, handler);
300

301
	return true;
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
}

static const char *const sndfile_suffixes[] = {
	"wav", "aiff", "aif", /* Microsoft / SGI / Apple */
	"au", "snd", /* Sun / DEC / NeXT */
	"paf", /* Paris Audio File */
	"iff", "svx", /* Commodore Amiga IFF / SVX */
	"sf", /* IRCAM */
	"voc", /* Creative */
	"w64", /* Soundforge */
	"pvf", /* Portable Voice Format */
	"xi", /* Fasttracker */
	"htk", /* HMM Tool Kit */
	"caf", /* Apple */
	"sd2", /* Sound Designer II */

	/* libsndfile also supports FLAC and Ogg Vorbis, but only by
	   linking with libFLAC and libvorbis - we can do better, we
	   have native plugins for these libraries */

322
	nullptr
323 324 325 326 327 328 329 330
};

static const char *const sndfile_mime_types[] = {
	"audio/x-wav",
	"audio/x-aiff",

	/* what are the MIME types of the other supported formats? */

331
	nullptr
332 333
};

334
const struct DecoderPlugin sndfile_decoder_plugin = {
335
	"sndfile",
336
	sndfile_init,
337 338 339 340
	nullptr,
	sndfile_stream_decode,
	nullptr,
	nullptr,
341
	sndfile_scan_stream,
342 343 344
	nullptr,
	sndfile_suffixes,
	sndfile_mime_types,
345
};