#include "echoion/standalone/AudioEncoder.hpp" extern "C" { #include #include #include #include #include } #include namespace Echoion::Standalone { namespace { constexpr int OUT_RATE = 48000; constexpr int CHANNELS = 2; constexpr int FRAME_SAMPLES = 960; // 20 ms @ 48 kHz per channel constexpr int FRAME_SHORTS = FRAME_SAMPLES * CHANNELS; constexpr int MAX_OPUS = 4000; } // namespace AudioEncoder::AudioEncoder(int bitrate, int inRate) : inRate_(inRate) { AVChannelLayout stereo = AV_CHANNEL_LAYOUT_STEREO; if (swr_alloc_set_opts2(&swr_, &stereo, AV_SAMPLE_FMT_S16, OUT_RATE, &stereo, AV_SAMPLE_FMT_S16, inRate_, 0, nullptr) < 0 || swr_init(swr_) < 0) { throw std::runtime_error("AudioEncoder: swresample init failed"); } int err = 0; enc_ = opus_encoder_create(OUT_RATE, CHANNELS, OPUS_APPLICATION_AUDIO, &err); if (err != OPUS_OK || !enc_) { throw std::runtime_error("AudioEncoder: opus encoder init failed"); } opus_encoder_ctl(enc_, OPUS_SET_BITRATE(bitrate)); opus_encoder_ctl(enc_, OPUS_SET_SIGNAL(OPUS_SIGNAL_MUSIC)); } AudioEncoder::~AudioEncoder() { if (enc_) { opus_encoder_destroy(enc_); } if (swr_) { swr_free(&swr_); } } std::vector> AudioEncoder::encode(std::span interleaved) { std::vector> out; const int inSamplesPerCh = static_cast(interleaved.size() / CHANNELS); if (inSamplesPerCh <= 0) { return out; } // Upper bound on resampled samples for this chunk. int maxOut = static_cast( av_rescale_rnd(swr_get_delay(swr_, inRate_) + inSamplesPerCh, OUT_RATE, inRate_, AV_ROUND_UP)); std::vector resampled( static_cast(maxOut) * CHANNELS, 0); const uint8_t* inPtr = reinterpret_cast(interleaved.data()); uint8_t* outPtr = reinterpret_cast(resampled.data()); int gotPerCh = swr_convert(swr_, &outPtr, maxOut, &inPtr, inSamplesPerCh); if (gotPerCh < 0) { return out; } pcm_.insert(pcm_.end(), resampled.begin(), resampled.begin() + static_cast(gotPerCh) * CHANNELS); // Emit as many full 20 ms frames as we have buffered. size_t consumed = 0; while (pcm_.size() - consumed >= static_cast(FRAME_SHORTS)) { uint8_t packet[MAX_OPUS]; int n = opus_encode(enc_, pcm_.data() + consumed, FRAME_SAMPLES, packet, MAX_OPUS); if (n > 0) { out.emplace_back(packet, packet + n); } consumed += FRAME_SHORTS; } if (consumed > 0) { pcm_.erase(pcm_.begin(), pcm_.begin() + static_cast(consumed)); } return out; } } // namespace Echoion::Standalone