wavpack_plugin.c 12.7 KB
Newer Older
1 2 3
/* the Music Player Daemon (MPD)
 * Copyright (C) 2003-2007 by Warren Dukes (warren.dukes@gmail.com)
 * This project's homepage is: http://www.musicpd.org
Max Kellermann's avatar
Max Kellermann committed
4
 *
5
 * WavPack support added by Laszlo Ashin <kodest@gmail.com>
Max Kellermann's avatar
Max Kellermann committed
6
 *
7 8 9 10 11 12 13 14 15 16 17 18 19 20
 * 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

21
#include "../decoder_api.h"
Max Kellermann's avatar
Max Kellermann committed
22
#include "../path.h"
23 24

#include <wavpack/wavpack.h>
25
#include <glib.h>
26

27 28 29
/* pick 1020 since its devisible for 8,16,24, and 32-bit audio */
#define CHUNK_SIZE		1020

30 31 32 33
#define ERRORLEN 80

static struct {
	const char *name;
34
	enum tag_type type;
35
} tagtypes[] = {
Max Kellermann's avatar
Max Kellermann committed
36 37 38 39 40 41 42 43 44 45 46
	{ "artist", TAG_ITEM_ARTIST },
	{ "album", TAG_ITEM_ALBUM },
	{ "title", TAG_ITEM_TITLE },
	{ "track", TAG_ITEM_TRACK },
	{ "name", TAG_ITEM_NAME },
	{ "genre", TAG_ITEM_GENRE },
	{ "date", TAG_ITEM_DATE },
	{ "composer", TAG_ITEM_COMPOSER },
	{ "performer", TAG_ITEM_PERFORMER },
	{ "comment", TAG_ITEM_COMMENT },
	{ "disc", TAG_ITEM_DISC },
47 48 49 50 51 52 53
};

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

Max Kellermann's avatar
Max Kellermann committed
61
	switch (bytes_per_sample) {
Max Kellermann's avatar
Max Kellermann committed
62 63 64 65 66 67 68
	case 1:
		while (samcnt--)
			*dst++ = *src++;
		break;
	case 2:
		while (samcnt--) {
			temp = *src++;
69
#ifdef WORDS_BIGENDIAN
Max Kellermann's avatar
Max Kellermann committed
70 71
			*dst++ = (uchar)(temp >> 8);
			*dst++ = (uchar)(temp);
72
#else
Max Kellermann's avatar
Max Kellermann committed
73 74
			*dst++ = (uchar)(temp);
			*dst++ = (uchar)(temp >> 8);
75
#endif
Max Kellermann's avatar
Max Kellermann committed
76 77 78 79 80 81
		}
		break;
	case 3:
		/* downscale to 16 bits */
		while (samcnt--) {
			temp = *src++;
82
#ifdef WORDS_BIGENDIAN
Max Kellermann's avatar
Max Kellermann committed
83 84
			*dst++ = (uchar)(temp >> 16);
			*dst++ = (uchar)(temp >> 8);
85
#else
Max Kellermann's avatar
Max Kellermann committed
86 87
			*dst++ = (uchar)(temp >> 8);
			*dst++ = (uchar)(temp >> 16);
88
#endif
Max Kellermann's avatar
Max Kellermann committed
89 90 91 92 93 94
		}
		break;
	case 4:
		/* downscale to 16 bits */
		while (samcnt--) {
			temp = *src++;
95
#ifdef WORDS_BIGENDIAN
Max Kellermann's avatar
Max Kellermann committed
96 97
			*dst++ = (uchar)(temp >> 24);
			*dst++ = (uchar)(temp >> 16);
98 99

#else
Max Kellermann's avatar
Max Kellermann committed
100 101
			*dst++ = (uchar)(temp >> 16);
			*dst++ = (uchar)(temp >> 24);
102
#endif
Max Kellermann's avatar
Max Kellermann committed
103 104
		}
		break;
105 106 107 108 109 110
	}
}

/*
 * This function converts floating point sample data to 16 bit integer.
 */
Max Kellermann's avatar
Max Kellermann committed
111
static void format_samples_float(mpd_unused int bytes_per_sample, void *buffer,
112
				 uint32_t samcnt)
113 114 115 116 117 118 119 120 121 122 123 124 125
{
	int16_t *dst = (int16_t *)buffer;
	float *src = (float *)buffer;

	while (samcnt--) {
		*dst++ = (int16_t)(*src++);
	}
}

