FlacEncoderPlugin.cxx 6.4 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
 * 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
#include "FlacEncoderPlugin.hxx"
21
#include "../EncoderAPI.hxx"
22
#include "AudioFormat.hxx"
23
#include "pcm/PcmBuffer.hxx"
24
#include "config/Domain.hxx"
25
#include "util/DynamicFifoBuffer.hxx"
26
#include "util/RuntimeError.hxx"
27 28 29

#include <FLAC/stream_encoder.h>

30 31 32 33
#if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
#error libFLAC is too old
#endif

34 35
class FlacEncoder final : public Encoder {
	const AudioFormat audio_format;
36

37
	FLAC__StreamEncoder *const fse;
38

39
	PcmBuffer expand_buffer;
40

41 42 43 44
	/**
	 * This buffer will hold encoded data from libFLAC until it is
	 * picked up with flac_encoder_read().
	 */
45 46 47
	DynamicFifoBuffer<uint8_t> output_buffer;

public:
48
	FlacEncoder(AudioFormat _audio_format, FLAC__StreamEncoder *_fse);
49 50 51 52 53 54

	~FlacEncoder() override {
		FLAC__stream_encoder_delete(fse);
	}

	/* virtual methods from class Encoder */
55
	void End() override {
56 57
		(void) FLAC__stream_encoder_finish(fse);
	}
58

59
	void Flush() override {
60 61 62
		(void) FLAC__stream_encoder_finish(fse);
	}

63
	void Write(const void *data, size_t length) override;
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81

	size_t Read(void *dest, size_t length) override {
		return output_buffer.Read((uint8_t *)dest, length);
	}

private:
	static FLAC__StreamEncoderWriteStatus WriteCallback(const FLAC__StreamEncoder *,
							    const FLAC__byte data[],
							    size_t bytes,
							    gcc_unused unsigned samples,
							    gcc_unused unsigned current_frame,
							    void *client_data) {
		auto &encoder = *(FlacEncoder *)client_data;
		encoder.output_buffer.Append((const uint8_t *)data, bytes);
		return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
	}
};

82
class PreparedFlacEncoder final : public PreparedEncoder {
83
	const unsigned compression;
84

85
public:
86
	PreparedFlacEncoder(const ConfigBlock &block);
87 88

	/* virtual methods from class PreparedEncoder */
89
	Encoder *Open(AudioFormat &audio_format) override;
90 91 92 93

	const char *GetMimeType() const override {
		return  "audio/flac";
	}
94
};
95

96 97
PreparedFlacEncoder::PreparedFlacEncoder(const ConfigBlock &block)
	:compression(block.GetBlockValue("compression", 5u))
98 99 100
{
}

101
static PreparedEncoder *
102
flac_encoder_init(const ConfigBlock &block)
103
{
104
	return new PreparedFlacEncoder(block);
105 106
}

107
static void
108
flac_encoder_setup(FLAC__StreamEncoder *fse, unsigned compression,
109
		   const AudioFormat &audio_format, unsigned bits_per_sample)
110
{
111 112 113
	if (!FLAC__stream_encoder_set_compression_level(fse, compression))
		throw FormatRuntimeError("error setting flac compression to %d",
					 compression);
114

115 116 117
	if (!FLAC__stream_encoder_set_channels(fse, audio_format.channels))
		throw FormatRuntimeError("error setting flac channels num to %d",
					 audio_format.channels);
118

119 120 121
	if (!FLAC__stream_encoder_set_bits_per_sample(fse, bits_per_sample))
		throw FormatRuntimeError("error setting flac bit format to %d",
					 bits_per_sample);
122 123

	if (!FLAC__stream_encoder_set_sample_rate(fse,
124 125 126
						  audio_format.sample_rate))
		throw FormatRuntimeError("error setting flac sample rate to %d",
					 audio_format.sample_rate);
127 128
}

129 130 131 132
FlacEncoder::FlacEncoder(AudioFormat _audio_format, FLAC__StreamEncoder *_fse)
	:Encoder(false),
	 audio_format(_audio_format), fse(_fse),
	 output_buffer(8192)
133
{
134
	/* this immediately outputs data through callback */
135

136 137 138 139 140
	auto init_status =
		FLAC__stream_encoder_init_stream(fse,
						 WriteCallback,
						 nullptr, nullptr, nullptr,
						 this);
141

142 143 144
	if (init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK)
		throw FormatRuntimeError("failed to initialize encoder: %s\n",
					 FLAC__StreamEncoderInitStatusString[init_status]);
145 146
}

147
Encoder *
148
PreparedFlacEncoder::Open(AudioFormat &audio_format)
149
{
150
	unsigned bits_per_sample;
151 152

	/* FIXME: flac should support 32bit as well */
153 154
	switch (audio_format.format) {
	case SampleFormat::S8:
155 156 157
		bits_per_sample = 8;
		break;

158
	case SampleFormat::S16:
159 160 161
		bits_per_sample = 16;
		break;

162
	case SampleFormat::S24_P32:
163 164 165 166 167
		bits_per_sample = 24;
		break;

	default:
		bits_per_sample = 24;
168
		audio_format.format = SampleFormat::S24_P32;
169
	}
170 171

	/* allocate the encoder */
172
	auto fse = FLAC__stream_encoder_new();
173 174
	if (fse == nullptr)
		throw std::runtime_error("FLAC__stream_encoder_new() failed");
175

176 177 178 179
	try {
		flac_encoder_setup(fse, compression,
				   audio_format, bits_per_sample);
	} catch (...) {
180
		FLAC__stream_encoder_delete(fse);
181
		throw;
182 183
	}

184
	return new FlacEncoder(audio_format, fse);
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
}

static inline void
pcm8_to_flac(int32_t *out, const int8_t *in, unsigned num_samples)
{
	while (num_samples > 0) {
		*out++ = *in++;
		--num_samples;
	}
}

static inline void
pcm16_to_flac(int32_t *out, const int16_t *in, unsigned num_samples)
{
	while (num_samples > 0) {
		*out++ = *in++;
		--num_samples;
	}
}

205 206
void
FlacEncoder::Write(const void *data, size_t length)
207 208
{
	void *exbuffer;
209
	const void *buffer = nullptr;
210 211 212

	/* format conversion */

213 214
	const unsigned num_frames = length / audio_format.GetFrameSize();
	const unsigned num_samples = num_frames * audio_format.channels;
215

216
	switch (audio_format.format) {
217
	case SampleFormat::S8:
218
		exbuffer = expand_buffer.Get(length * 4);
219 220
		pcm8_to_flac((int32_t *)exbuffer, (const int8_t *)data,
			     num_samples);
221 222
		buffer = exbuffer;
		break;
223

224
	case SampleFormat::S16:
225
		exbuffer = expand_buffer.Get(length * 2);
226 227
		pcm16_to_flac((int32_t *)exbuffer, (const int16_t *)data,
			      num_samples);
228 229
		buffer = exbuffer;
		break;
230

231 232
	case SampleFormat::S24_P32:
	case SampleFormat::S32:
233 234
		/* nothing need to be done; format is the same for
		   both mpd and libFLAC */
235 236
		buffer = data;
		break;
237 238 239

	default:
		gcc_unreachable();
240 241 242 243
	}

	/* feed samples to encoder */

244
	if (!FLAC__stream_encoder_process_interleaved(fse,
245
						      (const FLAC__int32 *)buffer,
246 247
						      num_frames))
		throw std::runtime_error("flac encoder process failed");
248 249
}

250
const EncoderPlugin flac_encoder_plugin = {
251 252
	"flac",
	flac_encoder_init,
253
};
254