DsdiffDecoderPlugin.cxx 12.6 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2019 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/ByteOrder.hxx"
36
#include "util/StringView.hxx"
37
#include "tag/Handler.hxx"
38
#include "DsdLib.hxx"
39

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

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

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

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

65
struct DsdiffMetaData {
66
	unsigned sample_rate, channels;
67
	bool bitreverse;
68
	offset_type chunk_size;
69 70
};

71
static bool lsbitfirst;
72 73

static bool
74
dsdiff_init(const ConfigBlock &block)
75
{
76
	lsbitfirst = block.GetBlockValue("lsbitfirst", false);
77 78 79
	return true;
}

80
static bool
81
dsdiff_read_id(DecoderClient *client, InputStream &is,
82
	       DsdId *id)
83
{
84
	return decoder_read_full(client, is, id, sizeof(*id));
85 86 87
}

static bool
88
dsdiff_read_chunk_header(DecoderClient *client, InputStream &is,
89
			 DsdiffChunkHeader *header)
90
{
91
	return decoder_read_full(client, is, header, sizeof(*header));
92 93 94
}

static bool
95
dsdiff_read_payload(DecoderClient *client, InputStream &is,
96
		    const DsdiffChunkHeader *header,
97 98
		    void *data, size_t length)
{
99
	uint64_t size = header->GetSize();
100 101 102
	if (size != (uint64_t)length)
		return false;

103
	return decoder_read_full(client, is, data, length);
104 105 106 107 108 109
}

/**
 * Read and parse a "SND" chunk inside "PROP".
 */
static bool
110
dsdiff_read_prop_snd(DecoderClient *client, InputStream &is,
111
		     DsdiffMetaData *metadata,
112
		     offset_type end_offset)
113
{
114
	DsdiffChunkHeader header;
115
	while (is.GetOffset() + sizeof(header) <= end_offset) {
116
		if (!dsdiff_read_chunk_header(client, is, &header))
117 118
			return false;

119
		offset_type chunk_end_offset = is.GetOffset()
120
			+ header.GetSize();
121 122 123
		if (chunk_end_offset > end_offset)
			return false;

124
		if (header.id.Equals("FS  ")) {
125
			uint32_t sample_rate;
126
			if (!dsdiff_read_payload(client, is, &header,
127 128 129 130
						 &sample_rate,
						 sizeof(sample_rate)))
				return false;

131
			metadata->sample_rate = FromBE32(sample_rate);
132
		} else if (header.id.Equals("CHNL")) {
133
			uint16_t channels;
134
			if (header.GetSize() < sizeof(channels) ||
135
			    !decoder_read_full(client, is,
136
					       &channels, sizeof(channels)) ||
137
			    !dsdlib_skip_to(client, is, chunk_end_offset))
138 139
				return false;

140
			metadata->channels = FromBE16(channels);
141 142
		} else if (header.id.Equals("CMPR")) {
			DsdId type;
143
			if (header.GetSize() < sizeof(type) ||
144
			    !decoder_read_full(client, is,
145
					       &type, sizeof(type)) ||
146
			    !dsdlib_skip_to(client, is, chunk_end_offset))
147 148
				return false;

149
			if (!type.Equals("DSD "))
150
				/* only uncompressed DSD audio data
151 152 153 154 155
				   is implemented */
				return false;
		} else {
			/* ignore unknown chunk */

156
			if (!dsdlib_skip_to(client, is, chunk_end_offset))
157 158 159 160
				return false;
		}
	}

161
	return is.GetOffset() == end_offset;
162 163 164 165 166 167
}

/**
 * Read and parse a "PROP" chunk.
 */
static bool
168
dsdiff_read_prop(DecoderClient *client, InputStream &is,
169 170
		 DsdiffMetaData *metadata,
		 const DsdiffChunkHeader *prop_header)
171
{
172
	uint64_t prop_size = prop_header->GetSize();
173
	const offset_type end_offset = is.GetOffset() + prop_size;
174

175
	DsdId prop_id;
176
	if (prop_size < sizeof(prop_id) ||
177
	    !dsdiff_read_id(client, is, &prop_id))
178 179
		return false;

180
	if (prop_id.Equals("SND "))
181
		return dsdiff_read_prop_snd(client, is, metadata, end_offset);
182 183
	else
		/* ignore unknown PROP chunk */
184
		return dsdlib_skip_to(client, is, end_offset);
185 186
}

187
static void
188
dsdiff_handle_native_tag(DecoderClient *client, InputStream &is,
189 190
			 TagHandler &handler,
			 offset_type tagoffset,
191
			 TagType type)
