WavpackDecoderPlugin.cxx 12.7 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright (C) 2003-2015 The Music Player Daemon Project
3
 * http://www.musicpd.org
Max Kellermann's avatar
Max Kellermann committed
4
 *
5 6 7 8 9 10 11 12 13
 * 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.
14 15 16 17
 *
 * 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.
18 19
 */

20
#include "config.h"
21
#include "WavpackDecoderPlugin.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 "tag/ApeTag.hxx"
27
#include "fs/Path.hxx"
28
#include "util/Error.hxx"
29
#include "util/Domain.hxx"
30
#include "util/Macros.hxx"
31
#include "util/Alloc.hxx"
32
#include "Log.hxx"
33 34

#include <wavpack/wavpack.h>
Max Kellermann's avatar
Max Kellermann committed
35 36

#include <assert.h>
37 38
#include <stdio.h>
#include <stdlib.h>
39 40 41

#define ERRORLEN 80

42 43
static constexpr Domain wavpack_domain("wavpack");

44 45 46 47 48 49
/** A pointer type for format converter function. */
typedef void (*format_samples_t)(
	int bytes_per_sample,
	void *buffer, uint32_t count
);

50 51 52
/*
 * This function has been borrowed from the tiny player found on
 * wavpack.com. Modifications were required because mpd only handles
53
 * max 24-bit samples.
54
 */
Max Kellermann's avatar
Max Kellermann committed
55
static void
56
format_samples_int(int bytes_per_sample, void *buffer, uint32_t count)
57
{
58
	int32_t *src = (int32_t *)buffer;
59

Max Kellermann's avatar
Max Kellermann committed
60
	switch (bytes_per_sample) {
61
	case 1: {
62
		int8_t *dst = (int8_t *)buffer;
63 64 65 66 67 68
		/*
		 * The asserts like the following one are because we do the
		 * formatting of samples within a single buffer. The size
		 * of the output samples never can be greater than the size
		 * of the input ones. Otherwise we would have an overflow.
		 */
69
		static_assert(sizeof(*dst) <= sizeof(*src), "Wrong size");
70 71

		/* pass through and align 8-bit samples */
72
		while (count--) {
Max Kellermann's avatar
Max Kellermann committed
73
			*dst++ = *src++;
74
		}
Max Kellermann's avatar
Max Kellermann committed
75
		break;
76 77
	}
	case 2: {
78 79
		uint16_t *dst = (uint16_t *)buffer;
		static_assert(sizeof(*dst) <= sizeof(*src), "Wrong size");
80 81

		/* pass through and align 16-bit samples */
82
		while (count--) {
83
			*dst++ = *src++;
Max Kellermann's avatar
Max Kellermann committed
84 85
		}
		break;
86
	}
87

Max Kellermann's avatar
Max Kellermann committed
88
	case 3:
89
	case 4:
90
		/* do nothing */
Max Kellermann's avatar
Max Kellermann committed
91
		break;
92
	}
93 94 95
}

/*
96
 * This function converts floating point sample data to 24-bit integer.
97
 */
98
static void
99
format_samples_float(gcc_unused int bytes_per_sample, void *buffer,
100
		     uint32_t count)
101
{
102
	float *p = (float *)buffer;
103

104
	while (count--) {
105 106
		*p /= (1 << 23);
		++p;
107 108 109
	}
}

110 111 112
/**
 * Choose a MPD sample format from libwavpacks' number of bits.
 */
113
static SampleFormat
114 115 116
wavpack_bits_to_sample_format(bool is_float, int bytes_per_sample)
{
	if (is_float)
117
		return SampleFormat::FLOAT;
118 119 120

	switch (bytes_per_sample) {
	case 1:
121
		return SampleFormat::S8;
122 123

	case 2:
124
		return SampleFormat::S16;
125 126

	case 3:
127
		return SampleFormat::S24_P32;
128 129

	case 4:
130
		return SampleFormat::S32;
131 132

	default:
133
		return SampleFormat::UNDEFINED;
134 135 136
	}
}

137 138 139 140
/*
 * This does the main decoding thing.
 * Requires an already opened WavpackContext.
 */
