DsdiffDecoderPlugin.cxx 13.3 KB
Newer Older
1
/*
2
 * Copyright (C) 2003-2013 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"
32
#include "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

#include <unistd.h>
42
#include <stdio.h> /* for SEEK_SET, SEEK_CUR */
43

44
struct DsdiffHeader {
45
	DsdId id;
46
	DsdUint64 size;
47
	DsdId format;
48 49
};

50
struct DsdiffChunkHeader {
51
	DsdId id;
52
	DsdUint64 size;
53 54 55 56 57

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

64 65 66 67 68
/** struct for DSDIFF native Artist and Title tags */
struct dsdiff_native_tag {
	uint32_t size;
};

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

83
static bool lsbitfirst;
84 85

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

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

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

static bool
107
dsdiff_read_payload(Decoder *decoder, InputStream &is,
108
		    const DsdiffChunkHeader *header,
109 110
		    void *data, size_t length)
{
111
	uint64_t size = header->GetSize();
112 113 114 115 116 117 118 119 120 121 122
	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
123
dsdiff_read_prop_snd(Decoder *decoder, InputStream &is,
124
		     DsdiffMetaData *metadata,
125
		     InputStream::offset_type end_offset)
126
{
127
	DsdiffChunkHeader header;
128
	while ((InputStream::offset_type)(is.GetOffset() + sizeof(header)) <= end_offset) {
129 130 131
		if (!dsdiff_read_chunk_header(decoder, is, &header))
			return false;

132
		InputStream::offset_type chunk_end_offset = is.GetOffset()
133
			+ header.GetSize();
134 135 136
		if (chunk_end_offset > end_offset)
			return false;

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

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

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

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

169
			if (!dsdlib_skip_to(decoder, is, chunk_end_offset))
170 171 172 173
				return false;
		}
	}

174
	return is.GetOffset() == end_offset;
175 176 177 178 179 180
}

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

188
	DsdId prop_id;
189 190 191 192
	if (prop_size < sizeof(prop_id) ||
	    !dsdiff_read_id(decoder, is, &prop_id))
		return false;

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

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

	struct dsdiff_native_tag metatag;

211
	if (!dsdlib_read(nullptr, is, &metatag, sizeof(metatag)))
212 213
		return;

214
	uint32_t length = FromBE32(metatag.size);
215 216 217 218 219 220 221 222 223

	/* 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;

224
	if (!dsdlib_read(nullptr, is, label, (size_t)length))
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
		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
241
dsdiff_read_metadata_extra(Decoder *decoder, InputStream &is,
242 243
			   DsdiffMetaData *metadata,
			   DsdiffChunkHeader *chunk_header,
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
			   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 */

261 262
	const auto size = is.GetSize();
	while (is.GetOffset() < size) {
263
		uint64_t chunk_size = chunk_header->GetSize();
264 265

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

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

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

293
		if (is.GetOffset() < size) {
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
			if (!dsdiff_read_chunk_header(decoder, is, chunk_header))
				return false;
		}
		chunk_size = 0;
	}
	/* 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;
}

321 322 323 324 325 326
/**
 * 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
327
dsdiff_read_metadata(Decoder *decoder, InputStream &is,
328 329
		     DsdiffMetaData *metadata,
		     DsdiffChunkHeader *chunk_header)
330
{
331
	DsdiffHeader header;
332
	if (!dsdlib_read(decoder, is, &header, sizeof(header)) ||
333 334
	    !header.id.Equals("FRM8") ||
	    !header.format.Equals("DSD "))
335 336 337
		return false;

	while (true) {
338 339
		if (!dsdiff_read_chunk_header(decoder, is,
					      chunk_header))
340 341
			return false;

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

356
			if (!dsdlib_skip_to(decoder, is, chunk_end_offset))
357 358 359 360 361
				return false;
		}
	}
}

362 363 364 365 366 367 368
static void
bit_reverse_buffer(uint8_t *p, uint8_t *end)
{
	for (; p < end; ++p)
		*p = bit_reverse(*p);
}

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

379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
	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 */
		unsigned now_frames = buffer_frames;
		size_t now_size = buffer_size;
		if (chunk_size < (uint64_t)now_size) {
			now_frames = (unsigned)chunk_size / frame_size;
			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;

401
		if (lsbitfirst)
402 403
			bit_reverse_buffer(buffer, buffer + nbytes);

404
		const auto cmd = decoder_data(decoder, is, buffer, nbytes, 0);
405
		switch (cmd) {
406
		case DecoderCommand::NONE:
407 408
			break;

409 410
		case DecoderCommand::START:
		case DecoderCommand::STOP:
411 412
			return false;

413
		case DecoderCommand::SEEK:
414 415

			/* Not implemented yet */
416 417 418 419
			decoder_seek_error(decoder);
			break;
		}
	}
420
	return dsdlib_skip(&decoder, is, chunk_size);
421 422 423
}

static void
424
dsdiff_stream_decode(Decoder &decoder, InputStream &is)
425
{
426
	DsdiffMetaData metadata;
427

428
	DsdiffChunkHeader chunk_header;
429
	/* check if it is is a proper DFF file */
430
	if (!dsdiff_read_metadata(&decoder, is, &metadata, &chunk_header))
431
		return;
432

433
	Error error;
434 435 436
	AudioFormat audio_format;
	if (!audio_format_init_checked(audio_format, metadata.sample_rate / 8,
				       SampleFormat::DSD,
437
				       metadata.channels, error)) {
438
		LogError(error);
439 440 441
		return;
	}

442 443 444 445 446
	/* 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;

447
	/* success: file was recognized */
448
	decoder_initialized(decoder, audio_format, false, songtime);
449

450 451
	/* every iteration of the following loop decodes one "DSD"
	   chunk from a DFF file */
452

453
	while (true) {
454
		chunk_size = chunk_header.GetSize();
455

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

		/* read next chunk header; the first one was read by
		   dsdiff_read_metadata() */
469
		if (!dsdiff_read_chunk_header(&decoder,
470 471
					      is, &chunk_header))
			break;
472 473 474
	}
}

475
static bool
476
dsdiff_scan_stream(InputStream &is,
477 478
		   gcc_unused const struct tag_handler *handler,
		   gcc_unused void *handler_ctx)
479
{
480 481
	DsdiffMetaData metadata;
	DsdiffChunkHeader chunk_header;
482

483
	/* First check for DFF metadata */
484
	if (!dsdiff_read_metadata(nullptr, is, &metadata, &chunk_header))
485
		return false;
486

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

494 495 496 497 498
	/* 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);

499
	/* Read additional metadata and created tags if available */
500
	dsdiff_read_metadata_extra(nullptr, is, &metadata, &chunk_header,
501 502
				   handler, handler_ctx);

503
	return true;
504 505 506 507
}

static const char *const dsdiff_suffixes[] = {
	"dff",
508
	nullptr
509 510 511 512
};

static const char *const dsdiff_mime_types[] = {
	"application/x-dff",
513
	nullptr
514 515
};

516
const struct DecoderPlugin dsdiff_decoder_plugin = {
517 518 519 520 521 522 523 524 525 526
	"dsdiff",
	dsdiff_init,
	nullptr,
	dsdiff_stream_decode,
	nullptr,
	nullptr,
	dsdiff_scan_stream,
	nullptr,
	dsdiff_suffixes,
	dsdiff_mime_types,
527
};