WavpackDecoderPlugin.cxx 13 KB
Newer Older
1
/*
2
 * Copyright (C) 2003-2013 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"
23
#include "InputStream.hxx"
24
#include "CheckAudioFormat.hxx"
25
#include "tag/TagHandler.hxx"
26
#include "tag/ApeTag.hxx"
27
#include "util/Error.hxx"
28
#include "util/Domain.hxx"
29
#include "util/Macros.hxx"
30
#include "Log.hxx"
31 32

#include <wavpack/wavpack.h>
33
#include <glib.h>
Max Kellermann's avatar
Max Kellermann committed
34 35

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

#define ERRORLEN 80

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

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

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

Max Kellermann's avatar
Max Kellermann committed
59
	switch (bytes_per_sample) {
60
	case 1: {
61
		int8_t *dst = (int8_t *)buffer;
62 63 64 65 66 67
		/*
		 * 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.
		 */
68
		static_assert(sizeof(*dst) <= sizeof(*src), "Wrong size");
69 70

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

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

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

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

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

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

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

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

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

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

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

136 137 138 139
/*
 * This does the main decoding thing.
 * Requires an already opened WavpackContext.
 */
140
static void
141
wavpack_decode(struct decoder *decoder, WavpackContext *wpc, bool can_seek)
142
{
143
	bool is_float;
144 145
	SampleFormat sample_format;
	AudioFormat audio_format;
146
	format_samples_t format_samples;
147
	float total_time;
148
	int bytes_per_sample, output_sample_size;
149

150 151 152 153
	is_float = (WavpackGetMode(wpc) & MODE_FLOAT) != 0;
	sample_format =
		wavpack_bits_to_sample_format(is_float,
					      WavpackGetBytesPerSample(wpc));
154

155
	Error error;
156
	if (!audio_format_init_checked(audio_format,
157 158
				       WavpackGetSampleRate(wpc),
				       sample_format,
159
				       WavpackGetNumChannels(wpc), error)) {
160
		LogError(error);
161 162 163
		return;
	}

164
	if (is_float) {
165
		format_samples = format_samples_float;
166
	} else {
167
		format_samples = format_samples_int;
168
	}
169

170 171
	total_time = WavpackGetNumSamples(wpc);
	total_time /= audio_format.sample_rate;
Max Kellermann's avatar
Max Kellermann committed
172
	bytes_per_sample = WavpackGetBytesPerSample(wpc);
173
	output_sample_size = audio_format.GetFrameSize();
174

175
	/* wavpack gives us all kind of samples in a 32-bit space */
176
	int32_t chunk[1024];
177
	const uint32_t samples_requested = ARRAY_SIZE(chunk) /
178
		audio_format.channels;
179

180
	decoder_initialized(decoder, audio_format, can_seek, total_time);
181

182 183 184
	DecoderCommand cmd = decoder_get_command(decoder);
	while (cmd != DecoderCommand::STOP) {
		if (cmd == DecoderCommand::SEEK) {
185
			if (can_seek) {
186 187
				unsigned where = decoder_seek_where(decoder) *
					audio_format.sample_rate;
188

189 190
				if (WavpackSeekSample(wpc, where)) {
					decoder_command_finished(decoder);
191
				} else {
192
					decoder_seek_error(decoder);
193
				}
194
			} else {
195
				decoder_seek_error(decoder);
196 197 198
			}
		}

199 200
		uint32_t samples_got = WavpackUnpackSamples(wpc, chunk,
							    samples_requested);
201
		if (samples_got == 0)
202 203
			break;

204 205 206 207 208
		int bitrate = (int)(WavpackGetInstantBitrate(wpc) / 1000 +
				    0.5);
		format_samples(bytes_per_sample, chunk,
			       samples_got * audio_format.channels);

209 210 211
		cmd = decoder_data(decoder, NULL, chunk,
				   samples_got * output_sample_size,
				   bitrate);
212
	}
213 214
}

