WavpackDecoderPlugin.cxx 13.2 KB
Newer Older
1
/*
2
 * Copyright 2003-2018 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/Handler.hxx"
26
#include "fs/Path.hxx"
27
#include "util/Macros.hxx"
28
#include "util/Alloc.hxx"
29
#include "util/ScopeExit.hxx"
30
#include "util/RuntimeError.hxx"
31 32

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

34
#include <stdexcept>
35
#include <memory>
36

37 38
#include <cstdlib>

Max Kellermann's avatar
Max Kellermann committed
39
#include <assert.h>
40 41 42

#define ERRORLEN 80

43 44
#ifdef OPEN_DSD_AS_PCM
/* libWavPack supports DSD since version 5 */
45 46 47
  #ifdef ENABLE_DSD
static constexpr int OPEN_DSD_FLAG = OPEN_DSD_NATIVE;
  #else
48
static constexpr int OPEN_DSD_FLAG = OPEN_DSD_AS_PCM;
49
  #endif
50 51 52 53 54
#else
/* no DSD support in this libWavPack version */
static constexpr int OPEN_DSD_FLAG = 0;
#endif

55 56 57 58 59 60 61 62 63 64 65 66 67
static WavpackContext *
WavpackOpenInput(Path path, int flags, int norm_offset)
{
	char error[ERRORLEN];
	auto *wpc = WavpackOpenFileInput(path.c_str(), error,
					 flags, norm_offset);
	if (wpc == nullptr)
		throw FormatRuntimeError("failed to open WavPack file \"%s\": %s",
					 path.c_str(), error);

	return wpc;
}

68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
#ifdef OPEN_DSD_AS_PCM

static WavpackContext *
WavpackOpenInput(WavpackStreamReader64 *reader, void *wv_id, void *wvc_id,
		 int flags, int norm_offset)
{
	char error[ERRORLEN];
	auto *wpc = WavpackOpenFileInputEx64(reader, wv_id, wvc_id, error,
					   flags, norm_offset);
	if (wpc == nullptr)
		throw FormatRuntimeError("failed to open WavPack stream: %s",
					 error);

	return wpc;
}

#else

86 87 88 89 90 91 92 93 94 95 96 97 98 99
static WavpackContext *
WavpackOpenInput(WavpackStreamReader *reader, void *wv_id, void *wvc_id,
		 int flags, int norm_offset)
{
	char error[ERRORLEN];
	auto *wpc = WavpackOpenFileInputEx(reader, wv_id, wvc_id, error,
					   flags, norm_offset);
	if (wpc == nullptr)
		throw FormatRuntimeError("failed to open WavPack stream: %s",
					 error);

	return wpc;
}

100 101
#endif

102 103
gcc_pure
static SignedSongTime
104
GetDuration(WavpackContext *wpc) noexcept
105
{
106 107 108 109 110 111 112
#ifdef OPEN_DSD_AS_PCM
	/* libWavPack 5 */
	const auto n_samples = WavpackGetNumSamples64(wpc);
	if (n_samples == -1)
		/* unknown */
		return SignedSongTime::Negative();
#else
113
	const uint32_t n_samples = WavpackGetNumSamples(wpc);
114 115 116
	if (n_samples == uint32_t(-1))
		/* unknown */
		return SignedSongTime::Negative();
117
#endif
118

119 120 121 122
	return SongTime::FromScale<uint64_t>(n_samples,
					     WavpackGetSampleRate(wpc));
}

123
/*
124
 * Convert integer samples.
125
 */
126
template<typename T>
Max Kellermann's avatar
Max Kellermann committed
127
static void
128
format_samples_int(void *buffer, uint32_t count)
129
{
130
	int32_t *src = (int32_t *)buffer;
131
	T *dst = (T *)buffer;
132 133 134 135 136 137 138 139
	/*
	 * 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.
	 */
	static_assert(sizeof(*dst) <= sizeof(*src), "Wrong size");

140
	/* pass through and align samples */
141
	std::copy_n(src, count, dst);
142 143 144
}

/*
145
 * No conversion necessary.
146
 */
147
static void
148
format_samples_nop(gcc_unused void *buffer, gcc_unused uint32_t count)
149
{
150
	/* do nothing */
151 152
}

153 154 155
/**
 * Choose a MPD sample format from libwavpacks' number of bits.
 */
156
static SampleFormat
157 158 159 160 161
wavpack_bits_to_sample_format(bool is_float,
#if defined(OPEN_DSD_AS_PCM) && defined(ENABLE_DSD)
			      bool is_dsd,
#endif
			      int bytes_per_sample)