141
static void
142
wavpack_decode(Decoder &decoder, WavpackContext *wpc, bool can_seek)
143
{
144 145
	bool is_float = (WavpackGetMode(wpc) & MODE_FLOAT) != 0;
	SampleFormat sample_format =
146 147
		wavpack_bits_to_sample_format(is_float,
					      WavpackGetBytesPerSample(wpc));
148

149
	Error error;
150
	AudioFormat audio_format;
151
	if (!audio_format_init_checked(audio_format,
152 153
				       WavpackGetSampleRate(wpc),
				       sample_format,
154
				       WavpackGetNumChannels(wpc), error)) {
155
		LogError(error);
156 157 158
		return;
	}

159 160 161
	const format_samples_t format_samples = is_float
		? format_samples_float
		: format_samples_int;
162

163 164 165
	const auto total_time =
		SongTime::FromScale<uint64_t>(WavpackGetNumSamples(wpc),
					      audio_format.sample_rate);
166 167 168

	const int bytes_per_sample = WavpackGetBytesPerSample(wpc);
	const int output_sample_size = audio_format.GetFrameSize();
169

170
	/* wavpack gives us all kind of samples in a 32-bit space */
171
	int32_t chunk[1024];
172
	const uint32_t samples_requested = ARRAY_SIZE(chunk) /
173
		audio_format.channels;
174

175
	decoder_initialized(decoder, audio_format, can_seek, total_time);
176

177 178 179
	DecoderCommand cmd = decoder_get_command(decoder);
	while (cmd != DecoderCommand::STOP) {
		if (cmd == DecoderCommand::SEEK) {
180
			if (can_seek) {
181
				auto where = decoder_seek_where_frame(decoder);
182

183 184
				if (WavpackSeekSample(wpc, where)) {
					decoder_command_finished(decoder);
185
				} else {
186
					decoder_seek_error(decoder);
187
				}
188
			} else {
189
				decoder_seek_error(decoder);
190 191 192
			}
		}

193 194
		uint32_t samples_got = WavpackUnpackSamples(wpc, chunk,
							    samples_requested);
195
		if (samples_got == 0)
196 197
			break;

198 199 200 201 202
		int bitrate = (int)(WavpackGetInstantBitrate(wpc) / 1000 +
				    0.5);
		format_samples(bytes_per_sample, chunk,
			       samples_got * audio_format.channels);

203
		cmd = decoder_data(decoder, nullptr, chunk,
204 205
				   samples_got * output_sample_size,
				   bitrate);
206
	}
207 208
}

209 210 211 212 213 214
/**
 * Locate and parse a floating point tag.  Returns true if it was
 * found.
 */
static bool
wavpack_tag_float(WavpackContext *wpc, const char *key, float *value_r)
215
{
216
	char buffer[64];
217
	if (WavpackGetTagItem(wpc, key, buffer, sizeof(buffer)) <= 0)
218
		return false;
219

220 221
	*value_r = atof(buffer);
	return true;
222 223
}

224
static bool
225
wavpack_replaygain(ReplayGainInfo &rgi,
226
		   WavpackContext *wpc)
227
{
228
	rgi.Clear();
229

230
	bool found = false;
231 232 233 234 235 236 237 238
	found |= wavpack_tag_float(wpc, "replaygain_track_gain",
				   &rgi.tuples[REPLAY_GAIN_TRACK].gain);
	found |= wavpack_tag_float(wpc, "replaygain_track_peak",
				   &rgi.tuples[REPLAY_GAIN_TRACK].peak);
	found |= wavpack_tag_float(wpc, "replaygain_album_gain",
				   &rgi.tuples[REPLAY_GAIN_ALBUM].gain);
	found |= wavpack_tag_float(wpc, "replaygain_album_peak",
				   &rgi.tuples[REPLAY_GAIN_ALBUM].peak);
239

240
	return found;
241 242
}

243 244
static void
wavpack_scan_tag_item(WavpackContext *wpc, const char *name,
245
		      TagType type,
246 247 248 249 250 251 252 253 254 255 256
		      const struct tag_handler *handler, void *handler_ctx)
{
	char buffer[1024];
	int len = WavpackGetTagItem(wpc, name, buffer, sizeof(buffer));
	if (len <= 0 || (unsigned)len >= sizeof(buffer))
		return;

	tag_handler_invoke_tag(handler, handler_ctx, type, buffer);

}

257 258 259 260
static void
wavpack_scan_pair(WavpackContext *wpc, const char *name,
		  const struct tag_handler *handler, void *handler_ctx)
{
261
	char buffer[8192];
262 263 264 265 266 267 268
	int len = WavpackGetTagItem(wpc, name, buffer, sizeof(buffer));
	if (len <= 0 || (unsigned)len >= sizeof(buffer))
		return;

	tag_handler_invoke_pair(handler, handler_ctx, name, buffer);
}

269 270 271
/*
 * Reads metainfo from the specified file.
 */
272
static bool
273
wavpack_scan_file(Path path_fs,
274
		  const struct tag_handler *handler, void *handler_ctx)