/*
 * This does the main decoding thing.
 * Requires an already opened WavpackContext.
 */
126
static void wavpack_decode(struct decoder * decoder,
127
                           WavpackContext *wpc, bool canseek,
128
                           ReplayGainInfo *replayGainInfo)
129
{
130
	struct audio_format audio_format;
Max Kellermann's avatar
Max Kellermann committed
131 132
	void (*format_samples)(int bytes_per_sample,
			       void *buffer, uint32_t samcnt);
133
	char chunk[CHUNK_SIZE];
134
	float file_time;
135 136 137
	int samplesreq, samplesgot;
	int allsamples;
	int position, outsamplesize;
Max Kellermann's avatar
Max Kellermann committed
138
	int bytes_per_sample;
139

140
	audio_format.sample_rate = WavpackGetSampleRate(wpc);
141 142
	audio_format.channels = WavpackGetReducedChannels(wpc);
	audio_format.bits = WavpackGetBitsPerSample(wpc);
143

144 145
	if (audio_format.bits > 16)
		audio_format.bits = 16;
146 147 148 149 150

	if ((WavpackGetMode(wpc) & MODE_FLOAT) == MODE_FLOAT)
		format_samples = format_samples_float;
	else
		format_samples = format_samples_int;
Laszlo Ashin's avatar
Laszlo Ashin committed
151 152 153 154 155 156
/*
	if ((WavpackGetMode(wpc) & MODE_WVC) == MODE_WVC)
		ERROR("decoding WITH wvc!!!\n");
	else
		ERROR("decoding without wvc\n");
*/
157
	allsamples = WavpackGetNumSamples(wpc);
Max Kellermann's avatar
Max Kellermann committed
158
	bytes_per_sample = WavpackGetBytesPerSample(wpc);
159

Max Kellermann's avatar
Max Kellermann committed
160
	outsamplesize = bytes_per_sample;
161 162
	if (outsamplesize > 2)
		outsamplesize = 2;
163
	outsamplesize *= audio_format.channels;
164

165
	samplesreq = sizeof(chunk) / (4 * audio_format.channels);
166

167
	decoder_initialized(decoder, &audio_format, false,
168
			    (float)allsamples / audio_format.sample_rate);
169

170 171 172
	position = 0;

	do {
173
		if (decoder_get_command(decoder) == DECODE_COMMAND_SEEK) {
174 175 176
			if (canseek) {
				int where;

177
				where = decoder_seek_where(decoder) *
178
					audio_format.sample_rate;
179
				if (WavpackSeekSample(wpc, where)) {
180
					position = where;
181 182 183
					decoder_command_finished(decoder);
				} else
					decoder_seek_error(decoder);
184
			} else {
185
				decoder_seek_error(decoder);
186 187 188
			}
		}

189
		if (decoder_get_command(decoder) == DECODE_COMMAND_STOP)
190 191 192 193 194 195 196 197
			break;

		samplesgot = WavpackUnpackSamples(wpc,
		                                  (int32_t *)chunk, samplesreq);
		if (samplesgot > 0) {
			int bitrate = (int)(WavpackGetInstantBitrate(wpc) /
			              1000 + 0.5);
			position += samplesgot;
198
			file_time = (float)position / audio_format.sample_rate;
199

Max Kellermann's avatar
Max Kellermann committed
200
			format_samples(bytes_per_sample, chunk,
201
			               samplesgot * audio_format.channels);
202

203
			decoder_data(decoder, NULL, chunk,
Max Kellermann's avatar
Max Kellermann committed
204 205 206
				     samplesgot * outsamplesize,
				     file_time, bitrate,
				     replayGainInfo);
207 208 209 210
		}
	} while (samplesgot == samplesreq);
}

211 212 213 214 215 216 217 218
static char *wavpack_tag(WavpackContext *wpc, char *key)
{
	char *value = NULL;
	int size;

	size = WavpackGetTagItem(wpc, key, NULL, 0);
	if (size > 0) {
		size++;
219
		value = g_malloc(size);
220 221 222 223 224 225 226 227
		WavpackGetTagItem(wpc, key, value, size);
	}

	return value;
}

