summaryrefslogtreecommitdiff
path: root/src/encoder/plugins/FlacEncoderPlugin.cxx
blob: 352434f41b172ed730b83b6299f1fd6683e9724d (plain)
1
2
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
/*
 * Copyright 2003-2021 The Music Player Daemon Project
 * 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 "FlacEncoderPlugin.hxx"
#include "../EncoderAPI.hxx"
#include "pcm/AudioFormat.hxx"
#include "pcm/Buffer.hxx"
#include "util/DynamicFifoBuffer.hxx"
#include "util/RuntimeError.hxx"
#include "util/Serial.hxx"
#include "util/StringUtil.hxx"

#include <FLAC/stream_encoder.h>
#include <FLAC/metadata.h>

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

class FlacEncoder final : public Encoder {
	const AudioFormat audio_format;

	FLAC__StreamEncoder *const fse;
	const unsigned compression;

	PcmBuffer expand_buffer;

	/**
	 * This buffer will hold encoded data from libFLAC until it is
	 * picked up with flac_encoder_read().
	 */
	DynamicFifoBuffer<uint8_t> output_buffer;

public:
	FlacEncoder(AudioFormat _audio_format, FLAC__StreamEncoder *_fse, unsigned _compression, bool _oggflac, bool _oggchaining);

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

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

	void Flush() override {
	}

	void PreTag() override {
		(void) FLAC__stream_encoder_finish(fse);
	}

	void SendTag(const Tag &tag) override;

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

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

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

class PreparedFlacEncoder final : public PreparedEncoder {
	const unsigned compression;
	const bool oggchaining;
	const bool oggflac;

public:
	explicit PreparedFlacEncoder(const ConfigBlock &block);

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

	[[nodiscard]] const char *GetMimeType() const noexcept override {
		if(oggflac)
			return  "audio/ogg";
		return "audio/flac";
	}
};

PreparedFlacEncoder::PreparedFlacEncoder(const ConfigBlock &block)
	:compression(block.GetBlockValue("compression", 5U)),
	oggchaining(block.GetBlockValue("oggchaining",false)),
	oggflac(block.GetBlockValue("oggflac",false) || oggchaining)
{
}

static PreparedEncoder *
flac_encoder_init(const ConfigBlock &block)
{
	return new PreparedFlacEncoder(block);
}

static void
flac_encoder_setup(FLAC__StreamEncoder *fse, unsigned compression,
		   const AudioFormat &audio_format)
{
	unsigned bits_per_sample;

	switch (audio_format.format) {
	case SampleFormat::S8:
		bits_per_sample = 8;
		break;

	case SampleFormat::S16:
		bits_per_sample = 16;
		break;

	default:
		bits_per_sample = 24;
	}

	if (!FLAC__stream_encoder_set_compression_level(fse, compression))
		throw FormatRuntimeError("error setting flac compression to %d",
					 compression);

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

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

	if (!FLAC__stream_encoder_set_sample_rate(fse,
						  audio_format.sample_rate))
		throw FormatRuntimeError("error setting flac sample rate to %d",
					 audio_format.sample_rate);

	if (!FLAC__stream_encoder_set_ogg_serial_number(fse,
						  GenerateSerial()))
		throw FormatRuntimeError("error setting ogg serial number");
}

FlacEncoder::FlacEncoder(AudioFormat _audio_format, FLAC__StreamEncoder *_fse, unsigned _compression, bool _oggflac, bool _oggchaining)
	:Encoder(_oggchaining),
	 audio_format(_audio_format), fse(_fse),
	 compression(_compression),
	 output_buffer(8192)
{
	/* this immediately outputs data through callback */

	auto init_status = _oggflac ?
		FLAC__stream_encoder_init_ogg_stream(fse,
						     nullptr, WriteCallback,
						     nullptr, nullptr, nullptr,
						     this)
		:
		FLAC__stream_encoder_init_stream(fse,
						 WriteCallback,
						 nullptr, nullptr, nullptr,
						 this);

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

Encoder *
PreparedFlacEncoder::Open(AudioFormat &audio_format)
{
	switch (audio_format.format) {
	case SampleFormat::S8:
		break;

	case SampleFormat::S16:
		break;

	case SampleFormat::S24_P32:
		break;

	default:
		audio_format.format = SampleFormat::S24_P32;
	}

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

	try {
		flac_encoder_setup(fse, compression, audio_format);
	} catch (...) {
		FLAC__stream_encoder_delete(fse);
		throw;
	}

	return new FlacEncoder(audio_format, fse, compression, oggflac, oggchaining);
}

void
FlacEncoder::SendTag(const Tag &tag)
{
	/* re-initialize encoder since flac_encoder_finish resets everything */
	flac_encoder_setup(fse, compression, audio_format);

	FLAC__StreamMetadata *metadata = FLAC__metadata_object_new(FLAC__METADATA_TYPE_VORBIS_COMMENT);
	FLAC__StreamMetadata_VorbisComment_Entry entry;

	for (const auto &item : tag) {
		char name[64];
		ToUpperASCII(name, tag_item_names[item.type], sizeof(name));
		FLAC__metadata_object_vorbiscomment_entry_from_name_value_pair(&entry, name, item.value);
		FLAC__metadata_object_vorbiscomment_append_comment(metadata, entry, false);
	}

	FLAC__stream_encoder_set_metadata(fse,&metadata,1);

	auto init_status = FLAC__stream_encoder_init_ogg_stream(fse,
							        nullptr, WriteCallback,
							        nullptr, nullptr, nullptr,
							        this);

	FLAC__metadata_object_delete(metadata);

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


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

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

void
FlacEncoder::Write(const void *data, size_t length)
{
	void *exbuffer;
	const void *buffer = nullptr;

	/* format conversion */

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

	switch (audio_format.format) {
	case SampleFormat::S8:
		exbuffer = expand_buffer.Get(length * 4);
		pcm8_to_flac((int32_t *)exbuffer, (const int8_t *)data,
			     num_samples);
		buffer = exbuffer;
		break;

	case SampleFormat::S16:
		exbuffer = expand_buffer.Get(length * 2);
		pcm16_to_flac((int32_t *)exbuffer, (const int16_t *)data,
			      num_samples);
		buffer = exbuffer;
		break;

	case SampleFormat::S24_P32:
	case SampleFormat::S32:
		/* nothing need to be done; format is the same for
		   both mpd and libFLAC */
		buffer = data;
		break;

	default:
		gcc_unreachable();
	}

	/* feed samples to encoder */

	if (!FLAC__stream_encoder_process_interleaved(fse,
						      (const FLAC__int32 *)buffer,
						      num_frames))
		throw std::runtime_error("flac encoder process failed");
}

const EncoderPlugin flac_encoder_plugin = {
	"flac",
	flac_encoder_init,
};