SndfileDecoderPlugin.cxx 7.49 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2021 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 "SndfileDecoderPlugin.hxx"
21
#include "../DecoderAPI.hxx"
Max Kellermann's avatar
Max Kellermann committed
22
#include "input/InputStream.hxx"
23
#include "pcm/CheckAudioFormat.hxx"
24
#include "tag/Handler.hxx"
25
#include "util/Domain.hxx"
26
#include "util/ScopeExit.hxx"
27
#include "util/StringView.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
Rosen Penev's avatar
Rosen Penev committed
37
sndfile_init([[maybe_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_much(client, is, buffer, size);
51 52 53
	}
};

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

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

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

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

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

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

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

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

static sf_count_t
Rosen Penev's avatar
Rosen Penev committed
110 111 112
sndfile_vio_write([[maybe_unused]] const void *ptr,
		  [[maybe_unused]] sf_count_t count,
		  [[maybe_unused]] void *user_data)
113 114 115 116 117 118 119 120
{
	/* no writing! */
	return -1;
}

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

124
	return is.GetOffset();
125 126 127
}

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

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

148 149
gcc_pure
static SampleFormat
150
sndfile_sample_format(const SF_INFO &info) noexcept
151
{
152 153 154 155 156 157 158 159 160 161 162 163 164
	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;
	}
165 166
}

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

175
static sf_count_t
176 177
sndfile_read_frames(SNDFILE *sf, SampleFormat format,
		    void *buffer, sf_count_t n_frames)
178
{
179 180 181 182 183 184 185 186 187 188 189 190 191 192
	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();
	}
193 194
}

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

	info.format = 0;

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

211 212
	AtScopeExit(sf) { sf_close(sf); };

213
	const auto audio_format = CheckAudioFormat(info);
214

215
	client.Ready(audio_format, info.seekable, sndfile_duration(info));
216

217
	char buffer[16384];
218 219 220

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

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

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

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

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

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

	info.format = 0;

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

281 282
	AtScopeExit(sf) { sf_close(sf); };

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

289 290 291 292 293
	try {
		handler.OnAudioFormat(CheckAudioFormat(info));
	} catch (...) {
	}

294
	handler.OnDuration(sndfile_duration(info));
295

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

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

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

320
	nullptr
321 322 323
};

static const char *const sndfile_mime_types[] = {
324 325
	"audio/wav",
	"audio/aiff",
326 327 328 329 330
	"audio/x-wav",
	"audio/x-aiff",

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

331
	nullptr
332 333
};

334 335 336 337 338
constexpr DecoderPlugin sndfile_decoder_plugin =
	DecoderPlugin("sndfile", sndfile_stream_decode, sndfile_scan_stream)
	.WithInit(sndfile_init)
	.WithSuffixes(sndfile_suffixes)
	.WithMimeTypes(sndfile_mime_types);