static ReplayGainInfo *wavpack_replaygain(WavpackContext *wpc)
{
228 229 230 231
	static char replaygain_track_gain[] = "replaygain_track_gain";
	static char replaygain_album_gain[] = "replaygain_album_gain";
	static char replaygain_track_peak[] = "replaygain_track_peak";
	static char replaygain_album_peak[] = "replaygain_album_peak";
Max Kellermann's avatar
Max Kellermann committed
232
	ReplayGainInfo *replay_gain_info;
233
	bool found = false;
234 235
	char *value;

Max Kellermann's avatar
Max Kellermann committed
236
	replay_gain_info = newReplayGainInfo();
237

238
	value = wavpack_tag(wpc, replaygain_track_gain);
239
	if (value) {
Max Kellermann's avatar
Max Kellermann committed
240
		replay_gain_info->trackGain = atof(value);
241
		free(value);
242
		found = true;
243 244
	}

245
	value = wavpack_tag(wpc, replaygain_album_gain);
246
	if (value) {
Max Kellermann's avatar
Max Kellermann committed
247
		replay_gain_info->albumGain = atof(value);
248
		free(value);
249
		found = true;
250 251
	}

252
	value = wavpack_tag(wpc, replaygain_track_peak);
253
	if (value) {
Max Kellermann's avatar
Max Kellermann committed
254
		replay_gain_info->trackPeak = atof(value);
255
		free(value);
256
		found = true;
257 258
	}

259
	value = wavpack_tag(wpc, replaygain_album_peak);
260
	if (value) {
Max Kellermann's avatar
Max Kellermann committed
261
		replay_gain_info->albumPeak = atof(value);
262
		free(value);
263
		found = true;
264 265 266 267
	}


	if (found)
Max Kellermann's avatar
Max Kellermann committed
268
		return replay_gain_info;
269

Max Kellermann's avatar
Max Kellermann committed
270
	freeReplayGainInfo(replay_gain_info);
271 272 273 274

	return NULL;
}

275 276 277
/*
 * Reads metainfo from the specified file.
 */
278
static struct tag *wavpack_tagdup(const char *fname)
279 280
{
	WavpackContext *wpc;
281
	struct tag *tag;
282 283 284
	char error[ERRORLEN];
	char *s;
	int ssize;
285
	int j;
286 287 288

	wpc = WavpackOpenFileInput(fname, error, OPEN_TAGS, 0);
	if (wpc == NULL) {
289 290
		g_warning("failed to open WavPack file \"%s\": %s\n",
			  fname, error);
291 292 293
		return NULL;
	}

294
	tag = tag_new();
295 296 297 298 299 300
	tag->time =
		(float)WavpackGetNumSamples(wpc) / WavpackGetSampleRate(wpc);

	ssize = 0;
	s = NULL;

301
	for (unsigned i = 0; i < G_N_ELEMENTS(tagtypes); ++i) {
302 303 304 305 306
		j = WavpackGetTagItem(wpc, tagtypes[i].name, NULL, 0);
		if (j > 0) {
			++j;

			if (s == NULL) {
307
				s = g_malloc(j);
308 309
				ssize = j;
			} else if (j > ssize) {
310
				char *t = (char *)g_realloc(s, j);
311 312 313 314 315
				ssize = j;
				s = t;
			}

			WavpackGetTagItem(wpc, tagtypes[i].name, s, j);
316
			tag_add_item(tag, tagtypes[i].type, s);
317 318 319
		}
	}

320
	g_free(s);
321 322 323 324 325 326 327

	WavpackCloseFile(wpc);

	return tag;
}

/*
328
 * mpd input_stream <=> WavpackStreamReader wrapper callbacks
329 330
 */

Laszlo Ashin's avatar
Laszlo Ashin committed
331
/* This struct is needed for per-stream last_byte storage. */
Max Kellermann's avatar
Max Kellermann committed
332
struct wavpack_input {
333
	struct decoder *decoder;
334
	struct input_stream *is;
Laszlo Ashin's avatar
Laszlo Ashin committed
335 336
	/* Needed for push_back_byte() */
	int last_byte;
Max Kellermann's avatar
Max Kellermann committed
337
};
Laszlo Ashin's avatar
Laszlo Ashin committed
338