162 163
{
	if (is_float)
164
		return SampleFormat::FLOAT;
165

166 167 168 169 170
#if defined(OPEN_DSD_AS_PCM) && defined(ENABLE_DSD)
	if (is_dsd)
		return SampleFormat::DSD;
#endif

171 172
	switch (bytes_per_sample) {
	case 1:
173
		return SampleFormat::S8;
174 175

	case 2:
176
		return SampleFormat::S16;
177 178

	case 3:
179
		return SampleFormat::S24_P32;
180 181

	case 4:
182
		return SampleFormat::S32;
183 184

	default:
185
		return SampleFormat::UNDEFINED;
186 187 188
	}
}

189 190
static AudioFormat
CheckAudioFormat(WavpackContext *wpc)
191
{
192
	const bool is_float = (WavpackGetMode(wpc) & MODE_FLOAT) != 0;
193 194 195
#if defined(OPEN_DSD_AS_PCM) && defined(ENABLE_DSD)
	const bool is_dsd = (WavpackGetQualifyMode(wpc) & QMODE_DSD_AUDIO) != 0;
#endif
196
	SampleFormat sample_format =
197
		wavpack_bits_to_sample_format(is_float,
198 199 200
#if defined(OPEN_DSD_AS_PCM) && defined(ENABLE_DSD)
					      is_dsd,
#endif
201
					      WavpackGetBytesPerSample(wpc));
202

203 204 205 206 207 208 209 210 211 212 213 214 215
	return CheckAudioFormat(WavpackGetSampleRate(wpc),
				sample_format,
				WavpackGetReducedChannels(wpc));
}

/*
 * This does the main decoding thing.
 * Requires an already opened WavpackContext.
 */
static void
wavpack_decode(DecoderClient &client, WavpackContext *wpc, bool can_seek)
{
	const auto audio_format = CheckAudioFormat(wpc);
216

217
	auto *format_samples = format_samples_nop;
218
	if (audio_format.format == SampleFormat::DSD)
219
		format_samples = format_samples_int<uint8_t>;
220
	else if (audio_format.format != SampleFormat::FLOAT) {
221 222
		switch (WavpackGetBytesPerSample(wpc)) {
		case 1:
223
			format_samples = format_samples_int<int8_t>;
224 225 226
			break;

		case 2:
227
			format_samples = format_samples_int<int16_t>;
228 229 230
			break;
		}
	}
231

232
	client.Ready(audio_format, can_seek, GetDuration(wpc));
233 234

	const int output_sample_size = audio_format.GetFrameSize();
235

236
	/* wavpack gives us all kind of samples in a 32-bit space */
237
	int32_t chunk[1024];
238
	const uint32_t samples_requested = ARRAY_SIZE(chunk) /
239
		audio_format.channels;
240

241
	DecoderCommand cmd = client.GetCommand();
242 243
	while (cmd != DecoderCommand::STOP) {
		if (cmd == DecoderCommand::SEEK) {
244
			if (can_seek) {
245
				auto where = client.GetSeekFrame();
246 247 248 249 250 251
#ifdef OPEN_DSD_AS_PCM
				bool success = WavpackSeekSample64(wpc, where);
#else
				bool success = WavpackSeekSample(wpc, where);
#endif
				if (!success) {
252
					/* seek errors are fatal */
253
					client.SeekError();
254
					break;
255
				}
256 257

				client.CommandFinished();
258
			} else {
259
				client.SeekError();
260 261 262
			}
		}

263 264
		uint32_t samples_got = WavpackUnpackSamples(wpc, chunk,
							    samples_requested);
265
		if (samples_got == 0)
266 267
			break;

268 269
		int bitrate = (int)(WavpackGetInstantBitrate(wpc) / 1000 +
				    0.5);
270
		format_samples(chunk, samples_got * audio_format.channels);
271

272 273 274
		cmd = client.SubmitData(nullptr, chunk,
					samples_got * output_sample_size,
					bitrate);
275
	}
276 277 278
}

/*
279
 * #InputStream <=> WavpackStreamReader wrapper callbacks
280 281
 */

Laszlo Ashin's avatar
Laszlo Ashin committed
282
/* This struct is needed for per-stream last_byte storage. */
283
struct WavpackInput {
284
	DecoderClient *const client;
285
	InputStream &is;
Laszlo Ashin's avatar
Laszlo Ashin committed
286 287
	/* Needed for push_back_byte() */
	int last_byte;
288

289
	constexpr WavpackInput(DecoderClient *_client, InputStream &_is)
290
		:client(_client), is(_is), last_byte(EOF) {}
291 292