215 216 217 218 219 220
/**
 * 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)
221
{
222 223 224 225 226 227
	char buffer[64];
	int ret;

	ret = WavpackGetTagItem(wpc, key, buffer, sizeof(buffer));
	if (ret <= 0)
		return false;
228

229 230
	*value_r = atof(buffer);
	return true;
231 232
}

233 234 235
static bool
wavpack_replaygain(struct replay_gain_info *replay_gain_info,
		   WavpackContext *wpc)
236
{
237
	bool found = false;
238

239
	replay_gain_info_init(replay_gain_info);
240

241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
	found |= wavpack_tag_float(
		wpc, "replaygain_track_gain",
		&replay_gain_info->tuples[REPLAY_GAIN_TRACK].gain
	);
	found |= wavpack_tag_float(
		wpc, "replaygain_track_peak",
		&replay_gain_info->tuples[REPLAY_GAIN_TRACK].peak
	);
	found |= wavpack_tag_float(
		wpc, "replaygain_album_gain",
		&replay_gain_info->tuples[REPLAY_GAIN_ALBUM].gain
	);
	found |= wavpack_tag_float(
		wpc, "replaygain_album_peak",
		&replay_gain_info->tuples[REPLAY_GAIN_ALBUM].peak
	);
257

258
	return found;
259 260
}

261 262 263 264 265 266 267 268 269 270 271 272 273 274
static void
wavpack_scan_tag_item(WavpackContext *wpc, const char *name,
		      enum tag_type type,
		      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);

}

275 276 277 278
static void
wavpack_scan_pair(WavpackContext *wpc, const char *name,
		  const struct tag_handler *handler, void *handler_ctx)
{
279
	char buffer[8192];
280 281 282 283 284 285 286
	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);
}

287 288 289
/*
 * Reads metainfo from the specified file.
 */
290 291 292
static bool
wavpack_scan_file(const char *fname,
		  const struct tag_handler *handler, void *handler_ctx)