275 276
{
	char error[ERRORLEN];
277 278
	WavpackContext *wpc = WavpackOpenFileInput(path_fs.c_str(), error,
						   OPEN_TAGS, 0);
279
	if (wpc == nullptr) {
280 281
		FormatError(wavpack_domain,
			    "failed to open WavPack file \"%s\": %s",
282
			    path_fs.c_str(), error);
283
		return false;
284 285
	}

286 287 288 289
	const auto duration =
		SongTime::FromScale<uint64_t>(WavpackGetNumSamples(wpc),
					      WavpackGetSampleRate(wpc));
	tag_handler_invoke_duration(handler, handler_ctx, duration);
290

291 292 293 294 295
	/* the WavPack format implies APEv2 tags, which means we can
	   reuse the mapping from tag_ape.c */

	for (unsigned i = 0; i < TAG_NUM_OF_ITEM_TYPES; ++i) {
		const char *name = tag_item_names[i];
296
		if (name != nullptr)
297
			wavpack_scan_tag_item(wpc, name, (TagType)i,
298 299 300
					      handler, handler_ctx);
	}

301
	for (const struct tag_table *i = ape_tags; i->name != nullptr; ++i)
302 303
		wavpack_scan_tag_item(wpc, i->name, i->type,
				      handler, handler_ctx);
304

305
	if (handler->pair != nullptr) {
306 307 308 309 310 311 312 313 314 315 316 317 318
		char name[64];

		for (int i = 0, n = WavpackGetNumTagItems(wpc);
		     i < n; ++i) {
			int len = WavpackGetTagItemIndexed(wpc, i, name,
							   sizeof(name));
			if (len <= 0 || (unsigned)len >= sizeof(name))
				continue;

			wavpack_scan_pair(wpc, name, handler, handler_ctx);
		}
	}

319 320
	WavpackCloseFile(wpc);

321
	return true;
322 323 324
}

/*
325
 * #InputStream <=> WavpackStreamReader wrapper callbacks
326 327
 */

Laszlo Ashin's avatar
Laszlo Ashin committed
328
/* This struct is needed for per-stream last_byte storage. */
329
struct WavpackInput {
330 331
	Decoder &decoder;
	InputStream &is;
Laszlo Ashin's avatar
Laszlo Ashin committed
332 333
	/* Needed for push_back_byte() */
	int last_byte;
334 335

	constexpr WavpackInput(Decoder &_decoder, InputStream &_is)
336
		:decoder(_decoder), is(_is), last_byte(EOF) {}
337 338

	int32_t ReadBytes(void *data, size_t bcount);
Max Kellermann's avatar
Max Kellermann committed
339
};
Laszlo Ashin's avatar
Laszlo Ashin committed
340

341
/**
342
 * Little wrapper for struct WavpackInput to cast from void *.
343
 */
344
static WavpackInput *
345 346 347
wpin(void *id)
{
	assert(id);
348
	return (WavpackInput *)id;
349 350
}

351
static int32_t
352
wavpack_input_read_bytes(void *id, void *data, int32_t bcount)
353 354 355 356 357 358
{
	return wpin(id)->ReadBytes(data, bcount);
}

int32_t
WavpackInput::ReadBytes(void *data, size_t bcount)
359 360 361 362
{
	uint8_t *buf = (uint8_t *)data;
	int32_t i = 0;

363 364 365
	if (last_byte != EOF) {
		*buf++ = last_byte;
		last_byte = EOF;
366 367 368
		--bcount;
		++i;
	}
369 370 371 372

	/* wavpack fails if we return a partial read, so we just wait
	   until the buffer is full */
	while (bcount > 0) {
373
		size_t nbytes = decoder_read(&decoder, is, buf, bcount);
374
		if (nbytes == 0) {
375 376
			/* EOF, error or a decoder command */
			break;
377
		}
378 379 380 381 382 383 384

		i += nbytes;
		bcount -= nbytes;
		buf += nbytes;
	}

	return i;
385 386
}

387
static uint32_t
388
wavpack_input_get_pos(void *id)
389
{
390 391 392
	WavpackInput &wpi = *wpin(id);

	return wpi.is.GetOffset();
393 394
}

395
static int
396
wavpack_input_set_pos_abs(void *id, uint32_t pos)
397
{
398 399 400
	WavpackInput &wpi = *wpin(id);

	return wpi.is.LockSeek(pos, IgnoreError()) ? 0 : -1;
401 402
}

403
static int
404
wavpack_input_set_pos_rel(void *id, int32_t delta, int mode)
405
{
406 407
	WavpackInput &wpi = *wpin(id);
	InputStream &is = wpi.is;
408

409
	offset_type offset = delta;
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
	switch (mode) {
	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;
	}

	return is.LockSeek(offset, IgnoreError()) ? 0 : -1;
430 431
}

432
static int
433
wavpack_input_push_back_byte(void *id, int c)
434
{
435 436 437 438
	WavpackInput &wpi = *wpin(id);

	if (wpi.last_byte == EOF) {
		wpi.last_byte = c;
439 440 441 442
		return c;
	} else {
		return EOF;
	}
443 444
}

