HybridDsdDecoderPlugin.cxx 6.85 KB
Newer Older
1
/*
2
 * Copyright 2003-2018 The Music Player Daemon Project
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
 * 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.
 */

#include "HybridDsdDecoderPlugin.hxx"
#include "../DecoderAPI.hxx"
#include "input/InputStream.hxx"
#include "system/ByteOrder.hxx"
#include "util/Domain.hxx"
#include "util/WritableBuffer.hxx"
#include "util/StaticFifoBuffer.hxx"
#include "Log.hxx"

#include <string.h>

static constexpr Domain hybrid_dsd_domain("hybrid_dsd");

namespace {

static bool
InitHybridDsdDecoder(const ConfigBlock &block)
{
38 39 40
	/* this plugin is disabled by default because for people
	   without a DSD DAC, the PCM (=ALAC) part of the file is
	   better */
41
	if (block.GetBlockParam("enabled") == nullptr) {
42 43
		LogDebug(hybrid_dsd_domain,
			 "The Hybrid DSD decoder is disabled because it was not explicitly enabled");
44 45 46 47 48 49
		return false;
	}

	return true;
}

50 51 52 53
/**
 * This exception gets thrown by FindHybridDsdData() to indicate a
 * file format error.
 */
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
struct UnsupportedFile {};

struct Mp4ChunkHeader {
	uint32_t size;
	char type[4];
};

void
ReadFull(DecoderClient &client, InputStream &input,
	 WritableBuffer<uint8_t> dest)
{
	while (!dest.empty()) {
		size_t nbytes = client.Read(input, dest.data, dest.size);
		if (nbytes == 0)
			throw UnsupportedFile();

		dest.skip_front(nbytes);
	}
}

void
ReadFull(DecoderClient &client, InputStream &input, WritableBuffer<void> dest)
{
	ReadFull(client, input, WritableBuffer<uint8_t>::FromVoid(dest));
}

template<typename T>
T
ReadFullT(DecoderClient &client, InputStream &input)
{
	T dest;
	ReadFull(client, input, WritableBuffer<void>(&dest, sizeof(dest)));
	return dest;
}

Mp4ChunkHeader
ReadHeader(DecoderClient &client, InputStream &input)
{
	return ReadFullT<Mp4ChunkHeader>(client, input);
}

uint32_t
ReadBE32(DecoderClient &client, InputStream &input)
{
	return FromBE32(ReadFullT<uint32_t>(client, input));
}

} /* anonymous namespace */

static std::pair<AudioFormat, offset_type>
FindHybridDsdData(DecoderClient &client, InputStream &input)
{
	auto audio_format = AudioFormat::Undefined();
107
	bool found_version = false;
108 109 110 111 112 113 114 115 116

	while (true) {
		auto header = ReadHeader(client, input);
		const size_t header_size = FromBE32(header.size);
		if (header_size < sizeof(header))
			throw UnsupportedFile();

		size_t remaining = header_size - sizeof(header);
		if (memcmp(header.type, "bphv", 4) == 0) {
117 118
			/* version; this plugin knows only version
			   1 */
119 120 121 122
			if (remaining != 4 || ReadBE32(client, input) != 1)
				throw UnsupportedFile();
			remaining -= 4;

123
			found_version = true;
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
		} else if (memcmp(header.type, "bphc", 4) == 0) {
			/* channel count */
			if (remaining != 4)
				throw UnsupportedFile();

			auto channels = ReadBE32(client, input);
			remaining -= 4;

			if (!audio_valid_channel_count(channels))
				throw UnsupportedFile();

			audio_format.channels = channels;
		} else if (memcmp(header.type, "bphr", 4) == 0) {
			/* (bit) sample rate */

			if (remaining != 4)
				throw UnsupportedFile();

			auto sample_rate = ReadBE32(client, input) / 8;
			remaining -= 4;

			if (!audio_valid_sample_rate(sample_rate))
				throw UnsupportedFile();

			audio_format.sample_rate = sample_rate;
		} else if (memcmp(header.type, "bphf", 4) == 0) {
150 151 152
			/* format: 0 = plain DSD; 1 = DST compressed
			   (only plain DSD is understood by this
			   plugin) */
153 154 155
			if (remaining != 4 || ReadBE32(client, input) != 0)
				throw UnsupportedFile();
			remaining -= 4;
156 157

			audio_format.format = SampleFormat::DSD;
158 159
		} else if (memcmp(header.type, "bphd", 4) == 0) {
			/* the actual DSD data */
160
			if (!found_version || !audio_format.IsValid())
161 162 163 164 165
				throw UnsupportedFile();

			return std::make_pair(audio_format, remaining);
		}

166
		/* skip this chunk payload */
167 168 169 170 171 172 173 174 175 176 177 178
		input.LockSkip(remaining);
	}
}

