TwolameEncoderPlugin.cxx 6.01 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2021 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 "TwolameEncoderPlugin.hxx"
21
#include "../EncoderAPI.hxx"
22
#include "pcm/AudioFormat.hxx"
23
#include "util/NumberParser.hxx"
24
#include "util/RuntimeError.hxx"
25
#include "util/Domain.hxx"
26
#include "Log.hxx"
27 28

#include <twolame.h>
29

30
#include <cassert>
31 32
#include <stdexcept>

33 34
#include <string.h>

35 36
class TwolameEncoder final : public Encoder {
	const AudioFormat audio_format;
37 38 39

	twolame_options *options;

40
	unsigned char output_buffer[32768];
41 42
	size_t output_buffer_length = 0;
	size_t output_buffer_position = 0;
43 44

	/**
45 46
	 * Call libtwolame's flush function when the output_buffer is
	 * empty?
47
	 */
48
	bool flush = false;
49

50 51 52 53 54
public:
	TwolameEncoder(const AudioFormat _audio_format,
		       twolame_options *_options)
		:Encoder(false),
		 audio_format(_audio_format), options(_options) {}
55
	~TwolameEncoder() noexcept override;
56 57 58

	/* virtual methods from class Encoder */

59
	void End() override {
60 61 62
		flush = true;
	}

63
	void Flush() override {
64 65 66
		flush = true;
	}

67
	void Write(const void *data, size_t length) override;
68
	size_t Read(void *dest, size_t length) noexcept override;
69 70
};

71
class PreparedTwolameEncoder final : public PreparedEncoder {
72 73 74
	float quality;
	int bitrate;

75
public:
Max Kellermann's avatar
Max Kellermann committed
76
	explicit PreparedTwolameEncoder(const ConfigBlock &block);
77 78

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

81
	[[nodiscard]] const char *GetMimeType() const noexcept override {
82 83
		return  "audio/mpeg";
	}
84
};
85

86
static constexpr Domain twolame_encoder_domain("twolame_encoder");
87

88
PreparedTwolameEncoder::PreparedTwolameEncoder(const ConfigBlock &block)
89 90 91 92
{
	const char *value;
	char *endptr;

93
	value = block.GetBlockValue("quality");
94
	if (value != nullptr) {
95 96
		/* a quality was configured (VBR) */

Rosen Penev's avatar
Rosen Penev committed
97
		quality = float(ParseDouble(value, &endptr));
98

Rosen Penev's avatar
Rosen Penev committed
99
		if (*endptr != '\0' || quality < -1.0f || quality > 10.0f)
100 101 102 103 104 105
			throw FormatRuntimeError("quality \"%s\" is not a number in the "
						 "range -1 to 10",
						 value);

		if (block.GetBlockValue("bitrate") != nullptr)
			throw std::runtime_error("quality and bitrate are both defined");
106 107 108
	} else {
		/* a bit rate was configured */

109
		value = block.GetBlockValue("bitrate");
110 111
		if (value == nullptr)
			throw std::runtime_error("neither bitrate nor quality defined");
112

113
		quality = -2.0;
114
		bitrate = ParseInt(value, &endptr);
115

116 117
		if (*endptr != '\0' || bitrate <= 0)
			throw std::runtime_error("bitrate should be a positive integer");
118 119 120
	}
}

121
static PreparedEncoder *
122
twolame_encoder_init(const ConfigBlock &block)
123
{
124 125
	FormatDebug(twolame_encoder_domain,
		    "libtwolame version %s", get_twolame_version());
126

127
	return new PreparedTwolameEncoder(block);
128 129
}

130
static void
131
twolame_encoder_setup(twolame_options *options, float quality, int bitrate,
132
		      const AudioFormat &audio_format)
133
{
Rosen Penev's avatar
Rosen Penev committed
134
	if (quality >= -1.0f) {
135 136
		/* a quality was configured (VBR) */

137 138 139 140 141
		if (0 != twolame_set_VBR(options, true))
			throw std::runtime_error("error setting twolame VBR mode");

		if (0 != twolame_set_VBR_q(options, quality))
			throw std::runtime_error("error setting twolame VBR quality");
142 143 144
	} else {
		/* a bit rate was configured */

145 146
		if (0 != twolame_set_brate(options, bitrate))
			throw std::runtime_error("error setting twolame bitrate");
147 148
	}

149 150
	if (0 != twolame_set_num_channels(options, audio_format.channels))
		throw std::runtime_error("error setting twolame num channels");
151

152
	if (0 != twolame_set_in_samplerate(options,
153 154
					   audio_format.sample_rate))
		throw std::runtime_error("error setting twolame sample rate");
155

156 157
	if (0 > twolame_init_params(options))
		throw std::runtime_error("error initializing twolame params");
158 159
}

160
Encoder *
161
PreparedTwolameEncoder::Open(AudioFormat &audio_format)
162
{
163 164
	audio_format.format = SampleFormat::S16;
	audio_format.channels = 2;
165

166
	auto options = twolame_init();
167 168
	if (options == nullptr)
		throw std::runtime_error("twolame_init() failed");
169

170 171 172 173
	try {
		twolame_encoder_setup(options, quality, bitrate,
				      audio_format);
	} catch (...) {
174
		twolame_close(&options);
175
		throw;
176 177
	}

178
	return new TwolameEncoder(audio_format, options);
179 180
}

181
TwolameEncoder::~TwolameEncoder() noexcept
182
{
183
	twolame_close(&options);
184 185
}

186 187
void
TwolameEncoder::Write(const void *data, size_t length)
188
{
Max Kellermann's avatar
Max Kellermann committed
189
	const auto *src = (const int16_t*)data;
190

191
	assert(output_buffer_position == output_buffer_length);
192

193
	const unsigned num_frames = length / audio_format.GetFrameSize();
194

195
	int bytes_out = twolame_encode_buffer_interleaved(options,
196
							  src, num_frames,
197 198
							  output_buffer,
							  sizeof(output_buffer));
199 200
	if (bytes_out < 0)
		throw std::runtime_error("twolame encoder failed");
201

202 203
	output_buffer_length = (size_t)bytes_out;
	output_buffer_position = 0;
204 205
}

206
size_t
207
TwolameEncoder::Read(void *dest, size_t length) noexcept
208
{
209
	assert(output_buffer_position <= output_buffer_length);
210

211 212 213
	if (output_buffer_position == output_buffer_length && flush) {
		int ret = twolame_encode_flush(options, output_buffer,
					       sizeof(output_buffer));
214
		if (ret > 0) {
215 216
			output_buffer_length = (size_t)ret;
			output_buffer_position = 0;
217
		}
218

219
		flush = false;
220 221 222
	}


223
	const size_t remainning = output_buffer_length - output_buffer_position;
224 225 226
	if (length > remainning)
		length = remainning;

227
	memcpy(dest, output_buffer + output_buffer_position, length);
228

229
	output_buffer_position += length;
230 231 232 233

	return length;
}

234
const EncoderPlugin twolame_encoder_plugin = {
235 236
	"twolame",
	twolame_encoder_init,
237
};