DsdiffDecoderPlugin.cxx 13.2 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright (C) 2003-2014 The Music Player Daemon Project
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
 * http://www.musicpd.org
 *
 * 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.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

20 21
/* \file
 *
22
 * This plugin decodes DSDIFF data (SACD) embedded in DFF files.
23
 * The DFF code was modeled after the specification found here:
24
 * http://www.sonicstudio.com/pdf/dsd/DSDIFF_1.5_Spec.pdf
25
 *
26
 * All functions common to both DSD decoders have been moved to dsdlib
27 28
 */

29
#include "config.h"
30
#include "DsdiffDecoderPlugin.hxx"
31
#include "../DecoderAPI.hxx"
Max Kellermann's avatar
Max Kellermann committed
32
#include "input/InputStream.hxx"
33
#include "CheckAudioFormat.hxx"
34
#include "util/bit_reverse.h"
35
#include "util/Error.hxx"
36
#include "system/ByteOrder.hxx"
37
#include "tag/TagHandler.hxx"
38
#include "DsdLib.hxx"
39
#include "Log.hxx"
40

41
struct DsdiffHeader {
42
	DsdId id;
43
	DffDsdUint64 size;
44
	DsdId format;
45 46
};

47
struct DsdiffChunkHeader {
48
	DsdId id;
49
	DffDsdUint64 size;
50 51 52 53 54

	/**
	 * Read the "size" attribute from the specified header, converting it
	 * to the host byte order if needed.
	 */
55
	constexpr
56
	uint64_t GetSize() const {
57
		return size.Read();
58
	}
59 60
};

61 62 63 64 65
/** struct for DSDIFF native Artist and Title tags */
struct dsdiff_native_tag {
	uint32_t size;
};

66
struct DsdiffMetaData {
67
	unsigned sample_rate, channels;
68 69
	bool bitreverse;
	uint64_t chunk_size;
70
#ifdef HAVE_ID3TAG
71
	InputStream::offset_type id3_offset;
72 73 74
	uint64_t id3_size;
#endif
	/** offset for artist tag */
75
	InputStream::offset_type diar_offset;
76
	/** offset for title tag */
77
	InputStream::offset_type diti_offset;
78 79
};

80
static bool lsbitfirst;
81 82

static bool
83
dsdiff_init(const config_param &param)
84
{
85
	lsbitfirst = param.GetBlockValue("lsbitfirst", false);
86 87 88
	return true;
}

89
static bool
90
dsdiff_read_id(Decoder *decoder, InputStream &is,
91
	       DsdId *id)
92
{
93
	return dsdlib_read(decoder, is, id, sizeof(*id));
94 95 96
}

static bool
97
dsdiff_read_chunk_header(Decoder *decoder, InputStream &is,
98
			 DsdiffChunkHeader *header)
99
{
100
	return dsdlib_read(decoder, is, header, sizeof(*header));
101 102 103
}

static bool
104
dsdiff_read_payload(Decoder *decoder, InputStream &is,
105
		    const DsdiffChunkHeader *header,
106 107
		    void *data, size_t length)
{
108
	uint64_t size = header->GetSize();
109 110 111 112 113 114 115 116 117 118 119
	if (size != (uint64_t)length)
		return false;

	size_t nbytes = decoder_read(decoder, is, data, length);
	return nbytes == length;
}

/**
 * Read and parse a "SND" chunk inside "PROP".
 */
static bool
120
dsdiff_read_prop_snd(Decoder *decoder, InputStream &is,
121
		     DsdiffMetaData *metadata,
122
		     InputStream::offset_type end_offset)
