FlacEncoderPlugin.cxx 6.46 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2020 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 "pcm/AudioFormat.hxx"
23
#include "pcm/Buffer.hxx"
24
#include "util/DynamicFifoBuffer.hxx"
25
#include "util/RuntimeError.hxx"
26 27 28

#include <FLAC/stream_encoder.h>

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

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

36
	FLAC__StreamEncoder *const fse;
37

38
	PcmBuffer expand_buffer;
39

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

public:
47
	FlacEncoder(AudioFormat _audio_format, FLAC__StreamEncoder *_fse);
48

49
	~FlacEncoder() noexcept override {
50 51 52 53
		FLAC__stream_encoder_delete(fse);
	}

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

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

62
	void Write(const void *data, size_t length) override;
63

64
	size_t Read(void *dest, size_t length) noexcept override {
65 66 67 68 69 70 71
		return output_buffer.Read((uint8_t *)dest, length);
	}

private:
	static FLAC__StreamEncoderWriteStatus WriteCallback(const FLAC__StreamEncoder *,
							    const FLAC__byte data[],
							    size_t bytes,
Rosen Penev's avatar
Rosen Penev committed
72 73
							    [[maybe_unused]] unsigned samples,
							    [[maybe_unused]] unsigned current_frame,
74
							    void *client_data) noexcept {
75 76 77 78 79 80
		auto &encoder = *(FlacEncoder *)client_data;
		encoder.output_buffer.Append((const uint8_t *)data, bytes);
		return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
	}
};

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

84
public:
Max Kellermann's avatar
Max Kellermann committed
85
	explicit PreparedFlacEncoder(const ConfigBlock &block);
86 87

	/* virtual methods from class PreparedEncoder */
88
	Encoder *Open(AudioFormat &audio_format) override;
89

90
	[[nodiscard]] const char *GetMimeType() const noexcept override {
91 92
		return  "audio/flac";
	}
93
};
94

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

183
	return new FlacEncoder(audio_format, fse);
184 185 186
}

static inline void
187
pcm8_to_flac(int32_t *out, const int8_t *in, unsigned num_samples) noexcept
188 189 190 191 192 193 194 195
{
	while (num_samples > 0) {
		*out++ = *in++;
		--num_samples;
	}
}

static inline void
196
pcm16_to_flac(int32_t *out, const int16_t *in, unsigned num_samples) noexcept
197 198 199 200 201 202 203
{
	while (num_samples > 0) {
		*out++ = *in++;
		--num_samples;
	}
}

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

	/* format conversion */

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

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

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

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

	default:
		gcc_unreachable();
239 240 241 242
	}

	/* feed samples to encoder */

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

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