	int32_t ReadBytes(void *data, size_t bcount);
293 294 295 296 297 298 299 300 301

	InputStream::offset_type GetPos() const {
		return is.GetOffset();
	}

	int SetPosAbs(InputStream::offset_type pos) {
		try {
			is.LockSeek(pos);
			return 0;
302
		} catch (...) {
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
			return -1;
		}
	}

	int SetPosRel(InputStream::offset_type delta, int mode) {
		offset_type offset = delta;
		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 SetPosAbs(offset);
	}

	int PushBackByte(int c) {
		if (last_byte == EOF) {
			last_byte = c;
			return c;
		} else {
			return EOF;
		}
	}

	InputStream::offset_type GetLength() const {
		if (!is.KnownSize())
			return 0;

		return is.GetSize();
	}

	bool CanSeek() const {
		return is.IsSeekable();
	}
Max Kellermann's avatar
Max Kellermann committed
350
};
Laszlo Ashin's avatar
Laszlo Ashin committed
351

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

362
static int32_t
363
wavpack_input_read_bytes(void *id, void *data, int32_t bcount)
364 365 366 367 368 369
{
	return wpin(id)->ReadBytes(data, bcount);
}

int32_t
WavpackInput::ReadBytes(void *data, size_t bcount)
370 371 372 373
{
	uint8_t *buf = (uint8_t *)data;
	int32_t i = 0;

374 375 376
	if (last_byte != EOF) {
		*buf++ = last_byte;
		last_byte = EOF;
377 378 379
		--bcount;
		++i;
	}
380 381 382 383

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

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

	return i;
396 397
}

398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
#ifdef OPEN_DSD_AS_PCM

static int64_t
wavpack_input_get_pos(void *id)
{
	WavpackInput &wpi = *wpin(id);
	return wpi.GetPos();
}

static int
wavpack_input_set_pos_abs(void *id, int64_t pos)
{
	WavpackInput &wpi = *wpin(id);
	return wpi.SetPosAbs(pos);
}

static int
wavpack_input_set_pos_rel(void *id, int64_t delta, int mode)
{
	WavpackInput &wpi = *wpin(id);
	return wpi.SetPosRel(delta, mode);
}

#else

423
static uint32_t
424
wavpack_input_get_pos(void *id)
425
{
426
	WavpackInput &wpi = *wpin(id);
427
	return wpi.GetPos();
428 429
}

430
static int
431
wavpack_input_set_pos_abs(void *id, uint32_t pos)
432
{
433
	WavpackInput &wpi = *wpin(id);
434
	return wpi.SetPosAbs(pos);
435 436
}

437
static int
438
wavpack_input_set_pos_rel(void *id, int32_t delta, int mode)
439
{
440
	WavpackInput &wpi = *wpin(id);
441
	return wpi.SetPosRel(delta, mode);
442 443
}

444 445
#endif

446
static int
447
wavpack_input_push_back_byte(void *id, int c)
448
{
449
	WavpackInput &wpi = *wpin(id);
450
	return wpi.PushBackByte(c);
451 452
}

453 454 455 456 457 458 459 460 461 462 463
#ifdef OPEN_DSD_AS_PCM

static int64_t
wavpack_input_get_length(void *id)
{
	WavpackInput &wpi = *wpin(id);
	return wpi.GetLength();
}

#else

464
static uint32_t
465
wavpack_input_get_length(void *id)
466
{
467
	WavpackInput &wpi = *wpin(id);
468
	return wpi.GetLength();
469 470
}

471 472
#endif

473
static int
474
wavpack_input_can_seek(void *id)
475
{
476
	WavpackInput &wpi = *wpin(id);
477
	return wpi.CanSeek();
478 479
}

480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
#ifdef OPEN_DSD_AS_PCM

static WavpackStreamReader64 mpd_is_reader = {
	wavpack_input_read_bytes,
	nullptr, /* write_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, /* truncate_here */
	nullptr, /* close */
};

#else

497
static WavpackStreamReader mpd_is_reader = {
498 499 500 501 502 503 504 505
	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 */
506 507
};

508 509
#endif