192
{
193
	if (!dsdlib_skip_to(client, is, tagoffset))
194 195 196 197
		return;

	struct dsdiff_native_tag metatag;

198
	if (!decoder_read_full(client, is, &metatag, sizeof(metatag)))
199 200
		return;

201
	uint32_t length = FromBE32(metatag.size);
202 203

	/* Check and limit size of the tag to prevent a stack overflow */
204
	constexpr size_t MAX_LENGTH = 1024;
205
	if (length == 0 || length > MAX_LENGTH)
206 207
		return;

208
	char string[MAX_LENGTH];
209 210 211
	char *label;
	label = string;

212
	if (!decoder_read_full(client, is, label, (size_t)length))
213 214
		return;

215
	handler.OnTag(type, {label, length});
216 217 218 219 220 221 222 223 224 225 226 227
	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
228
dsdiff_read_metadata_extra(DecoderClient *client, InputStream &is,
229 230
			   DsdiffMetaData *metadata,
			   DsdiffChunkHeader *chunk_header,
231
			   TagHandler &handler)
232 233 234
{

	/* skip from DSD data to next chunk header */
235
	if (!dsdlib_skip(client, is, metadata->chunk_size))
236
		return false;
237
	if (!dsdiff_read_chunk_header(client, is, chunk_header))
238 239
		return false;

240
	/** offset for artist tag */
241
	offset_type artist_offset = 0;
242
	/** offset for title tag */
243
	offset_type title_offset = 0;
244

245
#ifdef ENABLE_ID3TAG
246
	offset_type id3_offset = 0;
247 248 249 250 251
#endif

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

252
	do {
253
		offset_type chunk_size = chunk_header->GetSize();
254 255

		/* DIIN chunk, is directly followed by other chunks  */
256
		if (chunk_header->id.Equals("DIIN"))
257 258 259
			chunk_size = 0;

		/* DIAR chunk - DSDIFF native tag for Artist */
260
		if (chunk_header->id.Equals("DIAR")) {
261
			chunk_size = chunk_header->GetSize();
262
			artist_offset = is.GetOffset();
263 264 265
		}

		/* DITI chunk - DSDIFF native tag for Title */
266
		if (chunk_header->id.Equals("DITI")) {
267
			chunk_size = chunk_header->GetSize();
268
			title_offset = is.GetOffset();
269
		}
270
#ifdef ENABLE_ID3TAG
271
		/* 'ID3 ' chunk, offspec. Used by sacdextract */
272
		if (chunk_header->id.Equals("ID3 ")) {
273
			chunk_size = chunk_header->GetSize();
274
			id3_offset = is.GetOffset();
275 276 277
		}
#endif

278
		if (!dsdlib_skip(client, is, chunk_size))
279
			break;
280
	} while (dsdiff_read_chunk_header(client, is, chunk_header));
281 282 283

	/* done processing chunk headers, process tags if any */

284
#ifdef ENABLE_ID3TAG
285
	if (id3_offset != 0) {
286 287
		/* a ID3 tag has preference over the other tags, do not process
		   other tags if we have one */
288
		dsdlib_tag_id3(is, handler, id3_offset);
289 290 291 292
		return true;
	}
#endif

293
	if (artist_offset != 0)
294
		dsdiff_handle_native_tag(client, is, handler,
295
					 artist_offset, TAG_ARTIST);
296

297
	if (title_offset != 0)
298
		dsdiff_handle_native_tag(client, is, handler,
299
					 title_offset, TAG_TITLE);
300 301 302
	return true;
}

303 304 305 306 307 308
/**
 * 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
309
dsdiff_read_metadata(DecoderClient *client, InputStream &is,
310 311
		     DsdiffMetaData *metadata,
		     DsdiffChunkHeader *chunk_header)
312
{
313
	DsdiffHeader header;
314
	if (!decoder_read_full(client, is, &header, sizeof(header)) ||
315 316
	    !header.id.Equals("FRM8") ||
	    !header.format.Equals("DSD "))
317 318 319
		return false;

	while (true) {
320
		if (!dsdiff_read_chunk_header(client, is,
321
					      chunk_header))
322 323
			return false;

324
		if (chunk_header->id.Equals("PROP")) {
325
			if (!dsdiff_read_prop(client, is, metadata,
326
					      chunk_header))
327
					return false;
328
		} else if (chunk_header->id.Equals("DSD ")) {
329
			const offset_type chunk_size = chunk_header->GetSize();
330
			metadata->chunk_size = chunk_size;
331 332 333
			return true;
		} else {
			/* ignore unknown chunk */
334
			const offset_type chunk_size = chunk_header->GetSize();
335
			const offset_type chunk_end_offset =
336
				is.GetOffset() + chunk_size;
337

338
			if (!dsdlib_skip_to(client, is, chunk_end_offset))
339 340 341 342 343
				return false;
		}
	}
}

344 345 346 347 348 349 350
static void
bit_reverse_buffer(uint8_t *p, uint8_t *end)
{
	for (; p < end; ++p)
		*p = bit_reverse(*p);
}

351
static offset_type
352
FrameToOffset(uint64_t frame, unsigned channels)
353
{
354
	return frame * channels;
355 356
}

