SndfileDecoderPlugin.cxx 7.03 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright (C) 2003-2014 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/TagHandler.hxx"
26
#include "fs/Path.hxx"
27
#include "util/Error.hxx"
28 29
#include "util/Domain.hxx"
#include "Log.hxx"
30 31 32

#include <sndfile.h>

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

35 36 37 38 39 40 41
static bool
sndfile_init(gcc_unused const config_param &param)
{
       LogDebug(sndfile_domain, sf_version_string());
       return true;
}

42 43 44 45 46
struct SndfileInputStream {
	Decoder *const decoder;
	InputStream &is;

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

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

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

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

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

73
	offset_type offset = _offset;
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
	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;
	}

93
	Error error;
Max Kellermann's avatar
Max Kellermann committed
94
	if (!is.LockSeek(offset, error)) {
95
		LogError(error, "Seek failed");
96
		return -1;
97
	}
98

99
	return is.GetOffset();
100 101 102 103 104
}

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

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

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

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

125
	return is.GetOffset();
126 127 128 129 130 131 132
}

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

/**
 * Converts a frame number to a timestamp (in seconds).
 */
static float
144
frame_to_time(sf_count_t frame, const AudioFormat *audio_format)
145 146 147 148 149 150 151 152
{
	return (float)frame / (float)audio_format->sample_rate;
}

/**
 * Converts a timestamp (in seconds) to a frame number.
 */
static sf_count_t
153
time_to_frame(float t, const AudioFormat *audio_format)
154 155 156 157 158
{
	return (sf_count_t)(t * audio_format->sample_rate);
}

static void
159
sndfile_stream_decode(Decoder &decoder, InputStream &is)
160 161 162 163 164
{
	SF_INFO info;

	info.format = 0;

165
	SndfileInputStream sis{&decoder, is};
166
	SNDFILE *const sf = sf_open_virtual(&vio, SFM_READ, &info, &sis);
167
	if (sf == nullptr) {
168
		LogWarning(sndfile_domain, "sf_open_virtual() failed");
169 170 171 172 173 174
		return;
	}

	/* for now, always read 32 bit samples.  Later, we could lower
	   MPD's CPU usage by reading 16 bit samples with
	   sf_readf_short() on low-quality source files. */
175
	Error error;
176 177 178
	AudioFormat audio_format;
	if (!audio_format_init_checked(audio_format, info.samplerate,
				       SampleFormat::S32,
179
				       info.channels, error)) {
180
		LogError(error);
181 182 183
		return;
	}

184
	decoder_initialized(decoder, audio_format, info.seekable,
185 186
			    frame_to_time(info.frames, &audio_format));

187 188 189 190
	int buffer[4096];

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

192
	DecoderCommand cmd;
193
	do {
194
		sf_count_t num_frames = sf_readf_int(sf, buffer, read_frames);
195 196 197 198 199
		if (num_frames <= 0)
			break;

		cmd = decoder_data(decoder, is,
				   buffer, num_frames * frame_size,
200
				   0);
201
		if (cmd == DecoderCommand::SEEK) {
202 203 204 205 206 207 208 209
			sf_count_t c =
				time_to_frame(decoder_seek_where(decoder),
					      &audio_format);
			c = sf_seek(sf, c, SEEK_SET);
			if (c < 0)
				decoder_seek_error(decoder);
			else
				decoder_command_finished(decoder);
210
			cmd = DecoderCommand::NONE;
211
		}
212
	} while (cmd == DecoderCommand::NONE);
213 214 215 216

	sf_close(sf);
}

217 218 219 220 221 222 223 224 225
static void
sndfile_handle_tag(SNDFILE *sf, int str, TagType tag,
		   const struct tag_handler *handler, void *handler_ctx)
{
	const char *value = sf_get_string(sf, str);
	if (value != nullptr)
		tag_handler_invoke_tag(handler, handler_ctx, tag, value);
}

226 227 228 229 230 231
static constexpr struct {
	int8_t str;
	TagType tag;
} sndfile_tags[] = {
	{ SF_STR_TITLE, TAG_TITLE },
	{ SF_STR_ARTIST, TAG_ARTIST },
232
	{ SF_STR_COMMENT, TAG_COMMENT },
233
	{ SF_STR_DATE, TAG_DATE },
234 235 236
	{ SF_STR_ALBUM, TAG_ALBUM },
	{ SF_STR_TRACKNUMBER, TAG_TRACK },
	{ SF_STR_GENRE, TAG_GENRE },
237 238
};

239
static bool
240 241
sndfile_scan_stream(InputStream &is,
		    const struct tag_handler *handler, void *handler_ctx)
242 243 244 245 246
{
	SF_INFO info;

	info.format = 0;

247 248
	SndfileInputStream sis{nullptr, is};
	SNDFILE *const sf = sf_open_virtual(&vio, SFM_READ, &info, &sis);
249
	if (sf == nullptr)
250
		return false;
251 252 253

	if (!audio_valid_sample_rate(info.samplerate)) {
		sf_close(sf);
254
		FormatWarning(sndfile_domain,
255
			      "Invalid sample rate in %s", is.GetURI());
256
		return false;
257 258
	}

259 260
	tag_handler_invoke_duration(handler, handler_ctx,
				    info.frames / info.samplerate);
261

262 263
	for (auto i : sndfile_tags)
		sndfile_handle_tag(sf, i.str, i.tag, handler, handler_ctx);
264 265 266

	sf_close(sf);

267
	return true;
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
}

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 */

288
	nullptr
289 290 291 292 293 294 295 296
};

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

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

297
	nullptr
298 299
};

300
const struct DecoderPlugin sndfile_decoder_plugin = {
301
	"sndfile",
302
	sndfile_init,
303 304 305 306
	nullptr,
	sndfile_stream_decode,
	nullptr,
	nullptr,
307
	sndfile_scan_stream,
308 309 310
	nullptr,
	sndfile_suffixes,
	sndfile_mime_types,
311
};