445
static uint32_t
446
wavpack_input_get_length(void *id)
447
{
448 449 450 451
	WavpackInput &wpi = *wpin(id);
	InputStream &is = wpi.is;

	if (!is.KnownSize())
452 453
		return 0;

454
	return is.GetSize();
455 456
}

457
static int
458
wavpack_input_can_seek(void *id)
459
{
460 461 462 463
	WavpackInput &wpi = *wpin(id);
	InputStream &is = wpi.is;

	return is.IsSeekable();
464 465 466
}

static WavpackStreamReader mpd_is_reader = {
467 468 469 470 471 472 473 474
	wavpack_input_read_bytes,
	wavpack_input_get_pos,
	wavpack_input_set_pos_abs,
	wavpack_input_set_pos_rel,
	wavpack_input_push_back_byte,
	wavpack_input_get_length,
	wavpack_input_can_seek,
	nullptr /* no need to write edited tags */
475 476
};

477 478
static WavpackInput *
wavpack_open_wvc(Decoder &decoder, const char *uri)
479
{
480 481 482 483
	/*
	 * As we use dc->utf8url, this function will be bad for
	 * single files. utf8url is not absolute file path :/
	 */
484
	if (uri == nullptr)
485
		return nullptr;
486

487
	char *wvc_url = xstrcatdup(uri, "c");
488

489
	InputStream *is_wvc = decoder_open_uri(decoder, uri, IgnoreError());
490
	free(wvc_url);
Laszlo Ashin's avatar
Laszlo Ashin committed
491

492 493
	if (is_wvc == nullptr)
		return nullptr;
494

495
	return new WavpackInput(decoder, *is_wvc);
496
}
Laszlo Ashin's avatar
Laszlo Ashin committed
497

498 499 500
/*
 * Decodes a stream.
 */
501
static void
502
wavpack_streamdecode(Decoder &decoder, InputStream &is)
503
{
504
	int open_flags = OPEN_NORMALIZE;
505
	bool can_seek = is.IsSeekable();
Laszlo Ashin's avatar
Laszlo Ashin committed
506

507 508
	WavpackInput *wvc = wavpack_open_wvc(decoder, is.GetURI());
	if (wvc != nullptr) {
Laszlo Ashin's avatar
Laszlo Ashin committed
509
		open_flags |= OPEN_WVC;
510
		can_seek &= wvc->is.IsSeekable();
511
	}
Laszlo Ashin's avatar
Laszlo Ashin committed
512

513 514 515 516
	if (!can_seek) {
		open_flags |= OPEN_STREAMING;
	}

517
	WavpackInput isp(decoder, is);
518 519 520

	char error[ERRORLEN];
	WavpackContext *wpc =
521
		WavpackOpenFileInputEx(&mpd_is_reader, &isp, wvc,
522
				       error, open_flags, 23);
523

524
	if (wpc == nullptr) {
525 526
		FormatError(wavpack_domain,
			    "failed to open WavPack stream: %s", error);
527
		return;
528 529
	}

530
	wavpack_decode(decoder, wpc, can_seek);
531 532

	WavpackCloseFile(wpc);
533 534

	if (wvc != nullptr) {
535
		delete &wvc->is;
536
		delete wvc;
537
	}
538 539 540
}

/*
Laszlo Ashin's avatar
Laszlo Ashin committed
541
 * Decodes a file.
542
 */
543
static void
544
wavpack_filedecode(Decoder &decoder, Path path_fs)
545 546
{
	char error[ERRORLEN];
547
	WavpackContext *wpc = WavpackOpenFileInput(path_fs.c_str(), error,
548 549
						   OPEN_TAGS | OPEN_WVC | OPEN_NORMALIZE,
						   23);
550
	if (wpc == nullptr) {
551 552
		FormatWarning(wavpack_domain,
			      "failed to open WavPack file \"%s\": %s",
553
			      path_fs.c_str(), error);
554
		return;
555 556
	}

557 558 559
	ReplayGainInfo rgi;
	if (wavpack_replaygain(rgi, wpc))
		decoder_replay_gain(decoder, &rgi);
560

561 562
	wavpack_decode(decoder, wpc, true);

563 564 565
	WavpackCloseFile(wpc);
}

566 567
static char const *const wavpack_suffixes[] = {
	"wv",
568
	nullptr
569 570 571 572
};

static char const *const wavpack_mime_types[] = {
	"audio/x-wavpack",
573
	nullptr
574
};
575

576
const struct DecoderPlugin wavpack_decoder_plugin = {
577 578 579 580 581 582 583 584 585 586
	"wavpack",
	nullptr,
	nullptr,
	wavpack_streamdecode,
	wavpack_filedecode,
	wavpack_scan_file,
	nullptr,
	nullptr,
	wavpack_suffixes,
	wavpack_mime_types
587
};