Initial commit

This commit is contained in:
faumaray committed 2026-02-01 23:04:49 +03:00
commit a583c17916
56 files changed
+11025

No files matched your search

+630
View File
@@ -0,0 +1,630 @@
#include "echoion/core/AudioDecoder.hpp"
#include "echoion/core/NetworkClient.hpp"
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavutil/opt.h>
#include <libavutil/dict.h>
#include <libavutil/hwcontext.h>
#include <libavutil/samplefmt.h>
#include <libswresample/swresample.h>
}
#include <format>
#include <cstring>
#include <fstream>
#include <filesystem>
#include <thread>
namespace Echoion::Core {
AudioDecoder::AudioDecoder() = default;
AudioDecoder::~AudioDecoder() {
shutdown();
cleanupFfmpeg();
cleanupHardwareAccel();
}
Api::Result<void> AudioDecoder::initialize(const Api::HwAccelConfig& hwConfig) {
if (initialized_) {
return {};
}
if (zeroCopyEnabled_) {
Api::AudioBufferPool::instance().initialize(
outputSampleRate_ / 50 * outputChannels_,
256
);
}
if (hwConfig.isEnabled()) {
auto result = initializeHardwareAccel(hwConfig);
if (!result) {
ECHOION_LOG_WARNING(std::format("Hardware acceleration init failed: {}, falling back to software",
result.error().message));
}
}
av_log_set_level(AV_LOG_DEBUG);
initialized_ = true;
ECHOION_LOG_INFO("AudioDecoder initialized");
return {};
}
Api::Result<void> AudioDecoder::initializeHardwareAccel(const Api::HwAccelConfig& config) {
enum AVHWDeviceType hwType = AV_HWDEVICE_TYPE_NONE;
switch (config.type) {
case Api::HwAccelType::CUDA: hwType = AV_HWDEVICE_TYPE_CUDA; break;
case Api::HwAccelType::VAAPI: hwType = AV_HWDEVICE_TYPE_VAAPI; break;
case Api::HwAccelType::DXVA2: hwType = AV_HWDEVICE_TYPE_DXVA2; break;
case Api::HwAccelType::D3D11VA: hwType = AV_HWDEVICE_TYPE_D3D11VA; break;
case Api::HwAccelType::VideoToolbox: hwType = AV_HWDEVICE_TYPE_VIDEOTOOLBOX; break;
default: return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument, "Unsupported hardware acceleration type"));
}
if (av_hwdevice_find_type_by_name(av_hwdevice_get_type_name(hwType)) == AV_HWDEVICE_TYPE_NONE) {
return std::unexpected(Api::Error(Api::ErrorCode::NotSupported, "Hardware acceleration not available on this system"));
}
hwAccelType_ = config.type;
ECHOION_LOG_INFO(std::format("Hardware acceleration configured: {}", av_hwdevice_get_type_name(hwType)));
return {};
}
void AudioDecoder::shutdown() {
decoding_ = false;
shouldExit_ = true; // Signal FFmpeg to abort blocking I/O
cv_.notify_all();
if (decodeThread_.joinable()) {
decodeThread_.join();
}
closeSource();
initialized_ = false;
}
void AudioDecoder::cleanupHardwareAccel() {
if (hwFramesContext_) av_buffer_unref(&hwFramesContext_);
if (hwDeviceContext_) av_buffer_unref(&hwDeviceContext_);
hwAccelEnabled_ = false;
}
Api::Result<void> AudioDecoder::openSource(const std::string& url) {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Decoder not initialized"));
}
std::lock_guard<std::mutex> lock(mutex_);
closeSource();
currentUrl_ = url;
AVDictionary* options = nullptr;
av_dict_set(&options, "protocol_whitelist", "file,http,https,tls,tcp,udp,crypto,httpproxy,socks,socks5,socks5h", 0);
// CRITICAL: Use iOS User Agent to match the client that generated the URL.
// Mismatch between URL client (c=IOS) and User-Agent (Chrome) causes 403 Forbidden.
av_dict_set(&options, "user_agent",
"Mozilla/5.0 (Linux; Android 12; Quest 2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Mobile VR Safari/537.36", 0);
av_dict_set(&options, "timeout", "15000000", 0);
av_dict_set(&options, "reconnect", "1", 0);
av_dict_set(&options, "reconnect_streamed", "1", 0);
av_dict_set(&options, "reconnect_delay_max", "5", 0);
av_dict_set(&options, "analyzeduration", "20000000", 0);
av_dict_set(&options, "probesize", "10240000", 0);
if (proxyConfig_.has_value() && proxyConfig_->isValid()) {
std::string proxyUrl;
if (proxyConfig_->isSocks5()) {
// Use standard socks5:// scheme. FFmpeg http protocol handles this correctly.
// socks5h:// is often rejected by the http protocol handler, causing proxy bypass.
if (proxyConfig_->requiresAuth()) {
proxyUrl = std::format("socks5://{}:{}@{}:{}",
*proxyConfig_->username, *proxyConfig_->password,
proxyConfig_->host, proxyConfig_->port);
} else {
proxyUrl = std::format("socks5://{}:{}",
proxyConfig_->host, proxyConfig_->port);
}
} else {
if (proxyConfig_->requiresAuth()) {
proxyUrl = std::format("http://{}:{}@{}:{}",
*proxyConfig_->username, *proxyConfig_->password,
proxyConfig_->host, proxyConfig_->port);
} else {
proxyUrl = std::format("http://{}:{}",
proxyConfig_->host, proxyConfig_->port);
}
}
av_dict_set(&options, "proxy", proxyUrl.c_str(), 0);
ECHOION_LOG_INFO(std::format("Using proxy for ffmpeg: {}:{}", proxyConfig_->host, proxyConfig_->port));
}
ECHOION_LOG_DEBUG(std::format("Opening audio source: {}", url.substr(0, 80)));
// Allocate format context first (needed for interrupt callback)
formatContext_ = avformat_alloc_context();
if (!formatContext_) {
return std::unexpected(Api::Error(Api::ErrorCode::AudioError,
"Failed to allocate format context"));
}
// Set up interrupt callback to allow graceful shutdown during blocking I/O
shouldExit_ = false;
formatContext_->interrupt_callback.callback = [](void* ctx) -> int {
auto* decoder = static_cast<AudioDecoder*>(ctx);
return decoder->shouldExit_.load() ? 1 : 0;
};
formatContext_->interrupt_callback.opaque = this;
int ret = avformat_open_input(&formatContext_, url.c_str(), nullptr, &options);
if (options) {
av_dict_free(&options);
}
if (ret < 0) {
char errbuf[256];
av_strerror(ret, errbuf, sizeof(errbuf));
ECHOION_LOG_ERROR(std::format("FFmpeg failed to open input (error {}): {}", ret, errbuf));
return std::unexpected(Api::Error(Api::ErrorCode::AudioError,
std::format("Failed to open audio source: {} (FFmpeg error {}: {})",
url.substr(0, 80), ret, errbuf)));
}
ECHOION_LOG_DEBUG("avformat_open_input succeeded");
ret = avformat_find_stream_info(formatContext_, nullptr);
if (ret < 0) {
char errbuf[256];
av_strerror(ret, errbuf, sizeof(errbuf));
ECHOION_LOG_ERROR(std::format("FFmpeg failed to find stream info (error {}): {}", ret, errbuf));
avformat_close_input(&formatContext_);
return std::unexpected(Api::Error(Api::ErrorCode::AudioError,
std::format("Failed to find stream info: {}", errbuf)));
}
const AVCodec *decoder = nullptr;
audioStreamIndex_ = -1;
audioStreamIndex_ = av_find_best_stream(formatContext_, AVMEDIA_TYPE_AUDIO, -1,
-1, &decoder, 0);
if (audioStreamIndex_ == -1) {
avformat_close_input(&formatContext_);
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "No audio stream found"));
}
codecContext_ = avcodec_alloc_context3(decoder);
if (!codecContext_) {
avformat_close_input(&formatContext_);
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "Failed to allocate codec context"));
}
codecContext_->thread_count = 0; // Auto-detect CPU cores
codecContext_->thread_type = FF_THREAD_FRAME | FF_THREAD_SLICE;
ret = avcodec_parameters_to_context(codecContext_,
formatContext_->streams[audioStreamIndex_]->codecpar);
if (ret < 0) {
avcodec_free_context(&codecContext_);
avformat_close_input(&formatContext_);
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "Failed to copy codec parameters"));
}
ret = avcodec_open2(codecContext_, decoder, nullptr);
if (ret < 0) {
avcodec_free_context(&codecContext_);
avformat_close_input(&formatContext_);
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "Failed to open codec"));
}
frame_ = av_frame_alloc();
packet_ = av_packet_alloc();
if (!frame_ || !packet_) {
cleanupFfmpeg();
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "Failed to allocate frame/packet"));
}
streamInfo_.sampleRate = codecContext_->sample_rate;
streamInfo_.channels = codecContext_->ch_layout.nb_channels;
streamInfo_.bitrate = static_cast<uint32_t>(codecContext_->bit_rate);
streamInfo_.hwAccelerated = hwAccelEnabled_;
streamInfo_.hwAccelType = hwAccelType_;
if (formatContext_->duration != AV_NOPTS_VALUE) {
streamInfo_.duration = std::chrono::milliseconds(
formatContext_->duration * 1000 / AV_TIME_BASE);
}
switch (codecContext_->codec_id) {
case AV_CODEC_ID_MP3: streamInfo_.format = Api::AudioFormat::MP3; break;
case AV_CODEC_ID_AAC: streamInfo_.format = Api::AudioFormat::AAC; break;
case AV_CODEC_ID_OPUS: streamInfo_.format = Api::AudioFormat::Opus; break;
case AV_CODEC_ID_VORBIS: streamInfo_.format = Api::AudioFormat::Vorbis; break;
case AV_CODEC_ID_FLAC: streamInfo_.format = Api::AudioFormat::FLAC; break;
default: streamInfo_.format = Api::AudioFormat::Unknown; break;
}
// Setup resampler to output S16 (int16) like reference - avoids float->int conversion
AVChannelLayout outLayout;
av_channel_layout_default(&outLayout, static_cast<int>(outputChannels_));
ret = swr_alloc_set_opts2(&swrContext_,
&outLayout, AV_SAMPLE_FMT_S16, static_cast<int>(outputSampleRate_),
&codecContext_->ch_layout, codecContext_->sample_fmt, codecContext_->sample_rate,
0, nullptr);
if (codecContext_->sample_rate != outputSampleRate_) {
av_opt_set_int(swrContext_, "linear_interp", 1, 0);
av_opt_set_int(swrContext_, "filter_size", 256, 0);
}
if (ret < 0 || swr_init(swrContext_) < 0) {
cleanupFfmpeg();
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "Failed to initialize resampler"));
}
// Allocate output buffer for S16 samples (like reference)
constexpr int maxSamples = 4096;
av_samples_alloc(&outputBuffer_, nullptr, static_cast<int>(outputChannels_), maxSamples,
AV_SAMPLE_FMT_S16, 0);
decoding_ = true;
shouldExit_ = false;
decodeThread_ = std::jthread(&AudioDecoder::decodeThread, this);
ECHOION_LOG_INFO(std::format("Audio source opened: {} -> {} Hz, {} ch, in={} out=S16",
url, outputSampleRate_, outputChannels_,
av_get_sample_fmt_name(codecContext_->sample_fmt)));
return {};
}
void AudioDecoder::closeSource() {
decoding_ = false;
shouldExit_ = true; // Signal FFmpeg to abort blocking I/O
cv_.notify_all();
if (decodeThread_.joinable()) {
decodeThread_.join();
}
cleanupFfmpeg();
currentUrl_.clear();
currentPosition_ = std::chrono::milliseconds(0);
eof_ = false;
shouldExit_ = false; // Reset for next use
}
Api::Result<Api::DecodedAudio> AudioDecoder::decodeFrame() {
std::unique_lock<std::mutex> lock(mutex_);
cv_.wait(lock, [this] {
return !decodedQueue_.empty() || eof_ || !decoding_;
});
if (!decodedQueue_.empty()) {
auto audio = std::move(decodedQueue_.front());
decodedQueue_.pop();
cv_.notify_one();
std::lock_guard<std::mutex> statsLock(statsMutex_);
stats_.framesDecoded++;
ECHOION_LOG_DEBUG(std::format("Frame consumed: {} samples, {} ms",
audio.view.samplesPerChannel() * 2, audio.timestamp.count()));
return audio;
}
if (eof_) {
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "End of stream"));
}
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "Decoder stopped"));
}
static int callCount = 0;
bool AudioDecoder::getNextChunk(std::vector<int16_t>& outChunk, bool blocking) {
callCount++;
std::unique_lock<std::mutex> lock(mutex_);
if (blocking) {
cv_.wait(lock, [this] { return !int16Queue_.empty() || eof_.load(); });
}
if (int16Queue_.empty()) {
return false;
}
outChunk = std::move(int16Queue_.front());
int16Queue_.pop_front();
cv_.notify_one();
if (callCount <= 10 || callCount % 1000 == 0) {
ECHOION_LOG_DEBUG(std::format("getNextChunk {}: returned {} samples, queue left: {}",
callCount, outChunk.size(), int16Queue_.size()));
}
std::lock_guard<std::mutex> statsLock(statsMutex_);
stats_.framesDecoded++;
return true;
}
Api::Result<void> AudioDecoder::seek(std::chrono::milliseconds position) {
if (!formatContext_ || audioStreamIndex_ < 0) {
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "No source open"));
}
std::lock_guard<std::mutex> lock(mutex_);
int64_t targetPts = position.count() * AV_TIME_BASE / 1000;
int ret = av_seek_frame(formatContext_, -1, targetPts, AVSEEK_FLAG_BACKWARD);
if (ret < 0) {
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "Seek failed"));
}
avcodec_flush_buffers(codecContext_);
currentPosition_ = position;
std::queue<Api::DecodedAudio> empty;
std::swap(decodedQueue_, empty);
return {};
}
Api::Result<Api::AudioStreamInfo> AudioDecoder::getStreamInfo() const {
if (!initialized_ || !formatContext_) {
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "No source open"));
}
return streamInfo_;
}
std::chrono::milliseconds AudioDecoder::getPosition() const {
return currentPosition_;
}
bool AudioDecoder::hasMoreData() const {
std::lock_guard<std::mutex> lock(mutex_);
return !decodedQueue_.empty() || (!eof_ && decoding_);
}
void AudioDecoder::setOutputFormat(uint32_t sampleRate, uint32_t channels) {
outputSampleRate_ = sampleRate;
outputChannels_ = channels;
}
void AudioDecoder::setProxyConfig(const std::optional<Api::ProxyConfig>& proxy) {
proxyConfig_ = proxy;
}
AudioDecoder::Stats AudioDecoder::getStats() const {
std::lock_guard<std::mutex> lock(statsMutex_);
return stats_;
}
void AudioDecoder::decodeThread() {
ECHOION_LOG_DEBUG("Decode thread started");
constexpr int maxSamples = 4096;
int packetsRead = 0;
int framesProduced = 0;
while (decoding_.load()) {
// Check queue size limit
{
std::unique_lock<std::mutex> lock(mutex_);
if (int16Queue_.size() >= MAX_INT16_QUEUE_SIZE) {
cv_.wait(lock, [this] { return int16Queue_.size() < MAX_INT16_QUEUE_SIZE || !decoding_; });
if (!decoding_) break;
}
}
int ret = av_read_frame(formatContext_, packet_);
if (ret == AVERROR_EOF) {
break; // End of file - go to flush
}
if (ret < 0) {
continue; // Read error - try next packet
}
packetsRead++;
if (packet_->stream_index != audioStreamIndex_) {
av_packet_unref(packet_);
continue;
}
// Send packet to decoder - ignore errors like reference
avcodec_send_packet(codecContext_, packet_);
av_packet_unref(packet_);
// Receive all available frames
while (decoding_.load()) {
ret = avcodec_receive_frame(codecContext_, frame_);
if (ret == AVERROR(EAGAIN)) {
break; // Need more packets
}
if (ret < 0) {
break; // Error - continue to next packet
}
// Convert to S16 and queue (like reference)
int outSamples = swr_convert(swrContext_, &outputBuffer_, maxSamples,
const_cast<const uint8_t**>(frame_->data), frame_->nb_samples);
if (outSamples > 0) {
std::vector<int16_t> chunk(outSamples * outputChannels_);
std::memcpy(chunk.data(), outputBuffer_,
outSamples * outputChannels_ * sizeof(int16_t));
{
std::lock_guard<std::mutex> lock(mutex_);
int16Queue_.push_back(std::move(chunk));
}
cv_.notify_one();
framesProduced++;
if (framesProduced <= 5) {
ECHOION_LOG_DEBUG(std::format("Decode produced frame {}: {} samples",
framesProduced, chunk.size()));
}
}
}
}
// Final flush (CRITICAL - like reference)
avcodec_send_packet(codecContext_, nullptr);
while (decoding_.load()) {
int ret = avcodec_receive_frame(codecContext_, frame_);
if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN)) {
break;
}
if (ret < 0) break;
int outSamples = swr_convert(swrContext_, &outputBuffer_, 4096,
const_cast<const uint8_t**>(frame_->data), frame_->nb_samples);
if (outSamples > 0) {
std::vector<int16_t> chunk(outSamples * outputChannels_);
std::memcpy(chunk.data(), outputBuffer_,
outSamples * outputChannels_ * sizeof(int16_t));
{
std::lock_guard<std::mutex> lock(mutex_);
int16Queue_.push_back(std::move(chunk));
}
cv_.notify_one();
framesProduced++;
}
}
eof_ = true;
cv_.notify_all();
ECHOION_LOG_INFO(std::format("Decode finished. Packets: {}, Frames: {}",
packetsRead, framesProduced));
}
Api::Result<void> AudioDecoder::readPacket() {
int ret = av_read_frame(formatContext_, packet_);
if (ret < 0) {
if (ret == AVERROR_EOF) {
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "End of file"));
}
if (ret == AVERROR_EXIT) {
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "Interrupted"));
}
char errbuf[256];
av_strerror(ret, errbuf, sizeof(errbuf));
return std::unexpected(Api::Error(Api::ErrorCode::AudioError,
std::format("Error reading frame: {}", errbuf)));
}
if (packet_->stream_index != audioStreamIndex_) {
av_packet_unref(packet_);
return {};
}
// Send packet to decoder - don't check error, just like reference code
// Some packets may be corrupt but we continue to next
avcodec_send_packet(codecContext_, packet_);
av_packet_unref(packet_);
// Receive all available frames from the decoder
while (true) {
ret = avcodec_receive_frame(codecContext_, frame_);
if (ret == AVERROR(EAGAIN)) {
// Need more packets to produce a frame
break;
}
if (ret < 0) {
// Error receiving frame - log but continue to next packet
// Don't treat as fatal - Opus may have bad packets that are safe to skip
break;
}
Api::Result<Api::DecodedAudio> audio;
if (zeroCopyEnabled_) {
audio = convertFramePooled();
} else {
audio = convertFrame();
}
if (audio) {
std::lock_guard<std::mutex> lock(mutex_);
decodedQueue_.push(std::move(*audio));
cv_.notify_one();
}
}
return {};
}
Api::Result<Api::DecodedAudio> AudioDecoder::convertFrame() {
int outSamples = swr_get_out_samples(swrContext_, frame_->nb_samples);
std::vector<float> outputBuffer(outSamples * outputChannels_);
uint8_t* outData = reinterpret_cast<uint8_t*>(outputBuffer.data());
const uint8_t** inData = const_cast<const uint8_t**>(frame_->extended_data);
int converted = swr_convert(swrContext_, &outData, outSamples, inData, frame_->nb_samples);
if (converted < 0) {
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "Resampling failed"));
}
outputBuffer.resize(converted * outputChannels_);
if (frame_->pts != AV_NOPTS_VALUE) {
AVRational timeBase = formatContext_->streams[audioStreamIndex_]->time_base;
currentPosition_ = std::chrono::milliseconds(
frame_->pts * 1000 * timeBase.num / timeBase.den);
}
Api::DecodedAudio audio;
audio.view = Api::FloatAudioView(outputBuffer.data(), outputBuffer.size(), outputChannels_);
audio.sampleRate = outputSampleRate_;
audio.channels = outputChannels_;
audio.timestamp = currentPosition_;
return audio;
}
Api::Result<Api::DecodedAudio> AudioDecoder::convertFramePooled() {
int outSamples = swr_get_out_samples(swrContext_, frame_->nb_samples);
auto pooledBuffer = Api::AudioBufferPool::instance().acquireBuffer();
if (!pooledBuffer) return convertFrame();
uint8_t* outData = reinterpret_cast<uint8_t*>(pooledBuffer.get());
const uint8_t** inData = const_cast<const uint8_t**>(frame_->extended_data);
int converted = swr_convert(swrContext_, &outData, outSamples, inData, frame_->nb_samples);
if (converted < 0) return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "Resampling failed"));
if (frame_->pts != AV_NOPTS_VALUE) {
AVRational timeBase = formatContext_->streams[audioStreamIndex_]->time_base;
currentPosition_ = std::chrono::milliseconds(
frame_->pts * 1000 * timeBase.num / timeBase.den);
}
Api::DecodedAudio audio;
audio.pooledSamples = std::move(pooledBuffer);
audio.view = Api::FloatAudioView(audio.pooledSamples.get(), converted * outputChannels_, outputChannels_);
audio.sampleRate = outputSampleRate_;
audio.channels = outputChannels_;
audio.timestamp = currentPosition_;
return audio;
}
void AudioDecoder::cleanupFfmpeg() {
if (swrContext_) swr_free(&swrContext_);
if (frame_) av_frame_free(&frame_);
if (packet_) av_packet_free(&packet_);
if (codecContext_) avcodec_free_context(&codecContext_);
if (formatContext_) avformat_close_input(&formatContext_);
if (outputBuffer_) av_freep(&outputBuffer_);
audioStreamIndex_ = -1;
}
} // namespace Echoion::Core