339 340
static int32_t read_bytes(void *id, void *data, int32_t bcount)
{
Max Kellermann's avatar
Max Kellermann committed
341
	struct wavpack_input *isp = (struct wavpack_input *)id;
342 343 344
	uint8_t *buf = (uint8_t *)data;
	int32_t i = 0;

Laszlo Ashin's avatar
Laszlo Ashin committed
345 346 347
	if (isp->last_byte != EOF) {
		*buf++ = isp->last_byte;
		isp->last_byte = EOF;
348 349 350
		--bcount;
		++i;
	}
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366

	/* wavpack fails if we return a partial read, so we just wait
	   until the buffer is full */
	while (bcount > 0) {
		size_t nbytes = decoder_read(isp->decoder, isp->is,
					     buf, bcount);
		if (nbytes == 0)
			/* EOF, error or a decoder command */
			break;

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

	return i;
367 368 369 370
}

static uint32_t get_pos(void *id)
{
Max Kellermann's avatar
Max Kellermann committed
371
	return ((struct wavpack_input *)id)->is->offset;
372 373 374 375
}

static int set_pos_abs(void *id, uint32_t pos)
{
Max Kellermann's avatar
Max Kellermann committed
376
	return input_stream_seek(((struct wavpack_input *)id)->is, pos, SEEK_SET)
377
		? 0 : -1;
378 379 380 381
}

static int set_pos_rel(void *id, int32_t delta, int mode)
{
Max Kellermann's avatar
Max Kellermann committed
382
	return input_stream_seek(((struct wavpack_input *)id)->is, delta, mode)
383
		? 0 : -1;
384 385 386 387
}

static int push_back_byte(void *id, int c)
{
Max Kellermann's avatar
Max Kellermann committed
388
	((struct wavpack_input *)id)->last_byte = c;
389 390 391 392 393
	return 1;
}

static uint32_t get_length(void *id)
{
Max Kellermann's avatar
Max Kellermann committed
394
	return ((struct wavpack_input *)id)->is->size;
395 396 397 398
}

static int can_seek(void *id)
{
Max Kellermann's avatar
Max Kellermann committed
399
	return ((struct wavpack_input *)id)->is->seekable;
400 401 402 403 404 405 406 407 408 409 410 411 412
}

static WavpackStreamReader mpd_is_reader = {
	.read_bytes = read_bytes,
	.get_pos = get_pos,
	.set_pos_abs = set_pos_abs,
	.set_pos_rel = set_pos_rel,
	.push_back_byte = push_back_byte,
	.get_length = get_length,
	.can_seek = can_seek,
	.write_bytes = NULL /* no need to write edited tags */
};

Laszlo Ashin's avatar
Laszlo Ashin committed
413
static void
Max Kellermann's avatar
Max Kellermann committed
414 415
wavpack_input_init(struct wavpack_input *isp, struct decoder *decoder,
		   struct input_stream *is)
Laszlo Ashin's avatar
Laszlo Ashin committed
416
{
417
	isp->decoder = decoder;
Laszlo Ashin's avatar
Laszlo Ashin committed
418 419 420 421
	isp->is = is;
	isp->last_byte = EOF;
}

422 423 424
/*
 * Tries to decode the specified stream, and gives true if managed to do it.
 */
425
static bool wavpack_trydecode(struct input_stream *is)
426 427 428
{
	char error[ERRORLEN];
	WavpackContext *wpc;
Max Kellermann's avatar
Max Kellermann committed
429
	struct wavpack_input isp;
430

Max Kellermann's avatar
Max Kellermann committed
431
	wavpack_input_init(&isp, NULL, is);
Laszlo Ashin's avatar
Laszlo Ashin committed
432
	wpc = WavpackOpenFileInputEx(&mpd_is_reader, &isp, NULL, error,
433 434
	                             OPEN_STREAMING, 0);
	if (wpc == NULL)
435
		return false;
436 437 438

	WavpackCloseFile(wpc);

439
	return true;
440 441
}

442
static bool
443 444
wavpack_open_wvc(struct decoder *decoder, struct input_stream *is_wvc,
		 struct wavpack_input *wpi)
445
{
446 447
	char tmp[MPD_PATH_MAX];
	const char *utf8url;
Laszlo Ashin's avatar
Laszlo Ashin committed
448
	char *wvc_url = NULL;
449
	bool ret;
450 451
	char first_byte;
	size_t nbytes;
452 453 454 455 456 457 458

	/*
	 * As we use dc->utf8url, this function will be bad for
	 * single files. utf8url is not absolute file path :/
	 */
	utf8url = decoder_get_url(decoder, tmp);
	if (utf8url == NULL)
459
		return false;
Laszlo Ashin's avatar
Laszlo Ashin committed
460

461
	wvc_url = g_strconcat(utf8url, "c", NULL);
462
	ret = input_stream_open(is_wvc, wvc_url);
463
	g_free(wvc_url);
Laszlo Ashin's avatar
Laszlo Ashin committed
464

465
	if (!ret)
466
		return false;
467 468 469 470 471

	/*
	 * And we try to buffer in order to get know
	 * about a possible 404 error.
	 */
472 473 474 475
	nbytes = decoder_read(decoder, is_wvc,
			      &first_byte, sizeof(first_byte));
	if (nbytes == 0)
		return false;
Laszlo Ashin's avatar
Laszlo Ashin committed
476

477 478 479 480
	/* push it back */
	wavpack_input_init(wpi, decoder, is_wvc);
	wpi->last_byte = first_byte;
	return true;
481
}
Laszlo Ashin's avatar
Laszlo Ashin committed
482

483 484 485
/*
 * Decodes a stream.
 */
486
static bool
487
wavpack_streamdecode(struct decoder * decoder, struct input_stream *is)
488 489 490
{
	char error[ERRORLEN];
	WavpackContext *wpc;
491
	struct input_stream is_wvc;
492
	int open_flags = OPEN_2CH_MAX | OPEN_NORMALIZE /*| OPEN_STREAMING*/;
Max Kellermann's avatar
Max Kellermann committed
493
	struct wavpack_input isp, isp_wvc;
Laszlo Ashin's avatar
Laszlo Ashin committed
494

495
	if (wavpack_open_wvc(decoder, &is_wvc, &isp_wvc))
Laszlo Ashin's avatar
Laszlo Ashin committed
496 497
		open_flags |= OPEN_WVC;

Max Kellermann's avatar
Max Kellermann committed
498
	wavpack_input_init(&isp, decoder, is);
Laszlo Ashin's avatar
Laszlo Ashin committed
499 500
	wpc = WavpackOpenFileInputEx(&mpd_is_reader, &isp, &isp_wvc, error,
				     open_flags, 15);
501 502

	if (wpc == NULL) {
503
		g_warning("failed to open WavPack stream: %s\n", error);
504
		return false;
505 506
	}

507
	wavpack_decode(decoder, wpc, is->seekable, NULL);
508 509

	WavpackCloseFile(wpc);
510
	if (open_flags & OPEN_WVC)
511
		input_stream_close(&is_wvc);
512

513
	return true;
514 515 516
}

/*
Laszlo Ashin's avatar
Laszlo Ashin committed
517
 * Decodes a file.
518
 */
519
static bool
520
wavpack_filedecode(struct decoder *decoder, const char *fname)
521 522 523
{
	char error[ERRORLEN];
	WavpackContext *wpc;
Max Kellermann's avatar
Max Kellermann committed
524
	ReplayGainInfo *replay_gain_info;
525 526

	wpc = WavpackOpenFileInput(fname, error,
527 528
	                           OPEN_TAGS | OPEN_WVC |
	                           OPEN_2CH_MAX | OPEN_NORMALIZE, 15);
529
	if (wpc == NULL) {
530 531
		g_warning("failed to open WavPack file \"%s\": %s\n",
			  fname, error);
532
		return false;
533 534
	}

Max Kellermann's avatar
Max Kellermann committed
535
	replay_gain_info = wavpack_replaygain(wpc);
536

537
	wavpack_decode(decoder, wpc, true, replay_gain_info);
538

Max Kellermann's avatar
Max Kellermann committed
539 540
	if (replay_gain_info)
		freeReplayGainInfo(replay_gain_info);
541 542 543

	WavpackCloseFile(wpc);

544
	return true;
545 546
}

Max Kellermann's avatar
Max Kellermann committed
547 548
static char const *const wavpack_suffixes[] = { "wv", NULL };
static char const *const wavpack_mime_types[] = { "audio/x-wavpack", NULL };
549

Max Kellermann's avatar
Max Kellermann committed
550
const struct decoder_plugin wavpack_plugin = {
551 552 553 554 555
	.name = "wavpack",
	.try_decode = wavpack_trydecode,
	.stream_decode = wavpack_streamdecode,
	.file_decode = wavpack_filedecode,
	.tag_dup = wavpack_tagdup,
Max Kellermann's avatar
Max Kellermann committed
556 557
	.suffixes = wavpack_suffixes,
	.mime_types = wavpack_mime_types
558
};