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
#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
	bool bitreverse;
69
	offset_type chunk_size;
70 71
};

72
static bool lsbitfirst;
73 74

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	struct dsdiff_native_tag metatag;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

368
	uint8_t buffer[8192];
369

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

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

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

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

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

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

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

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

	return true;
416 417 418
}

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

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

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

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

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

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

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

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

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

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

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

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

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

476
	return true;
477 478 479 480
}

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

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

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