diff options
author | Max Kellermann <max@duempel.org> | 2014-01-23 23:09:14 +0100 |
---|---|---|
committer | Max Kellermann <max@duempel.org> | 2014-01-23 23:09:14 +0100 |
commit | 655ad344140ee250f8becf67544dbe035a3460b1 (patch) | |
tree | 1f9cf0ce40ba07378d2c129d765034c24284ffbe /src/encoder/plugins | |
parent | 017eecb8e8403f154fbd8c009437eb09abc60310 (diff) | |
download | mpd-655ad344140ee250f8becf67544dbe035a3460b1.tar.gz mpd-655ad344140ee250f8becf67544dbe035a3460b1.tar.xz mpd-655ad344140ee250f8becf67544dbe035a3460b1.zip |
Encoder*: move to src/encoder
.. and move the plugins to src/encoder/plugins/.
Diffstat (limited to 'src/encoder/plugins')
19 files changed, 2758 insertions, 0 deletions
diff --git a/src/encoder/plugins/FlacEncoderPlugin.cxx b/src/encoder/plugins/FlacEncoderPlugin.cxx new file mode 100644 index 000000000..ebdd101f3 --- /dev/null +++ b/src/encoder/plugins/FlacEncoderPlugin.cxx @@ -0,0 +1,325 @@ +/* + * Copyright (C) 2003-2014 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 "config.h" +#include "FlacEncoderPlugin.hxx" +#include "../EncoderAPI.hxx" +#include "AudioFormat.hxx" +#include "pcm/PcmBuffer.hxx" +#include "ConfigError.hxx" +#include "util/Manual.hxx" +#include "util/DynamicFifoBuffer.hxx" +#include "util/Error.hxx" +#include "util/Domain.hxx" + +#include <FLAC/stream_encoder.h> + +#if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7 +#error libFLAC is too old +#endif + +struct flac_encoder { + Encoder encoder; + + AudioFormat audio_format; + unsigned compression; + + FLAC__StreamEncoder *fse; + + PcmBuffer expand_buffer; + + /** + * This buffer will hold encoded data from libFLAC until it is + * picked up with flac_encoder_read(). + */ + Manual<DynamicFifoBuffer<uint8_t>> output_buffer; + + flac_encoder():encoder(flac_encoder_plugin) {} +}; + +static constexpr Domain flac_encoder_domain("vorbis_encoder"); + +static bool +flac_encoder_configure(struct flac_encoder *encoder, const config_param ¶m, + gcc_unused Error &error) +{ + encoder->compression = param.GetBlockValue("compression", 5u); + + return true; +} + +static Encoder * +flac_encoder_init(const config_param ¶m, Error &error) +{ + flac_encoder *encoder = new flac_encoder(); + + /* load configuration from "param" */ + if (!flac_encoder_configure(encoder, param, error)) { + /* configuration has failed, roll back and return error */ + delete encoder; + return nullptr; + } + + return &encoder->encoder; +} + +static void +flac_encoder_finish(Encoder *_encoder) +{ + struct flac_encoder *encoder = (struct flac_encoder *)_encoder; + + /* the real libFLAC cleanup was already performed by + flac_encoder_close(), so no real work here */ + delete encoder; +} + +static bool +flac_encoder_setup(struct flac_encoder *encoder, unsigned bits_per_sample, + Error &error) +{ + if ( !FLAC__stream_encoder_set_compression_level(encoder->fse, + encoder->compression)) { + error.Format(config_domain, + "error setting flac compression to %d", + encoder->compression); + return false; + } + + if ( !FLAC__stream_encoder_set_channels(encoder->fse, + encoder->audio_format.channels)) { + error.Format(config_domain, + "error setting flac channels num to %d", + encoder->audio_format.channels); + return false; + } + if ( !FLAC__stream_encoder_set_bits_per_sample(encoder->fse, + bits_per_sample)) { + error.Format(config_domain, + "error setting flac bit format to %d", + bits_per_sample); + return false; + } + if ( !FLAC__stream_encoder_set_sample_rate(encoder->fse, + encoder->audio_format.sample_rate)) { + error.Format(config_domain, + "error setting flac sample rate to %d", + encoder->audio_format.sample_rate); + return false; + } + return true; +} + +static FLAC__StreamEncoderWriteStatus +flac_write_callback(gcc_unused const FLAC__StreamEncoder *fse, + const FLAC__byte data[], + size_t bytes, + gcc_unused unsigned samples, + gcc_unused unsigned current_frame, void *client_data) +{ + struct flac_encoder *encoder = (struct flac_encoder *) client_data; + + //transfer data to buffer + encoder->output_buffer->Append((const uint8_t *)data, bytes); + + return FLAC__STREAM_ENCODER_WRITE_STATUS_OK; +} + +static void +flac_encoder_close(Encoder *_encoder) +{ + struct flac_encoder *encoder = (struct flac_encoder *)_encoder; + + FLAC__stream_encoder_delete(encoder->fse); + + encoder->expand_buffer.Clear(); + encoder->output_buffer.Destruct(); +} + +static bool +flac_encoder_open(Encoder *_encoder, AudioFormat &audio_format, Error &error) +{ + struct flac_encoder *encoder = (struct flac_encoder *)_encoder; + unsigned bits_per_sample; + + encoder->audio_format = audio_format; + + /* FIXME: flac should support 32bit as well */ + switch (audio_format.format) { + case SampleFormat::S8: + bits_per_sample = 8; + break; + + case SampleFormat::S16: + bits_per_sample = 16; + break; + + case SampleFormat::S24_P32: + bits_per_sample = 24; + break; + + default: + bits_per_sample = 24; + audio_format.format = SampleFormat::S24_P32; + } + + /* allocate the encoder */ + encoder->fse = FLAC__stream_encoder_new(); + if (encoder->fse == nullptr) { + error.Set(flac_encoder_domain, "flac_new() failed"); + return false; + } + + if (!flac_encoder_setup(encoder, bits_per_sample, error)) { + FLAC__stream_encoder_delete(encoder->fse); + return false; + } + + encoder->output_buffer.Construct(8192); + + /* this immediately outputs data through callback */ + + { + FLAC__StreamEncoderInitStatus init_status; + + init_status = FLAC__stream_encoder_init_stream(encoder->fse, + flac_write_callback, + nullptr, nullptr, nullptr, encoder); + + if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) { + error.Format(flac_encoder_domain, + "failed to initialize encoder: %s\n", + FLAC__StreamEncoderInitStatusString[init_status]); + flac_encoder_close(_encoder); + return false; + } + } + + return true; +} + + +static bool +flac_encoder_flush(Encoder *_encoder, gcc_unused Error &error) +{ + struct flac_encoder *encoder = (struct flac_encoder *)_encoder; + + (void) FLAC__stream_encoder_finish(encoder->fse); + return true; +} + +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; + } +} + +static bool +flac_encoder_write(Encoder *_encoder, + const void *data, size_t length, + gcc_unused Error &error) +{ + struct flac_encoder *encoder = (struct flac_encoder *)_encoder; + unsigned num_frames, num_samples; + void *exbuffer; + const void *buffer = nullptr; + + /* format conversion */ + + num_frames = length / encoder->audio_format.GetFrameSize(); + num_samples = num_frames * encoder->audio_format.channels; + + switch (encoder->audio_format.format) { + case SampleFormat::S8: + exbuffer = encoder->expand_buffer.Get(length * 4); + pcm8_to_flac((int32_t *)exbuffer, (const int8_t *)data, + num_samples); + buffer = exbuffer; + break; + + case SampleFormat::S16: + exbuffer = encoder->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(encoder->fse, + (const FLAC__int32 *)buffer, + num_frames)) { + error.Set(flac_encoder_domain, "flac encoder process failed"); + return false; + } + + return true; +} + +static size_t +flac_encoder_read(Encoder *_encoder, void *dest, size_t length) +{ + struct flac_encoder *encoder = (struct flac_encoder *)_encoder; + + return encoder->output_buffer->Read((uint8_t *)dest, length); +} + +static const char * +flac_encoder_get_mime_type(gcc_unused Encoder *_encoder) +{ + return "audio/flac"; +} + +const EncoderPlugin flac_encoder_plugin = { + "flac", + flac_encoder_init, + flac_encoder_finish, + flac_encoder_open, + flac_encoder_close, + flac_encoder_flush, + flac_encoder_flush, + nullptr, + nullptr, + flac_encoder_write, + flac_encoder_read, + flac_encoder_get_mime_type, +}; + diff --git a/src/encoder/plugins/FlacEncoderPlugin.hxx b/src/encoder/plugins/FlacEncoderPlugin.hxx new file mode 100644 index 000000000..0cdc01600 --- /dev/null +++ b/src/encoder/plugins/FlacEncoderPlugin.hxx @@ -0,0 +1,25 @@ +/* + * Copyright (C) 2003-2014 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. + */ + +#ifndef MPD_ENCODER_FLAC_HXX +#define MPD_ENCODER_FLAC_HXX + +extern const struct EncoderPlugin flac_encoder_plugin; + +#endif diff --git a/src/encoder/plugins/LameEncoderPlugin.cxx b/src/encoder/plugins/LameEncoderPlugin.cxx new file mode 100644 index 000000000..484c4d0fe --- /dev/null +++ b/src/encoder/plugins/LameEncoderPlugin.cxx @@ -0,0 +1,293 @@ +/* + * Copyright (C) 2003-2014 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 "config.h" +#include "LameEncoderPlugin.hxx" +#include "../EncoderAPI.hxx" +#include "AudioFormat.hxx" +#include "ConfigError.hxx" +#include "util/NumberParser.hxx" +#include "util/ReusableArray.hxx" +#include "util/Manual.hxx" +#include "util/Error.hxx" +#include "util/Domain.hxx" + +#include <lame/lame.h> + +#include <assert.h> +#include <string.h> + +struct LameEncoder final { + Encoder encoder; + + AudioFormat audio_format; + float quality; + int bitrate; + + lame_global_flags *gfp; + + Manual<ReusableArray<unsigned char, 32768>> output_buffer; + unsigned char *output_begin, *output_end; + + LameEncoder():encoder(lame_encoder_plugin) {} + + bool Configure(const config_param ¶m, Error &error); +}; + +static constexpr Domain lame_encoder_domain("lame_encoder"); + +bool +LameEncoder::Configure(const config_param ¶m, Error &error) +{ + const char *value; + char *endptr; + + value = param.GetBlockValue("quality"); + if (value != nullptr) { + /* a quality was configured (VBR) */ + + quality = ParseDouble(value, &endptr); + + if (*endptr != '\0' || quality < -1.0 || quality > 10.0) { + error.Format(config_domain, + "quality \"%s\" is not a number in the " + "range -1 to 10", + value); + return false; + } + + if (param.GetBlockValue("bitrate") != nullptr) { + error.Set(config_domain, + "quality and bitrate are both defined"); + return false; + } + } else { + /* a bit rate was configured */ + + value = param.GetBlockValue("bitrate"); + if (value == nullptr) { + error.Set(config_domain, + "neither bitrate nor quality defined"); + return false; + } + + quality = -2.0; + bitrate = ParseInt(value, &endptr); + + if (*endptr != '\0' || bitrate <= 0) { + error.Set(config_domain, + "bitrate should be a positive integer"); + return false; + } + } + + return true; +} + +static Encoder * +lame_encoder_init(const config_param ¶m, Error &error) +{ + LameEncoder *encoder = new LameEncoder(); + + /* load configuration from "param" */ + if (!encoder->Configure(param, error)) { + /* configuration has failed, roll back and return error */ + delete encoder; + return nullptr; + } + + return &encoder->encoder; +} + +static void +lame_encoder_finish(Encoder *_encoder) +{ + LameEncoder *encoder = (LameEncoder *)_encoder; + + /* the real liblame cleanup was already performed by + lame_encoder_close(), so no real work here */ + delete encoder; +} + +static bool +lame_encoder_setup(LameEncoder *encoder, Error &error) +{ + if (encoder->quality >= -1.0) { + /* a quality was configured (VBR) */ + + if (0 != lame_set_VBR(encoder->gfp, vbr_rh)) { + error.Set(lame_encoder_domain, + "error setting lame VBR mode"); + return false; + } + if (0 != lame_set_VBR_q(encoder->gfp, encoder->quality)) { + error.Set(lame_encoder_domain, + "error setting lame VBR quality"); + return false; + } + } else { + /* a bit rate was configured */ + + if (0 != lame_set_brate(encoder->gfp, encoder->bitrate)) { + error.Set(lame_encoder_domain, + "error setting lame bitrate"); + return false; + } + } + + if (0 != lame_set_num_channels(encoder->gfp, + encoder->audio_format.channels)) { + error.Set(lame_encoder_domain, + "error setting lame num channels"); + return false; + } + + if (0 != lame_set_in_samplerate(encoder->gfp, + encoder->audio_format.sample_rate)) { + error.Set(lame_encoder_domain, + "error setting lame sample rate"); + return false; + } + + if (0 != lame_set_out_samplerate(encoder->gfp, + encoder->audio_format.sample_rate)) { + error.Set(lame_encoder_domain, + "error setting lame out sample rate"); + return false; + } + + if (0 > lame_init_params(encoder->gfp)) { + error.Set(lame_encoder_domain, + "error initializing lame params"); + return false; + } + + return true; +} + +static bool +lame_encoder_open(Encoder *_encoder, AudioFormat &audio_format, Error &error) +{ + LameEncoder *encoder = (LameEncoder *)_encoder; + + audio_format.format = SampleFormat::S16; + audio_format.channels = 2; + + encoder->audio_format = audio_format; + + encoder->gfp = lame_init(); + if (encoder->gfp == nullptr) { + error.Set(lame_encoder_domain, "lame_init() failed"); + return false; + } + + if (!lame_encoder_setup(encoder, error)) { + lame_close(encoder->gfp); + return false; + } + + encoder->output_buffer.Construct(); + encoder->output_begin = encoder->output_end = nullptr; + + return true; +} + +static void +lame_encoder_close(Encoder *_encoder) +{ + LameEncoder *encoder = (LameEncoder *)_encoder; + + lame_close(encoder->gfp); + encoder->output_buffer.Destruct(); +} + +static bool +lame_encoder_write(Encoder *_encoder, + const void *data, size_t length, + gcc_unused Error &error) +{ + LameEncoder *encoder = (LameEncoder *)_encoder; + const int16_t *src = (const int16_t*)data; + + assert(encoder->output_begin == encoder->output_end); + + const unsigned num_frames = + length / encoder->audio_format.GetFrameSize(); + const unsigned num_samples = + length / encoder->audio_format.GetSampleSize(); + + /* worst-case formula according to LAME documentation */ + const size_t output_buffer_size = 5 * num_samples / 4 + 7200; + const auto output_buffer = encoder->output_buffer->Get(output_buffer_size); + + /* this is for only 16-bit audio */ + + int bytes_out = lame_encode_buffer_interleaved(encoder->gfp, + const_cast<short *>(src), + num_frames, + output_buffer, + output_buffer_size); + + if (bytes_out < 0) { + error.Set(lame_encoder_domain, "lame encoder failed"); + return false; + } + + encoder->output_begin = output_buffer; + encoder->output_end = output_buffer + bytes_out; + return true; +} + +static size_t +lame_encoder_read(Encoder *_encoder, void *dest, size_t length) +{ + LameEncoder *encoder = (LameEncoder *)_encoder; + + const auto begin = encoder->output_begin; + assert(begin <= encoder->output_end); + const size_t remainning = encoder->output_end - begin; + if (length > remainning) + length = remainning; + + memcpy(dest, begin, length); + + encoder->output_begin = begin + length; + return length; +} + +static const char * +lame_encoder_get_mime_type(gcc_unused Encoder *_encoder) +{ + return "audio/mpeg"; +} + +const EncoderPlugin lame_encoder_plugin = { + "lame", + lame_encoder_init, + lame_encoder_finish, + lame_encoder_open, + lame_encoder_close, + nullptr, + nullptr, + nullptr, + nullptr, + lame_encoder_write, + lame_encoder_read, + lame_encoder_get_mime_type, +}; diff --git a/src/encoder/plugins/LameEncoderPlugin.hxx b/src/encoder/plugins/LameEncoderPlugin.hxx new file mode 100644 index 000000000..03e398f67 --- /dev/null +++ b/src/encoder/plugins/LameEncoderPlugin.hxx @@ -0,0 +1,25 @@ +/* + * Copyright (C) 2003-2014 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. + */ + +#ifndef MPD_ENCODER_LAME_HXX +#define MPD_ENCODER_LAME_HXX + +extern const struct EncoderPlugin lame_encoder_plugin; + +#endif diff --git a/src/encoder/plugins/NullEncoderPlugin.cxx b/src/encoder/plugins/NullEncoderPlugin.cxx new file mode 100644 index 000000000..1d571d465 --- /dev/null +++ b/src/encoder/plugins/NullEncoderPlugin.cxx @@ -0,0 +1,105 @@ +/* + * Copyright (C) 2003-2014 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 "config.h" +#include "NullEncoderPlugin.hxx" +#include "../EncoderAPI.hxx" +#include "util/Manual.hxx" +#include "util/DynamicFifoBuffer.hxx" +#include "Compiler.h" + +#include <assert.h> + +struct NullEncoder final { + Encoder encoder; + + Manual<DynamicFifoBuffer<uint8_t>> buffer; + + NullEncoder() + :encoder(null_encoder_plugin) {} +}; + +static Encoder * +null_encoder_init(gcc_unused const config_param ¶m, + gcc_unused Error &error) +{ + NullEncoder *encoder = new NullEncoder(); + return &encoder->encoder; +} + +static void +null_encoder_finish(Encoder *_encoder) +{ + NullEncoder *encoder = (NullEncoder *)_encoder; + + delete encoder; +} + +static void +null_encoder_close(Encoder *_encoder) +{ + NullEncoder *encoder = (NullEncoder *)_encoder; + + encoder->buffer.Destruct(); +} + + +static bool +null_encoder_open(Encoder *_encoder, + gcc_unused AudioFormat &audio_format, + gcc_unused Error &error) +{ + NullEncoder *encoder = (NullEncoder *)_encoder; + encoder->buffer.Construct(8192); + return true; +} + +static bool +null_encoder_write(Encoder *_encoder, + const void *data, size_t length, + gcc_unused Error &error) +{ + NullEncoder *encoder = (NullEncoder *)_encoder; + + encoder->buffer->Append((const uint8_t *)data, length); + return length; +} + +static size_t +null_encoder_read(Encoder *_encoder, void *dest, size_t length) +{ + NullEncoder *encoder = (NullEncoder *)_encoder; + + return encoder->buffer->Read((uint8_t *)dest, length); +} + +const EncoderPlugin null_encoder_plugin = { + "null", + null_encoder_init, + null_encoder_finish, + null_encoder_open, + null_encoder_close, + nullptr, + nullptr, + nullptr, + nullptr, + null_encoder_write, + null_encoder_read, + nullptr, +}; diff --git a/src/encoder/plugins/NullEncoderPlugin.hxx b/src/encoder/plugins/NullEncoderPlugin.hxx new file mode 100644 index 000000000..6acf88e49 --- /dev/null +++ b/src/encoder/plugins/NullEncoderPlugin.hxx @@ -0,0 +1,25 @@ +/* + * Copyright (C) 2003-2014 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. + */ + +#ifndef MPD_ENCODER_NULL_HXX +#define MPD_ENCODER_NULL_HXX + +extern const struct EncoderPlugin null_encoder_plugin; + +#endif diff --git a/src/encoder/plugins/OggSerial.cxx b/src/encoder/plugins/OggSerial.cxx new file mode 100644 index 000000000..677829439 --- /dev/null +++ b/src/encoder/plugins/OggSerial.cxx @@ -0,0 +1,43 @@ +/* + * Copyright (C) 2003-2014 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 "OggSerial.hxx" +#include "system/Clock.hxx" +#include "Compiler.h" + +#include <atomic> + +static std::atomic_uint next_ogg_serial; + +int +GenerateOggSerial() +{ + unsigned serial = ++next_ogg_serial; + if (gcc_unlikely(serial < 16)) { + /* first-time initialization: seed with a clock value, + which is random enough for our use */ + + /* this code is not race-free, but good enough */ + const unsigned seed = MonotonicClockMS(); + next_ogg_serial = serial = seed; + } + + return serial; +} + diff --git a/src/encoder/plugins/OggSerial.hxx b/src/encoder/plugins/OggSerial.hxx new file mode 100644 index 000000000..ceba8ebf9 --- /dev/null +++ b/src/encoder/plugins/OggSerial.hxx @@ -0,0 +1,29 @@ +/* + * Copyright (C) 2003-2014 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. + */ + +#ifndef MPD_OGG_SERIAL_HXX +#define MPD_OGG_SERIAL_HXX + +/** + * Generate the next pseudo-random Ogg serial. + */ +int +GenerateOggSerial(); + +#endif diff --git a/src/encoder/plugins/OggStream.hxx b/src/encoder/plugins/OggStream.hxx new file mode 100644 index 000000000..805238c1d --- /dev/null +++ b/src/encoder/plugins/OggStream.hxx @@ -0,0 +1,128 @@ +/* + * Copyright (C) 2003-2014 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. + */ + +#ifndef MPD_OGG_STREAM_HXX +#define MPD_OGG_STREAM_HXX + +#include "check.h" + +#include <ogg/ogg.h> + +#include <assert.h> +#include <string.h> +#include <stdint.h> + +class OggStream { + ogg_stream_state state; + + bool flush; + +#ifndef NDEBUG + bool initialized; +#endif + +public: +#ifndef NDEBUG + OggStream():initialized(false) {} + ~OggStream() { + assert(!initialized); + } +#endif + + void Initialize(int serialno) { + assert(!initialized); + + ogg_stream_init(&state, serialno); + + /* set "flush" to true, so the caller gets the full + headers on the first read() */ + flush = true; + +#ifndef NDEBUG + initialized = true; +#endif + } + + void Reinitialize(int serialno) { + assert(initialized); + + ogg_stream_reset_serialno(&state, serialno); + + /* set "flush" to true, so the caller gets the full + headers on the first read() */ + flush = true; + } + + void Deinitialize() { + assert(initialized); + + ogg_stream_clear(&state); + +#ifndef NDEBUG + initialized = false; +#endif + } + + void Flush() { + assert(initialized); + + flush = true; + } + + void PacketIn(const ogg_packet &packet) { + assert(initialized); + + ogg_stream_packetin(&state, + const_cast<ogg_packet *>(&packet)); + } + + bool PageOut(ogg_page &page) { + int result = ogg_stream_pageout(&state, &page); + if (result == 0 && flush) { + flush = false; + result = ogg_stream_flush(&state, &page); + } + + return result != 0; + } + + size_t PageOut(void *_buffer, size_t size) { + ogg_page page; + if (!PageOut(page)) + return 0; + + assert(page.header_len > 0 || page.body_len > 0); + + size_t header_len = (size_t)page.header_len; + size_t body_len = (size_t)page.body_len; + assert(header_len <= size); + + if (header_len + body_len > size) + /* TODO: better overflow handling */ + body_len = size - header_len; + + uint8_t *buffer = (uint8_t *)_buffer; + memcpy(buffer, page.header, header_len); + memcpy(buffer + header_len, page.body, body_len); + + return header_len + body_len; + } +}; + +#endif diff --git a/src/encoder/plugins/OpusEncoderPlugin.cxx b/src/encoder/plugins/OpusEncoderPlugin.cxx new file mode 100644 index 000000000..9fbdc8711 --- /dev/null +++ b/src/encoder/plugins/OpusEncoderPlugin.cxx @@ -0,0 +1,420 @@ +/* + * Copyright (C) 2003-2014 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 "config.h" +#include "OpusEncoderPlugin.hxx" +#include "OggStream.hxx" +#include "OggSerial.hxx" +#include "../EncoderAPI.hxx" +#include "AudioFormat.hxx" +#include "ConfigError.hxx" +#include "util/Error.hxx" +#include "util/Domain.hxx" +#include "system/ByteOrder.hxx" + +#include <opus.h> +#include <ogg/ogg.h> + +#include <glib.h> + +#include <assert.h> +#include <stdlib.h> + +struct opus_encoder { + /** the base class */ + Encoder encoder; + + /* configuration */ + + opus_int32 bitrate; + int complexity; + int signal; + + /* runtime information */ + + AudioFormat audio_format; + + size_t frame_size; + + size_t buffer_frames, buffer_size, buffer_position; + uint8_t *buffer; + + OpusEncoder *enc; + + unsigned char buffer2[1275 * 3 + 7]; + + OggStream stream; + + int lookahead; + + ogg_int64_t packetno; + + ogg_int64_t granulepos; + + opus_encoder():encoder(opus_encoder_plugin) {} +}; + +static constexpr Domain opus_encoder_domain("opus_encoder"); + +static bool +opus_encoder_configure(struct opus_encoder *encoder, + const config_param ¶m, Error &error) +{ + const char *value = param.GetBlockValue("bitrate", "auto"); + if (strcmp(value, "auto") == 0) + encoder->bitrate = OPUS_AUTO; + else if (strcmp(value, "max") == 0) + encoder->bitrate = OPUS_BITRATE_MAX; + else { + char *endptr; + encoder->bitrate = strtoul(value, &endptr, 10); + if (endptr == value || *endptr != 0 || + encoder->bitrate < 500 || encoder->bitrate > 512000) { + error.Set(config_domain, "Invalid bit rate"); + return false; + } + } + + encoder->complexity = param.GetBlockValue("complexity", 10u); + if (encoder->complexity > 10) { + error.Format(config_domain, "Invalid complexity"); + return false; + } + + value = param.GetBlockValue("signal", "auto"); + if (strcmp(value, "auto") == 0) + encoder->signal = OPUS_AUTO; + else if (strcmp(value, "voice") == 0) + encoder->signal = OPUS_SIGNAL_VOICE; + else if (strcmp(value, "music") == 0) + encoder->signal = OPUS_SIGNAL_MUSIC; + else { + error.Format(config_domain, "Invalid signal"); + return false; + } + + return true; +} + +static Encoder * +opus_encoder_init(const config_param ¶m, Error &error) +{ + opus_encoder *encoder = new opus_encoder(); + + /* load configuration from "param" */ + if (!opus_encoder_configure(encoder, param, error)) { + /* configuration has failed, roll back and return error */ + delete encoder; + return NULL; + } + + return &encoder->encoder; +} + +static void +opus_encoder_finish(Encoder *_encoder) +{ + struct opus_encoder *encoder = (struct opus_encoder *)_encoder; + + /* the real libopus cleanup was already performed by + opus_encoder_close(), so no real work here */ + delete encoder; +} + +static bool +opus_encoder_open(Encoder *_encoder, + AudioFormat &audio_format, + Error &error) +{ + struct opus_encoder *encoder = (struct opus_encoder *)_encoder; + + /* libopus supports only 48 kHz */ + audio_format.sample_rate = 48000; + + if (audio_format.channels > 2) + audio_format.channels = 1; + + switch (audio_format.format) { + case SampleFormat::S16: + case SampleFormat::FLOAT: + break; + + case SampleFormat::S8: + audio_format.format = SampleFormat::S16; + break; + + default: + audio_format.format = SampleFormat::FLOAT; + break; + } + + encoder->audio_format = audio_format; + encoder->frame_size = audio_format.GetFrameSize(); + + int error_code; + encoder->enc = opus_encoder_create(audio_format.sample_rate, + audio_format.channels, + OPUS_APPLICATION_AUDIO, + &error_code); + if (encoder->enc == nullptr) { + error.Set(opus_encoder_domain, error_code, + opus_strerror(error_code)); + return false; + } + + opus_encoder_ctl(encoder->enc, OPUS_SET_BITRATE(encoder->bitrate)); + opus_encoder_ctl(encoder->enc, + OPUS_SET_COMPLEXITY(encoder->complexity)); + opus_encoder_ctl(encoder->enc, OPUS_SET_SIGNAL(encoder->signal)); + + opus_encoder_ctl(encoder->enc, OPUS_GET_LOOKAHEAD(&encoder->lookahead)); + + encoder->buffer_frames = audio_format.sample_rate / 50; + encoder->buffer_size = encoder->frame_size * encoder->buffer_frames; + encoder->buffer_position = 0; + encoder->buffer = (unsigned char *)g_malloc(encoder->buffer_size); + + encoder->stream.Initialize(GenerateOggSerial()); + encoder->packetno = 0; + + return true; +} + +static void +opus_encoder_close(Encoder *_encoder) +{ + struct opus_encoder *encoder = (struct opus_encoder *)_encoder; + + encoder->stream.Deinitialize(); + g_free(encoder->buffer); + opus_encoder_destroy(encoder->enc); +} + +static bool +opus_encoder_do_encode(struct opus_encoder *encoder, bool eos, + Error &error) +{ + assert(encoder->buffer_position == encoder->buffer_size); + + opus_int32 result = + encoder->audio_format.format == SampleFormat::S16 + ? opus_encode(encoder->enc, + (const opus_int16 *)encoder->buffer, + encoder->buffer_frames, + encoder->buffer2, + sizeof(encoder->buffer2)) + : opus_encode_float(encoder->enc, + (const float *)encoder->buffer, + encoder->buffer_frames, + encoder->buffer2, + sizeof(encoder->buffer2)); + if (result < 0) { + error.Set(opus_encoder_domain, "Opus encoder error"); + return false; + } + + encoder->granulepos += encoder->buffer_frames; + + ogg_packet packet; + packet.packet = encoder->buffer2; + packet.bytes = result; + packet.b_o_s = false; + packet.e_o_s = eos; + packet.granulepos = encoder->granulepos; + packet.packetno = encoder->packetno++; + encoder->stream.PacketIn(packet); + + encoder->buffer_position = 0; + + return true; +} + +static bool +opus_encoder_end(Encoder *_encoder, Error &error) +{ + struct opus_encoder *encoder = (struct opus_encoder *)_encoder; + + encoder->stream.Flush(); + + memset(encoder->buffer + encoder->buffer_position, 0, + encoder->buffer_size - encoder->buffer_position); + encoder->buffer_position = encoder->buffer_size; + + return opus_encoder_do_encode(encoder, true, error); +} + +static bool +opus_encoder_flush(Encoder *_encoder, gcc_unused Error &error) +{ + struct opus_encoder *encoder = (struct opus_encoder *)_encoder; + + encoder->stream.Flush(); + return true; +} + +static bool +opus_encoder_write_silence(struct opus_encoder *encoder, unsigned fill_frames, + Error &error) +{ + size_t fill_bytes = fill_frames * encoder->frame_size; + + while (fill_bytes > 0) { + size_t nbytes = + encoder->buffer_size - encoder->buffer_position; + if (nbytes > fill_bytes) + nbytes = fill_bytes; + + memset(encoder->buffer + encoder->buffer_position, + 0, nbytes); + encoder->buffer_position += nbytes; + fill_bytes -= nbytes; + + if (encoder->buffer_position == encoder->buffer_size && + !opus_encoder_do_encode(encoder, false, error)) + return false; + } + + return true; +} + +static bool +opus_encoder_write(Encoder *_encoder, + const void *_data, size_t length, + Error &error) +{ + struct opus_encoder *encoder = (struct opus_encoder *)_encoder; + const uint8_t *data = (const uint8_t *)_data; + + if (encoder->lookahead > 0) { + /* generate some silence at the beginning of the + stream */ + + assert(encoder->buffer_position == 0); + + if (!opus_encoder_write_silence(encoder, encoder->lookahead, + error)) + return false; + + encoder->lookahead = 0; + } + + while (length > 0) { + size_t nbytes = + encoder->buffer_size - encoder->buffer_position; + if (nbytes > length) + nbytes = length; + + memcpy(encoder->buffer + encoder->buffer_position, + data, nbytes); + data += nbytes; + length -= nbytes; + encoder->buffer_position += nbytes; + + if (encoder->buffer_position == encoder->buffer_size && + !opus_encoder_do_encode(encoder, false, error)) + return false; + } + + return true; +} + +static void +opus_encoder_generate_head(struct opus_encoder *encoder) +{ + unsigned char header[19]; + memcpy(header, "OpusHead", 8); + header[8] = 1; + header[9] = encoder->audio_format.channels; + *(uint16_t *)(header + 10) = ToLE16(encoder->lookahead); + *(uint32_t *)(header + 12) = + ToLE32(encoder->audio_format.sample_rate); + header[16] = 0; + header[17] = 0; + header[18] = 0; + + ogg_packet packet; + packet.packet = header; + packet.bytes = 19; + packet.b_o_s = true; + packet.e_o_s = false; + packet.granulepos = 0; + packet.packetno = encoder->packetno++; + encoder->stream.PacketIn(packet); + encoder->stream.Flush(); +} + +static void +opus_encoder_generate_tags(struct opus_encoder *encoder) +{ + const char *version = opus_get_version_string(); + size_t version_length = strlen(version); + + size_t comments_size = 8 + 4 + version_length + 4; + unsigned char *comments = (unsigned char *)g_malloc(comments_size); + memcpy(comments, "OpusTags", 8); + *(uint32_t *)(comments + 8) = ToLE32(version_length); + memcpy(comments + 12, version, version_length); + *(uint32_t *)(comments + 12 + version_length) = ToLE32(0); + + ogg_packet packet; + packet.packet = comments; + packet.bytes = comments_size; + packet.b_o_s = false; + packet.e_o_s = false; + packet.granulepos = 0; + packet.packetno = encoder->packetno++; + encoder->stream.PacketIn(packet); + encoder->stream.Flush(); + + g_free(comments); +} + +static size_t +opus_encoder_read(Encoder *_encoder, void *dest, size_t length) +{ + struct opus_encoder *encoder = (struct opus_encoder *)_encoder; + + if (encoder->packetno == 0) + opus_encoder_generate_head(encoder); + else if (encoder->packetno == 1) + opus_encoder_generate_tags(encoder); + + return encoder->stream.PageOut(dest, length); +} + +static const char * +opus_encoder_get_mime_type(gcc_unused Encoder *_encoder) +{ + return "audio/ogg"; +} + +const EncoderPlugin opus_encoder_plugin = { + "opus", + opus_encoder_init, + opus_encoder_finish, + opus_encoder_open, + opus_encoder_close, + opus_encoder_end, + opus_encoder_flush, + nullptr, + nullptr, + opus_encoder_write, + opus_encoder_read, + opus_encoder_get_mime_type, +}; diff --git a/src/encoder/plugins/OpusEncoderPlugin.hxx b/src/encoder/plugins/OpusEncoderPlugin.hxx new file mode 100644 index 000000000..4e71694b9 --- /dev/null +++ b/src/encoder/plugins/OpusEncoderPlugin.hxx @@ -0,0 +1,25 @@ +/* + * Copyright (C) 2003-2014 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. + */ + +#ifndef MPD_ENCODER_OPUS_H +#define MPD_ENCODER_OPUS_H + +extern const struct EncoderPlugin opus_encoder_plugin; + +#endif diff --git a/src/encoder/plugins/ShineEncoderPlugin.cxx b/src/encoder/plugins/ShineEncoderPlugin.cxx new file mode 100644 index 000000000..5b1b95a27 --- /dev/null +++ b/src/encoder/plugins/ShineEncoderPlugin.cxx @@ -0,0 +1,271 @@ +/* + * Copyright (C) 2003-2014 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 "ShineEncoderPlugin.hxx" +#include "config.h" +#include "../EncoderAPI.hxx" +#include "AudioFormat.hxx" +#include "ConfigError.hxx" +#include "util/Manual.hxx" +#include "util/NumberParser.hxx" +#include "util/DynamicFifoBuffer.hxx" +#include "util/Error.hxx" +#include "util/Domain.hxx" + +extern "C" +{ +#include <shine/layer3.h> +} + +static constexpr size_t BUFFER_INIT_SIZE = 8192; +static constexpr unsigned CHANNELS = 2; + +struct ShineEncoder { + Encoder encoder; + + AudioFormat audio_format; + + shine_t shine; + + shine_config_t config; + + size_t frame_size; + size_t input_pos; + int16_t *stereo[CHANNELS]; + + Manual<DynamicFifoBuffer<uint8_t>> output_buffer; + + ShineEncoder():encoder(shine_encoder_plugin){} + + bool Configure(const config_param ¶m, Error &error); + + bool Setup(Error &error); + + bool WriteChunk(bool flush); +}; + +static constexpr Domain shine_encoder_domain("shine_encoder"); + +inline bool +ShineEncoder::Configure(const config_param ¶m, + gcc_unused Error &error) +{ + shine_set_config_mpeg_defaults(&config.mpeg); + config.mpeg.bitr = param.GetBlockValue("bitrate", 128); + + return true; +} + +static Encoder * +shine_encoder_init(const config_param ¶m, Error &error) +{ + ShineEncoder *encoder = new ShineEncoder(); + + /* load configuration from "param" */ + if (!encoder->Configure(param, error)) { + /* configuration has failed, roll back and return error */ + delete encoder; + return nullptr; + } + + return &encoder->encoder; +} + +static void +shine_encoder_finish(Encoder *_encoder) +{ + ShineEncoder *encoder = (ShineEncoder *)_encoder; + + delete encoder; +} + +inline bool +ShineEncoder::Setup(Error &error) +{ + config.mpeg.mode = audio_format.channels == 2 ? STEREO : MONO; + config.wave.samplerate = audio_format.sample_rate; + config.wave.channels = + audio_format.channels == 2 ? PCM_STEREO : PCM_MONO; + + if (shine_check_config(config.wave.samplerate, config.mpeg.bitr) < 0) { + error.Format(config_domain, + "error configuring shine. " + "samplerate %d and bitrate %d configuration" + " not supported.", + config.wave.samplerate, + config.mpeg.bitr); + + return false; + } + + shine = shine_initialise(&config); + + if (!shine) { + error.Format(config_domain, + "error initializing shine."); + + return false; + } + + frame_size = shine_samples_per_pass(shine); + + return true; +} + +static bool +shine_encoder_open(Encoder *_encoder, AudioFormat &audio_format, Error &error) +{ + ShineEncoder *encoder = (ShineEncoder *)_encoder; + + audio_format.format = SampleFormat::S16; + audio_format.channels = CHANNELS; + encoder->audio_format = audio_format; + + if (!encoder->Setup(error)) + return false; + + encoder->stereo[0] = new int16_t[encoder->frame_size]; + encoder->stereo[1] = new int16_t[encoder->frame_size]; + /* workaround for bug: + https://github.com/savonet/shine/issues/11 */ + encoder->input_pos = SHINE_MAX_SAMPLES + 1; + + encoder->output_buffer.Construct(BUFFER_INIT_SIZE); + + return true; +} + +static void +shine_encoder_close(Encoder *_encoder) +{ + ShineEncoder *encoder = (ShineEncoder *)_encoder; + + if (encoder->input_pos > SHINE_MAX_SAMPLES) { + /* write zero chunk */ + encoder->input_pos = 0; + encoder->WriteChunk(true); + } + + shine_close(encoder->shine); + delete[] encoder->stereo[0]; + delete[] encoder->stereo[1]; + encoder->output_buffer.Destruct(); +} + +bool +ShineEncoder::WriteChunk(bool flush) +{ + if (flush || input_pos == frame_size) { + long written; + + if (flush) { + /* fill remaining with 0s */ + for (; input_pos < frame_size; input_pos++) { + stereo[0][input_pos] = stereo[1][input_pos] = 0; + } + } + + const uint8_t *out = + shine_encode_buffer(shine, stereo, &written); + + if (written > 0) + output_buffer->Append(out, written); + + input_pos = 0; + } + + return true; +} + +static bool +shine_encoder_write(Encoder *_encoder, + const void *_data, size_t length, + gcc_unused Error &error) +{ + ShineEncoder *encoder = (ShineEncoder *)_encoder; + const int16_t *data = (const int16_t*)_data; + length /= sizeof(*data) * encoder->audio_format.channels; + size_t written = 0; + + if (encoder->input_pos > SHINE_MAX_SAMPLES) { + encoder->input_pos = 0; + } + + /* write all data to de-interleaved buffers */ + while (written < length) { + for (; + written < length + && encoder->input_pos < encoder->frame_size; + written++, encoder->input_pos++) { + const size_t base = + written * encoder->audio_format.channels; + encoder->stereo[0][encoder->input_pos] = data[base]; + encoder->stereo[1][encoder->input_pos] = data[base + 1]; + } + /* write if chunk is filled */ + encoder->WriteChunk(false); + } + + return true; +} + +static bool +shine_encoder_flush(Encoder *_encoder, gcc_unused Error &error) +{ + ShineEncoder *encoder = (ShineEncoder *)_encoder; + long written; + + /* flush buffers and flush shine */ + encoder->WriteChunk(true); + const uint8_t *data = shine_flush(encoder->shine, &written); + + if (written > 0) + encoder->output_buffer->Append(data, written); + + return true; +} + +static size_t +shine_encoder_read(Encoder *_encoder, void *dest, size_t length) +{ + ShineEncoder *encoder = (ShineEncoder *)_encoder; + + return encoder->output_buffer->Read((uint8_t *)dest, length); +} + +static const char * +shine_encoder_get_mime_type(gcc_unused Encoder *_encoder) +{ + return "audio/mpeg"; +} + +const EncoderPlugin shine_encoder_plugin = { + "shine", + shine_encoder_init, + shine_encoder_finish, + shine_encoder_open, + shine_encoder_close, + shine_encoder_flush, + shine_encoder_flush, + nullptr, + nullptr, + shine_encoder_write, + shine_encoder_read, + shine_encoder_get_mime_type, +}; diff --git a/src/encoder/plugins/ShineEncoderPlugin.hxx b/src/encoder/plugins/ShineEncoderPlugin.hxx new file mode 100644 index 000000000..8b1520a74 --- /dev/null +++ b/src/encoder/plugins/ShineEncoderPlugin.hxx @@ -0,0 +1,25 @@ +/* + * Copyright (C) 2003-2014 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. + */ + +#ifndef MPD_ENCODER_SHINE_HXX +#define MPD_ENCODER_SHINE_HXX + +extern const struct EncoderPlugin shine_encoder_plugin; + +#endif diff --git a/src/encoder/plugins/TwolameEncoderPlugin.cxx b/src/encoder/plugins/TwolameEncoderPlugin.cxx new file mode 100644 index 000000000..cea72bfdd --- /dev/null +++ b/src/encoder/plugins/TwolameEncoderPlugin.cxx @@ -0,0 +1,314 @@ +/* + * Copyright (C) 2003-2014 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 "config.h" +#include "TwolameEncoderPlugin.hxx" +#include "../EncoderAPI.hxx" +#include "AudioFormat.hxx" +#include "ConfigError.hxx" +#include "util/NumberParser.hxx" +#include "util/Error.hxx" +#include "util/Domain.hxx" +#include "Log.hxx" + +#include <twolame.h> + +#include <assert.h> +#include <string.h> + +struct TwolameEncoder final { + Encoder encoder; + + AudioFormat audio_format; + float quality; + int bitrate; + + twolame_options *options; + + unsigned char output_buffer[32768]; + size_t output_buffer_length; + size_t output_buffer_position; + + /** + * Call libtwolame's flush function when the output_buffer is + * empty? + */ + bool flush; + + TwolameEncoder():encoder(twolame_encoder_plugin) {} + + bool Configure(const config_param ¶m, Error &error); +}; + +static constexpr Domain twolame_encoder_domain("twolame_encoder"); + +bool +TwolameEncoder::Configure(const config_param ¶m, Error &error) +{ + const char *value; + char *endptr; + + value = param.GetBlockValue("quality"); + if (value != nullptr) { + /* a quality was configured (VBR) */ + + quality = ParseDouble(value, &endptr); + + if (*endptr != '\0' || quality < -1.0 || quality > 10.0) { + error.Format(config_domain, + "quality \"%s\" is not a number in the " + "range -1 to 10", + value); + return false; + } + + if (param.GetBlockValue("bitrate") != nullptr) { + error.Set(config_domain, + "quality and bitrate are both defined"); + return false; + } + } else { + /* a bit rate was configured */ + + value = param.GetBlockValue("bitrate"); + if (value == nullptr) { + error.Set(config_domain, + "neither bitrate nor quality defined"); + return false; + } + + quality = -2.0; + bitrate = ParseInt(value, &endptr); + + if (*endptr != '\0' || bitrate <= 0) { + error.Set(config_domain, + "bitrate should be a positive integer"); + return false; + } + } + + return true; +} + +static Encoder * +twolame_encoder_init(const config_param ¶m, Error &error_r) +{ + FormatDebug(twolame_encoder_domain, + "libtwolame version %s", get_twolame_version()); + + TwolameEncoder *encoder = new TwolameEncoder(); + + /* load configuration from "param" */ + if (!encoder->Configure(param, error_r)) { + /* configuration has failed, roll back and return error */ + delete encoder; + return nullptr; + } + + return &encoder->encoder; +} + +static void +twolame_encoder_finish(Encoder *_encoder) +{ + TwolameEncoder *encoder = (TwolameEncoder *)_encoder; + + /* the real libtwolame cleanup was already performed by + twolame_encoder_close(), so no real work here */ + delete encoder; +} + +static bool +twolame_encoder_setup(TwolameEncoder *encoder, Error &error) +{ + if (encoder->quality >= -1.0) { + /* a quality was configured (VBR) */ + + if (0 != twolame_set_VBR(encoder->options, true)) { + error.Set(twolame_encoder_domain, + "error setting twolame VBR mode"); + return false; + } + if (0 != twolame_set_VBR_q(encoder->options, encoder->quality)) { + error.Set(twolame_encoder_domain, + "error setting twolame VBR quality"); + return false; + } + } else { + /* a bit rate was configured */ + + if (0 != twolame_set_brate(encoder->options, encoder->bitrate)) { + error.Set(twolame_encoder_domain, + "error setting twolame bitrate"); + return false; + } + } + + if (0 != twolame_set_num_channels(encoder->options, + encoder->audio_format.channels)) { + error.Set(twolame_encoder_domain, + "error setting twolame num channels"); + return false; + } + + if (0 != twolame_set_in_samplerate(encoder->options, + encoder->audio_format.sample_rate)) { + error.Set(twolame_encoder_domain, + "error setting twolame sample rate"); + return false; + } + + if (0 > twolame_init_params(encoder->options)) { + error.Set(twolame_encoder_domain, + "error initializing twolame params"); + return false; + } + + return true; +} + +static bool +twolame_encoder_open(Encoder *_encoder, AudioFormat &audio_format, + Error &error) +{ + TwolameEncoder *encoder = (TwolameEncoder *)_encoder; + + audio_format.format = SampleFormat::S16; + audio_format.channels = 2; + + encoder->audio_format = audio_format; + + encoder->options = twolame_init(); + if (encoder->options == nullptr) { + error.Set(twolame_encoder_domain, "twolame_init() failed"); + return false; + } + + if (!twolame_encoder_setup(encoder, error)) { + twolame_close(&encoder->options); + return false; + } + + encoder->output_buffer_length = 0; + encoder->output_buffer_position = 0; + encoder->flush = false; + + return true; +} + +static void +twolame_encoder_close(Encoder *_encoder) +{ + TwolameEncoder *encoder = (TwolameEncoder *)_encoder; + + twolame_close(&encoder->options); +} + +static bool +twolame_encoder_flush(Encoder *_encoder, gcc_unused Error &error) +{ + TwolameEncoder *encoder = (TwolameEncoder *)_encoder; + + encoder->flush = true; + return true; +} + +static bool +twolame_encoder_write(Encoder *_encoder, + const void *data, size_t length, + gcc_unused Error &error) +{ + TwolameEncoder *encoder = (TwolameEncoder *)_encoder; + const int16_t *src = (const int16_t*)data; + + assert(encoder->output_buffer_position == + encoder->output_buffer_length); + + const unsigned num_frames = + length / encoder->audio_format.GetFrameSize(); + + int bytes_out = twolame_encode_buffer_interleaved(encoder->options, + src, num_frames, + encoder->output_buffer, + sizeof(encoder->output_buffer)); + if (bytes_out < 0) { + error.Set(twolame_encoder_domain, "twolame encoder failed"); + return false; + } + + encoder->output_buffer_length = (size_t)bytes_out; + encoder->output_buffer_position = 0; + return true; +} + +static size_t +twolame_encoder_read(Encoder *_encoder, void *dest, size_t length) +{ + TwolameEncoder *encoder = (TwolameEncoder *)_encoder; + + assert(encoder->output_buffer_position <= + encoder->output_buffer_length); + + if (encoder->output_buffer_position == encoder->output_buffer_length && + encoder->flush) { + int ret = twolame_encode_flush(encoder->options, + encoder->output_buffer, + sizeof(encoder->output_buffer)); + if (ret > 0) { + encoder->output_buffer_length = (size_t)ret; + encoder->output_buffer_position = 0; + } + + encoder->flush = false; + } + + + const size_t remainning = encoder->output_buffer_length + - encoder->output_buffer_position; + if (length > remainning) + length = remainning; + + memcpy(dest, encoder->output_buffer + encoder->output_buffer_position, + length); + + encoder->output_buffer_position += length; + + return length; +} + +static const char * +twolame_encoder_get_mime_type(gcc_unused Encoder *_encoder) +{ + return "audio/mpeg"; +} + +const EncoderPlugin twolame_encoder_plugin = { + "twolame", + twolame_encoder_init, + twolame_encoder_finish, + twolame_encoder_open, + twolame_encoder_close, + twolame_encoder_flush, + twolame_encoder_flush, + nullptr, + nullptr, + twolame_encoder_write, + twolame_encoder_read, + twolame_encoder_get_mime_type, +}; diff --git a/src/encoder/plugins/TwolameEncoderPlugin.hxx b/src/encoder/plugins/TwolameEncoderPlugin.hxx new file mode 100644 index 000000000..531dd3e90 --- /dev/null +++ b/src/encoder/plugins/TwolameEncoderPlugin.hxx @@ -0,0 +1,25 @@ +/* + * Copyright (C) 2003-2014 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. + */ + +#ifndef MPD_ENCODER_TWOLAME_HXX +#define MPD_ENCODER_TWOLAME_HXX + +extern const struct EncoderPlugin twolame_encoder_plugin; + +#endif diff --git a/src/encoder/plugins/VorbisEncoderPlugin.cxx b/src/encoder/plugins/VorbisEncoderPlugin.cxx new file mode 100644 index 000000000..356d67571 --- /dev/null +++ b/src/encoder/plugins/VorbisEncoderPlugin.cxx @@ -0,0 +1,365 @@ +/* + * Copyright (C) 2003-2014 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 "config.h" +#include "VorbisEncoderPlugin.hxx" +#include "OggStream.hxx" +#include "OggSerial.hxx" +#include "../EncoderAPI.hxx" +#include "tag/Tag.hxx" +#include "AudioFormat.hxx" +#include "ConfigError.hxx" +#include "util/NumberParser.hxx" +#include "util/Error.hxx" +#include "util/Domain.hxx" + +#include <vorbis/vorbisenc.h> + +#include <glib.h> + +struct vorbis_encoder { + /** the base class */ + Encoder encoder; + + /* configuration */ + + float quality; + int bitrate; + + /* runtime information */ + + AudioFormat audio_format; + + vorbis_dsp_state vd; + vorbis_block vb; + vorbis_info vi; + + OggStream stream; + + vorbis_encoder():encoder(vorbis_encoder_plugin) {} +}; + +static constexpr Domain vorbis_encoder_domain("vorbis_encoder"); + +static bool +vorbis_encoder_configure(struct vorbis_encoder *encoder, + const config_param ¶m, Error &error) +{ + const char *value = param.GetBlockValue("quality"); + if (value != nullptr) { + /* a quality was configured (VBR) */ + + char *endptr; + encoder->quality = ParseDouble(value, &endptr); + + if (*endptr != '\0' || encoder->quality < -1.0 || + encoder->quality > 10.0) { + error.Format(config_domain, + "quality \"%s\" is not a number in the " + "range -1 to 10", + value); + return false; + } + + if (param.GetBlockValue("bitrate") != nullptr) { + error.Set(config_domain, + "quality and bitrate are both defined"); + return false; + } + } else { + /* a bit rate was configured */ + + value = param.GetBlockValue("bitrate"); + if (value == nullptr) { + error.Set(config_domain, + "neither bitrate nor quality defined"); + return false; + } + + encoder->quality = -2.0; + + char *endptr; + encoder->bitrate = ParseInt(value, &endptr); + if (*endptr != '\0' || encoder->bitrate <= 0) { + error.Set(config_domain, + "bitrate should be a positive integer"); + return false; + } + } + + return true; +} + +static Encoder * +vorbis_encoder_init(const config_param ¶m, Error &error) +{ + vorbis_encoder *encoder = new vorbis_encoder(); + + /* load configuration from "param" */ + if (!vorbis_encoder_configure(encoder, param, error)) { + /* configuration has failed, roll back and return error */ + delete encoder; + return nullptr; + } + + return &encoder->encoder; +} + +static void +vorbis_encoder_finish(Encoder *_encoder) +{ + struct vorbis_encoder *encoder = (struct vorbis_encoder *)_encoder; + + /* the real libvorbis/libogg cleanup was already performed by + vorbis_encoder_close(), so no real work here */ + delete encoder; +} + +static bool +vorbis_encoder_reinit(struct vorbis_encoder *encoder, Error &error) +{ + vorbis_info_init(&encoder->vi); + + if (encoder->quality >= -1.0) { + /* a quality was configured (VBR) */ + + if (0 != vorbis_encode_init_vbr(&encoder->vi, + encoder->audio_format.channels, + encoder->audio_format.sample_rate, + encoder->quality * 0.1)) { + error.Set(vorbis_encoder_domain, + "error initializing vorbis vbr"); + vorbis_info_clear(&encoder->vi); + return false; + } + } else { + /* a bit rate was configured */ + + if (0 != vorbis_encode_init(&encoder->vi, + encoder->audio_format.channels, + encoder->audio_format.sample_rate, -1.0, + encoder->bitrate * 1000, -1.0)) { + error.Set(vorbis_encoder_domain, + "error initializing vorbis encoder"); + vorbis_info_clear(&encoder->vi); + return false; + } + } + + vorbis_analysis_init(&encoder->vd, &encoder->vi); + vorbis_block_init(&encoder->vd, &encoder->vb); + encoder->stream.Initialize(GenerateOggSerial()); + + return true; +} + +static void +vorbis_encoder_headerout(struct vorbis_encoder *encoder, vorbis_comment *vc) +{ + ogg_packet packet, comments, codebooks; + + vorbis_analysis_headerout(&encoder->vd, vc, + &packet, &comments, &codebooks); + + encoder->stream.PacketIn(packet); + encoder->stream.PacketIn(comments); + encoder->stream.PacketIn(codebooks); +} + +static void +vorbis_encoder_send_header(struct vorbis_encoder *encoder) +{ + vorbis_comment vc; + + vorbis_comment_init(&vc); + vorbis_encoder_headerout(encoder, &vc); + vorbis_comment_clear(&vc); +} + +static bool +vorbis_encoder_open(Encoder *_encoder, + AudioFormat &audio_format, + Error &error) +{ + struct vorbis_encoder *encoder = (struct vorbis_encoder *)_encoder; + + audio_format.format = SampleFormat::FLOAT; + + encoder->audio_format = audio_format; + + if (!vorbis_encoder_reinit(encoder, error)) + return false; + + vorbis_encoder_send_header(encoder); + + return true; +} + +static void +vorbis_encoder_clear(struct vorbis_encoder *encoder) +{ + encoder->stream.Deinitialize(); + vorbis_block_clear(&encoder->vb); + vorbis_dsp_clear(&encoder->vd); + vorbis_info_clear(&encoder->vi); +} + +static void +vorbis_encoder_close(Encoder *_encoder) +{ + struct vorbis_encoder *encoder = (struct vorbis_encoder *)_encoder; + + vorbis_encoder_clear(encoder); +} + +static void +vorbis_encoder_blockout(struct vorbis_encoder *encoder) +{ + while (vorbis_analysis_blockout(&encoder->vd, &encoder->vb) == 1) { + vorbis_analysis(&encoder->vb, nullptr); + vorbis_bitrate_addblock(&encoder->vb); + + ogg_packet packet; + while (vorbis_bitrate_flushpacket(&encoder->vd, &packet)) + encoder->stream.PacketIn(packet); + } +} + +static bool +vorbis_encoder_flush(Encoder *_encoder, gcc_unused Error &error) +{ + struct vorbis_encoder *encoder = (struct vorbis_encoder *)_encoder; + + encoder->stream.Flush(); + return true; +} + +static bool +vorbis_encoder_pre_tag(Encoder *_encoder, gcc_unused Error &error) +{ + struct vorbis_encoder *encoder = (struct vorbis_encoder *)_encoder; + + vorbis_analysis_wrote(&encoder->vd, 0); + vorbis_encoder_blockout(encoder); + + /* reinitialize vorbis_dsp_state and vorbis_block to reset the + end-of-stream marker */ + vorbis_block_clear(&encoder->vb); + vorbis_dsp_clear(&encoder->vd); + vorbis_analysis_init(&encoder->vd, &encoder->vi); + vorbis_block_init(&encoder->vd, &encoder->vb); + + encoder->stream.Flush(); + return true; +} + +static void +copy_tag_to_vorbis_comment(vorbis_comment *vc, const Tag *tag) +{ + for (unsigned i = 0; i < tag->num_items; i++) { + const TagItem &item = *tag->items[i]; + char *name = g_ascii_strup(tag_item_names[item.type], -1); + vorbis_comment_add_tag(vc, name, item.value); + g_free(name); + } +} + +static bool +vorbis_encoder_tag(Encoder *_encoder, const Tag *tag, + gcc_unused Error &error) +{ + struct vorbis_encoder *encoder = (struct vorbis_encoder *)_encoder; + vorbis_comment comment; + + /* write the vorbis_comment object */ + + vorbis_comment_init(&comment); + copy_tag_to_vorbis_comment(&comment, tag); + + /* reset ogg_stream_state and begin a new stream */ + + encoder->stream.Reinitialize(GenerateOggSerial()); + + /* send that vorbis_comment to the ogg_stream_state */ + + vorbis_encoder_headerout(encoder, &comment); + vorbis_comment_clear(&comment); + + return true; +} + +static void +interleaved_to_vorbis_buffer(float **dest, const float *src, + unsigned num_frames, unsigned num_channels) +{ + for (unsigned i = 0; i < num_frames; i++) + for (unsigned j = 0; j < num_channels; j++) + dest[j][i] = *src++; +} + +static bool +vorbis_encoder_write(Encoder *_encoder, + const void *data, size_t length, + gcc_unused Error &error) +{ + struct vorbis_encoder *encoder = (struct vorbis_encoder *)_encoder; + + unsigned num_frames = length / encoder->audio_format.GetFrameSize(); + + /* this is for only 16-bit audio */ + + interleaved_to_vorbis_buffer(vorbis_analysis_buffer(&encoder->vd, + num_frames), + (const float *)data, + num_frames, + encoder->audio_format.channels); + + vorbis_analysis_wrote(&encoder->vd, num_frames); + vorbis_encoder_blockout(encoder); + return true; +} + +static size_t +vorbis_encoder_read(Encoder *_encoder, void *dest, size_t length) +{ + struct vorbis_encoder *encoder = (struct vorbis_encoder *)_encoder; + + return encoder->stream.PageOut(dest, length); +} + +static const char * +vorbis_encoder_get_mime_type(gcc_unused Encoder *_encoder) +{ + return "audio/ogg"; +} + +const EncoderPlugin vorbis_encoder_plugin = { + "vorbis", + vorbis_encoder_init, + vorbis_encoder_finish, + vorbis_encoder_open, + vorbis_encoder_close, + vorbis_encoder_pre_tag, + vorbis_encoder_flush, + vorbis_encoder_pre_tag, + vorbis_encoder_tag, + vorbis_encoder_write, + vorbis_encoder_read, + vorbis_encoder_get_mime_type, +}; diff --git a/src/encoder/plugins/VorbisEncoderPlugin.hxx b/src/encoder/plugins/VorbisEncoderPlugin.hxx new file mode 100644 index 000000000..80703bf88 --- /dev/null +++ b/src/encoder/plugins/VorbisEncoderPlugin.hxx @@ -0,0 +1,25 @@ +/* + * Copyright (C) 2003-2014 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. + */ + +#ifndef MPD_ENCODER_VORBIS_H +#define MPD_ENCODER_VORBIS_H + +extern const struct EncoderPlugin vorbis_encoder_plugin; + +#endif diff --git a/src/encoder/plugins/WaveEncoderPlugin.cxx b/src/encoder/plugins/WaveEncoderPlugin.cxx new file mode 100644 index 000000000..97a26e821 --- /dev/null +++ b/src/encoder/plugins/WaveEncoderPlugin.cxx @@ -0,0 +1,265 @@ +/* + * Copyright (C) 2003-2014 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 "config.h" +#include "WaveEncoderPlugin.hxx" +#include "../EncoderAPI.hxx" +#include "system/ByteOrder.hxx" +#include "util/Manual.hxx" +#include "util/DynamicFifoBuffer.hxx" + +#include <assert.h> +#include <string.h> + +struct WaveEncoder { + Encoder encoder; + unsigned bits; + + Manual<DynamicFifoBuffer<uint8_t>> buffer; + + WaveEncoder():encoder(wave_encoder_plugin) {} +}; + +struct wave_header { + uint32_t id_riff; + uint32_t riff_size; + uint32_t id_wave; + uint32_t id_fmt; + uint32_t fmt_size; + uint16_t format; + uint16_t channels; + uint32_t freq; + uint32_t byterate; + uint16_t blocksize; + uint16_t bits; + uint32_t id_data; + uint32_t data_size; +}; + +static void +fill_wave_header(struct wave_header *header, int channels, int bits, + int freq, int block_size) +{ + int data_size = 0x0FFFFFFF; + + /* constants */ + header->id_riff = ToLE32(0x46464952); + header->id_wave = ToLE32(0x45564157); + header->id_fmt = ToLE32(0x20746d66); + header->id_data = ToLE32(0x61746164); + + /* wave format */ + header->format = ToLE16(1); // PCM_FORMAT + header->channels = ToLE16(channels); + header->bits = ToLE16(bits); + header->freq = ToLE32(freq); + header->blocksize = ToLE16(block_size); + header->byterate = ToLE32(freq * block_size); + + /* chunk sizes (fake data length) */ + header->fmt_size = ToLE32(16); + header->data_size = ToLE32(data_size); + header->riff_size = ToLE32(4 + (8 + 16) + (8 + data_size)); +} + +static Encoder * +wave_encoder_init(gcc_unused const config_param ¶m, + gcc_unused Error &error) +{ + WaveEncoder *encoder = new WaveEncoder(); + return &encoder->encoder; +} + +static void +wave_encoder_finish(Encoder *_encoder) +{ + WaveEncoder *encoder = (WaveEncoder *)_encoder; + + delete encoder; +} + +static bool +wave_encoder_open(Encoder *_encoder, + AudioFormat &audio_format, + gcc_unused Error &error) +{ + WaveEncoder *encoder = (WaveEncoder *)_encoder; + + assert(audio_format.IsValid()); + + switch (audio_format.format) { + case SampleFormat::S8: + encoder->bits = 8; + break; + + case SampleFormat::S16: + encoder->bits = 16; + break; + + case SampleFormat::S24_P32: + encoder->bits = 24; + break; + + case SampleFormat::S32: + encoder->bits = 32; + break; + + default: + audio_format.format = SampleFormat::S16; + encoder->bits = 16; + break; + } + + encoder->buffer.Construct(8192); + + auto range = encoder->buffer->Write(); + assert(range.size >= sizeof(wave_header)); + wave_header *header = (wave_header *)range.data; + + /* create PCM wave header in initial buffer */ + fill_wave_header(header, + audio_format.channels, + encoder->bits, + audio_format.sample_rate, + (encoder->bits / 8) * audio_format.channels); + + encoder->buffer->Append(sizeof(*header)); + + return true; +} + +static void +wave_encoder_close(Encoder *_encoder) +{ + WaveEncoder *encoder = (WaveEncoder *)_encoder; + + encoder->buffer.Destruct(); +} + +static size_t +pcm16_to_wave(uint16_t *dst16, const uint16_t *src16, size_t length) +{ + size_t cnt = length >> 1; + while (cnt > 0) { + *dst16++ = ToLE16(*src16++); + cnt--; + } + return length; +} + +static size_t +pcm32_to_wave(uint32_t *dst32, const uint32_t *src32, size_t length) +{ + size_t cnt = length >> 2; + while (cnt > 0){ + *dst32++ = ToLE32(*src32++); + cnt--; + } + return length; +} + +static size_t +pcm24_to_wave(uint8_t *dst8, const uint32_t *src32, size_t length) +{ + uint32_t value; + uint8_t *dst_old = dst8; + + length = length >> 2; + while (length > 0){ + value = *src32++; + *dst8++ = (value) & 0xFF; + *dst8++ = (value >> 8) & 0xFF; + *dst8++ = (value >> 16) & 0xFF; + length--; + } + //correct buffer length + return (dst8 - dst_old); +} + +static bool +wave_encoder_write(Encoder *_encoder, + const void *src, size_t length, + gcc_unused Error &error) +{ + WaveEncoder *encoder = (WaveEncoder *)_encoder; + + uint8_t *dst = encoder->buffer->Write(length); + + if (IsLittleEndian()) { + switch (encoder->bits) { + case 8: + case 16: + case 32:// optimized cases + memcpy(dst, src, length); + break; + case 24: + length = pcm24_to_wave(dst, (const uint32_t *)src, length); + break; + } + } else { + switch (encoder->bits) { + case 8: + memcpy(dst, src, length); + break; + case 16: + length = pcm16_to_wave((uint16_t *)dst, + (const uint16_t *)src, length); + break; + case 24: + length = pcm24_to_wave(dst, (const uint32_t *)src, length); + break; + case 32: + length = pcm32_to_wave((uint32_t *)dst, + (const uint32_t *)src, length); + break; + } + } + + encoder->buffer->Append(length); + return true; +} + +static size_t +wave_encoder_read(Encoder *_encoder, void *dest, size_t length) +{ + WaveEncoder *encoder = (WaveEncoder *)_encoder; + + return encoder->buffer->Read((uint8_t *)dest, length); +} + +static const char * +wave_encoder_get_mime_type(gcc_unused Encoder *_encoder) +{ + return "audio/wav"; +} + +const EncoderPlugin wave_encoder_plugin = { + "wave", + wave_encoder_init, + wave_encoder_finish, + wave_encoder_open, + wave_encoder_close, + nullptr, + nullptr, + nullptr, + nullptr, + wave_encoder_write, + wave_encoder_read, + wave_encoder_get_mime_type, +}; diff --git a/src/encoder/plugins/WaveEncoderPlugin.hxx b/src/encoder/plugins/WaveEncoderPlugin.hxx new file mode 100644 index 000000000..341b98adc --- /dev/null +++ b/src/encoder/plugins/WaveEncoderPlugin.hxx @@ -0,0 +1,25 @@ +/* + * Copyright (C) 2003-2014 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. + */ + +#ifndef MPD_ENCODER_WAVE_HXX +#define MPD_ENCODER_WAVE_HXX + +extern const struct EncoderPlugin wave_encoder_plugin; + +#endif |