123
{
124
	DsdiffChunkHeader header;
125
	while ((InputStream::offset_type)(is.GetOffset() + sizeof(header)) <= end_offset) {
126 127 128
		if (!dsdiff_read_chunk_header(decoder, is, &header))
			return false;

129
		InputStream::offset_type chunk_end_offset = is.GetOffset()
130
			+ header.GetSize();
131 132 133
		if (chunk_end_offset > end_offset)
			return false;

134
		if (header.id.Equals("FS  ")) {
135 136 137 138 139 140
			uint32_t sample_rate;
			if (!dsdiff_read_payload(decoder, is, &header,
						 &sample_rate,
						 sizeof(sample_rate)))
				return false;

141
			metadata->sample_rate = FromBE32(sample_rate);
142
		} else if (header.id.Equals("CHNL")) {
143
			uint16_t channels;
144
			if (header.GetSize() < sizeof(channels) ||
145
			    !dsdlib_read(decoder, is,
146
					 &channels, sizeof(channels)) ||
147
			    !dsdlib_skip_to(decoder, is, chunk_end_offset))
148 149
				return false;

150
			metadata->channels = FromBE16(channels);
151 152
		} else if (header.id.Equals("CMPR")) {
			DsdId type;
153
			if (header.GetSize() < sizeof(type) ||
154
			    !dsdlib_read(decoder, is,
155
					 &type, sizeof(type)) ||
156
			    !dsdlib_skip_to(decoder, is, chunk_end_offset))
157 158
				return false;

159
			if (!type.Equals("DSD "))
160
				/* only uncompressed DSD audio data
161 162 163 164 165
				   is implemented */
				return false;
		} else {
			/* ignore unknown chunk */

166
			if (!dsdlib_skip_to(decoder, is, chunk_end_offset))
167 168 169 170
				return false;
		}
	}

171
	return is.GetOffset() == end_offset;
172 173 174 175 176 177
}

/**
 * Read and parse a "PROP" chunk.
 */
static bool
178
dsdiff_read_prop(Decoder *decoder, InputStream &is,
179 180
		 DsdiffMetaData *metadata,
		 const DsdiffChunkHeader *prop_header)
181
{
182
	uint64_t prop_size = prop_header->GetSize();
183
	InputStream::offset_type end_offset = is.GetOffset() + prop_size;
184

185
	DsdId prop_id;
186 187 188 189
	if (prop_size < sizeof(prop_id) ||
	    !dsdiff_read_id(decoder, is, &prop_id))
		return false;

190
	if (prop_id.Equals("SND "))
191 192 193
		return dsdiff_read_prop_snd(decoder, is, metadata, end_offset);
	else
		/* ignore unknown PROP chunk */
194
		return dsdlib_skip_to(decoder, is, end_offset);
195 196
}

197
static void
198
dsdiff_handle_native_tag(InputStream &is,
199
			 const struct tag_handler *handler,
200
			 void *handler_ctx, InputStream::offset_type tagoffset,
201
			 TagType type)
202
{
203
	if (!dsdlib_skip_to(nullptr, is, tagoffset))
204 205 206 207
		return;

	struct dsdiff_native_tag metatag;

208
	if (!dsdlib_read(nullptr, is, &metatag, sizeof(metatag)))
209 210
		return;

211
	uint32_t length = FromBE32(metatag.size);
212 213 214 215 216 217 218 219 220

	/* Check and limit size of the tag to prevent a stack overflow */
	if (length == 0 || length > 60)
		return;

	char string[length];
	char *label;
	label = string;

221
	if (!dsdlib_read(nullptr, is, label, (size_t)length))
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
		return;

	string[length] = '\0';
	tag_handler_invoke_tag(handler, handler_ctx, type, label);
	return;
}

/**
 * Read and parse additional metadata chunks for tagging purposes. By default
 * dsdiff files only support equivalents for artist and title but some of the
 * extract tools add an id3 tag to provide more tags. If such id3 is found
 * this will be used for tagging otherwise the native tags (if any) will be
 * used
 */