357 358 359 360
/**
 * Decode one "DSD" chunk.
 */
static bool
361
dsdiff_decode_chunk(DecoderClient &client, InputStream &is,
362
		    unsigned channels, unsigned sample_rate,
363
		    const offset_type total_bytes)
364
{
365 366
	const offset_type start_offset = is.GetOffset();

367
	uint8_t buffer[8192];
368

369 370 371
	const size_t sample_size = sizeof(buffer[0]);
	const size_t frame_size = channels * sample_size;
	const unsigned buffer_frames = sizeof(buffer) / frame_size;
372
	const size_t buffer_size = buffer_frames * frame_size;
373

374
	auto cmd = client.GetCommand();
375
	for (offset_type remaining_bytes = total_bytes;
376
	     remaining_bytes >= frame_size && cmd != DecoderCommand::STOP;) {
377
		if (cmd == DecoderCommand::SEEK) {
378
			uint64_t frame = client.GetSeekFrame();
379
			offset_type offset = FrameToOffset(frame, channels);
380
			if (offset >= total_bytes) {
381
				client.CommandFinished();
382 383 384
				break;
			}

385
			if (dsdlib_skip_to(&client, is,
386
					   start_offset + offset)) {
387
				client.CommandFinished();
388 389
				remaining_bytes = total_bytes - offset;
			} else
390
				client.SeekError();
391 392
		}

393 394 395
		/* see how much aligned data from the remaining chunk
		   fits into the local buffer */
		size_t now_size = buffer_size;
396 397
		if (remaining_bytes < (offset_type)now_size) {
			unsigned now_frames = remaining_bytes / frame_size;
398 399 400
			now_size = now_frames * frame_size;
		}

401
		if (!decoder_read_full(&client, is, buffer, now_size))
402 403
			return false;

404
		const size_t nbytes = now_size;
405
		remaining_bytes -= nbytes;
406

407
		if (lsbitfirst)
408 409
			bit_reverse_buffer(buffer, buffer + nbytes);

410 411
		cmd = client.SubmitData(is, buffer, nbytes,
					sample_rate / 1000);
412
	}
413 414

	return true;
415 416 417
}

static void
418
dsdiff_stream_decode(DecoderClient &client, InputStream &is)
419
{
420
	DsdiffMetaData metadata;
421

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

427 428 429
	auto audio_format = CheckAudioFormat(metadata.sample_rate / 8,
					     SampleFormat::DSD,
					     metadata.channels);
430

431
	/* calculate song time from DSD chunk size and sample frequency */
432
	offset_type chunk_size = metadata.chunk_size;
433 434 435 436

	uint64_t n_frames = chunk_size / audio_format.channels;
	auto songtime = SongTime::FromScale<uint64_t>(n_frames,
						      audio_format.sample_rate);
437

438
	/* success: file was recognized */
439
	client.Ready(audio_format, is.IsSeekable(), songtime);
440

441 442
	/* every iteration of the following loop decodes one "DSD"
	   chunk from a DFF file */
443

444
	dsdiff_decode_chunk(client, is,
445 446 447
			    metadata.channels,
			    metadata.sample_rate,
			    chunk_size);
448 449
}

450
static bool
451
dsdiff_scan_stream(InputStream &is, TagHandler &handler) noexcept
452
{
453 454
	DsdiffMetaData metadata;
	DsdiffChunkHeader chunk_header;
455

456
	/* First check for DFF metadata */
457
	if (!dsdiff_read_metadata(nullptr, is, &metadata, &chunk_header))
458
		return false;
459

460 461 462 463
	const auto sample_rate = metadata.sample_rate / 8;
	if (!audio_valid_sample_rate(sample_rate) ||
	    !audio_valid_channel_count(metadata.channels))
		return false;
464

465
	/* calculate song time and add as tag */
466
	uint64_t n_frames = metadata.chunk_size / metadata.channels;
467
	auto songtime = SongTime::FromScale<uint64_t>(n_frames,
468
						      sample_rate);
469
	handler.OnDuration(songtime);
470

471
	/* Read additional metadata and created tags if available */
472
	dsdiff_read_metadata_extra(nullptr, is, &metadata, &chunk_header,
473
				   handler);
474

475
	return true;
476 477 478 479
}

static const char *const dsdiff_suffixes[] = {
	"dff",
480
	nullptr
481 482 483 484
};

static const char *const dsdiff_mime_types[] = {
	"application/x-dff",
485 486
	"audio/x-dff",
	"audio/x-dsd",
487
	nullptr
488 489
};

490 491 492 493 494
constexpr DecoderPlugin dsdiff_decoder_plugin =
	DecoderPlugin("dsdiff", dsdiff_stream_decode, dsdiff_scan_stream)
	.WithInit(dsdiff_init)
	.WithSuffixes(dsdiff_suffixes)
	.WithMimeTypes(dsdiff_mime_types);