WavpackDecoderPlugin.cxx 13.1 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2021 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 "pcm/CheckAudioFormat.hxx"
25
#include "tag/Handler.hxx"
26
#include "fs/Path.hxx"
27
#include "util/AllocatedString.hxx"
28
#include "util/Math.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 <algorithm>
35 36
#include <cassert>
#include <cstdlib>
37
#include <iterator>
38
#include <memory>
39

40 41
using std::string_view_literals::operator""sv;

42 43
#define ERRORLEN 80

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

56 57 58 59 60 61 62 63 64 65 66 67 68
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;
}

69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
#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

87 88 89 90 91 92 93 94 95 96 97 98 99 100
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;
}

101 102
#endif

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

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

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

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

/*
146
 * No conversion necessary.
147
 */
148
static void
Rosen Penev's avatar
Rosen Penev committed
149
format_samples_nop([[maybe_unused]] void *buffer, [[maybe_unused]] uint32_t count)
150
{
151
	/* do nothing */
152 153
}

154 155 156
/**
 * Choose a MPD sample format from libwavpacks' number of bits.
 */
157
static SampleFormat
158 159 160 161 162
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)
163 164
{
	if (is_float)
165
		return SampleFormat::FLOAT;
166

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

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

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

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

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

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

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

204 205 206 207 208 209 210 211 212 213 214 215 216
	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);
217

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

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

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

	const int output_sample_size = audio_format.GetFrameSize();
236

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

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

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

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

269
		int bitrate = lround(WavpackGetInstantBitrate(wpc) / 1000);
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
	[[nodiscard]] InputStream::offset_type GetPos() const {
295 296 297 298 299 300 301
		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
			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;
		}
	}

340
	[[nodiscard]] InputStream::offset_type GetLength() const {
341 342 343 344 345 346
		if (!is.KnownSize())
			return 0;

		return is.GetSize();
	}

347
	[[nodiscard]] bool CanSeek() const {
348 349
		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
{
Max Kellermann's avatar
Max Kellermann committed
371
	auto *buf = (uint8_t *)data;
372 373
	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
#ifdef OPEN_DSD_AS_PCM

static int64_t
wavpack_input_get_pos(void *id)
{
403
	const auto &wpi = *wpin(id);
404 405 406 407 408 409
	return wpi.GetPos();
}

static int
wavpack_input_set_pos_abs(void *id, int64_t pos)
{
410
	auto &wpi = *wpin(id);
411 412 413 414 415 416
	return wpi.SetPosAbs(pos);
}

static int
wavpack_input_set_pos_rel(void *id, int64_t delta, int mode)
{
417
	auto &wpi = *wpin(id);
418 419 420 421 422
	return wpi.SetPosRel(delta, mode);
}

#else

423
static uint32_t
424
wavpack_input_get_pos(void *id)
425
{
426
	const auto &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
	auto &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
	auto &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
	auto &wpi = *wpin(id);
450
	return wpi.PushBackByte(c);
451 452
}

453 454 455 456 457
#ifdef OPEN_DSD_AS_PCM

static int64_t
wavpack_input_get_length(void *id)
{
458
	const auto &wpi = *wpin(id);
459 460 461 462 463
	return wpi.GetLength();
}

#else

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

471 472
#endif

473
static int
474
wavpack_input_can_seek(void *id)
475
{
476
	const auto &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, std::string_view uri)
512
{
513
	const AllocatedString wvc_url{uri, "c"sv};
514

515
	try {
516
		return client.OpenUri(wvc_url.c_str());
517
	} catch (...) {
518 519
		return nullptr;
	}
520
}
Laszlo Ashin's avatar
Laszlo Ashin committed
521

522 523 524
/*
 * Decodes a stream.
 */
525
static void
526
wavpack_streamdecode(DecoderClient &client, InputStream &is)
527
{
528
	int open_flags = OPEN_DSD_FLAG | OPEN_NORMALIZE;
529
	bool can_seek = is.IsSeekable();
Laszlo Ashin's avatar
Laszlo Ashin committed
530

531
	std::unique_ptr<WavpackInput> wvc;
532
	auto is_wvc = wavpack_open_wvc(client, is.GetURI());
533
	if (is_wvc) {
Laszlo Ashin's avatar
Laszlo Ashin committed
534
		open_flags |= OPEN_WVC;
535
		can_seek &= is_wvc->IsSeekable();
Laszlo Ashin's avatar
Laszlo Ashin committed
536

537
		wvc = std::make_unique<WavpackInput>(&client, *is_wvc);
538
	}
539

540 541 542 543
	if (!can_seek) {
		open_flags |= OPEN_STREAMING;
	}

544
	WavpackInput isp(&client, is);
545

546 547
	auto *wpc = WavpackOpenInput(&mpd_is_reader, &isp, wvc.get(),
				     open_flags, 0);
548 549 550
	AtScopeExit(wpc) {
		WavpackCloseFile(wpc);
	};
551

552
	wavpack_decode(client, wpc, can_seek);
553 554 555
}

/*
Laszlo Ashin's avatar
Laszlo Ashin committed
556
 * Decodes a file.
557
 */
558
static void
559
wavpack_filedecode(DecoderClient &client, Path path_fs)
560
{
561 562 563
	auto *wpc = WavpackOpenInput(path_fs,
				     OPEN_DSD_FLAG | OPEN_NORMALIZE | OPEN_WVC,
				     0);
564 565 566 567
	AtScopeExit(wpc) {
		WavpackCloseFile(wpc);
	};

568
	wavpack_decode(client, wpc, true);
569 570
}

571 572 573 574 575 576 577 578 579 580 581 582 583
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));
}

584 585 586 587
/*
 * Reads metainfo from the specified file.
 */
static bool
588
wavpack_scan_file(Path path_fs, TagHandler &handler) noexcept
589
{
590 591 592 593 594 595 596 597
	WavpackContext *wpc;

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

598 599 600 601
	AtScopeExit(wpc) {
		WavpackCloseFile(wpc);
	};

602
	Scan(wpc, handler);
603 604 605
	return true;
}

606
static bool
607
wavpack_scan_stream(InputStream &is, TagHandler &handler)
608 609
{
	WavpackInput isp(nullptr, is);
610 611 612 613 614 615 616 617 618

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

619 620 621 622
	AtScopeExit(wpc) {
		WavpackCloseFile(wpc);
	};

623
	Scan(wpc, handler);
624 625 626
	return true;
}

627
static constexpr const char *wavpack_suffixes[] = {
628
	"wv",
629
	nullptr
630 631
};

632
static constexpr const char *wavpack_mime_types[] = {
633
	"audio/x-wavpack",
634
	nullptr
635
};
636

637 638 639 640 641
constexpr DecoderPlugin wavpack_decoder_plugin =
	DecoderPlugin("wavpack", wavpack_streamdecode, wavpack_scan_stream,
		      wavpack_filedecode, wavpack_scan_file)
	.WithSuffixes(wavpack_suffixes)
	.WithMimeTypes(wavpack_mime_types);