static bool
238
dsdiff_read_metadata_extra(Decoder *decoder, InputStream &is,
239 240
			   DsdiffMetaData *metadata,
			   DsdiffChunkHeader *chunk_header,
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
			   const struct tag_handler *handler,
			   void *handler_ctx)
{

	/* skip from DSD data to next chunk header */
	if (!dsdlib_skip(decoder, is, metadata->chunk_size))
		return false;
	if (!dsdiff_read_chunk_header(decoder, is, chunk_header))
		return false;

#ifdef HAVE_ID3TAG
	metadata->id3_size = 0;
#endif

	/* Now process all the remaining chunk headers in the stream
	   and record their position and size */

258 259
	const auto size = is.GetSize();
	while (is.GetOffset() < size) {
260
		uint64_t chunk_size = chunk_header->GetSize();
261 262

		/* DIIN chunk, is directly followed by other chunks  */
263
		if (chunk_header->id.Equals("DIIN"))
264 265 266
			chunk_size = 0;

		/* DIAR chunk - DSDIFF native tag for Artist */
267
		if (chunk_header->id.Equals("DIAR")) {
268
			chunk_size = chunk_header->GetSize();
269
			metadata->diar_offset = is.GetOffset();
270 271 272
		}

		/* DITI chunk - DSDIFF native tag for Title */
273
		if (chunk_header->id.Equals("DITI")) {
274
			chunk_size = chunk_header->GetSize();
275
			metadata->diti_offset = is.GetOffset();
276 277 278
		}
#ifdef HAVE_ID3TAG
		/* 'ID3 ' chunk, offspec. Used by sacdextract */
279
		if (chunk_header->id.Equals("ID3 ")) {
280
			chunk_size = chunk_header->GetSize();
281
			metadata->id3_offset = is.GetOffset();
282 283 284 285 286 287 288 289
			metadata->id3_size = chunk_size;
		}
#endif
		if (chunk_size != 0) {
			if (!dsdlib_skip(decoder, is, chunk_size))
				break;
		}

290
		if (is.GetOffset() < size) {
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
			if (!dsdiff_read_chunk_header(decoder, is, chunk_header))
				return false;
		}
	}
	/* done processing chunk headers, process tags if any */

#ifdef HAVE_ID3TAG
	if (metadata->id3_offset != 0)
	{
		/* a ID3 tag has preference over the other tags, do not process
		   other tags if we have one */
		dsdlib_tag_id3(is, handler, handler_ctx, metadata->id3_offset);
		return true;
	}
#endif

	if (metadata->diar_offset != 0)
		dsdiff_handle_native_tag(is, handler, handler_ctx,
					 metadata->diar_offset, TAG_ARTIST);

	if (metadata->diti_offset != 0)
		dsdiff_handle_native_tag(is, handler, handler_ctx,
					 metadata->diti_offset, TAG_TITLE);
	return true;
}

317 318 319 320 321 322
/**
 * Read and parse all metadata chunks at the beginning.  Stop when the
 * first "DSD" chunk is seen, and return its header in the
 * "chunk_header" parameter.
 */
static bool
323
dsdiff_read_metadata(Decoder *decoder, InputStream &is,
324 325
		     DsdiffMetaData *metadata,
		     DsdiffChunkHeader *chunk_header)
326
{
327
	DsdiffHeader header;
328
	if (!dsdlib_read(decoder, is, &header, sizeof(header)) ||
329 330
	    !header.id.Equals("FRM8") ||
	    !header.format.Equals("DSD "))
331 332 333
		return false;

	while (true) {
334 335
		if (!dsdiff_read_chunk_header(decoder, is,
					      chunk_header))
336 337
			return false;

338
		if (chunk_header->id.Equals("PROP")) {
339 340
			if (!dsdiff_read_prop(decoder, is, metadata,
					      chunk_header))
341
					return false;
342
		} else if (chunk_header->id.Equals("DSD ")) {
343
			const uint64_t chunk_size = chunk_header->GetSize();
344
			metadata->chunk_size = chunk_size;
345 346 347
			return true;
		} else {
			/* ignore unknown chunk */
348
			const uint64_t chunk_size = chunk_header->GetSize();
349 350
			InputStream::offset_type chunk_end_offset =
				is.GetOffset() + chunk_size;
351

352
			if (!dsdlib_skip_to(decoder, is, chunk_end_offset))
353 354 355 356 357
				return false;
		}
	}
}

358 359 360 361 362 363 364
static void
bit_reverse_buffer(uint8_t *p, uint8_t *end)
{
	for (; p < end; ++p)
		*p = bit_reverse(*p);
}

365 366 367 368
/**
 * Decode one "DSD" chunk.
 */
static bool
369
dsdiff_decode_chunk(Decoder &decoder, InputStream &is,
370
		    unsigned channels,
371
		    uint64_t chunk_size)
372 373
{
	uint8_t buffer[8192];
374

375 376 377 378 379 380 381 382 383 384 385
	const size_t sample_size = sizeof(buffer[0]);
	const size_t frame_size = channels * sample_size;
	const unsigned buffer_frames = sizeof(buffer) / frame_size;
	const unsigned buffer_samples = buffer_frames * frame_size;
	const size_t buffer_size = buffer_samples * sample_size;

	while (chunk_size > 0) {
		/* see how much aligned data from the remaining chunk
		   fits into the local buffer */
		size_t now_size = buffer_size;
		if (chunk_size < (uint64_t)now_size) {
386 387
			unsigned now_frames =
				(unsigned)chunk_size / frame_size;
388 389 390 391 392 393 394 395 396
			now_size = now_frames * frame_size;
		}

		size_t nbytes = decoder_read(decoder, is, buffer, now_size);
		if (nbytes != now_size)
			return false;

		chunk_size -= nbytes;

397
		if (lsbitfirst)
398 399
			bit_reverse_buffer(buffer, buffer + nbytes);

400
		const auto cmd = decoder_data(decoder, is, buffer, nbytes, 0);
401
		switch (cmd) {
402
		case DecoderCommand::NONE:
403 404
			break;

405 406
		case DecoderCommand::START:
		case DecoderCommand::STOP:
407 408
			return false;

409
		case DecoderCommand::SEEK:
410 411

			/* Not implemented yet */
412 413 414 415
			decoder_seek_error(decoder);
			break;
		}
	}
416
	return dsdlib_skip(&decoder, is, chunk_size);
417 418 419
}