510
static InputStreamPtr
511
wavpack_open_wvc(DecoderClient &client, const char *uri)
512
{
513 514 515 516
	/*
	 * As we use dc->utf8url, this function will be bad for
	 * single files. utf8url is not absolute file path :/
	 */
517
	if (uri == nullptr)
518
		return nullptr;
519

520
	char *wvc_url = xstrcatdup(uri, "c");
521 522 523
	AtScopeExit(wvc_url) {
		free(wvc_url);
	};
524

525
	try {
526
		return client.OpenUri(uri);
527
	} catch (...) {
528 529
		return nullptr;
	}
530
}
Laszlo Ashin's avatar
Laszlo Ashin committed
531

532 533 534
/*
 * Decodes a stream.
 */
535
static void
536
wavpack_streamdecode(DecoderClient &client, InputStream &is)
537
{
538
	int open_flags = OPEN_DSD_FLAG | OPEN_NORMALIZE;
539
	bool can_seek = is.IsSeekable();
Laszlo Ashin's avatar
Laszlo Ashin committed
540

541
	std::unique_ptr<WavpackInput> wvc;
542
	auto is_wvc = wavpack_open_wvc(client, is.GetURI());
543
	if (is_wvc) {
Laszlo Ashin's avatar
Laszlo Ashin committed
544
		open_flags |= OPEN_WVC;
545
		can_seek &= is_wvc->IsSeekable();
Laszlo Ashin's avatar
Laszlo Ashin committed
546

547
		wvc.reset(new WavpackInput(&client, *is_wvc));
548
	}
549

550 551 552 553
	if (!can_seek) {
		open_flags |= OPEN_STREAMING;
	}

554
	WavpackInput isp(&client, is);
555

556 557
	auto *wpc = WavpackOpenInput(&mpd_is_reader, &isp, wvc.get(),
				     open_flags, 0);
558 559 560
	AtScopeExit(wpc) {
		WavpackCloseFile(wpc);
	};
561

562
	wavpack_decode(client, wpc, can_seek);
563 564 565
}

/*
Laszlo Ashin's avatar
Laszlo Ashin committed
566
 * Decodes a file.
567
 */
568
static void
569
wavpack_filedecode(DecoderClient &client, Path path_fs)
570
{
571 572 573
	auto *wpc = WavpackOpenInput(path_fs,
				     OPEN_DSD_FLAG | OPEN_NORMALIZE | OPEN_WVC,
				     0);
574 575 576 577
	AtScopeExit(wpc) {
		WavpackCloseFile(wpc);
	};

578
	wavpack_decode(client, wpc, true);
579 580
}

581 582 583 584 585 586 587 588 589 590 591 592 593
static void
Scan(WavpackContext *wpc,TagHandler &handler) noexcept
{
	try {
		handler.OnAudioFormat(CheckAudioFormat(wpc));
	} catch (...) {
	}

	const auto duration = GetDuration(wpc);
	if (!duration.IsNegative())
		handler.OnDuration(SongTime(duration));
}

594 595 596 597
/*
 * Reads metainfo from the specified file.
 */
static bool
598
wavpack_scan_file(Path path_fs, TagHandler &handler) noexcept
599
{
600 601 602 603 604 605 606 607
	WavpackContext *wpc;

	try {
		wpc = WavpackOpenInput(path_fs, OPEN_DSD_FLAG, 0);
	} catch (...) {
		return false;
	}

608 609 610 611
	AtScopeExit(wpc) {
		WavpackCloseFile(wpc);
	};

612
	Scan(wpc, handler);
613 614 615
	return true;
}

616
static bool
617
wavpack_scan_stream(InputStream &is, TagHandler &handler) noexcept
618 619
{
	WavpackInput isp(nullptr, is);
620 621 622 623 624 625 626 627 628

	WavpackContext *wpc;
	try {
		wpc = WavpackOpenInput(&mpd_is_reader, &isp, nullptr,
					     OPEN_DSD_FLAG, 0);
	} catch (...) {
		return false;
	}

629 630 631 632
	AtScopeExit(wpc) {
		WavpackCloseFile(wpc);
	};

633
	Scan(wpc, handler);
634 635 636
	return true;
}

637 638
static char const *const wavpack_suffixes[] = {
	"wv",
639
	nullptr
640 641 642 643
};

static char const *const wavpack_mime_types[] = {
	"audio/x-wavpack",
644
	nullptr
645
};
646

647
const struct DecoderPlugin wavpack_decoder_plugin = {
648 649 650 651 652 653
	"wavpack",
	nullptr,
	nullptr,
	wavpack_streamdecode,
	wavpack_filedecode,
	wavpack_scan_file,
654
	wavpack_scan_stream,
655 656 657
	nullptr,
	wavpack_suffixes,
	wavpack_mime_types
658
};