293 294 295 296 297 298
{
	WavpackContext *wpc;
	char error[ERRORLEN];

	wpc = WavpackOpenFileInput(fname, error, OPEN_TAGS, 0);
	if (wpc == NULL) {
299 300 301
		FormatError(wavpack_domain,
			    "failed to open WavPack file \"%s\": %s",
			    fname, error);
302
		return false;
303 304
	}

305 306 307
	tag_handler_invoke_duration(handler, handler_ctx,
				    WavpackGetNumSamples(wpc) /
				    WavpackGetSampleRate(wpc));
308

309 310 311 312 313 314 315 316 317 318 319
	/* 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];
		if (name != NULL)
			wavpack_scan_tag_item(wpc, name, (enum tag_type)i,
					      handler, handler_ctx);
	}

	for (const struct tag_table *i = ape_tags; i->name != NULL; ++i)
320 321
		wavpack_scan_tag_item(wpc, i->name, i->type,
				      handler, handler_ctx);
322

323 324 325 326 327 328 329 330 331 332 333 334 335 336
	if (handler->pair != NULL) {
		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);
		}
	}

337 338
	WavpackCloseFile(wpc);

339
	return true;
340 341 342
}

/*
343
 * mpd input_stream <=> WavpackStreamReader wrapper callbacks
344 345
 */

Laszlo Ashin's avatar
Laszlo Ashin committed
346
/* This struct is needed for per-stream last_byte storage. */
Max Kellermann's avatar
Max Kellermann committed
347
struct wavpack_input {
348
	struct decoder *decoder;
349
	struct input_stream *is;
Laszlo Ashin's avatar
Laszlo Ashin committed
350 351
	/* Needed for push_back_byte() */
	int last_byte;
Max Kellermann's avatar
Max Kellermann committed
352
};
Laszlo Ashin's avatar
Laszlo Ashin committed
353

354 355 356 357 358 359 360
/**
 * Little wrapper for struct wavpack_input to cast from void *.
 */
static struct wavpack_input *
wpin(void *id)
{
	assert(id);
361
	return (struct wavpack_input *)id;
362 363
}

364
static int32_t
365
wavpack_input_read_bytes(void *id, void *data, int32_t bcount)
366 367 368 369
{
	uint8_t *buf = (uint8_t *)data;
	int32_t i = 0;

370 371 372
	if (wpin(id)->last_byte != EOF) {
		*buf++ = wpin(id)->last_byte;
		wpin(id)->last_byte = EOF;
373 374 375
		--bcount;
		++i;
	}
376 377 378 379

	/* wavpack fails if we return a partial read, so we just wait
	   until the buffer is full */
	while (bcount > 0) {
380 381 382
		size_t nbytes = decoder_read(
			wpin(id)->decoder, wpin(id)->is, buf, bcount
		);
383
		if (nbytes == 0) {
384 385
			/* EOF, error or a decoder command */
			break;
386
		}
387 388 389 390 391 392 393

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

	return i;
394 395
}

396
static uint32_t
397
wavpack_input_get_pos(void *id)
398
{
399
	return wpin(id)->is->offset;
400 401
}

402
static int
403
wavpack_input_set_pos_abs(void *id, uint32_t pos)
404
{
405
	return wpin(id)->is->LockSeek(pos, SEEK_SET, IgnoreError()) ? 0 : -1;
406 407
}

408
static int
409
wavpack_input_set_pos_rel(void *id, int32_t delta, int mode)
410
{
411
	return wpin(id)->is->LockSeek(delta, mode, IgnoreError()) ? 0 : -1;
412 413
}

414
static int
415
wavpack_input_push_back_byte(void *id, int c)
416
{
417 418 419 420 421 422
	if (wpin(id)->last_byte == EOF) {
		wpin(id)->last_byte = c;
		return c;
	} else {
		return EOF;
	}
423 424
}

425
static uint32_t
426
wavpack_input_get_length(void *id)
427
{
428 429 430
	if (wpin(id)->is->size < 0)
		return 0;

431
	return wpin(id)->is->size;
432 433
}

434
static int
435
wavpack_input_can_seek(void *id)
436
{
437
	return wpin(id)->is->seekable;
438 439 440
}

static WavpackStreamReader mpd_is_reader = {
441 442 443 444 445 446 447 448
	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 */
449 450
};

Laszlo Ashin's avatar
Laszlo Ashin committed
451
static void
Max Kellermann's avatar
Max Kellermann committed
452 453
wavpack_input_init(struct wavpack_input *isp, struct decoder *decoder,
		   struct input_stream *is)
Laszlo Ashin's avatar
Laszlo Ashin committed
454
{
455
	isp->decoder = decoder;
Laszlo Ashin's avatar
Laszlo Ashin committed
456 457 458 459
	isp->is = is;
	isp->last_byte = EOF;
}

460
static struct input_stream *
461
wavpack_open_wvc(struct decoder *decoder, const char *uri,
462
		 Mutex &mutex, Cond &cond,
463
		 struct wavpack_input *wpi)
464
{
465
	struct input_stream *is_wvc;
Laszlo Ashin's avatar
Laszlo Ashin committed
466
	char *wvc_url = NULL;
467 468
	char first_byte;
	size_t nbytes;
469 470 471 472 473

	/*
	 * As we use dc->utf8url, this function will be bad for
	 * single files. utf8url is not absolute file path :/
	 */
474
	if (uri == NULL)
475
		return nullptr;
476

477
	wvc_url = g_strconcat(uri, "c", NULL);
478

479
	is_wvc = input_stream::Open(wvc_url, mutex, cond, IgnoreError());
480
	g_free(wvc_url);
Laszlo Ashin's avatar
Laszlo Ashin committed
481

482 483
	if (is_wvc == NULL)
		return NULL;
484 485 486 487 488

	/*
	 * And we try to buffer in order to get know
	 * about a possible 404 error.
	 */
489 490 491
	nbytes = decoder_read(
		decoder, is_wvc, &first_byte, sizeof(first_byte)
	);
492
	if (nbytes == 0) {
493
		is_wvc->Close();
494
		return NULL;
495
	}
Laszlo Ashin's avatar
Laszlo Ashin committed
496

497 498 499
	/* push it back */
	wavpack_input_init(wpi, decoder, is_wvc);
	wpi->last_byte = first_byte;
500
	return is_wvc;
501
}
Laszlo Ashin's avatar
Laszlo Ashin committed
502

503 504 505
/*
 * Decodes a stream.
 */
506
static void
507
wavpack_streamdecode(struct decoder * decoder, struct input_stream *is)
508 509 510
{
	char error[ERRORLEN];
	WavpackContext *wpc;
511
	struct input_stream *is_wvc;
512
	int open_flags = OPEN_NORMALIZE;
Max Kellermann's avatar
Max Kellermann committed
513
	struct wavpack_input isp, isp_wvc;
514
	bool can_seek = is->seekable;
Laszlo Ashin's avatar
Laszlo Ashin committed
515

516 517
	is_wvc = wavpack_open_wvc(decoder, is->uri.c_str(),
				  is->mutex, is->cond,
518
				  &isp_wvc);
519
	if (is_wvc != NULL) {
Laszlo Ashin's avatar
Laszlo Ashin committed
520
		open_flags |= OPEN_WVC;
521
		can_seek &= is_wvc->seekable;
522
	}
Laszlo Ashin's avatar
Laszlo Ashin committed
523

524 525 526 527
	if (!can_seek) {
		open_flags |= OPEN_STREAMING;
	}

Max Kellermann's avatar
Max Kellermann committed
528
	wavpack_input_init(&isp, decoder, is);
529
	wpc = WavpackOpenFileInputEx(
530 531 532
		&mpd_is_reader, &isp,
		open_flags & OPEN_WVC ? &isp_wvc : NULL,
		error, open_flags, 23
533
	);
534 535

	if (wpc == NULL) {
536 537
		FormatError(wavpack_domain,
			    "failed to open WavPack stream: %s", error);
538
		return;
539 540
	}

541
	wavpack_decode(decoder, wpc, can_seek);
542 543

	WavpackCloseFile(wpc);
544
	if (open_flags & OPEN_WVC) {
545
		is_wvc->Close();
546
	}
547 548 549
}

/*
Laszlo Ashin's avatar
Laszlo Ashin committed
550
 * Decodes a file.
551
 */
552
static void
553
wavpack_filedecode(struct decoder *decoder, const char *fname)
554 555 556 557
{
	char error[ERRORLEN];
	WavpackContext *wpc;

558 559
	wpc = WavpackOpenFileInput(
		fname, error,
560
		OPEN_TAGS | OPEN_WVC | OPEN_NORMALIZE, 23
561
	);
562
	if (wpc == NULL) {
563 564 565
		FormatWarning(wavpack_domain,
			      "failed to open WavPack file \"%s\": %s",
			      fname, error);
566
		return;
567 568
	}

569 570 571
	struct replay_gain_info replay_gain_info;
	if (wavpack_replaygain(&replay_gain_info, wpc))
		decoder_replay_gain(decoder, &replay_gain_info);
572

573 574
	wavpack_decode(decoder, wpc, true);

575 576 577
	WavpackCloseFile(wpc);
}

578 579 580 581 582 583 584 585 586
static char const *const wavpack_suffixes[] = {
	"wv",
	NULL
};

static char const *const wavpack_mime_types[] = {
	"audio/x-wavpack",
	NULL
};
587

588
const struct decoder_plugin wavpack_decoder_plugin = {
589 590 591 592 593 594 595 596 597 598
	"wavpack",
	nullptr,
	nullptr,
	wavpack_streamdecode,
	wavpack_filedecode,
	wavpack_scan_file,
	nullptr,
	nullptr,
	wavpack_suffixes,
	wavpack_mime_types
599
};