DsdiffDecoderPlugin.cxx 12.7 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2017 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 "system/ByteOrder.hxx"
36
#include "tag/Handler.hxx"
37
#include "DsdLib.hxx"
38
#include "Log.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(InputStream &is,
189
			 const TagHandler &handler,
190
			 void *handler_ctx, offset_type tagoffset,
191
			 TagType type)
192
{
193
	if (!dsdlib_skip_to(nullptr, is, tagoffset))
194 195 196 197
		return;

	struct dsdiff_native_tag metatag;

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

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

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

207
	char string[length + 1];
208 209 210
	char *label;
	label = string;

211
	if (!decoder_read_full(nullptr, is, label, (size_t)length))
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
		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
228
dsdiff_read_metadata_extra(DecoderClient *client, InputStream &is,
229 230
			   DsdiffMetaData *metadata,
			   DsdiffChunkHeader *chunk_header,
231
			   const TagHandler &handler,
232 233 234 235
			   void *handler_ctx)
{

	/* 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, handler_ctx, id3_offset);
290 291 292 293
		return true;
	}
#endif

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

298
	if (title_offset != 0)
299
		dsdiff_handle_native_tag(is, handler, handler_ctx,
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,
453
		   gcc_unused const TagHandler &handler,
454
		   gcc_unused void *handler_ctx)
455
{
456 457
	DsdiffMetaData metadata;
	DsdiffChunkHeader chunk_header;
458

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

463 464 465
	auto audio_format = CheckAudioFormat(metadata.sample_rate / 8,
					     SampleFormat::DSD,
					     metadata.channels);
466

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

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

477
	return true;
478 479 480 481
}

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

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

490
const struct DecoderPlugin dsdiff_decoder_plugin = {
491 492 493 494 495 496 497 498 499 500
	"dsdiff",
	dsdiff_init,
	nullptr,
	dsdiff_stream_decode,
	nullptr,
	nullptr,
	dsdiff_scan_stream,
	nullptr,
	dsdiff_suffixes,
	dsdiff_mime_types,
501
};