static void
HybridDsdDecode(DecoderClient &client, InputStream &input)
{
	if (!input.CheapSeeking())
		/* probe only if seeking is cheap, i.e. not for HTTP
		   streams */
		return;

179
	uint64_t total_frames;
180
	size_t frame_size;
181
	unsigned kbit_rate;
182 183 184

	try {
		auto result = FindHybridDsdData(client, input);
185
		auto duration = result.first.SizeToTime<SignedSongTime>(result.second);
186
		client.Ready(result.first, true, duration);
187
		frame_size = result.first.GetFrameSize();
188
		kbit_rate = frame_size * result.first.sample_rate /
189
			(1024U / 8U);
190
		total_frames = result.second / frame_size;
191
	} catch (UnsupportedFile) {
192 193
		/* not a Hybrid-DSD file; let the next decoder plugin
		   (e.g. FFmpeg) handle it */
194 195 196
		return;
	}

197 198 199
	const offset_type start_offset = input.GetOffset();
	offset_type remaining_bytes = total_frames * frame_size;

200 201 202 203
	StaticFifoBuffer<uint8_t, 16384> buffer;

	auto cmd = client.GetCommand();
	while (remaining_bytes > 0) {
204 205
		uint64_t seek_frame;

206 207 208 209 210 211 212 213 214
		switch (cmd) {
		case DecoderCommand::NONE:
		case DecoderCommand::START:
			break;

		case DecoderCommand::STOP:
			return;

		case DecoderCommand::SEEK:
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
			seek_frame = client.GetSeekFrame();
			if (seek_frame >= total_frames) {
				/* seeking past the end */
				client.CommandFinished();
				return;
			}

			try {
				input.LockSeek(start_offset + seek_frame * frame_size);
				remaining_bytes = (total_frames - seek_frame) * frame_size;
				buffer.Clear();
				client.CommandFinished();
			} catch (...) {
				LogError(std::current_exception());
				client.SeekError();
			}

			cmd = DecoderCommand::NONE;
233 234 235
			break;
		}

236
		/* fill the buffer */
237 238
		auto w = buffer.Write();
		if (!w.empty()) {
239
			if (remaining_bytes < (1<<30ULL) &&
240 241 242 243 244 245 246 247 248 249 250 251
			    w.size > size_t(remaining_bytes))
				w.size = remaining_bytes;

			const size_t nbytes = client.Read(input,
							  w.data, w.size);
			if (nbytes == 0)
				return;

			remaining_bytes -= nbytes;
			buffer.Append(nbytes);
		}

252
		/* submit the buffer to our client */
253 254 255 256 257
		auto r = buffer.Read();
		auto n_frames = r.size / frame_size;
		if (n_frames > 0) {
			cmd = client.SubmitData(input, r.data,
						n_frames * frame_size,
258
						kbit_rate);
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
			buffer.Consume(n_frames * frame_size);
		}
	}
}

static const char *const hybrid_dsd_suffixes[] = {
	"m4a",
	nullptr
};

const struct DecoderPlugin hybrid_dsd_decoder_plugin = {
	"hybrid_dsd",
	InitHybridDsdDecoder,
	nullptr,
	HybridDsdDecode,
	nullptr,
	nullptr,
276 277
	/* no scan method here; the FFmpeg plugin will do that for us,
	   and we only do the decoding */
278 279 280 281 282
	nullptr,
	nullptr,
	hybrid_dsd_suffixes,
	nullptr,
};