WavpackDecoderPlugin.cxx 12.7 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright (C) 2003-2014 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 "Log.hxx"
32 33

#include <wavpack/wavpack.h>
34
#include <glib.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 166 167
	const float total_time = float(WavpackGetNumSamples(wpc))
		/ audio_format.sample_rate;

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

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

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

176 177 178
	DecoderCommand cmd = decoder_get_command(decoder);
	while (cmd != DecoderCommand::STOP) {
		if (cmd == DecoderCommand::SEEK) {
179
			if (can_seek) {
180 181
				unsigned where = decoder_seek_where(decoder) *
					audio_format.sample_rate;
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
	tag_handler_invoke_duration(handler, handler_ctx,
				    WavpackGetNumSamples(wpc) /
				    WavpackGetSampleRate(wpc));
289

290 291 292 293 294
	/* 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];
295
		if (name != nullptr)
296
			wavpack_scan_tag_item(wpc, name, (TagType)i,
297 298 299
					      handler, handler_ctx);
	}

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

304
	if (handler->pair != nullptr) {
305 306 307 308 309 310 311 312 313 314 315 316 317
		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);
		}
	}

318 319
	WavpackCloseFile(wpc);

320
	return true;
321 322 323
}

/*
324
 * mpd input_stream <=> WavpackStreamReader wrapper callbacks
325 326
 */

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

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

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

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

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

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

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

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

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

	return i;
384 385
}

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

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

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

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

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

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

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

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

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

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

453
	return is.GetSize();
454 455
}

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

	return is.IsSeekable();
463 464 465
}

static WavpackStreamReader mpd_is_reader = {
466 467 468 469 470 471 472 473
	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 */
474 475
};

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

486
	char *wvc_url = g_strconcat(uri, "c", nullptr);
487

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

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

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

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

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

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

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

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

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

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

	WavpackCloseFile(wpc);
532 533

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

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

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

560 561
	wavpack_decode(decoder, wpc, true);

562 563 564
	WavpackCloseFile(wpc);
}

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

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

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