static void
420
dsdiff_stream_decode(Decoder &decoder, InputStream &is)
421
{
422
	DsdiffMetaData metadata;
423

424
	DsdiffChunkHeader chunk_header;
425
	/* check if it is is a proper DFF file */
426
	if (!dsdiff_read_metadata(&decoder, is, &metadata, &chunk_header))
427
		return;
428

429
	Error error;
430 431 432
	AudioFormat audio_format;
	if (!audio_format_init_checked(audio_format, metadata.sample_rate / 8,
				       SampleFormat::DSD,
433
				       metadata.channels, error)) {
434
		LogError(error);
435 436 437
		return;
	}

438 439 440 441 442
	/* calculate song time from DSD chunk size and sample frequency */
	uint64_t chunk_size = metadata.chunk_size;
	float songtime = ((chunk_size / metadata.channels) * 8) /
			 (float) metadata.sample_rate;

443
	/* success: file was recognized */
444
	decoder_initialized(decoder, audio_format, false, songtime);
445

446 447
	/* every iteration of the following loop decodes one "DSD"
	   chunk from a DFF file */
448

449
	while (true) {
450
		chunk_size = chunk_header.GetSize();
451

452
		if (chunk_header.id.Equals("DSD ")) {
453 454 455
			if (!dsdiff_decode_chunk(decoder, is,
						 metadata.channels,
						 chunk_size))
456
					break;
457 458
		} else {
			/* ignore other chunks */
459
			if (!dsdlib_skip(&decoder, is, chunk_size))
460 461
				break;
		}
462 463 464

		/* read next chunk header; the first one was read by
		   dsdiff_read_metadata() */
465
		if (!dsdiff_read_chunk_header(&decoder,
466 467
					      is, &chunk_header))
			break;
468 469 470
	}
}

471
static bool
472
dsdiff_scan_stream(InputStream &is,
473 474
		   gcc_unused const struct tag_handler *handler,
		   gcc_unused void *handler_ctx)
475
{
476 477
	DsdiffMetaData metadata;
	DsdiffChunkHeader chunk_header;
478

479
	/* First check for DFF metadata */
480
	if (!dsdiff_read_metadata(nullptr, is, &metadata, &chunk_header))
481
		return false;
482

483 484 485
	AudioFormat audio_format;
	if (!audio_format_init_checked(audio_format, metadata.sample_rate / 8,
				       SampleFormat::DSD,
486
				       metadata.channels, IgnoreError()))
487
		/* refuse to parse files which we cannot play anyway */
488
		return false;
489

490 491 492 493 494
	/* calculate song time and add as tag */
	unsigned songtime = ((metadata.chunk_size / metadata.channels) * 8) /
			    metadata.sample_rate;
	tag_handler_invoke_duration(handler, handler_ctx, songtime);

495
	/* Read additional metadata and created tags if available */
496
	dsdiff_read_metadata_extra(nullptr, is, &metadata, &chunk_header,
497 498
				   handler, handler_ctx);

499
	return true;
500 501 502 503
}

static const char *const dsdiff_suffixes[] = {
	"dff",
504
	nullptr
505 506 507 508
};

static const char *const dsdiff_mime_types[] = {
	"application/x-dff",
509
	nullptr
510 511
};

512
const struct DecoderPlugin dsdiff_decoder_plugin = {
513 514 515 516 517 518 519 520 521 522
	"dsdiff",
	dsdiff_init,
	nullptr,
	dsdiff_stream_decode,
	nullptr,
	nullptr,
	dsdiff_scan_stream,
	nullptr,
	dsdiff_suffixes,
	dsdiff_mime_types,
523
};