1 parent
df99b6ea7f
commit
d146f11f02
63 files changed
+8331
-2709
No files matched your search
+137
-287
@@ -4,7 +4,6 @@ extern "C" {
|
||||
#include <libavcodec/avcodec.h>
|
||||
#include <libavformat/avformat.h>
|
||||
#include <libavutil/dict.h>
|
||||
#include <libavutil/hwcontext.h>
|
||||
#include <libavutil/opt.h>
|
||||
#include <libavutil/samplefmt.h>
|
||||
#include <libswresample/swresample.h>
|
||||
@@ -23,78 +22,22 @@ namespace Echoion::Core
|
||||
{
|
||||
shutdown();
|
||||
cleanupFfmpeg();
|
||||
cleanupHardwareAccel();
|
||||
}
|
||||
|
||||
Api::Result<void>
|
||||
AudioDecoder::initialize(const Api::HwAccelConfig& hwConfig)
|
||||
Api::Result<void> AudioDecoder::initialize()
|
||||
{
|
||||
if (initialized_) {
|
||||
return {};
|
||||
}
|
||||
|
||||
if (zeroCopyEnabled_) {
|
||||
Api::AudioBufferPool::instance().initialize(
|
||||
outputSampleRate_ / 50 * outputChannels_, 256);
|
||||
}
|
||||
|
||||
if (hwConfig.isEnabled()) {
|
||||
auto result = initializeHardwareAccel(hwConfig);
|
||||
if (!result) {
|
||||
Void::Log::warn(
|
||||
"AudioDecoder", "{}",
|
||||
std::format("Hardware acceleration init failed: {}, "
|
||||
"falling back to software",
|
||||
result.error().message));
|
||||
}
|
||||
}
|
||||
av_log_set_level(AV_LOG_DEBUG);
|
||||
// Errors only: AV_LOG_DEBUG makes FFmpeg log every packet, which is
|
||||
// both noisy and measurably slow on the decode thread.
|
||||
av_log_set_level(AV_LOG_ERROR);
|
||||
initialized_ = true;
|
||||
Void::Log::info("AudioDecoder", "{}", "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 Api::fail(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 Api::fail(
|
||||
Api::ErrorCode::NotSupported,
|
||||
"Hardware acceleration not available on this system");
|
||||
}
|
||||
|
||||
hwAccelType_ = config.type;
|
||||
Void::Log::info("AudioDecoder", "{}",
|
||||
std::format("Hardware acceleration configured: {}",
|
||||
av_hwdevice_get_type_name(hwType)));
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
void AudioDecoder::shutdown()
|
||||
{
|
||||
decoding_ = false;
|
||||
@@ -109,17 +52,6 @@ namespace Echoion::Core
|
||||
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_) {
|
||||
@@ -294,42 +226,46 @@ namespace Echoion::Core
|
||||
"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_;
|
||||
{
|
||||
// streamInfo_ is read from other threads via getStreamInfo();
|
||||
// mutex_ is already held for the whole of openSource() (acquired
|
||||
// at the top), which is what makes these writes safe.
|
||||
streamInfo_.sampleRate = codecContext_->sample_rate;
|
||||
streamInfo_.channels = codecContext_->ch_layout.nb_channels;
|
||||
streamInfo_.bitrate =
|
||||
static_cast<uint32_t>(codecContext_->bit_rate);
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
streamSampleRate_ = static_cast<uint32_t>(
|
||||
codecContext_->sample_rate > 0 ? codecContext_->sample_rate
|
||||
: 48000);
|
||||
|
||||
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;
|
||||
@@ -340,7 +276,8 @@ namespace Echoion::Core
|
||||
&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_) {
|
||||
if (codecContext_->sample_rate !=
|
||||
static_cast<int>(outputSampleRate_)) {
|
||||
av_opt_set_int(swrContext_, "linear_interp", 1, 0);
|
||||
av_opt_set_int(swrContext_, "filter_size", 256, 0);
|
||||
}
|
||||
@@ -382,49 +319,16 @@ namespace Echoion::Core
|
||||
|
||||
cleanupFfmpeg();
|
||||
currentUrl_.clear();
|
||||
currentPosition_ = std::chrono::milliseconds(0);
|
||||
currentPositionMs_ = 0;
|
||||
eof_ = false;
|
||||
shouldExit_ = false; // Reset for next use
|
||||
}
|
||||
|
||||
Api::Result<Api::DecodedAudio> AudioDecoder::decodeFrame()
|
||||
bool AudioDecoder::getNextChunk(std::vector<int16_t>& outChunk,
|
||||
bool blocking)
|
||||
{
|
||||
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++;
|
||||
|
||||
Void::Log::debug("AudioDecoder", "{}",
|
||||
std::format("Frame consumed: {} samples, {} ms",
|
||||
audio.view.samplesPerChannel() * 2,
|
||||
audio.timestamp.count()));
|
||||
|
||||
return audio;
|
||||
}
|
||||
|
||||
if (eof_) {
|
||||
return Api::fail(Api::ErrorCode::AudioError, "End of stream");
|
||||
}
|
||||
|
||||
return Api::fail(Api::ErrorCode::AudioError, "Decoder stopped");
|
||||
}
|
||||
static int callCount = 0;
|
||||
|
||||
bool AudioDecoder::getNextChunk(std::vector<short>& outChunk, bool blocking)
|
||||
{
|
||||
callCount++;
|
||||
|
||||
std::unique_lock<std::mutex> lock(mutex_);
|
||||
|
||||
if (blocking) {
|
||||
cv_.wait(lock,
|
||||
[this] { return !int16Queue_.empty() || eof_.load(); });
|
||||
@@ -434,20 +338,17 @@ namespace Echoion::Core
|
||||
return false;
|
||||
}
|
||||
|
||||
outChunk = std::move(int16Queue_.front());
|
||||
// Swap instead of copy: the caller receives the decoded chunk and
|
||||
// their previous buffer's storage goes to the recycle free-list for
|
||||
// decodeThread() to reuse. Zero copies, zero allocations per chunk.
|
||||
std::vector<int16_t>& front = int16Queue_.front();
|
||||
outChunk.swap(front);
|
||||
front.clear(); // keep capacity, drop stale samples
|
||||
if (recycledChunks_.size() < MAX_INT16_QUEUE_SIZE) {
|
||||
recycledChunks_.push_back(std::move(front));
|
||||
}
|
||||
int16Queue_.pop_front();
|
||||
cv_.notify_one();
|
||||
|
||||
if (callCount <= 10 || callCount % 1000 == 0) {
|
||||
Void::Log::debug(
|
||||
"AudioDecoder", "{}",
|
||||
std::format(
|
||||
"getNextChunk {}: returned {} samples, queue left: {}",
|
||||
callCount, outChunk.size(), int16Queue_.size()));
|
||||
}
|
||||
|
||||
std::lock_guard<std::mutex> statsLock(statsMutex_);
|
||||
stats_.framesDecoded++;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -468,12 +369,10 @@ namespace Echoion::Core
|
||||
}
|
||||
|
||||
avcodec_flush_buffers(codecContext_);
|
||||
currentPosition_ = position;
|
||||
currentPositionMs_ = position.count();
|
||||
|
||||
// Clear pending audio data
|
||||
int16Queue_.clear();
|
||||
std::queue<Api::DecodedAudio> empty;
|
||||
std::swap(decodedQueue_, empty);
|
||||
|
||||
return {};
|
||||
}
|
||||
@@ -483,6 +382,7 @@ namespace Echoion::Core
|
||||
if (!initialized_ || !formatContext_) {
|
||||
return Api::fail(Api::ErrorCode::AudioError, "No source open");
|
||||
}
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return streamInfo_;
|
||||
}
|
||||
|
||||
@@ -492,13 +392,7 @@ namespace Echoion::Core
|
||||
// Note: This is updated when frames are decoded, not when played
|
||||
// For accurate playback position, use
|
||||
// MusicManager::getPlaybackPosition()
|
||||
return currentPosition_;
|
||||
}
|
||||
|
||||
bool AudioDecoder::hasMoreData() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return !decodedQueue_.empty() || (!eof_ && decoding_);
|
||||
return std::chrono::milliseconds(currentPositionMs_.load());
|
||||
}
|
||||
|
||||
void AudioDecoder::setOutputFormat(uint32_t sampleRate, uint32_t channels)
|
||||
@@ -513,10 +407,20 @@ namespace Echoion::Core
|
||||
proxyConfig_ = proxy;
|
||||
}
|
||||
|
||||
AudioDecoder::Stats AudioDecoder::getStats() const
|
||||
std::vector<int16_t> AudioDecoder::acquireChunkBuffer(size_t samples)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(statsMutex_);
|
||||
return stats_;
|
||||
std::vector<int16_t> chunk;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (!recycledChunks_.empty()) {
|
||||
chunk = std::move(recycledChunks_.back());
|
||||
recycledChunks_.pop_back();
|
||||
}
|
||||
}
|
||||
// resize() reuses the recycled buffer's capacity (no allocation when it
|
||||
// is already large enough); allocates only on first use or growth.
|
||||
chunk.resize(samples);
|
||||
return chunk;
|
||||
}
|
||||
|
||||
void AudioDecoder::decodeThread()
|
||||
@@ -569,16 +473,41 @@ namespace Echoion::Core
|
||||
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);
|
||||
// Track decode position from frame timestamps. Without this
|
||||
// getPosition() stays at 0 forever, which silently disabled
|
||||
// the near-end prefetch (it never saw the track approaching
|
||||
// its end) — every transition took the slow synchronous
|
||||
// resolve path.
|
||||
if (frame_->pts != AV_NOPTS_VALUE) {
|
||||
AVRational tb =
|
||||
formatContext_->streams[audioStreamIndex_]->time_base;
|
||||
currentPositionMs_ =
|
||||
frame_->pts * 1000 * tb.num / tb.den;
|
||||
}
|
||||
|
||||
if (outSamples > 0) {
|
||||
std::vector<int16_t> chunk(outSamples * outputChannels_);
|
||||
// Convert to S16 and queue. One output buffer holds at most
|
||||
// maxSamples per call; anything beyond that stays in
|
||||
// swresample's internal FIFO, so keep draining (input =
|
||||
// nullptr) until it is empty — otherwise large input frames
|
||||
// (WAV blocks, high upsampling ratios) silently lose the
|
||||
// remainder and playback runs short.
|
||||
const uint8_t** inData =
|
||||
const_cast<const uint8_t**>(frame_->data);
|
||||
int inSamples = frame_->nb_samples;
|
||||
while (true) {
|
||||
int outSamples = swr_convert(swrContext_, &outputBuffer_,
|
||||
maxSamples, inData,
|
||||
inSamples);
|
||||
inData = nullptr; // input consumed on the first call
|
||||
inSamples = 0;
|
||||
if (outSamples <= 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
const size_t chunkSamples = outSamples * outputChannels_;
|
||||
std::vector<int16_t> chunk = acquireChunkBuffer(chunkSamples);
|
||||
std::memcpy(chunk.data(), outputBuffer_,
|
||||
outSamples * outputChannels_ * sizeof(int16_t));
|
||||
chunkSamples * sizeof(int16_t));
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
@@ -586,18 +515,12 @@ namespace Echoion::Core
|
||||
}
|
||||
cv_.notify_one();
|
||||
framesProduced++;
|
||||
|
||||
if (framesProduced <= 5) {
|
||||
Void::Log::debug(
|
||||
"AudioDecoder", "{}",
|
||||
std::format("Decode produced frame {}: {} samples",
|
||||
framesProduced, chunk.size()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Final flush (CRITICAL - like reference)
|
||||
// Final flush (CRITICAL - like reference): drain the codec, then the
|
||||
// resampler FIFO.
|
||||
avcodec_send_packet(codecContext_, nullptr);
|
||||
while (decoding_.load()) {
|
||||
int ret = avcodec_receive_frame(codecContext_, frame_);
|
||||
@@ -608,14 +531,22 @@ namespace Echoion::Core
|
||||
break;
|
||||
}
|
||||
|
||||
int outSamples = swr_convert(
|
||||
swrContext_, &outputBuffer_, 4096,
|
||||
const_cast<const uint8_t**>(frame_->data), frame_->nb_samples);
|
||||
const uint8_t** inData =
|
||||
const_cast<const uint8_t**>(frame_->data);
|
||||
int inSamples = frame_->nb_samples;
|
||||
while (true) {
|
||||
int outSamples = swr_convert(swrContext_, &outputBuffer_,
|
||||
maxSamples, inData, inSamples);
|
||||
inData = nullptr;
|
||||
inSamples = 0;
|
||||
if (outSamples <= 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (outSamples > 0) {
|
||||
std::vector<int16_t> chunk(outSamples * outputChannels_);
|
||||
const size_t chunkSamples = outSamples * outputChannels_;
|
||||
std::vector<int16_t> chunk = acquireChunkBuffer(chunkSamples);
|
||||
std::memcpy(chunk.data(), outputBuffer_,
|
||||
outSamples * outputChannels_ * sizeof(int16_t));
|
||||
chunkSamples * sizeof(int16_t));
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
@@ -626,6 +557,25 @@ namespace Echoion::Core
|
||||
}
|
||||
}
|
||||
|
||||
// Resampler delay tail (samples still buffered for the filter).
|
||||
while (decoding_.load()) {
|
||||
int outSamples = swr_convert(swrContext_, &outputBuffer_,
|
||||
maxSamples, nullptr, 0);
|
||||
if (outSamples <= 0) {
|
||||
break;
|
||||
}
|
||||
const size_t chunkSamples = outSamples * outputChannels_;
|
||||
std::vector<int16_t> chunk = acquireChunkBuffer(chunkSamples);
|
||||
std::memcpy(chunk.data(), outputBuffer_,
|
||||
chunkSamples * 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();
|
||||
|
||||
@@ -634,106 +584,6 @@ namespace Echoion::Core
|
||||
packetsRead, framesProduced));
|
||||
}
|
||||
|
||||
Api::Result<void> AudioDecoder::readPacket()
|
||||
{
|
||||
int ret = av_read_frame(formatContext_, packet_);
|
||||
if (ret < 0) {
|
||||
if (ret == AVERROR_EOF) {
|
||||
return Api::fail(Api::ErrorCode::AudioError, "End of file");
|
||||
}
|
||||
if (ret == AVERROR_EXIT) {
|
||||
return Api::fail(Api::ErrorCode::AudioError, "Interrupted");
|
||||
}
|
||||
char errbuf[256];
|
||||
av_strerror(ret, errbuf, sizeof(errbuf));
|
||||
return Api::fail(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);
|
||||
// Use int16_t for direct output (no float conversion)
|
||||
std::vector<int16_t> 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 Api::fail(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.samples = std::move(outputBuffer);
|
||||
audio.view = Api::Int16AudioView(audio.samples.data(),
|
||||
audio.samples.size(), outputChannels_);
|
||||
audio.sampleRate = outputSampleRate_;
|
||||
audio.channels = outputChannels_;
|
||||
audio.timestamp = currentPosition_;
|
||||
return audio;
|
||||
}
|
||||
|
||||
Api::Result<Api::DecodedAudio> AudioDecoder::convertFramePooled()
|
||||
{
|
||||
// Using int16_t (short) for direct TeamSpeak compatibility
|
||||
// Both pooled and non-pooled versions now use the same int16 format
|
||||
return convertFrame();
|
||||
}
|
||||
|
||||
void AudioDecoder::cleanupFfmpeg()
|
||||
{
|
||||
if (swrContext_) {
|
||||
|
||||
+21
-8
@@ -49,6 +49,10 @@ namespace Echoion::Core
|
||||
auto categoryEmoji =
|
||||
[](CommandCategory c) -> std::string_view {
|
||||
switch (c) {
|
||||
case CommandCategory::Play:
|
||||
return "\xe2\x96\xb6"; // play triangle
|
||||
case CommandCategory::Search:
|
||||
return "\xf0\x9f\x94\x8d"; // magnifier
|
||||
case CommandCategory::Music:
|
||||
return "\xf0\x9f\x8e\xb5"; // music note
|
||||
case CommandCategory::Queue:
|
||||
@@ -64,12 +68,12 @@ namespace Echoion::Core
|
||||
};
|
||||
|
||||
for (const auto& [cat, cmds] : grouped) {
|
||||
// Collapsible section per category (TS6 supports
|
||||
// <details>/<summary>). Blank lines around the inner
|
||||
// content let the Markdown render inside the block.
|
||||
helpMsg += std::format(
|
||||
"<details>\n<summary>{} {} Commands</summary>\n\n",
|
||||
categoryEmoji(cat), toString(cat));
|
||||
// Collapsible section per category. TeamSpeak uses the
|
||||
// markdown-it container syntax ":::details <title>" …
|
||||
// ":::" (not HTML <details>).
|
||||
helpMsg += std::format(":::details {} {} Commands\n\n",
|
||||
categoryEmoji(cat),
|
||||
toString(cat));
|
||||
|
||||
for (const auto& [name, cmd] : cmds) {
|
||||
if (!cmd->getUsage().empty()) {
|
||||
@@ -99,7 +103,7 @@ namespace Echoion::Core
|
||||
helpMsg += "\n";
|
||||
}
|
||||
|
||||
helpMsg += "</details>\n\n";
|
||||
helpMsg += ":::\n\n";
|
||||
}
|
||||
|
||||
ctx.reply(helpMsg);
|
||||
@@ -462,22 +466,27 @@ namespace Echoion::Core
|
||||
void CommandManager::registerBuiltinCommands()
|
||||
{
|
||||
registerCommand<PlayCommand>("play");
|
||||
registerCommand<YoutubePlayCommand>("pyt");
|
||||
registerCommand<YandexPlayCommand>("pya");
|
||||
registerCommand<SelectCommand>("select");
|
||||
registerCommand<PauseCommand>("pause");
|
||||
registerCommand<ResumeCommand>("resume");
|
||||
registerCommand<StopCommand>("stop");
|
||||
registerCommand<SkipCommand>("skip");
|
||||
// registerCommand<SeekCommand>("seek");
|
||||
registerCommand<SeekCommand>("seek");
|
||||
registerCommand<VolumeCommand>("volume");
|
||||
registerCommand<QueueCommand>("queue");
|
||||
registerCommand<RemoveCommand>("remove");
|
||||
registerCommand<ClearCommand>("clear");
|
||||
registerCommand<MoveCommand>("move");
|
||||
registerCommand<ShuffleCommand>("shuffle");
|
||||
registerCommand<AutoplayCommand>("autoplay");
|
||||
registerCommand<RepeatCommand>("repeat");
|
||||
registerCommand<PlaylistCommand>("playlist");
|
||||
registerCommand<NowPlayingCommand>("np");
|
||||
registerCommand<SearchCommand>("search");
|
||||
registerCommand<YoutubeSearchCommand>("youtube");
|
||||
registerCommand<YandexSearchCommand>("yandex");
|
||||
registerCommand<ReloadCommand>("reload");
|
||||
registerCommand<ReloadConfigCommand>("reloadconfig");
|
||||
registerCommand<SubscribeCommand>("subscribe");
|
||||
@@ -486,6 +495,10 @@ namespace Echoion::Core
|
||||
registerCommand<UnsubscribeIdCommand>("unsubscribeid");
|
||||
registerCommand<UnsubscribeAllCommand>("unsubscribeall");
|
||||
registerCommand<RpcInfoCommand>("rpc");
|
||||
registerCommand<HistoryCommand>("history");
|
||||
registerCommand<StatsCommand>("stats");
|
||||
registerCommand<FavoriteCommand>("fav");
|
||||
registerCommand<AnnounceCommand>("announce");
|
||||
}
|
||||
|
||||
void CommandManager::registerHelpCommand()
|
||||
|
||||
+3
-13
@@ -64,7 +64,7 @@ namespace Echoion::Core
|
||||
|
||||
std::cout << std::format("[INFO] Configuration loaded from {}",
|
||||
path.string())
|
||||
<< std::endl;
|
||||
<< '\n';
|
||||
return config;
|
||||
}
|
||||
|
||||
@@ -117,11 +117,7 @@ namespace Echoion::Core
|
||||
config.bot.commandPrefix = "!";
|
||||
config.bot.defaultVolume = 0.5f;
|
||||
config.bot.maxQueueSize = 100;
|
||||
config.bot.trackTimeout = std::chrono::milliseconds(30000);
|
||||
config.bot.autoReconnect = true;
|
||||
config.bot.reconnectDelay = std::chrono::milliseconds(5000);
|
||||
config.bot.maxReconnectAttempts = 5;
|
||||
config.bot.preferredQuality = Api::AudioQuality::High;
|
||||
config.bot.trackTimeout = std::chrono::milliseconds(10000);
|
||||
config.bot.allowPlaylistImports = true;
|
||||
|
||||
// Default YouTube config
|
||||
@@ -154,17 +150,11 @@ namespace Echoion::Core
|
||||
config.features.autoStartOnSubscribe = true;
|
||||
config.features.pauseOnEmptySubscribers = true;
|
||||
config.features.resumeOnSubscriberReturn = true;
|
||||
config.features.shuffleMode = "random";
|
||||
config.features.shuffleMode = "off";
|
||||
config.features.repeatMode = "off";
|
||||
config.features.maxHistorySize = 50;
|
||||
|
||||
// Default advanced config
|
||||
config.advanced.sampleRate = 192000;
|
||||
config.advanced.channels = 2;
|
||||
config.advanced.bufferSize = 7680;
|
||||
config.advanced.commandThreadPoolSize = 4;
|
||||
config.advanced.networkThreadPoolSize = 4;
|
||||
config.advanced.decoderThreads = 2;
|
||||
config.advanced.cacheEnabled = true;
|
||||
config.advanced.cacheMaxSize = "1GB";
|
||||
config.advanced.cacheTTL = 86400;
|
||||
|
||||
@@ -44,6 +44,12 @@ namespace Echoion::Api
|
||||
return config_.network;
|
||||
}
|
||||
|
||||
const SourcesConfig& ConfigManager::getSources() const
|
||||
{
|
||||
std::shared_lock lock(mutex_);
|
||||
return config_.sources;
|
||||
}
|
||||
|
||||
const TeamSpeakConfig& ConfigManager::getTeamSpeak() const
|
||||
{
|
||||
std::shared_lock lock(mutex_);
|
||||
|
||||
@@ -248,6 +248,15 @@ namespace Echoion::Core
|
||||
}
|
||||
});
|
||||
|
||||
// Proactive private-message send path (announcements).
|
||||
musicManager_->setMessageCallback(
|
||||
[this](uint64_t clientId, const std::string& text) {
|
||||
if (pluginInterface_) {
|
||||
[[maybe_unused]] auto r =
|
||||
pluginInterface_->sendTextMessage(clientId, text);
|
||||
}
|
||||
});
|
||||
|
||||
// Set up subscription change callback to update whisper list
|
||||
musicManager_->setSubscriptionChangeCallback(
|
||||
[this]() { updateWhisperList(); });
|
||||
@@ -833,8 +842,11 @@ namespace Echoion::Core
|
||||
// Re-apply network settings to every outbound client (NetworkClient,
|
||||
// yt-dlp, ffmpeg), not just the HTTP client.
|
||||
if (musicManager_) {
|
||||
musicManager_->applyBotConfig(config.bot);
|
||||
musicManager_->applyFeaturesConfig(config.features);
|
||||
musicManager_->applyNetworkConfig(config.network);
|
||||
musicManager_->applyYouTubeConfig(config.youtube);
|
||||
musicManager_->applySourcesConfig(config.sources);
|
||||
} else if (networkClient_) {
|
||||
networkClient_->setProxy(config.network.proxy);
|
||||
}
|
||||
@@ -844,6 +856,9 @@ namespace Echoion::Core
|
||||
.clientId = 0,
|
||||
.timestamp = std::chrono::system_clock::now()});
|
||||
|
||||
eventBus_.publish(
|
||||
Api::Events::ConfigReloaded{.newConfig = config.bot});
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
@@ -916,12 +931,18 @@ namespace Echoion::Core
|
||||
// outbound client (HTTP NetworkClient, yt-dlp, ffmpeg) — not just the
|
||||
// config copy. Without this the YouTube API kept using the old/no proxy.
|
||||
if (musicManager_) {
|
||||
musicManager_->applyBotConfig(config_.bot);
|
||||
musicManager_->applyFeaturesConfig(config_.features);
|
||||
musicManager_->applyNetworkConfig(config_.network);
|
||||
musicManager_->applyYouTubeConfig(config_.youtube);
|
||||
musicManager_->applySourcesConfig(config_.sources);
|
||||
} else if (networkClient_) {
|
||||
networkClient_->setProxy(config_.network.proxy);
|
||||
}
|
||||
|
||||
eventBus_.publish(
|
||||
Api::Events::ConfigReloaded{.newConfig = config_.bot});
|
||||
|
||||
Void::Log::info("Core", "{}", "Configuration reloaded from disk");
|
||||
return {};
|
||||
}
|
||||
|
||||
+35
-1
@@ -82,10 +82,12 @@ namespace Echoion::Core
|
||||
rpcServer_->broadcastEvent("playback.finished", "{}");
|
||||
}
|
||||
|
||||
// Update playback record as completed
|
||||
// Update playback record as completed, keeping the history
|
||||
// bounded per features.maxHistorySize.
|
||||
if (database_) {
|
||||
database_->recordPlayback(evt.track, 0, evt.finalPosition,
|
||||
true);
|
||||
database_->trimHistory(config_.features.maxHistorySize);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -234,6 +236,38 @@ namespace Echoion::Core
|
||||
}
|
||||
});
|
||||
|
||||
eventBus_.subscribe<QueueShuffled>(
|
||||
[this](const QueueShuffled&) mutable {
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent("queue.shuffled", "{}");
|
||||
}
|
||||
});
|
||||
|
||||
eventBus_.subscribe<PlaybackError>(
|
||||
[this](const PlaybackError& evt) mutable {
|
||||
if (rpcServer_) {
|
||||
// Build via the JSON model: the error message may
|
||||
// contain quotes/newlines that must be escaped.
|
||||
Void::Json::Value payload = Void::Json::object();
|
||||
auto& obj = payload.as_object();
|
||||
obj.emplace_back("message",
|
||||
Void::Json::Value{evt.message});
|
||||
obj.emplace_back(
|
||||
"track", evt.track
|
||||
? Void::Json::Value{evt.track->title}
|
||||
: Void::Json::Value{nullptr});
|
||||
rpcServer_->broadcastEvent(
|
||||
"playback.error", Void::Json::serialize(payload, {}));
|
||||
}
|
||||
});
|
||||
|
||||
eventBus_.subscribe<ConfigReloaded>(
|
||||
[this](const ConfigReloaded&) mutable {
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent("config.reloaded", "{}");
|
||||
}
|
||||
});
|
||||
|
||||
Void::Log::info("Core", "{}", "EventBus subscriptions set up");
|
||||
}
|
||||
|
||||
|
||||
+656
-19
@@ -6,8 +6,11 @@
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Data/Reflect.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <format>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
@@ -19,9 +22,9 @@ namespace Echoion::Core
|
||||
}
|
||||
|
||||
// Authentication - expects JSON with either "nickname" (for initial
|
||||
// request) or "token" (for validation)
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(Api::RpcMethod::Authenticate)),
|
||||
// request) or "token" (for validation). The same handler backs
|
||||
// Authenticate, RequestLoginToken and ValidateLoginToken.
|
||||
auto authHandler =
|
||||
[this](const std::string& params,
|
||||
uint64_t clientId) -> Api::Result<std::string> {
|
||||
// Parse JSON params
|
||||
@@ -46,6 +49,34 @@ namespace Echoion::Core
|
||||
}
|
||||
if (*validResult) {
|
||||
rpcServer_->addAuthenticatedClient(clientId);
|
||||
// Mark the client as admin if its TeamSpeak identity is
|
||||
// in a configured admin server group.
|
||||
if (auto uid =
|
||||
database_->getUidFromRpcToken(*req.token);
|
||||
uid && uid->has_value() && pluginInterface_ &&
|
||||
!config_.teamspeak.adminGroups.empty()) {
|
||||
if (auto clients = pluginInterface_->getClients()) {
|
||||
for (const auto& c : *clients) {
|
||||
if (c.uniqueIdentifier == **uid) {
|
||||
bool admin = false;
|
||||
for (uint64_t ag :
|
||||
config_.teamspeak.adminGroups) {
|
||||
for (uint64_t cg : c.serverGroups) {
|
||||
if (ag == cg) {
|
||||
admin = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (admin) {
|
||||
std::lock_guard<std::mutex> lock(
|
||||
adminMutex_);
|
||||
adminClients_.push_back(clientId);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return toJson(Dto::SuccessMessage{
|
||||
.message = "Authentication successful"});
|
||||
} else {
|
||||
@@ -135,19 +166,39 @@ namespace Echoion::Core
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"Authentication request must include either "
|
||||
"'nickname' or 'token'");
|
||||
});
|
||||
};
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(Api::RpcMethod::Authenticate)),
|
||||
authHandler);
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(Api::RpcMethod::RequestLoginToken)),
|
||||
authHandler);
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(
|
||||
static_cast<int>(Api::RpcMethod::ValidateLoginToken)),
|
||||
authHandler);
|
||||
|
||||
// Playback control
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(Api::RpcMethod::Play)),
|
||||
[this](const std::string& params,
|
||||
uint64_t clientId) -> Api::Result<std::string> {
|
||||
// Parse query from params (simple implementation)
|
||||
std::string query = params;
|
||||
// Remove quotes if present
|
||||
if (query.size() >= 2 && query.front() == '"' &&
|
||||
query.back() == '"') {
|
||||
query = query.substr(1, query.size() - 2);
|
||||
// Prefer {"query":"..."}; fall back to a bare (optionally
|
||||
// quoted) string for compatibility.
|
||||
std::string query;
|
||||
if (auto parsed = Void::Json::parse(params)) {
|
||||
if (auto req =
|
||||
Void::Json::from_json<Dto::QueueTrackRequest>(
|
||||
*parsed)) {
|
||||
query = req->query;
|
||||
}
|
||||
}
|
||||
if (query.empty()) {
|
||||
query = params;
|
||||
if (query.size() >= 2 && query.front() == '"' &&
|
||||
query.back() == '"') {
|
||||
query = query.substr(1, query.size() - 2);
|
||||
}
|
||||
}
|
||||
auto result = musicManager_->play(query, clientId);
|
||||
if (!result) {
|
||||
@@ -192,8 +243,15 @@ namespace Echoion::Core
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(Api::RpcMethod::Skip)),
|
||||
[this](const std::string& params,
|
||||
uint64_t clientId) -> Api::Result<std::string> {
|
||||
auto result = skip(1);
|
||||
uint64_t) -> Api::Result<std::string> {
|
||||
uint32_t count = 1;
|
||||
if (auto parsed = Void::Json::parse(params)) {
|
||||
if (auto req =
|
||||
Void::Json::from_json<Dto::SkipRequest>(*parsed)) {
|
||||
count = req->count > 0 ? req->count : 1;
|
||||
}
|
||||
}
|
||||
auto result = skip(count);
|
||||
if (!result) {
|
||||
return std::unexpected(result.error());
|
||||
}
|
||||
@@ -204,14 +262,18 @@ namespace Echoion::Core
|
||||
std::to_string(static_cast<int>(Api::RpcMethod::SetVolume)),
|
||||
[this](const std::string& params,
|
||||
uint64_t clientId) -> Api::Result<std::string> {
|
||||
// Parse volume from params - expect {"volume":0.5}
|
||||
float volume = 0.5f;
|
||||
if (params.find("volume") != std::string::npos) {
|
||||
size_t pos = params.find(':');
|
||||
if (pos != std::string::npos) {
|
||||
volume = std::stof(params.substr(pos + 1));
|
||||
}
|
||||
// Parse {"volume":0.0-1.0} via reflection DTO.
|
||||
auto parsed = Void::Json::parse(params);
|
||||
if (!parsed) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"Invalid volume request");
|
||||
}
|
||||
auto req = Void::Json::from_json<Dto::VolumeRequest>(*parsed);
|
||||
if (!req) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"Invalid volume request");
|
||||
}
|
||||
float volume = std::clamp(req->volume, 0.0f, 1.0f);
|
||||
auto result = setVolume(volume);
|
||||
if (!result) {
|
||||
return std::unexpected(result.error());
|
||||
@@ -272,6 +334,581 @@ namespace Echoion::Core
|
||||
.shuffle = state->shuffle});
|
||||
});
|
||||
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(Api::RpcMethod::Seek)),
|
||||
[this](const std::string& params,
|
||||
uint64_t) -> Api::Result<std::string> {
|
||||
auto parsed = Void::Json::parse(params);
|
||||
if (!parsed) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"Invalid seek request");
|
||||
}
|
||||
auto req = Void::Json::from_json<Dto::SeekRequest>(*parsed);
|
||||
if (!req) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"Invalid seek request");
|
||||
}
|
||||
auto result = seek(std::chrono::milliseconds(req->position));
|
||||
if (!result) {
|
||||
return std::unexpected(result.error());
|
||||
}
|
||||
return toJson(Dto::Success{});
|
||||
});
|
||||
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(Api::RpcMethod::QueueTrack)),
|
||||
[this](const std::string& params,
|
||||
uint64_t clientId) -> Api::Result<std::string> {
|
||||
auto parsed = Void::Json::parse(params);
|
||||
if (!parsed) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"Invalid queue request");
|
||||
}
|
||||
auto req =
|
||||
Void::Json::from_json<Dto::QueueTrackRequest>(*parsed);
|
||||
if (!req) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"Invalid queue request");
|
||||
}
|
||||
auto result = queueTrack(req->query, clientId);
|
||||
if (!result) {
|
||||
return std::unexpected(result.error());
|
||||
}
|
||||
return toJson(Dto::QueuedResponse{.queueId = *result});
|
||||
});
|
||||
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(Api::RpcMethod::RemoveFromQueue)),
|
||||
[this](const std::string& params,
|
||||
uint64_t) -> Api::Result<std::string> {
|
||||
auto parsed = Void::Json::parse(params);
|
||||
if (!parsed) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"Invalid remove request");
|
||||
}
|
||||
auto req = Void::Json::from_json<Dto::QueueIdRequest>(*parsed);
|
||||
if (!req) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"Invalid remove request");
|
||||
}
|
||||
auto result = removeFromQueue(req->queueId);
|
||||
if (!result) {
|
||||
return std::unexpected(result.error());
|
||||
}
|
||||
return toJson(Dto::Success{});
|
||||
});
|
||||
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(Api::RpcMethod::ClearQueue)),
|
||||
[this](const std::string&,
|
||||
uint64_t) -> Api::Result<std::string> {
|
||||
auto result = clearQueue();
|
||||
if (!result) {
|
||||
return std::unexpected(result.error());
|
||||
}
|
||||
return toJson(Dto::Success{});
|
||||
});
|
||||
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(Api::RpcMethod::MoveInQueue)),
|
||||
[this](const std::string& params,
|
||||
uint64_t) -> Api::Result<std::string> {
|
||||
auto parsed = Void::Json::parse(params);
|
||||
if (!parsed) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"Invalid move request");
|
||||
}
|
||||
auto req = Void::Json::from_json<Dto::MoveRequest>(*parsed);
|
||||
if (!req) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"Invalid move request");
|
||||
}
|
||||
auto result = moveInQueue(req->queueId, req->newPosition);
|
||||
if (!result) {
|
||||
return std::unexpected(result.error());
|
||||
}
|
||||
return toJson(Dto::Success{});
|
||||
});
|
||||
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(Api::RpcMethod::SearchTracks)),
|
||||
[this](const std::string& params,
|
||||
uint64_t) -> Api::Result<std::string> {
|
||||
auto parsed = Void::Json::parse(params);
|
||||
if (!parsed) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"Invalid search request");
|
||||
}
|
||||
auto req = Void::Json::from_json<Dto::SearchRequest>(*parsed);
|
||||
if (!req) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"Invalid search request");
|
||||
}
|
||||
auto result = musicManager_->search(req->query);
|
||||
if (!result) {
|
||||
return std::unexpected(result.error());
|
||||
}
|
||||
Dto::SearchResults resp;
|
||||
resp.tracks.reserve(result->tracks.size());
|
||||
for (const auto& t : result->tracks) {
|
||||
resp.tracks.push_back(Dto::toTrack(t));
|
||||
}
|
||||
return toJson(resp);
|
||||
});
|
||||
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(Api::RpcMethod::GetTrackInfo)),
|
||||
[this](const std::string& params,
|
||||
uint64_t) -> Api::Result<std::string> {
|
||||
auto parsed = Void::Json::parse(params);
|
||||
if (!parsed) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"Invalid track info request");
|
||||
}
|
||||
auto req = Void::Json::from_json<Dto::TrackIdRequest>(*parsed);
|
||||
if (!req) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"Invalid track info request");
|
||||
}
|
||||
// No arbitrary-id lookup exists; resolve via search top result.
|
||||
auto result = musicManager_->search(req->id);
|
||||
if (!result) {
|
||||
return std::unexpected(result.error());
|
||||
}
|
||||
if (result->tracks.empty()) {
|
||||
return Api::fail(Api::ErrorCode::NotFound,
|
||||
"Track not found");
|
||||
}
|
||||
return toJson(Dto::toTrack(result->tracks.front()));
|
||||
});
|
||||
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(Api::RpcMethod::ToggleShuffle)),
|
||||
[this](const std::string&,
|
||||
uint64_t) -> Api::Result<std::string> {
|
||||
auto result = musicManager_->toggleShuffle();
|
||||
if (!result) {
|
||||
return std::unexpected(result.error());
|
||||
}
|
||||
return toJson(Dto::Shuffle{.shuffle = *result});
|
||||
});
|
||||
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(Api::RpcMethod::ToggleRepeat)),
|
||||
[this](const std::string&,
|
||||
uint64_t) -> Api::Result<std::string> {
|
||||
auto result = musicManager_->toggleRepeat();
|
||||
if (!result) {
|
||||
return std::unexpected(result.error());
|
||||
}
|
||||
return toJson(Dto::Repeat{.repeat = *result});
|
||||
});
|
||||
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(Api::RpcMethod::ShuffleQueue)),
|
||||
[this](const std::string&,
|
||||
uint64_t) -> Api::Result<std::string> {
|
||||
auto result = musicManager_->shuffleQueue();
|
||||
if (!result) {
|
||||
return std::unexpected(result.error());
|
||||
}
|
||||
return toJson(Dto::Success{});
|
||||
});
|
||||
|
||||
// Playlists
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(Api::RpcMethod::LoadPlaylist)),
|
||||
[this](const std::string& params,
|
||||
uint64_t clientId) -> Api::Result<std::string> {
|
||||
auto parsed = Void::Json::parse(params);
|
||||
if (!parsed) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"Invalid playlist request");
|
||||
}
|
||||
auto req =
|
||||
Void::Json::from_json<Dto::PlaylistIdRequest>(*parsed);
|
||||
if (!req) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"Invalid playlist request");
|
||||
}
|
||||
auto result = loadPlaylist(req->playlistId, clientId);
|
||||
if (!result) {
|
||||
return std::unexpected(result.error());
|
||||
}
|
||||
return toJson(Dto::Success{});
|
||||
});
|
||||
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(Api::RpcMethod::GetPlaylists)),
|
||||
[this](const std::string&,
|
||||
uint64_t) -> Api::Result<std::string> {
|
||||
if (!database_) {
|
||||
return Api::fail(Api::ErrorCode::ServiceUnavailable,
|
||||
"Database unavailable");
|
||||
}
|
||||
auto playlists = database_->getAllPlaylists();
|
||||
if (!playlists) {
|
||||
return std::unexpected(playlists.error());
|
||||
}
|
||||
Dto::PlaylistList resp;
|
||||
resp.playlists.reserve(playlists->size());
|
||||
for (const auto& p : *playlists) {
|
||||
resp.playlists.push_back(Dto::PlaylistBrief{
|
||||
.id = std::to_string(p.id),
|
||||
.name = p.name,
|
||||
.description = p.description,
|
||||
.trackCount =
|
||||
static_cast<std::uint32_t>(p.tracks.size())});
|
||||
}
|
||||
return toJson(resp);
|
||||
});
|
||||
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(Api::RpcMethod::GetPlaylist)),
|
||||
[this](const std::string& params,
|
||||
uint64_t) -> Api::Result<std::string> {
|
||||
if (!database_) {
|
||||
return Api::fail(Api::ErrorCode::ServiceUnavailable,
|
||||
"Database unavailable");
|
||||
}
|
||||
auto parsed = Void::Json::parse(params);
|
||||
if (!parsed) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"Invalid playlist request");
|
||||
}
|
||||
auto req =
|
||||
Void::Json::from_json<Dto::PlaylistIdRequest>(*parsed);
|
||||
if (!req) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"Invalid playlist request");
|
||||
}
|
||||
uint64_t playlistId = 0;
|
||||
try {
|
||||
playlistId = std::stoull(req->playlistId);
|
||||
} catch (const std::exception&) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"Playlist id must be numeric");
|
||||
}
|
||||
auto playlist = database_->getPlaylist(playlistId);
|
||||
if (!playlist) {
|
||||
return std::unexpected(playlist.error());
|
||||
}
|
||||
if (!playlist->has_value()) {
|
||||
return Api::fail(Api::ErrorCode::NotFound,
|
||||
"Playlist not found");
|
||||
}
|
||||
Dto::PlaylistContents resp;
|
||||
resp.id = std::to_string((*playlist)->id);
|
||||
resp.name = (*playlist)->name;
|
||||
resp.description = (*playlist)->description;
|
||||
resp.tracks.reserve((*playlist)->tracks.size());
|
||||
for (const auto& t : (*playlist)->tracks) {
|
||||
resp.tracks.push_back(Dto::toTrack(t));
|
||||
}
|
||||
return toJson(resp);
|
||||
});
|
||||
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(Api::RpcMethod::GetHistory)),
|
||||
[this](const std::string& params,
|
||||
uint64_t) -> Api::Result<std::string> {
|
||||
if (!database_) {
|
||||
return Api::fail(Api::ErrorCode::ServiceUnavailable,
|
||||
"Database unavailable");
|
||||
}
|
||||
uint32_t limit = 20;
|
||||
if (!params.empty()) {
|
||||
if (auto parsed = Void::Json::parse(params)) {
|
||||
if (auto req = Void::Json::from_json<
|
||||
Dto::HistoryRequest>(*parsed)) {
|
||||
limit = std::clamp(req->limit, 1u, 100u);
|
||||
}
|
||||
}
|
||||
}
|
||||
auto recent = database_->getRecentlyPlayed(0, limit);
|
||||
if (!recent) {
|
||||
return std::unexpected(recent.error());
|
||||
}
|
||||
Dto::HistoryResponse resp;
|
||||
resp.tracks.reserve(recent->size());
|
||||
for (const auto& t : *recent) {
|
||||
resp.tracks.push_back(Dto::toTrack(t));
|
||||
}
|
||||
return toJson(resp);
|
||||
});
|
||||
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(Api::RpcMethod::GetStats)),
|
||||
[this](const std::string&,
|
||||
uint64_t) -> Api::Result<std::string> {
|
||||
if (!database_) {
|
||||
return Api::fail(Api::ErrorCode::ServiceUnavailable,
|
||||
"Database unavailable");
|
||||
}
|
||||
auto stats = database_->getStatistics(0);
|
||||
if (!stats) {
|
||||
return std::unexpected(stats.error());
|
||||
}
|
||||
return toJson(Dto::StatsResponse{
|
||||
.totalPlays = stats->totalPlays,
|
||||
.totalTracks = stats->totalTracks,
|
||||
.totalPlaytimeMs = stats->totalPlaytimeMs,
|
||||
.mostPlayedTitle =
|
||||
stats->mostPlayedTrack
|
||||
? std::optional(stats->mostPlayedTrack->title)
|
||||
: std::nullopt,
|
||||
.mostPlayedCount = stats->mostPlayedCount});
|
||||
});
|
||||
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(Api::RpcMethod::SavePlaylist)),
|
||||
[this](const std::string& params,
|
||||
uint64_t clientId) -> Api::Result<std::string> {
|
||||
if (!database_) {
|
||||
return Api::fail(Api::ErrorCode::ServiceUnavailable,
|
||||
"Database unavailable");
|
||||
}
|
||||
auto parsed = Void::Json::parse(params);
|
||||
if (!parsed) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"Invalid save-playlist request");
|
||||
}
|
||||
auto req =
|
||||
Void::Json::from_json<Dto::SavePlaylistRequest>(*parsed);
|
||||
if (!req || req->name.empty()) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"Playlist name is required");
|
||||
}
|
||||
// Persist the current queue as a new playlist. Ownership is
|
||||
// recorded as the RPC client id (no TS-uid→user mapping yet).
|
||||
auto created = database_->createPlaylist(
|
||||
req->name, req->description, clientId);
|
||||
if (!created) {
|
||||
return std::unexpected(created.error());
|
||||
}
|
||||
auto queue = getQueue();
|
||||
if (queue) {
|
||||
std::uint32_t position = 0;
|
||||
for (const auto& entry : *queue) {
|
||||
(void)database_->addTrackToPlaylist(
|
||||
*created, entry.track, position++);
|
||||
}
|
||||
}
|
||||
return toJson(Dto::QueuedResponse{.queueId = *created});
|
||||
});
|
||||
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(Api::RpcMethod::DeletePlaylist)),
|
||||
[this](const std::string& params,
|
||||
uint64_t) -> Api::Result<std::string> {
|
||||
if (!database_) {
|
||||
return Api::fail(Api::ErrorCode::ServiceUnavailable,
|
||||
"Database unavailable");
|
||||
}
|
||||
auto parsed = Void::Json::parse(params);
|
||||
if (!parsed) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"Invalid delete-playlist request");
|
||||
}
|
||||
auto req =
|
||||
Void::Json::from_json<Dto::PlaylistIdRequest>(*parsed);
|
||||
if (!req) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"Invalid delete-playlist request");
|
||||
}
|
||||
std::uint64_t id = 0;
|
||||
try {
|
||||
id = std::stoull(req->playlistId);
|
||||
} catch (const std::exception&) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"Invalid playlist id");
|
||||
}
|
||||
auto result = database_->deletePlaylist(id);
|
||||
if (!result) {
|
||||
return std::unexpected(result.error());
|
||||
}
|
||||
return toJson(Dto::Success{});
|
||||
});
|
||||
|
||||
// Configuration
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(Api::RpcMethod::GetConfig)),
|
||||
[this](const std::string&,
|
||||
uint64_t clientId) -> Api::Result<std::string> {
|
||||
// Config may contain secrets — admin only.
|
||||
if (!isAdmin(clientId)) {
|
||||
return Api::fail(Api::ErrorCode::PermissionDenied,
|
||||
"Admin privileges required");
|
||||
}
|
||||
// Returns the config as a JSON string (already serialized).
|
||||
return getConfigJson();
|
||||
});
|
||||
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(Api::RpcMethod::SetConfig)),
|
||||
[this](const std::string& params,
|
||||
uint64_t clientId) -> Api::Result<std::string> {
|
||||
if (!isAdmin(clientId)) {
|
||||
return Api::fail(Api::ErrorCode::PermissionDenied,
|
||||
"Admin privileges required");
|
||||
}
|
||||
auto result = updateConfigJson(params);
|
||||
if (!result) {
|
||||
return std::unexpected(result.error());
|
||||
}
|
||||
return toJson(Dto::Success{});
|
||||
});
|
||||
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(Api::RpcMethod::ReloadConfig)),
|
||||
[this](const std::string&,
|
||||
uint64_t) -> Api::Result<std::string> {
|
||||
auto result = reloadConfig();
|
||||
if (!result) {
|
||||
return std::unexpected(result.error());
|
||||
}
|
||||
return toJson(Dto::Success{});
|
||||
});
|
||||
|
||||
// ── Admin / system ──────────────────────────────────────────────────
|
||||
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(Api::RpcMethod::Logout)),
|
||||
[this](const std::string&,
|
||||
uint64_t clientId) -> Api::Result<std::string> {
|
||||
rpcServer_->removeAuthenticatedClient(clientId);
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(adminMutex_);
|
||||
std::erase(adminClients_, clientId);
|
||||
}
|
||||
return toJson(Dto::Success{});
|
||||
});
|
||||
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(Api::RpcMethod::GetServerInfo)),
|
||||
[this](const std::string&,
|
||||
uint64_t) -> Api::Result<std::string> {
|
||||
Dto::ServerInfo info;
|
||||
info.version = Api::VERSION_STRING;
|
||||
info.uptimeSeconds = rpcServer_->getUptime().count();
|
||||
info.connectedClients = static_cast<std::uint32_t>(
|
||||
rpcServer_->getClientCount());
|
||||
if (database_) {
|
||||
if (auto count = database_->getSubscriberCount()) {
|
||||
info.subscribers =
|
||||
static_cast<std::uint32_t>(*count);
|
||||
}
|
||||
}
|
||||
if (auto queue = getQueue()) {
|
||||
info.queueLength =
|
||||
static_cast<std::uint32_t>(queue->size());
|
||||
}
|
||||
return toJson(info);
|
||||
});
|
||||
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(Api::RpcMethod::GetAuditLog)),
|
||||
[this](const std::string&,
|
||||
uint64_t clientId) -> Api::Result<std::string> {
|
||||
if (!isAdmin(clientId)) {
|
||||
return Api::fail(Api::ErrorCode::PermissionDenied,
|
||||
"Admin privileges required");
|
||||
}
|
||||
Dto::AuditLogResponse resp;
|
||||
for (const auto& e : rpcServer_->getAuditLog()) {
|
||||
resp.entries.push_back(Dto::AuditEntryDto{
|
||||
.clientId = e.clientId,
|
||||
.method = e.method,
|
||||
.timestamp = std::chrono::duration_cast<
|
||||
std::chrono::seconds>(
|
||||
e.timestamp.time_since_epoch())
|
||||
.count()});
|
||||
}
|
||||
return toJson(resp);
|
||||
});
|
||||
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(Api::RpcMethod::ManageUsers)),
|
||||
[this](const std::string& params,
|
||||
uint64_t clientId) -> Api::Result<std::string> {
|
||||
if (!isAdmin(clientId)) {
|
||||
return Api::fail(Api::ErrorCode::PermissionDenied,
|
||||
"Admin privileges required");
|
||||
}
|
||||
if (!database_) {
|
||||
return Api::fail(Api::ErrorCode::ServiceUnavailable,
|
||||
"Database unavailable");
|
||||
}
|
||||
auto parsed = Void::Json::parse(params);
|
||||
if (!parsed) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"Invalid manage-users request");
|
||||
}
|
||||
auto req =
|
||||
Void::Json::from_json<Dto::ManageUsersRequest>(*parsed);
|
||||
if (!req) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"Invalid manage-users request");
|
||||
}
|
||||
if (req->action == "remove") {
|
||||
if (!req->uid || req->uid->empty()) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"uid required for remove");
|
||||
}
|
||||
auto result = database_->removeSubscriber(*req->uid);
|
||||
if (!result) {
|
||||
return std::unexpected(result.error());
|
||||
}
|
||||
return toJson(Dto::Success{});
|
||||
}
|
||||
// Default: list subscribers.
|
||||
auto subs = database_->getAllSubscribers();
|
||||
if (!subs) {
|
||||
return std::unexpected(subs.error());
|
||||
}
|
||||
Dto::UsersResponse resp;
|
||||
resp.users.reserve(subs->size());
|
||||
for (const auto& s : *subs) {
|
||||
resp.users.push_back(Dto::SubscriberDto{
|
||||
.uid = s.uid, .nickname = s.nickname});
|
||||
}
|
||||
return toJson(resp);
|
||||
});
|
||||
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(Api::RpcMethod::HotReload)),
|
||||
[this](const std::string&,
|
||||
uint64_t clientId) -> Api::Result<std::string> {
|
||||
if (!isAdmin(clientId)) {
|
||||
return Api::fail(Api::ErrorCode::PermissionDenied,
|
||||
"Admin privileges required");
|
||||
}
|
||||
auto result = prepareForHotReload();
|
||||
if (!result) {
|
||||
return std::unexpected(result.error());
|
||||
}
|
||||
return toJson(Dto::Success{});
|
||||
});
|
||||
|
||||
rpcServer_->registerHandler(
|
||||
std::to_string(static_cast<int>(Api::RpcMethod::Shutdown)),
|
||||
[this](const std::string&,
|
||||
uint64_t clientId) -> Api::Result<std::string> {
|
||||
if (!isAdmin(clientId)) {
|
||||
return Api::fail(Api::ErrorCode::PermissionDenied,
|
||||
"Admin privileges required");
|
||||
}
|
||||
// Defer the actual shutdown so this success response is
|
||||
// delivered before the server tears down.
|
||||
std::thread([this]() {
|
||||
std::this_thread::sleep_for(
|
||||
std::chrono::milliseconds(250));
|
||||
(void)shutdown();
|
||||
}).detach();
|
||||
return toJson(Dto::SuccessMessage{
|
||||
.message = "Shutting down"});
|
||||
});
|
||||
|
||||
Void::Log::info("Core", "{}", "RPC handlers registered");
|
||||
}
|
||||
|
||||
|
||||
+362
-38
@@ -264,11 +264,55 @@ namespace Echoion::Api
|
||||
[[maybe_unused]] auto ins = impl_->voidDb.exec(
|
||||
"INSERT INTO schema_migrations (version) VALUES (4)");
|
||||
|
||||
Void::Log::info("Database", "{}",
|
||||
Void::Log::info("Database", "{}",
|
||||
"Database migration 4 applied: RPC tokens table added");
|
||||
}
|
||||
|
||||
impl_->version = 4;
|
||||
// Migration 5: generic key/value store (instance persistence, small
|
||||
// bits of state that don't deserve their own table)
|
||||
if (currentVersion < 5) {
|
||||
const char* migration5 = R"(
|
||||
CREATE TABLE IF NOT EXISTS kv_store (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
)";
|
||||
|
||||
if (auto r = impl_->voidDb.exec(migration5); !r) {
|
||||
return fail(ErrorCode::DatabaseError, r.error().message());
|
||||
}
|
||||
|
||||
[[maybe_unused]] auto ins = impl_->voidDb.exec(
|
||||
"INSERT INTO schema_migrations (version) VALUES (5)");
|
||||
|
||||
Void::Log::info("Database", "{}",
|
||||
"Database migration 5 applied: kv_store table added");
|
||||
}
|
||||
|
||||
// Migration 6: persist the shortened track URL alongside history,
|
||||
// favorites and playlist tracks so YouTube links render short
|
||||
// everywhere (they are reconstructed from the DB, which previously
|
||||
// only kept the long originalUrl).
|
||||
if (currentVersion < 6) {
|
||||
const char* migration6 = R"(
|
||||
ALTER TABLE playback_history ADD COLUMN track_short_url TEXT;
|
||||
ALTER TABLE user_favorites ADD COLUMN track_short_url TEXT;
|
||||
ALTER TABLE playlist_tracks ADD COLUMN track_short_url TEXT;
|
||||
)";
|
||||
|
||||
if (auto r = impl_->voidDb.exec(migration6); !r) {
|
||||
return fail(ErrorCode::DatabaseError, r.error().message());
|
||||
}
|
||||
|
||||
[[maybe_unused]] auto ins = impl_->voidDb.exec(
|
||||
"INSERT INTO schema_migrations (version) VALUES (6)");
|
||||
|
||||
Void::Log::info("Database", "{}",
|
||||
"Database migration 6 applied: track_short_url columns added");
|
||||
}
|
||||
|
||||
impl_->version = 6;
|
||||
return {};
|
||||
}
|
||||
|
||||
@@ -374,7 +418,7 @@ namespace Echoion::Api
|
||||
|
||||
// Load tracks
|
||||
const char* tracksSql = R"(
|
||||
SELECT track_url, track_title, track_artist, track_thumbnail
|
||||
SELECT track_url, track_title, track_artist, track_thumbnail, track_short_url
|
||||
FROM playlist_tracks
|
||||
WHERE playlist_id = ?
|
||||
ORDER BY position;
|
||||
@@ -396,6 +440,12 @@ namespace Echoion::Api
|
||||
if (!tracks.is_null(3)) {
|
||||
track.thumbnailUrl = tracks.column_text(3);
|
||||
}
|
||||
if (!tracks.is_null(4)) {
|
||||
if (auto shortUrl = tracks.column_text(4);
|
||||
!shortUrl.empty()) {
|
||||
track.shortenedUrl = shortUrl;
|
||||
}
|
||||
}
|
||||
playlist.tracks.push_back(track);
|
||||
}
|
||||
}
|
||||
@@ -434,6 +484,37 @@ namespace Echoion::Api
|
||||
return playlists;
|
||||
}
|
||||
|
||||
Result<std::vector<Playlist>> Database::getAllPlaylists()
|
||||
{
|
||||
std::shared_lock<std::shared_mutex> lock(mutex_);
|
||||
std::vector<Playlist> playlists;
|
||||
|
||||
const char* sql = R"(
|
||||
SELECT id, name, description, created_by, is_public, external_id
|
||||
FROM playlists
|
||||
ORDER BY updated_at DESC;
|
||||
)";
|
||||
|
||||
auto stmtRes = impl_->voidDb.prepare(sql);
|
||||
if (!stmtRes) {
|
||||
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
||||
}
|
||||
auto& stmt = *stmtRes;
|
||||
|
||||
while (stmt.step().value_or(false)) {
|
||||
Playlist playlist;
|
||||
playlist.id = static_cast<uint64_t>(stmt.column_int(0));
|
||||
playlist.name = stmt.column_text(1);
|
||||
playlist.description = stmt.column_text(2);
|
||||
playlist.createdBy = static_cast<uint64_t>(stmt.column_int(3));
|
||||
playlist.isPublic = stmt.column_int(4) != 0;
|
||||
playlist.externalId = stmt.column_text(5);
|
||||
playlists.push_back(playlist);
|
||||
}
|
||||
|
||||
return playlists;
|
||||
}
|
||||
|
||||
Result<void> Database::deletePlaylist(uint64_t id)
|
||||
{
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
@@ -457,9 +538,9 @@ namespace Echoion::Api
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
|
||||
const char* sql = R"(
|
||||
INSERT INTO playlist_tracks
|
||||
(playlist_id, track_url, track_title, track_artist, track_thumbnail, position)
|
||||
VALUES (?, ?, ?, ?, ?, ?);
|
||||
INSERT INTO playlist_tracks
|
||||
(playlist_id, track_url, track_title, track_artist, track_thumbnail, track_short_url, position)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?);
|
||||
)";
|
||||
|
||||
auto stmtRes = impl_->voidDb.prepare(sql);
|
||||
@@ -472,7 +553,8 @@ namespace Echoion::Api
|
||||
.bind(3, track.title)
|
||||
.bind(4, track.artist)
|
||||
.bind(5, track.thumbnailUrl.value_or(""))
|
||||
.bind(6, static_cast<int>(position));
|
||||
.bind(6, track.shortenedUrl.value_or(""))
|
||||
.bind(7, static_cast<int>(position));
|
||||
[[maybe_unused]] auto stepRes = stmt.step();
|
||||
|
||||
// Update playlist timestamp
|
||||
@@ -493,9 +575,9 @@ namespace Echoion::Api
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
|
||||
const char* sql = R"(
|
||||
INSERT INTO playback_history
|
||||
(track_url, track_title, track_artist, played_by, duration_ms, completed)
|
||||
VALUES (?, ?, ?, ?, ?, ?);
|
||||
INSERT INTO playback_history
|
||||
(track_url, track_title, track_artist, played_by, duration_ms, completed, track_short_url)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?);
|
||||
)";
|
||||
|
||||
auto stmtRes = impl_->voidDb.prepare(sql);
|
||||
@@ -508,7 +590,8 @@ namespace Echoion::Api
|
||||
.bind(3, track.artist)
|
||||
.bind(4, static_cast<std::int64_t>(playedBy))
|
||||
.bind(5, static_cast<std::int64_t>(duration.count()))
|
||||
.bind(6, completed ? 1 : 0);
|
||||
.bind(6, completed ? 1 : 0)
|
||||
.bind(7, track.shortenedUrl.value_or(""));
|
||||
[[maybe_unused]] auto stepRes = stmt.step();
|
||||
|
||||
return {};
|
||||
@@ -523,7 +606,7 @@ namespace Echoion::Api
|
||||
std::vector<PlaybackHistoryEntry> history;
|
||||
|
||||
const char* sql = R"(
|
||||
SELECT id, track_url, track_title, track_artist, played_at, duration_ms, completed
|
||||
SELECT id, track_url, track_title, track_artist, played_at, duration_ms, completed, track_short_url
|
||||
FROM playback_history
|
||||
WHERE played_by = ?
|
||||
ORDER BY played_at DESC
|
||||
@@ -549,6 +632,9 @@ namespace Echoion::Api
|
||||
entry.duration =
|
||||
std::chrono::milliseconds(stmt.column_int(5));
|
||||
entry.completed = stmt.column_int(6) != 0;
|
||||
if (auto shortUrl = stmt.column_text(7); !shortUrl.empty()) {
|
||||
entry.track.shortenedUrl = shortUrl;
|
||||
}
|
||||
history.push_back(entry);
|
||||
}
|
||||
|
||||
@@ -560,9 +646,9 @@ namespace Echoion::Api
|
||||
{
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
const char* sql = R"(
|
||||
INSERT OR REPLACE INTO user_favorites
|
||||
(user_id, track_url, track_title, track_artist)
|
||||
VALUES (?, ?, ?, ?);
|
||||
INSERT OR REPLACE INTO user_favorites
|
||||
(user_id, track_url, track_title, track_artist, track_short_url)
|
||||
VALUES (?, ?, ?, ?, ?);
|
||||
)";
|
||||
|
||||
auto stmtRes = impl_->voidDb.prepare(sql);
|
||||
@@ -575,6 +661,7 @@ namespace Echoion::Api
|
||||
stmt.bind(2, track.originalUrl);
|
||||
stmt.bind(3, track.title);
|
||||
stmt.bind(4, track.artist);
|
||||
stmt.bind(5, track.shortenedUrl.value_or(""));
|
||||
|
||||
[[maybe_unused]] auto stepRes = stmt.step();
|
||||
|
||||
@@ -629,7 +716,7 @@ namespace Echoion::Api
|
||||
std::vector<FavoriteTrack> favorites;
|
||||
|
||||
const char* sql = R"(
|
||||
SELECT track_url, track_title, track_artist, added_at
|
||||
SELECT track_url, track_title, track_artist, added_at, track_short_url
|
||||
FROM user_favorites
|
||||
WHERE user_id = ?
|
||||
ORDER BY added_at DESC;
|
||||
@@ -651,6 +738,9 @@ namespace Echoion::Api
|
||||
stmt.column_text(1);
|
||||
fav.track.artist =
|
||||
stmt.column_text(2);
|
||||
if (auto shortUrl = stmt.column_text(4); !shortUrl.empty()) {
|
||||
fav.track.shortenedUrl = shortUrl;
|
||||
}
|
||||
fav.userId = userId;
|
||||
favorites.push_back(fav);
|
||||
}
|
||||
@@ -680,8 +770,9 @@ namespace Echoion::Api
|
||||
stmt.bind(1, static_cast<std::int64_t>(keepCount));
|
||||
[[maybe_unused]] auto stepRes = stmt.step();
|
||||
|
||||
// Vacuum to reclaim space
|
||||
[[maybe_unused]] auto execRes = impl_->voidDb.exec("VACUUM;");
|
||||
// No VACUUM here: this runs after every finished track and a full
|
||||
// vacuum would rewrite the whole file each time. Use vacuum()
|
||||
// explicitly for space reclamation.
|
||||
|
||||
return {};
|
||||
}
|
||||
@@ -822,25 +913,79 @@ namespace Echoion::Api
|
||||
return count;
|
||||
}
|
||||
|
||||
// Stub implementations for missing methods
|
||||
Result<void>
|
||||
Database::updatePlaylist(uint64_t id,
|
||||
const std::optional<std::string>& name,
|
||||
const std::optional<std::string>& description,
|
||||
const std::optional<bool>& isPublic)
|
||||
{
|
||||
(void)id;
|
||||
(void)name;
|
||||
(void)description;
|
||||
(void)isPublic;
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
const char* sql = R"(
|
||||
UPDATE playlists SET
|
||||
name = COALESCE(?, name),
|
||||
description = COALESCE(?, description),
|
||||
is_public = COALESCE(?, is_public),
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = ?;
|
||||
)";
|
||||
|
||||
auto stmtRes = impl_->voidDb.prepare(sql);
|
||||
if (!stmtRes) {
|
||||
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
||||
}
|
||||
auto& stmt = *stmtRes;
|
||||
stmt.bind(1, name);
|
||||
stmt.bind(2, description);
|
||||
if (isPublic) {
|
||||
stmt.bind(3, *isPublic ? 1 : 0);
|
||||
} else {
|
||||
stmt.bind(3, nullptr);
|
||||
}
|
||||
stmt.bind(4, static_cast<std::int64_t>(id));
|
||||
[[maybe_unused]] auto stepRes = stmt.step();
|
||||
return {};
|
||||
}
|
||||
|
||||
Result<void> Database::removeTrackFromPlaylist(uint64_t playlistId,
|
||||
uint64_t trackId)
|
||||
{
|
||||
(void)playlistId;
|
||||
(void)trackId;
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
|
||||
// Delete the row, then compact positions so ordering stays dense.
|
||||
[[maybe_unused]] auto begin = impl_->voidDb.exec("BEGIN;");
|
||||
|
||||
std::int64_t removedPos = -1;
|
||||
if (auto posRes = impl_->voidDb.prepare(
|
||||
"SELECT position FROM playlist_tracks WHERE id = ? AND "
|
||||
"playlist_id = ?;")) {
|
||||
auto& posStmt = *posRes;
|
||||
posStmt.bind(1, static_cast<std::int64_t>(trackId))
|
||||
.bind(2, static_cast<std::int64_t>(playlistId));
|
||||
if (posStmt.step().value_or(false)) {
|
||||
removedPos = posStmt.column_int(0);
|
||||
}
|
||||
}
|
||||
if (removedPos < 0) {
|
||||
[[maybe_unused]] auto rollback = impl_->voidDb.exec("ROLLBACK;");
|
||||
return fail(ErrorCode::NotFound, "Track not in playlist");
|
||||
}
|
||||
|
||||
if (auto delRes = impl_->voidDb.prepare(
|
||||
"DELETE FROM playlist_tracks WHERE id = ?;")) {
|
||||
auto& delStmt = *delRes;
|
||||
delStmt.bind(1, static_cast<std::int64_t>(trackId));
|
||||
[[maybe_unused]] auto s = delStmt.step();
|
||||
}
|
||||
if (auto shiftRes = impl_->voidDb.prepare(
|
||||
"UPDATE playlist_tracks SET position = position - 1 WHERE "
|
||||
"playlist_id = ? AND position > ?;")) {
|
||||
auto& shiftStmt = *shiftRes;
|
||||
shiftStmt.bind(1, static_cast<std::int64_t>(playlistId))
|
||||
.bind(2, removedPos);
|
||||
[[maybe_unused]] auto s = shiftStmt.step();
|
||||
}
|
||||
|
||||
[[maybe_unused]] auto commit = impl_->voidDb.exec("COMMIT;");
|
||||
return {};
|
||||
}
|
||||
|
||||
@@ -848,18 +993,92 @@ namespace Echoion::Api
|
||||
uint64_t trackId,
|
||||
uint32_t newPosition)
|
||||
{
|
||||
(void)playlistId;
|
||||
(void)trackId;
|
||||
(void)newPosition;
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
|
||||
[[maybe_unused]] auto begin = impl_->voidDb.exec("BEGIN;");
|
||||
|
||||
std::int64_t oldPos = -1;
|
||||
if (auto posRes = impl_->voidDb.prepare(
|
||||
"SELECT position FROM playlist_tracks WHERE id = ? AND "
|
||||
"playlist_id = ?;")) {
|
||||
auto& posStmt = *posRes;
|
||||
posStmt.bind(1, static_cast<std::int64_t>(trackId))
|
||||
.bind(2, static_cast<std::int64_t>(playlistId));
|
||||
if (posStmt.step().value_or(false)) {
|
||||
oldPos = posStmt.column_int(0);
|
||||
}
|
||||
}
|
||||
if (oldPos < 0) {
|
||||
[[maybe_unused]] auto rollback = impl_->voidDb.exec("ROLLBACK;");
|
||||
return fail(ErrorCode::NotFound, "Track not in playlist");
|
||||
}
|
||||
|
||||
const auto newPos = static_cast<std::int64_t>(newPosition);
|
||||
const char* shiftSql =
|
||||
oldPos < newPos
|
||||
? "UPDATE playlist_tracks SET position = position - 1 WHERE "
|
||||
"playlist_id = ? AND position > ? AND position <= ?;"
|
||||
: "UPDATE playlist_tracks SET position = position + 1 WHERE "
|
||||
"playlist_id = ? AND position >= ? AND position < ?;";
|
||||
if (auto shiftRes = impl_->voidDb.prepare(shiftSql)) {
|
||||
auto& shiftStmt = *shiftRes;
|
||||
if (oldPos < newPos) {
|
||||
shiftStmt.bind(1, static_cast<std::int64_t>(playlistId))
|
||||
.bind(2, oldPos)
|
||||
.bind(3, newPos);
|
||||
} else {
|
||||
shiftStmt.bind(1, static_cast<std::int64_t>(playlistId))
|
||||
.bind(2, newPos)
|
||||
.bind(3, oldPos);
|
||||
}
|
||||
[[maybe_unused]] auto s = shiftStmt.step();
|
||||
}
|
||||
if (auto moveRes = impl_->voidDb.prepare(
|
||||
"UPDATE playlist_tracks SET position = ? WHERE id = ?;")) {
|
||||
auto& moveStmt = *moveRes;
|
||||
moveStmt.bind(1, newPos).bind(2, static_cast<std::int64_t>(trackId));
|
||||
[[maybe_unused]] auto s = moveStmt.step();
|
||||
}
|
||||
|
||||
[[maybe_unused]] auto commit = impl_->voidDb.exec("COMMIT;");
|
||||
return {};
|
||||
}
|
||||
|
||||
Result<std::vector<TrackInfo>> Database::getRecentlyPlayed(uint64_t userId,
|
||||
size_t limit)
|
||||
{
|
||||
(void)userId;
|
||||
(void)limit;
|
||||
return std::vector<TrackInfo>{};
|
||||
std::shared_lock<std::shared_mutex> lock(mutex_);
|
||||
std::vector<TrackInfo> tracks;
|
||||
|
||||
// userId 0 = global history. Deduplicate by URL, newest first.
|
||||
const char* sql = R"(
|
||||
SELECT track_url, track_title, track_artist, MAX(played_at), MAX(track_short_url)
|
||||
FROM playback_history
|
||||
WHERE (?1 = 0 OR played_by = ?1)
|
||||
GROUP BY track_url
|
||||
ORDER BY MAX(played_at) DESC
|
||||
LIMIT ?2;
|
||||
)";
|
||||
|
||||
auto stmtRes = impl_->voidDb.prepare(sql);
|
||||
if (!stmtRes) {
|
||||
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
||||
}
|
||||
auto& stmt = *stmtRes;
|
||||
stmt.bind(1, static_cast<std::int64_t>(userId))
|
||||
.bind(2, static_cast<std::int64_t>(limit));
|
||||
|
||||
while (stmt.step().value_or(false)) {
|
||||
TrackInfo track;
|
||||
track.originalUrl = stmt.column_text(0);
|
||||
track.title = stmt.column_text(1);
|
||||
track.artist = stmt.column_text(2);
|
||||
if (auto shortUrl = stmt.column_text(4); !shortUrl.empty()) {
|
||||
track.shortenedUrl = shortUrl;
|
||||
}
|
||||
tracks.push_back(std::move(track));
|
||||
}
|
||||
return tracks;
|
||||
}
|
||||
|
||||
Result<PlaybackStatistics> Database::getStatistics(
|
||||
@@ -867,25 +1086,130 @@ namespace Echoion::Api
|
||||
std::optional<std::chrono::system_clock::time_point>
|
||||
since)
|
||||
{
|
||||
(void)userId;
|
||||
(void)since;
|
||||
return PlaybackStatistics{};
|
||||
std::shared_lock<std::shared_mutex> lock(mutex_);
|
||||
(void)since; // "since" filtering can come with a real need for it
|
||||
PlaybackStatistics stats;
|
||||
|
||||
if (auto totalsRes = impl_->voidDb.prepare(R"(
|
||||
SELECT COUNT(*), COUNT(DISTINCT track_url), COALESCE(SUM(duration_ms), 0)
|
||||
FROM playback_history
|
||||
WHERE (?1 = 0 OR played_by = ?1);
|
||||
)")) {
|
||||
auto& stmt = *totalsRes;
|
||||
stmt.bind(1, static_cast<std::int64_t>(userId));
|
||||
if (stmt.step().value_or(false)) {
|
||||
stats.totalPlays = static_cast<uint64_t>(stmt.column_int(0));
|
||||
stats.totalTracks = static_cast<uint64_t>(stmt.column_int(1));
|
||||
stats.totalPlaytimeMs =
|
||||
static_cast<uint64_t>(stmt.column_int(2));
|
||||
}
|
||||
}
|
||||
|
||||
if (auto topRes = impl_->voidDb.prepare(R"(
|
||||
SELECT track_url, track_title, track_artist, COUNT(*) AS plays, MAX(track_short_url)
|
||||
FROM playback_history
|
||||
WHERE (?1 = 0 OR played_by = ?1)
|
||||
GROUP BY track_url
|
||||
ORDER BY plays DESC
|
||||
LIMIT 1;
|
||||
)")) {
|
||||
auto& stmt = *topRes;
|
||||
stmt.bind(1, static_cast<std::int64_t>(userId));
|
||||
if (stmt.step().value_or(false)) {
|
||||
TrackInfo track;
|
||||
track.originalUrl = stmt.column_text(0);
|
||||
track.title = stmt.column_text(1);
|
||||
track.artist = stmt.column_text(2);
|
||||
if (auto shortUrl = stmt.column_text(4); !shortUrl.empty()) {
|
||||
track.shortenedUrl = shortUrl;
|
||||
}
|
||||
stats.mostPlayedTrack = std::move(track);
|
||||
stats.mostPlayedCount =
|
||||
static_cast<uint64_t>(stmt.column_int(3));
|
||||
}
|
||||
}
|
||||
|
||||
return stats;
|
||||
}
|
||||
|
||||
Result<std::vector<std::pair<TrackInfo, uint64_t>>>
|
||||
Database::getMostPlayed(uint64_t userId, size_t limit)
|
||||
{
|
||||
(void)userId;
|
||||
(void)limit;
|
||||
return std::vector<std::pair<TrackInfo, uint64_t>>{};
|
||||
std::shared_lock<std::shared_mutex> lock(mutex_);
|
||||
std::vector<std::pair<TrackInfo, uint64_t>> result;
|
||||
|
||||
const char* sql = R"(
|
||||
SELECT track_url, track_title, track_artist, COUNT(*) AS plays, MAX(track_short_url)
|
||||
FROM playback_history
|
||||
WHERE (?1 = 0 OR played_by = ?1)
|
||||
GROUP BY track_url
|
||||
ORDER BY plays DESC
|
||||
LIMIT ?2;
|
||||
)";
|
||||
|
||||
auto stmtRes = impl_->voidDb.prepare(sql);
|
||||
if (!stmtRes) {
|
||||
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
||||
}
|
||||
auto& stmt = *stmtRes;
|
||||
stmt.bind(1, static_cast<std::int64_t>(userId))
|
||||
.bind(2, static_cast<std::int64_t>(limit));
|
||||
|
||||
while (stmt.step().value_or(false)) {
|
||||
TrackInfo track;
|
||||
track.originalUrl = stmt.column_text(0);
|
||||
track.title = stmt.column_text(1);
|
||||
track.artist = stmt.column_text(2);
|
||||
if (auto shortUrl = stmt.column_text(4); !shortUrl.empty()) {
|
||||
track.shortenedUrl = shortUrl;
|
||||
}
|
||||
result.emplace_back(std::move(track),
|
||||
static_cast<uint64_t>(stmt.column_int(3)));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
Result<std::optional<std::string>> Database::getKv(const std::string& key)
|
||||
{
|
||||
std::shared_lock<std::shared_mutex> lock(mutex_);
|
||||
auto stmtRes = impl_->voidDb.prepare(
|
||||
"SELECT value FROM kv_store WHERE key = ?;");
|
||||
if (!stmtRes) {
|
||||
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
||||
}
|
||||
auto& stmt = *stmtRes;
|
||||
stmt.bind(1, key);
|
||||
if (stmt.step().value_or(false)) {
|
||||
return std::optional<std::string>{stmt.column_text(0)};
|
||||
}
|
||||
return std::optional<std::string>{};
|
||||
}
|
||||
|
||||
Result<void> Database::setKv(const std::string& key,
|
||||
const std::string& value)
|
||||
{
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
auto stmtRes = impl_->voidDb.prepare(R"(
|
||||
INSERT OR REPLACE INTO kv_store (key, value, updated_at)
|
||||
VALUES (?, ?, CURRENT_TIMESTAMP);
|
||||
)");
|
||||
if (!stmtRes) {
|
||||
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
|
||||
}
|
||||
auto& stmt = *stmtRes;
|
||||
stmt.bind(1, key).bind(2, value);
|
||||
[[maybe_unused]] auto stepRes = stmt.step();
|
||||
return {};
|
||||
}
|
||||
|
||||
Result<void> Database::executeQuery(const std::string& sql,
|
||||
RowCallback callback)
|
||||
{
|
||||
// Deliberately unimplemented: free-form SQL over the RPC surface is
|
||||
// a footgun. Dedicated accessors (getKv/setKv, ...) cover the needs.
|
||||
(void)sql;
|
||||
(void)callback;
|
||||
return {};
|
||||
return fail(ErrorCode::NotSupported, "executeQuery is not available");
|
||||
}
|
||||
|
||||
// Database manager
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <MemoryPool.hpp>
|
||||
#include <format>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Api
|
||||
{
|
||||
|
||||
AudioBufferPool& AudioBufferPool::instance()
|
||||
{
|
||||
static AudioBufferPool instance;
|
||||
return instance;
|
||||
}
|
||||
|
||||
void AudioBufferPool::initialize(size_t bufferSize, size_t poolSize)
|
||||
{
|
||||
bufferSize_ = bufferSize;
|
||||
pool_ = std::make_unique<Void::BufferPool::BufferPool<int16_t>>();
|
||||
|
||||
// Pre-warm the size-class bucket: acquire then immediately drop
|
||||
// `poolSize` buffers so subsequent acquireBuffer() calls reuse storage.
|
||||
{
|
||||
std::vector<AudioSampleBuffer> warm;
|
||||
warm.reserve(poolSize);
|
||||
for (size_t i = 0; i < poolSize; ++i) {
|
||||
warm.push_back(pool_->acquire(bufferSize));
|
||||
}
|
||||
} // buffers returned to the pool here
|
||||
|
||||
Void::Log::info("MemoryPool", "{}", std::format(
|
||||
"AudioBufferPool initialized: {} buffers of {} samples (~{} KB)",
|
||||
poolSize, bufferSize,
|
||||
(bufferSize * poolSize * sizeof(int16_t)) / 1024));
|
||||
}
|
||||
|
||||
void AudioBufferPool::shutdown()
|
||||
{
|
||||
pool_.reset();
|
||||
Void::Log::info("MemoryPool", "{}", "AudioBufferPool shutdown");
|
||||
}
|
||||
|
||||
AudioSampleBuffer AudioBufferPool::acquireBuffer()
|
||||
{
|
||||
if (!pool_) {
|
||||
return AudioSampleBuffer{};
|
||||
}
|
||||
return pool_->acquire(bufferSize_);
|
||||
}
|
||||
|
||||
size_t AudioBufferPool::getAvailableBuffers() const
|
||||
{
|
||||
return pool_ ? pool_->stats().pooled : 0;
|
||||
}
|
||||
|
||||
size_t AudioBufferPool::getTotalBuffers() const
|
||||
{
|
||||
return pool_ ? static_cast<size_t>(pool_->stats().allocations) : 0;
|
||||
}
|
||||
|
||||
} // namespace Echoion::Api
|
||||
+940
-1676
File diff suppressed because it is too large.
Load diff
@@ -80,6 +80,25 @@ namespace Echoion::Core
|
||||
return executeWithRetry(req);
|
||||
}
|
||||
|
||||
Api::Result<Void::Net::Response>
|
||||
NetworkClient::getDirect(std::string_view url,
|
||||
const std::vector<Void::Net::Header>& headers)
|
||||
{
|
||||
Void::Net::Request req;
|
||||
req.url = std::string(url);
|
||||
req.method = Void::Net::Method::Get;
|
||||
req.headers = headers;
|
||||
|
||||
// Deliberately no proxy and no retry (see header).
|
||||
Void::Net::HttpClient client;
|
||||
auto result = client.send(req);
|
||||
if (!result) {
|
||||
return Api::fail(Api::ErrorCode::NetworkError,
|
||||
result.error().message());
|
||||
}
|
||||
return std::move(*result);
|
||||
}
|
||||
|
||||
Api::Result<Void::Net::Response>
|
||||
NetworkClient::get(std::string_view url,
|
||||
const std::vector<Void::Net::Header>& headers)
|
||||
|
||||
+43
-14
@@ -76,18 +76,12 @@ namespace Echoion::Core
|
||||
// ~ThreadPool then joins every worker.
|
||||
clientPool_.reset();
|
||||
|
||||
// Wait for server thread with timeout
|
||||
// The acceptor was cancelled and ioContext_ stopped above, so the
|
||||
// accept loop exits promptly. Join unconditionally: detaching
|
||||
// here let the thread outlive ioContext_ (use-after-free when the
|
||||
// core library unloads).
|
||||
if (serverThread_.joinable()) {
|
||||
// Give it a moment to clean up
|
||||
auto start = std::chrono::steady_clock::now();
|
||||
while (serverThread_.joinable() &&
|
||||
std::chrono::steady_clock::now() - start <
|
||||
std::chrono::seconds(2)) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(50));
|
||||
}
|
||||
if (serverThread_.joinable()) {
|
||||
serverThread_.detach(); // Force detach if still running
|
||||
}
|
||||
serverThread_.join();
|
||||
}
|
||||
|
||||
if (acceptor_.has_value()) {
|
||||
@@ -120,10 +114,15 @@ namespace Echoion::Core
|
||||
acceptComplete = true;
|
||||
});
|
||||
|
||||
// Poll until accept completes or we're stopped
|
||||
// Block until the accept completes or we're stopped. stop()
|
||||
// clears running_, cancels the acceptor and calls
|
||||
// ioContext_.stop(), so run_one() returns promptly instead of
|
||||
// the previous 10ms busy-poll.
|
||||
while (!acceptComplete.load() && running_.load()) {
|
||||
ioContext_.poll_one();
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
||||
if (ioContext_.stopped()) {
|
||||
break;
|
||||
}
|
||||
ioContext_.run_one();
|
||||
}
|
||||
|
||||
// Cancel pending operation if we're stopping
|
||||
@@ -276,6 +275,18 @@ namespace Echoion::Core
|
||||
}
|
||||
}
|
||||
|
||||
// Record the (authorized) invocation in the bounded audit ring.
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(auditMutex_);
|
||||
auditLog_.push_back(AuditEntry{
|
||||
.clientId = clientId,
|
||||
.method = static_cast<int>(request.method),
|
||||
.timestamp = std::chrono::system_clock::now()});
|
||||
if (auditLog_.size() > MAX_AUDIT_ENTRIES) {
|
||||
auditLog_.pop_front();
|
||||
}
|
||||
}
|
||||
|
||||
// Find handler
|
||||
std::string methodName =
|
||||
std::to_string(static_cast<int>(request.method));
|
||||
@@ -402,6 +413,24 @@ namespace Echoion::Core
|
||||
handlers_.erase(method);
|
||||
}
|
||||
|
||||
std::vector<RpcServer::AuditEntry> RpcServer::getAuditLog() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(auditMutex_);
|
||||
return {auditLog_.begin(), auditLog_.end()};
|
||||
}
|
||||
|
||||
size_t RpcServer::getClientCount() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(clientsMutex_);
|
||||
return clients_.size();
|
||||
}
|
||||
|
||||
std::chrono::seconds RpcServer::getUptime() const
|
||||
{
|
||||
return std::chrono::duration_cast<std::chrono::seconds>(
|
||||
std::chrono::steady_clock::now() - startTime_);
|
||||
}
|
||||
|
||||
void RpcServer::setAuthToken(const std::string& token)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(authMutex_);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include "echoion/core/SignatureCipher.hpp"
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <quickjs.h>
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <filesystem>
|
||||
|
||||
@@ -0,0 +1,281 @@
|
||||
#include "echoion/core/SubscriptionService.hpp"
|
||||
|
||||
#include <Events.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
Api::Result<void>
|
||||
SubscriptionService::initialize(std::shared_ptr<Api::Database> database)
|
||||
{
|
||||
manager_ = std::make_unique<SubscriptionManager>();
|
||||
return manager_->initialize(std::move(database));
|
||||
}
|
||||
|
||||
Api::Result<std::string> SubscriptionService::subscribe(uint64_t clientId)
|
||||
{
|
||||
if (!manager_) {
|
||||
return Api::fail(Api::ErrorCode::ServiceUnavailable,
|
||||
"Subscription manager not initialized");
|
||||
}
|
||||
if (!clientInfo_) {
|
||||
return Api::fail(Api::ErrorCode::NotInitialized,
|
||||
"Client info callback not set");
|
||||
}
|
||||
|
||||
auto clientInfo = clientInfo_(clientId);
|
||||
if (!clientInfo) {
|
||||
return Api::fail(Api::ErrorCode::NotFound,
|
||||
"Could not get client info");
|
||||
}
|
||||
|
||||
const auto& [uid, nickname] = *clientInfo;
|
||||
const bool added = manager_->subscribe(uid, nickname);
|
||||
|
||||
Void::Log::info("SubscriptionService", "{}",
|
||||
std::format("Subscribe: client {} ({}), added={}",
|
||||
clientId, nickname, added));
|
||||
|
||||
// A subscriber appeared: if this policy paused playback earlier,
|
||||
// bring it back.
|
||||
if (added && pausedForNoSubscribers_.load() &&
|
||||
resumeOnReturn_.load() && requestResume_) {
|
||||
if (requestResume_()) {
|
||||
pausedForNoSubscribers_ = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Always refresh the whisper list on subscribe so offline->online
|
||||
// transitions take effect.
|
||||
if (onChange_) {
|
||||
onChange_();
|
||||
}
|
||||
|
||||
emit(Api::Events::UserSubscribed{
|
||||
.uid = uid, .nickname = nickname, .clientId = clientId});
|
||||
|
||||
if (added) {
|
||||
return "You are now subscribed to the bot's audio output!";
|
||||
}
|
||||
return "You are still subscribed (was already in database).";
|
||||
}
|
||||
|
||||
Api::Result<std::string> SubscriptionService::unsubscribe(uint64_t clientId)
|
||||
{
|
||||
if (!manager_) {
|
||||
return Api::fail(Api::ErrorCode::ServiceUnavailable,
|
||||
"Subscription manager not initialized");
|
||||
}
|
||||
if (!clientInfo_) {
|
||||
return Api::fail(Api::ErrorCode::NotInitialized,
|
||||
"Client info callback not set");
|
||||
}
|
||||
|
||||
auto clientInfo = clientInfo_(clientId);
|
||||
if (!clientInfo) {
|
||||
return Api::fail(Api::ErrorCode::NotFound,
|
||||
"Could not get client info");
|
||||
}
|
||||
|
||||
const auto& [uid, nickname] = *clientInfo;
|
||||
const bool removed = manager_->unsubscribe(uid);
|
||||
|
||||
if (removed) {
|
||||
pauseIfAudienceGone();
|
||||
if (onChange_) {
|
||||
onChange_();
|
||||
}
|
||||
emit(Api::Events::UserUnsubscribed{
|
||||
.uid = uid, .nickname = nickname, .clientId = clientId});
|
||||
return "You are now unsubscribed from the bot's audio output.";
|
||||
}
|
||||
return "You were not subscribed.";
|
||||
}
|
||||
|
||||
Api::Result<std::string>
|
||||
SubscriptionService::unsubscribeByUid(const std::string& uid)
|
||||
{
|
||||
if (!manager_) {
|
||||
return Api::fail(Api::ErrorCode::ServiceUnavailable,
|
||||
"Subscription manager not initialized");
|
||||
}
|
||||
|
||||
const bool removed = manager_->unsubscribe(uid);
|
||||
if (removed) {
|
||||
pauseIfAudienceGone();
|
||||
if (onChange_) {
|
||||
onChange_();
|
||||
}
|
||||
return "Subscriber removed successfully.";
|
||||
}
|
||||
return "Subscriber not found.";
|
||||
}
|
||||
|
||||
Api::Result<std::string> SubscriptionService::clearAllSubscriptions()
|
||||
{
|
||||
if (!manager_) {
|
||||
return Api::fail(Api::ErrorCode::ServiceUnavailable,
|
||||
"Subscription manager not initialized");
|
||||
}
|
||||
|
||||
const bool cleared = manager_->clearAll();
|
||||
if (cleared) {
|
||||
// Audience is definitionally gone now.
|
||||
if (pauseOnEmpty_.load() && requestPause_ && requestPause_()) {
|
||||
pausedForNoSubscribers_ = true;
|
||||
}
|
||||
if (onChange_) {
|
||||
onChange_();
|
||||
}
|
||||
return "All subscriptions cleared.";
|
||||
}
|
||||
return "Failed to clear subscriptions.";
|
||||
}
|
||||
|
||||
bool SubscriptionService::isSubscribed(uint64_t clientId) const
|
||||
{
|
||||
if (!manager_ || !clientInfo_) {
|
||||
return false;
|
||||
}
|
||||
auto clientInfo = clientInfo_(clientId);
|
||||
if (!clientInfo) {
|
||||
return false;
|
||||
}
|
||||
return manager_->isSubscribed(clientInfo->first);
|
||||
}
|
||||
|
||||
bool SubscriptionService::hasSubscribers() const
|
||||
{
|
||||
return manager_ && manager_->hasSubscribers();
|
||||
}
|
||||
|
||||
bool SubscriptionService::hasOnlineSubscribers() const
|
||||
{
|
||||
if (!manager_ || !uidToClientId_) {
|
||||
return false;
|
||||
}
|
||||
for (const auto& uid : manager_->getSubscribedUids()) {
|
||||
if (uidToClientId_(uid).has_value()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
std::set<uint64_t> SubscriptionService::getSubscribedClients() const
|
||||
{
|
||||
std::set<uint64_t> clientIds;
|
||||
if (!manager_ || !uidToClientId_) {
|
||||
return clientIds;
|
||||
}
|
||||
for (const auto& uid : manager_->getSubscribedUids()) {
|
||||
if (auto clientId = uidToClientId_(uid)) {
|
||||
clientIds.insert(*clientId);
|
||||
}
|
||||
}
|
||||
return clientIds;
|
||||
}
|
||||
|
||||
std::set<std::string> SubscriptionService::getOnlineSubscriberUids() const
|
||||
{
|
||||
std::set<std::string> onlineUids;
|
||||
if (!manager_ || !uidToClientId_) {
|
||||
return onlineUids;
|
||||
}
|
||||
for (const auto& uid : manager_->getSubscribedUids()) {
|
||||
if (uidToClientId_(uid).has_value()) {
|
||||
onlineUids.insert(uid);
|
||||
}
|
||||
}
|
||||
return onlineUids;
|
||||
}
|
||||
|
||||
std::vector<SubscriptionManager::Subscriber>
|
||||
SubscriptionService::getSubscribers() const
|
||||
{
|
||||
if (!manager_) {
|
||||
return {};
|
||||
}
|
||||
return manager_->getSubscribers();
|
||||
}
|
||||
|
||||
bool SubscriptionService::onClientConnected(uint64_t clientId)
|
||||
{
|
||||
if (!manager_ || !clientInfo_) {
|
||||
return false;
|
||||
}
|
||||
|
||||
auto clientInfo = clientInfo_(clientId);
|
||||
if (!clientInfo) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto& [uid, nickname] = *clientInfo;
|
||||
if (!manager_->isSubscribed(uid)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Void::Log::info(
|
||||
"SubscriptionService", "{}",
|
||||
std::format("Subscribed user {} ({}) connected, moving to online",
|
||||
nickname, uid));
|
||||
|
||||
manager_->updateNickname(uid, nickname);
|
||||
|
||||
if (onChange_) {
|
||||
onChange_();
|
||||
}
|
||||
|
||||
if (pausedForNoSubscribers_.load() && resumeOnReturn_.load() &&
|
||||
requestResume_) {
|
||||
if (requestResume_()) {
|
||||
pausedForNoSubscribers_ = false;
|
||||
}
|
||||
return false; // resumed; no auto-start needed
|
||||
}
|
||||
|
||||
return true; // subscribed user online; caller may auto-start playback
|
||||
}
|
||||
|
||||
void SubscriptionService::onClientDisconnected(uint64_t clientId)
|
||||
{
|
||||
if (!manager_ || !clientInfo_) {
|
||||
return;
|
||||
}
|
||||
|
||||
auto clientInfo = clientInfo_(clientId);
|
||||
if (!clientInfo) {
|
||||
return;
|
||||
}
|
||||
|
||||
const auto& [uid, nickname] = *clientInfo;
|
||||
if (!manager_->isSubscribed(uid)) {
|
||||
return;
|
||||
}
|
||||
|
||||
Void::Log::info(
|
||||
"SubscriptionService", "{}",
|
||||
std::format("Subscribed user {} ({}) disconnected, moving offline",
|
||||
nickname, uid));
|
||||
|
||||
if (onChange_) {
|
||||
onChange_();
|
||||
}
|
||||
pauseIfAudienceGone();
|
||||
}
|
||||
|
||||
void SubscriptionService::pauseIfAudienceGone()
|
||||
{
|
||||
if (!pauseOnEmpty_.load() || hasOnlineSubscribers()) {
|
||||
return;
|
||||
}
|
||||
if (requestPause_ && requestPause_()) {
|
||||
Void::Log::info("SubscriptionService", "{}",
|
||||
"No online subscribers left, paused playback");
|
||||
pausedForNoSubscribers_ = true;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,235 @@
|
||||
#include "echoion/core/TrackCache.hpp"
|
||||
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <charconv>
|
||||
#include <format>
|
||||
#include <system_error>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
namespace
|
||||
{
|
||||
std::filesystem::path defaultCacheDir()
|
||||
{
|
||||
if (const char* cacheHome = std::getenv("XDG_CACHE_HOME")) {
|
||||
return std::filesystem::path(cacheHome) / "echoion" /
|
||||
"tracks";
|
||||
}
|
||||
if (const char* home = std::getenv("HOME")) {
|
||||
return std::filesystem::path(home) / ".cache" / "echoion" /
|
||||
"tracks";
|
||||
}
|
||||
return std::filesystem::temp_directory_path() / "echoion_tracks";
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TrackCache::TrackCache(Config config, std::filesystem::path dirOverride) :
|
||||
config_(config),
|
||||
dir_(dirOverride.empty() ? defaultCacheDir() : std::move(dirOverride))
|
||||
{
|
||||
if (config_.enabled) {
|
||||
std::error_code ec;
|
||||
std::filesystem::create_directories(dir_, ec);
|
||||
if (ec) {
|
||||
Void::Log::warn(
|
||||
"TrackCache", "{}",
|
||||
std::format("Cannot create cache dir {}: {}",
|
||||
dir_.string(), ec.message()));
|
||||
config_.enabled = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
uint64_t TrackCache::parseSize(const std::string& text)
|
||||
{
|
||||
uint64_t value = 0;
|
||||
auto [suffixPtr, ec] =
|
||||
std::from_chars(text.data(), text.data() + text.size(), value);
|
||||
if (ec != std::errc{}) {
|
||||
return 0;
|
||||
}
|
||||
std::string suffix(suffixPtr, text.data() + text.size());
|
||||
std::transform(suffix.begin(), suffix.end(), suffix.begin(),
|
||||
[](unsigned char c) {
|
||||
return static_cast<char>(std::toupper(c));
|
||||
});
|
||||
if (suffix == "KB" || suffix == "K") {
|
||||
return value << 10;
|
||||
}
|
||||
if (suffix == "MB" || suffix == "M") {
|
||||
return value << 20;
|
||||
}
|
||||
if (suffix == "GB" || suffix == "G") {
|
||||
return value << 30;
|
||||
}
|
||||
if (suffix.empty() || suffix == "B") {
|
||||
return value;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
std::string TrackCache::sanitize(const std::string& trackId)
|
||||
{
|
||||
std::string out;
|
||||
out.reserve(trackId.size());
|
||||
for (char c : trackId) {
|
||||
const bool safe = (c >= 'A' && c <= 'Z') ||
|
||||
(c >= 'a' && c <= 'z') ||
|
||||
(c >= '0' && c <= '9') || c == '-' || c == '_';
|
||||
out.push_back(safe ? c : '_');
|
||||
}
|
||||
if (out.empty()) {
|
||||
out = "track";
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::filesystem::path
|
||||
TrackCache::pathFor(const std::string& trackId,
|
||||
const std::string& extension) const
|
||||
{
|
||||
return dir_ / (sanitize(trackId) + extension);
|
||||
}
|
||||
|
||||
std::optional<std::string> TrackCache::lookup(const std::string& trackId)
|
||||
{
|
||||
if (!config_.enabled) {
|
||||
return std::nullopt;
|
||||
}
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
const std::string stem = sanitize(trackId);
|
||||
std::error_code ec;
|
||||
for (const auto& entry :
|
||||
std::filesystem::directory_iterator(dir_, ec)) {
|
||||
if (!entry.is_regular_file(ec) ||
|
||||
entry.path().stem().string() != stem) {
|
||||
continue;
|
||||
}
|
||||
// TTL check
|
||||
const auto age = std::filesystem::file_time_type::clock::now() -
|
||||
entry.last_write_time(ec);
|
||||
if (age > config_.ttl) {
|
||||
std::filesystem::remove(entry.path(), ec);
|
||||
return std::nullopt;
|
||||
}
|
||||
// Bump LRU (mtime doubles as the recency marker).
|
||||
std::filesystem::last_write_time(
|
||||
entry.path(),
|
||||
std::filesystem::file_time_type::clock::now(), ec);
|
||||
return entry.path().string();
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
std::string TrackCache::store(const std::string& trackId,
|
||||
const std::string& filePath)
|
||||
{
|
||||
if (!config_.enabled) {
|
||||
return filePath;
|
||||
}
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
std::filesystem::path source(filePath);
|
||||
std::error_code ec;
|
||||
if (!std::filesystem::exists(source, ec)) {
|
||||
return filePath;
|
||||
}
|
||||
|
||||
const auto target =
|
||||
pathFor(trackId, source.extension().string());
|
||||
std::filesystem::rename(source, target, ec);
|
||||
if (ec) {
|
||||
// Cross-device move: fall back to copy+remove.
|
||||
ec.clear();
|
||||
std::filesystem::copy_file(
|
||||
source, target,
|
||||
std::filesystem::copy_options::overwrite_existing, ec);
|
||||
if (ec) {
|
||||
Void::Log::warn(
|
||||
"TrackCache", "{}",
|
||||
std::format("Failed to cache {}: {}", filePath,
|
||||
ec.message()));
|
||||
return filePath;
|
||||
}
|
||||
std::filesystem::remove(source, ec);
|
||||
}
|
||||
|
||||
Void::Log::info("TrackCache", "{}",
|
||||
std::format("Cached track {} ({})", trackId,
|
||||
target.filename().string()));
|
||||
sweepLocked();
|
||||
return target.string();
|
||||
}
|
||||
|
||||
bool TrackCache::owns(const std::string& filePath) const
|
||||
{
|
||||
return filePath.starts_with(dir_.string());
|
||||
}
|
||||
|
||||
void TrackCache::sweep()
|
||||
{
|
||||
if (!config_.enabled) {
|
||||
return;
|
||||
}
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
sweepLocked();
|
||||
}
|
||||
|
||||
void TrackCache::sweepLocked()
|
||||
{
|
||||
struct Entry {
|
||||
std::filesystem::path path;
|
||||
std::filesystem::file_time_type mtime;
|
||||
uint64_t size = 0;
|
||||
};
|
||||
std::vector<Entry> entries;
|
||||
uint64_t totalBytes = 0;
|
||||
|
||||
std::error_code ec;
|
||||
const auto now = std::filesystem::file_time_type::clock::now();
|
||||
for (const auto& entry :
|
||||
std::filesystem::directory_iterator(dir_, ec)) {
|
||||
if (!entry.is_regular_file(ec)) {
|
||||
continue;
|
||||
}
|
||||
const auto mtime = entry.last_write_time(ec);
|
||||
if (now - mtime > config_.ttl) {
|
||||
std::filesystem::remove(entry.path(), ec);
|
||||
continue;
|
||||
}
|
||||
const auto size =
|
||||
static_cast<uint64_t>(entry.file_size(ec));
|
||||
totalBytes += size;
|
||||
entries.push_back(
|
||||
Entry{.path = entry.path(), .mtime = mtime, .size = size});
|
||||
}
|
||||
|
||||
if (totalBytes <= config_.maxBytes) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Evict least-recently-used first.
|
||||
std::sort(entries.begin(), entries.end(),
|
||||
[](const Entry& a, const Entry& b) {
|
||||
return a.mtime < b.mtime;
|
||||
});
|
||||
for (const auto& entry : entries) {
|
||||
if (totalBytes <= config_.maxBytes) {
|
||||
break;
|
||||
}
|
||||
std::filesystem::remove(entry.path, ec);
|
||||
if (!ec) {
|
||||
totalBytes -= entry.size;
|
||||
Void::Log::debug(
|
||||
"TrackCache", "{}",
|
||||
std::format("Evicted {}",
|
||||
entry.path.filename().string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace Echoion::Core
|
||||
+436
-274
File diff suppressed because it is too large.
Load diff
+59
-35
@@ -23,7 +23,15 @@ namespace Echoion::Core
|
||||
{
|
||||
}
|
||||
|
||||
YtDlpManager::~YtDlpManager() { stopThreadPool(); }
|
||||
YtDlpManager::~YtDlpManager()
|
||||
{
|
||||
// The init thread may still be downloading/verifying and would
|
||||
// otherwise touch pool_/members mid-destruction.
|
||||
if (initThread_.joinable()) {
|
||||
initThread_.join();
|
||||
}
|
||||
stopThreadPool();
|
||||
}
|
||||
|
||||
std::filesystem::path YtDlpManager::getStorageDir() const
|
||||
{
|
||||
@@ -88,11 +96,16 @@ namespace Echoion::Core
|
||||
|
||||
bool YtDlpManager::isAvailable() const
|
||||
{
|
||||
return std::filesystem::exists(getExecutablePath());
|
||||
// False until the background init verified the binary — the source
|
||||
// router skips the yt-dlp sources until then.
|
||||
return initialized_.load();
|
||||
}
|
||||
|
||||
Api::Result<void> YtDlpManager::initialize()
|
||||
{
|
||||
if (initThread_.joinable()) {
|
||||
return {}; // init already running (or finished) in background
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
@@ -124,48 +137,59 @@ namespace Echoion::Core
|
||||
Void::Log::debug("YtDlpManager", "{}", std::format("yt-dlp executable path: {}",
|
||||
executablePath_.string()));
|
||||
|
||||
// Check if yt-dlp exists
|
||||
bool exists = std::filesystem::exists(executablePath_);
|
||||
Void::Log::debug("YtDlpManager", "{}", std::format("yt-dlp exists: {}", exists));
|
||||
} // Release lock; everything below runs off the caller's thread.
|
||||
|
||||
// Download/update and the subprocess version check can take seconds
|
||||
// (10s timeout each) — that used to run inline and stalled every
|
||||
// core start and hot reload. Run it in the background instead;
|
||||
// isAvailable() stays false (and the router skips the yt-dlp
|
||||
// sources) until the binary is verified. The lock discipline is
|
||||
// preserved: downloadYtDlp()/getVersion() run without mutex_ held
|
||||
// (getVersion -> execute -> getCookieArgs takes it).
|
||||
initThread_ = std::jthread([this]() {
|
||||
const bool exists = std::filesystem::exists(executablePath_);
|
||||
if (!exists) {
|
||||
Void::Log::info("YtDlpManager", "{}", "yt-dlp not found, downloading...");
|
||||
Void::Log::info("YtDlpManager", "{}",
|
||||
"yt-dlp not found, downloading...");
|
||||
auto result = downloadYtDlp();
|
||||
if (!result) {
|
||||
return result;
|
||||
Void::Log::error(
|
||||
"YtDlpManager", "{}",
|
||||
std::format("yt-dlp download failed: {}",
|
||||
result.error().message));
|
||||
return;
|
||||
}
|
||||
} else if (autoUpdateEnabled_.load() && shouldUpdate()) {
|
||||
Void::Log::info("YtDlpManager", "{}",
|
||||
"yt-dlp may be outdated, updating...");
|
||||
auto result = update();
|
||||
if (!result) {
|
||||
Void::Log::warn("YtDlpManager", "{}",
|
||||
std::format("yt-dlp update failed: {}",
|
||||
result.error().toString()));
|
||||
}
|
||||
} else if (shouldUpdate()) {
|
||||
Void::Log::info("YtDlpManager", "{}",
|
||||
"yt-dlp may be outdated, updating in background...");
|
||||
// Start async update to avoid blocking initialization
|
||||
std::thread([this]() {
|
||||
auto result = update();
|
||||
if (!result) {
|
||||
Void::Log::warn("YtDlpManager", "{}",
|
||||
std::format("yt-dlp update failed: {}",
|
||||
result.error().toString()));
|
||||
}
|
||||
}).detach();
|
||||
}
|
||||
} // Release lock before calling getVersion() to avoid deadlock with
|
||||
// getCookieArgs()
|
||||
|
||||
// Verify it works (outside lock to prevent deadlock with
|
||||
// execute()->getCookieArgs())
|
||||
Void::Log::info("YtDlpManager", "{}", "Checking yt-dlp version...");
|
||||
std::string version = getVersion();
|
||||
if (version.empty()) {
|
||||
return Api::fail(Api::ErrorCode::ServiceUnavailable,
|
||||
"yt-dlp executable not working");
|
||||
}
|
||||
Void::Log::info("YtDlpManager", "{}",
|
||||
"Checking yt-dlp version...");
|
||||
const std::string version = getVersion();
|
||||
if (version.empty()) {
|
||||
Void::Log::error("YtDlpManager", "{}",
|
||||
"yt-dlp executable not working");
|
||||
return;
|
||||
}
|
||||
|
||||
Void::Log::info("YtDlpManager", "{}", std::format("yt-dlp ready: {}", version));
|
||||
{
|
||||
// startThreadPool touches threadPoolSize_/pool_, which
|
||||
// setThreadPoolSize mutates under the same lock.
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
startThreadPool();
|
||||
initialized_ = true;
|
||||
}
|
||||
Void::Log::info("YtDlpManager", "{}",
|
||||
std::format("yt-dlp ready: {}", version));
|
||||
});
|
||||
|
||||
// Start thread pool for async operations
|
||||
startThreadPool();
|
||||
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
initialized_ = true;
|
||||
return {};
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
#include <NetworkInterface.hpp>
|
||||
#include <format>
|
||||
#include <future>
|
||||
#include <mutex>
|
||||
#include <regex>
|
||||
|
||||
namespace Echoion::Core
|
||||
@@ -11,16 +12,23 @@ namespace Echoion::Core
|
||||
|
||||
std::string getPublicIpAddress()
|
||||
{
|
||||
// Try to get public IP from external services
|
||||
// Try to get public IP from external services. The cache is shared
|
||||
// across threads (this command can run concurrently), so guard it with a
|
||||
// mutex. The mutex is only held around cache reads/writes, never across
|
||||
// the blocking network calls below.
|
||||
static std::mutex cacheMutex;
|
||||
static std::string cachedIp;
|
||||
static std::chrono::steady_clock::time_point lastFetch;
|
||||
|
||||
// Cache IP for 5 minutes to avoid excessive API calls
|
||||
auto now = std::chrono::steady_clock::now();
|
||||
if (!cachedIp.empty() &&
|
||||
std::chrono::duration_cast<std::chrono::minutes>(now - lastFetch)
|
||||
.count() < 5) {
|
||||
return cachedIp;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(cacheMutex);
|
||||
if (!cachedIp.empty() &&
|
||||
std::chrono::duration_cast<std::chrono::minutes>(now - lastFetch)
|
||||
.count() < 5) {
|
||||
return cachedIp;
|
||||
}
|
||||
}
|
||||
|
||||
// List of services to try
|
||||
@@ -55,6 +63,7 @@ namespace Echoion::Core
|
||||
std::regex ipRegex(
|
||||
R"(^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$)");
|
||||
if (std::regex_match(ip, ipRegex)) {
|
||||
std::lock_guard<std::mutex> lock(cacheMutex);
|
||||
cachedIp = ip;
|
||||
lastFetch = now;
|
||||
return cachedIp;
|
||||
@@ -67,6 +76,7 @@ namespace Echoion::Core
|
||||
}
|
||||
|
||||
// Return cached IP or localhost if all services failed
|
||||
std::lock_guard<std::mutex> lock(cacheMutex);
|
||||
return cachedIp.empty() ? "127.0.0.1" : cachedIp;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,939 @@
|
||||
#include "echoion/core/playback/PlaybackEngine.hpp"
|
||||
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
namespace
|
||||
{
|
||||
constexpr size_t MAX_BUFFER_SHORTS =
|
||||
PlaybackEngine::SHORTS_PER_CHUNK * 50;
|
||||
} // namespace
|
||||
|
||||
PlaybackEngine::PlaybackEngine(IPlaybackHost& host) : host_(host) {}
|
||||
|
||||
PlaybackEngine::~PlaybackEngine() { shutdown(); }
|
||||
|
||||
Api::Result<void> PlaybackEngine::initialize(
|
||||
const std::optional<Void::Net::ProxyConfig>& proxy)
|
||||
{
|
||||
if (initialized_.exchange(true)) {
|
||||
return {};
|
||||
}
|
||||
|
||||
proxy_ = proxy;
|
||||
|
||||
for (DecoderSlot* slot : {¤t_, &next_}) {
|
||||
slot->decoder = std::make_unique<AudioDecoder>();
|
||||
auto result = slot->decoder->initialize();
|
||||
if (!result) {
|
||||
initialized_ = false;
|
||||
return result;
|
||||
}
|
||||
slot->decoder->setOutputFormat(SAMPLE_RATE, CHANNELS);
|
||||
slot->decoder->setProxyConfig(proxy_);
|
||||
}
|
||||
|
||||
ring_.reserve(MAX_BUFFER_SHORTS + SHORTS_PER_CHUNK);
|
||||
outChunk_.assign(SHORTS_PER_CHUNK, 0);
|
||||
|
||||
thread_ = std::jthread([this](std::stop_token st) { run(st); });
|
||||
Void::Log::info("PlaybackEngine", "{}", "Playback engine started");
|
||||
return {};
|
||||
}
|
||||
|
||||
void PlaybackEngine::shutdown()
|
||||
{
|
||||
if (!initialized_.exchange(false)) {
|
||||
return;
|
||||
}
|
||||
thread_.request_stop();
|
||||
mailboxCv_.notify_all();
|
||||
if (thread_.joinable()) {
|
||||
thread_.join();
|
||||
}
|
||||
current_.closeAndReset();
|
||||
next_.closeAndReset();
|
||||
if (current_.decoder) {
|
||||
current_.decoder->shutdown();
|
||||
}
|
||||
if (next_.decoder) {
|
||||
next_.decoder->shutdown();
|
||||
}
|
||||
Void::Log::info("PlaybackEngine", "{}", "Playback engine stopped");
|
||||
}
|
||||
|
||||
void PlaybackEngine::setProxyConfig(
|
||||
const std::optional<Void::Net::ProxyConfig>& proxy)
|
||||
{
|
||||
proxy_ = proxy;
|
||||
// Applies to the NEXT openSource; in-flight decodes keep their
|
||||
// connection.
|
||||
if (current_.decoder) {
|
||||
current_.decoder->setProxyConfig(proxy);
|
||||
}
|
||||
if (next_.decoder) {
|
||||
next_.decoder->setProxyConfig(proxy);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- control -------------------------------------------------------
|
||||
|
||||
void PlaybackEngine::post(Command cmd)
|
||||
{
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mailboxMutex_);
|
||||
mailbox_.push_back(std::move(cmd));
|
||||
}
|
||||
mailboxCv_.notify_one();
|
||||
}
|
||||
|
||||
void PlaybackEngine::playNow(Api::QueueEntry entry, std::string streamUrl,
|
||||
bool isLocalFile)
|
||||
{
|
||||
post(CmdPlayNow{.entry = std::move(entry),
|
||||
.url = std::move(streamUrl),
|
||||
.isLocalFile = isLocalFile});
|
||||
}
|
||||
|
||||
void PlaybackEngine::start() { post(CmdStart{}); }
|
||||
void PlaybackEngine::pause() { post(CmdPause{}); }
|
||||
void PlaybackEngine::resume() { post(CmdResume{}); }
|
||||
void PlaybackEngine::stopPlayback() { post(CmdStop{}); }
|
||||
void PlaybackEngine::skip(uint32_t count) { post(CmdSkip{count}); }
|
||||
|
||||
void PlaybackEngine::seekTo(std::chrono::milliseconds position)
|
||||
{
|
||||
post(CmdSeek{position});
|
||||
}
|
||||
|
||||
void PlaybackEngine::restore(Api::QueueEntry entry, std::string streamUrl,
|
||||
std::chrono::milliseconds position,
|
||||
bool paused)
|
||||
{
|
||||
post(CmdRestore{.entry = std::move(entry),
|
||||
.url = std::move(streamUrl),
|
||||
.position = position,
|
||||
.paused = paused});
|
||||
}
|
||||
|
||||
std::optional<Api::QueueEntry> PlaybackEngine::currentEntry() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(currentEntryMutex_);
|
||||
return publishedEntry_;
|
||||
}
|
||||
|
||||
std::chrono::milliseconds PlaybackEngine::currentDuration() const
|
||||
{
|
||||
return std::chrono::milliseconds(currentDurationMs_.load());
|
||||
}
|
||||
|
||||
// ---- engine thread ---------------------------------------------------
|
||||
|
||||
void PlaybackEngine::run(std::stop_token st)
|
||||
{
|
||||
Void::Log::debug("PlaybackEngine", "{}", "Engine thread running");
|
||||
|
||||
while (!st.stop_requested()) {
|
||||
// Idle: nothing playing and nothing warming — sleep on mailbox.
|
||||
if (current_.state == DecoderSlot::State::Idle) {
|
||||
std::unique_lock<std::mutex> lock(mailboxMutex_);
|
||||
mailboxCv_.wait(lock, [&] {
|
||||
return !mailbox_.empty() || st.stop_requested();
|
||||
});
|
||||
lock.unlock();
|
||||
if (st.stop_requested()) {
|
||||
break;
|
||||
}
|
||||
drainMailbox();
|
||||
if (current_.state == DecoderSlot::State::Idle) {
|
||||
continue;
|
||||
}
|
||||
// A track just started: reset cadence.
|
||||
nextTick_ = std::chrono::steady_clock::now();
|
||||
}
|
||||
|
||||
drainMailbox();
|
||||
if (st.stop_requested() ||
|
||||
current_.state == DecoderSlot::State::Idle) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (paused_.load()) {
|
||||
// Keep commands responsive; emit nothing while paused.
|
||||
std::unique_lock<std::mutex> lock(mailboxMutex_);
|
||||
mailboxCv_.wait_for(lock, std::chrono::milliseconds(50), [&] {
|
||||
return !mailbox_.empty() || st.stop_requested();
|
||||
});
|
||||
nextTick_ = std::chrono::steady_clock::now();
|
||||
continue;
|
||||
}
|
||||
|
||||
// Current slot may still be resolving (late resolve / playNow
|
||||
// failed fallback): emit silence on cadence within grace.
|
||||
if (current_.state == DecoderSlot::State::Resolving) {
|
||||
pollNextResolve(); // also polls current_ (see below)
|
||||
}
|
||||
|
||||
// 1) Fill the ring buffer from the active decoder.
|
||||
if (current_.state == DecoderSlot::State::Active ||
|
||||
current_.state == DecoderSlot::State::Warming) {
|
||||
if (current_.state == DecoderSlot::State::Warming) {
|
||||
activateSlot(current_);
|
||||
}
|
||||
while (ring_.size() < MAX_BUFFER_SHORTS &&
|
||||
current_.decoder->getNextChunk(incomingChunk_)) {
|
||||
ring_.append(std::span<const short>(
|
||||
incomingChunk_.data(), incomingChunk_.size()));
|
||||
}
|
||||
}
|
||||
|
||||
// 2) Prefetch the next track near the end of the current one.
|
||||
maybeStartPrefetch();
|
||||
pollNextResolve();
|
||||
|
||||
// 2b) Crossfade: swap to the warm slot early and mix the
|
||||
// outgoing tail into the incoming audio.
|
||||
{
|
||||
const auto fade = crossfadeMs_.load();
|
||||
if (fade > 0 && fadeTail_.empty() &&
|
||||
current_.state == DecoderSlot::State::Active &&
|
||||
next_.state == DecoderSlot::State::Warming &&
|
||||
!host_.repeatEnabled()) {
|
||||
const auto duration = std::chrono::milliseconds(
|
||||
currentDurationMs_.load());
|
||||
const auto position = clock_.position();
|
||||
if (duration.count() > 0 &&
|
||||
duration - position <=
|
||||
std::chrono::milliseconds(fade)) {
|
||||
beginCrossfade();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3) Position bookkeeping / events.
|
||||
positionTick();
|
||||
|
||||
// 4) Emit one chunk per 20ms tick.
|
||||
const bool fading =
|
||||
!fadeTail_.empty() && fadePos_ < fadeTail_.size();
|
||||
if (ring_.size() >= SHORTS_PER_CHUNK || fading) {
|
||||
// Full chunk available, OR a crossfade is in progress (the
|
||||
// outgoing tail covers a not-yet-full incoming ring so the
|
||||
// handoff has no silent gap).
|
||||
silenceSince_ = {};
|
||||
emitChunk(true);
|
||||
} else if (current_.state == DecoderSlot::State::Active &&
|
||||
current_.decoder->isFinished()) {
|
||||
// Flush the tail (shorter than one chunk), zero-padded.
|
||||
if (!ring_.empty()) {
|
||||
emitChunk(true);
|
||||
} else {
|
||||
handleTrackEnd();
|
||||
continue; // cadence continues; no extra sleep
|
||||
}
|
||||
} else if (current_.state == DecoderSlot::State::Resolving) {
|
||||
// Waiting for a late resolve: keep the stream alive with
|
||||
// silence, bounded by the configured resolve grace.
|
||||
if (silenceSince_.time_since_epoch().count() == 0) {
|
||||
silenceSince_ = std::chrono::steady_clock::now();
|
||||
}
|
||||
if (std::chrono::steady_clock::now() - silenceSince_ >
|
||||
std::chrono::milliseconds(resolveGraceMs_.load())) {
|
||||
Void::Log::warn(
|
||||
"PlaybackEngine", "{}",
|
||||
"Track resolve exceeded grace period, skipping");
|
||||
host_.onPlaybackError(
|
||||
Api::Error{Api::ErrorCode::NetworkError,
|
||||
"Stream resolve timed out"},
|
||||
current_.entry);
|
||||
current_.closeAndReset();
|
||||
silenceSince_ = {};
|
||||
if (!beginNextFromQueue()) {
|
||||
publishCurrent(std::nullopt);
|
||||
playing_ = false;
|
||||
clock_.stop();
|
||||
host_.onEngineIdle();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
emitChunk(false); // silence
|
||||
} else {
|
||||
// Underrun: decoder alive but momentarily starved (slow
|
||||
// network, or the incoming decoder spinning up after a
|
||||
// handoff). Emit SILENCE on the normal cadence — the TS3
|
||||
// custom capture device pops ("reopens the channel") if the
|
||||
// audio callback stops firing, so we must keep feeding it
|
||||
// every 20ms even when there's no music yet.
|
||||
emitChunk(false);
|
||||
}
|
||||
|
||||
nextTick_ += std::chrono::milliseconds(CHUNK_MS);
|
||||
std::this_thread::sleep_until(nextTick_);
|
||||
}
|
||||
|
||||
Void::Log::debug("PlaybackEngine", "{}", "Engine thread exiting");
|
||||
}
|
||||
|
||||
void PlaybackEngine::drainMailbox()
|
||||
{
|
||||
std::deque<Command> commands;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mailboxMutex_);
|
||||
commands.swap(mailbox_);
|
||||
}
|
||||
for (auto& cmd : commands) {
|
||||
std::visit([this](auto&& c) { handle(std::move(c)); },
|
||||
std::move(cmd));
|
||||
}
|
||||
}
|
||||
|
||||
void PlaybackEngine::handle(CmdPlayNow&& cmd)
|
||||
{
|
||||
// Replace whatever is playing.
|
||||
ring_.clear();
|
||||
clearFade();
|
||||
current_.closeAndReset();
|
||||
next_.closeAndReset();
|
||||
consecutiveFailures_ = 0;
|
||||
|
||||
current_.entry = std::move(cmd.entry);
|
||||
if (openSlot(current_, cmd.url, cmd.isLocalFile)) {
|
||||
activateSlot(current_);
|
||||
} else {
|
||||
// Open failed — retry via the download-to-file path.
|
||||
retryViaDownload(current_);
|
||||
}
|
||||
playing_ = true;
|
||||
paused_ = false;
|
||||
nextTick_ = std::chrono::steady_clock::now();
|
||||
}
|
||||
|
||||
bool PlaybackEngine::retryViaDownload(DecoderSlot& slot)
|
||||
{
|
||||
if (!slot.entry || slot.triedDownload) {
|
||||
return false;
|
||||
}
|
||||
slot.triedDownload = true;
|
||||
auto entry = *slot.entry;
|
||||
slot.state = DecoderSlot::State::Resolving;
|
||||
slot.resolveStartedAt = std::chrono::steady_clock::now();
|
||||
slot.resolveFuture = std::async(std::launch::async, [this, entry]() {
|
||||
// preferDownload=true evicts the poisoned cache entry and
|
||||
// downloads through the proxy (yt-dlp handles SOCKS5).
|
||||
return host_.resolveStream(entry, true);
|
||||
});
|
||||
Void::Log::info("PlaybackEngine", "{}",
|
||||
"Open failed; retrying via download-to-file");
|
||||
return true;
|
||||
}
|
||||
|
||||
void PlaybackEngine::handle(CmdStart&&)
|
||||
{
|
||||
if (current_.state != DecoderSlot::State::Idle || paused_.load()) {
|
||||
return;
|
||||
}
|
||||
if (beginNextFromQueue()) {
|
||||
playing_ = true;
|
||||
nextTick_ = std::chrono::steady_clock::now();
|
||||
}
|
||||
}
|
||||
|
||||
void PlaybackEngine::handle(CmdPause&&)
|
||||
{
|
||||
if (!playing_.load() || paused_.exchange(true)) {
|
||||
return;
|
||||
}
|
||||
clock_.pause();
|
||||
}
|
||||
|
||||
void PlaybackEngine::handle(CmdResume&&)
|
||||
{
|
||||
if (!paused_.exchange(false)) {
|
||||
return;
|
||||
}
|
||||
clock_.resume();
|
||||
nextTick_ = std::chrono::steady_clock::now();
|
||||
}
|
||||
|
||||
void PlaybackEngine::handle(CmdStop&&)
|
||||
{
|
||||
ring_.clear();
|
||||
clearFade();
|
||||
if (current_.isLocalFile && !current_.openUrl.empty()) {
|
||||
host_.onLocalFileDone(current_.openUrl);
|
||||
}
|
||||
if (next_.isLocalFile && !next_.openUrl.empty()) {
|
||||
host_.onLocalFileDone(next_.openUrl);
|
||||
}
|
||||
current_.closeAndReset();
|
||||
next_.closeAndReset();
|
||||
playing_ = false;
|
||||
paused_ = false;
|
||||
clock_.stop();
|
||||
publishCurrent(std::nullopt);
|
||||
currentDurationMs_ = 0;
|
||||
}
|
||||
|
||||
void PlaybackEngine::handle(CmdSkip&& cmd)
|
||||
{
|
||||
if (current_.state == DecoderSlot::State::Idle) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (current_.entry) {
|
||||
host_.onTrackFinished(*current_.entry, clock_.position());
|
||||
}
|
||||
|
||||
ring_.clear();
|
||||
clearFade();
|
||||
if (current_.isLocalFile && !current_.openUrl.empty()) {
|
||||
host_.onLocalFileDone(current_.openUrl);
|
||||
}
|
||||
current_.closeAndReset();
|
||||
|
||||
// Consume (count - 1) additional entries from the queue.
|
||||
for (uint32_t i = 1; i < cmd.count; ++i) {
|
||||
if (!host_.takeAnyNextTrack()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Gapless skip: if the warm slot holds the next track and we skipped
|
||||
// exactly one, promote it instantly.
|
||||
if (cmd.count == 1 && next_.state == DecoderSlot::State::Warming) {
|
||||
std::swap(current_, next_);
|
||||
next_.closeAndReset();
|
||||
// Commit the queue pop that the prefetch only peeked; a stale
|
||||
// peek (queue edited meanwhile) falls through to a re-resolve.
|
||||
if (current_.entry &&
|
||||
host_.takeNextTrack(current_.entry->queueId)) {
|
||||
activateSlot(current_);
|
||||
return;
|
||||
}
|
||||
current_.closeAndReset();
|
||||
}
|
||||
|
||||
next_.closeAndReset();
|
||||
if (!beginNextFromQueue()) {
|
||||
playing_ = false;
|
||||
clock_.stop();
|
||||
publishCurrent(std::nullopt);
|
||||
host_.onEngineIdle();
|
||||
}
|
||||
}
|
||||
|
||||
void PlaybackEngine::handle(CmdSeek&& cmd)
|
||||
{
|
||||
if (current_.state != DecoderSlot::State::Active ||
|
||||
!current_.decoder) {
|
||||
return;
|
||||
}
|
||||
ring_.clear();
|
||||
clearFade();
|
||||
auto result = current_.decoder->seek(cmd.position);
|
||||
if (result) {
|
||||
clock_.seekTo(cmd.position);
|
||||
} else {
|
||||
Void::Log::error("PlaybackEngine", "{}",
|
||||
std::format("Seek failed: {}",
|
||||
result.error().message));
|
||||
}
|
||||
}
|
||||
|
||||
void PlaybackEngine::handle(CmdRestore&& cmd)
|
||||
{
|
||||
ring_.clear();
|
||||
clearFade();
|
||||
current_.closeAndReset();
|
||||
next_.closeAndReset();
|
||||
|
||||
current_.entry = std::move(cmd.entry);
|
||||
if (!openSlot(current_, cmd.url, false)) {
|
||||
Void::Log::error("PlaybackEngine", "{}",
|
||||
"Hot-reload restore failed to open source");
|
||||
current_.closeAndReset();
|
||||
return;
|
||||
}
|
||||
if (cmd.position.count() > 0) {
|
||||
auto seekResult = current_.decoder->seek(cmd.position);
|
||||
if (!seekResult) {
|
||||
Void::Log::warn("PlaybackEngine", "{}",
|
||||
"Restore seek failed; playing from start");
|
||||
}
|
||||
}
|
||||
activateSlot(current_, cmd.position);
|
||||
playing_ = true;
|
||||
paused_ = cmd.paused;
|
||||
if (cmd.paused) {
|
||||
clock_.pause();
|
||||
}
|
||||
nextTick_ = std::chrono::steady_clock::now();
|
||||
}
|
||||
|
||||
// ---- track flow ------------------------------------------------------
|
||||
|
||||
bool PlaybackEngine::beginNextFromQueue()
|
||||
{
|
||||
auto entry = host_.takeAnyNextTrack();
|
||||
if (!entry) {
|
||||
return false;
|
||||
}
|
||||
|
||||
current_.entry = std::move(entry);
|
||||
current_.state = DecoderSlot::State::Resolving;
|
||||
current_.resolveStartedAt = std::chrono::steady_clock::now();
|
||||
auto entryCopy = *current_.entry;
|
||||
current_.resolveFuture =
|
||||
std::async(std::launch::async, [this, entryCopy]() {
|
||||
return host_.resolveStream(entryCopy, false);
|
||||
});
|
||||
playing_ = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
void PlaybackEngine::maybeStartPrefetch()
|
||||
{
|
||||
if (current_.state != DecoderSlot::State::Active ||
|
||||
next_.state != DecoderSlot::State::Idle) {
|
||||
return;
|
||||
}
|
||||
|
||||
const auto duration =
|
||||
std::chrono::milliseconds(currentDurationMs_.load());
|
||||
if (duration.count() <= 0) {
|
||||
return;
|
||||
}
|
||||
const auto position = clock_.position();
|
||||
const bool nearEnd =
|
||||
duration <= PREFETCH_THRESHOLD
|
||||
? position >= std::chrono::seconds(2)
|
||||
: (duration - position) <= PREFETCH_THRESHOLD;
|
||||
if (!nearEnd) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Repeat replays the current entry; the resolve is usually cached.
|
||||
std::optional<Api::QueueEntry> upcoming =
|
||||
host_.repeatEnabled() ? current_.entry : host_.peekNextTrack();
|
||||
if (!upcoming) {
|
||||
return;
|
||||
}
|
||||
|
||||
next_.entry = std::move(upcoming);
|
||||
next_.state = DecoderSlot::State::Resolving;
|
||||
next_.resolveStartedAt = std::chrono::steady_clock::now();
|
||||
auto entryCopy = *next_.entry;
|
||||
next_.resolveFuture =
|
||||
std::async(std::launch::async, [this, entryCopy]() {
|
||||
return host_.resolveStream(entryCopy, false);
|
||||
});
|
||||
Void::Log::info(
|
||||
"PlaybackEngine", "{}",
|
||||
std::format("Prefetching next track: {} - {}",
|
||||
entryCopy.track.title, entryCopy.track.artist));
|
||||
}
|
||||
|
||||
void PlaybackEngine::pollNextResolve()
|
||||
{
|
||||
for (DecoderSlot* slot : {&next_, ¤t_}) {
|
||||
if (slot->state != DecoderSlot::State::Resolving ||
|
||||
!slot->resolveFuture.valid()) {
|
||||
continue;
|
||||
}
|
||||
if (slot->resolveFuture.wait_for(std::chrono::seconds(0)) !=
|
||||
std::future_status::ready) {
|
||||
continue;
|
||||
}
|
||||
|
||||
auto result = slot->resolveFuture.get();
|
||||
if (!result) {
|
||||
Void::Log::warn(
|
||||
"PlaybackEngine", "{}",
|
||||
std::format("Stream resolve failed: {}",
|
||||
result.error().message));
|
||||
host_.onPlaybackError(result.error(), slot->entry);
|
||||
const bool wasCurrent = (slot == ¤t_);
|
||||
slot->closeAndReset();
|
||||
if (wasCurrent) {
|
||||
if (++consecutiveFailures_ >= MAX_CONSECUTIVE_FAILURES ||
|
||||
!beginNextFromQueue()) {
|
||||
playing_ = false;
|
||||
clock_.stop();
|
||||
publishCurrent(std::nullopt);
|
||||
host_.onEngineIdle();
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// Heuristic: download fallback paths land in the temp dir; the
|
||||
// host tells us via resolveStream contract (paths vs URLs).
|
||||
const bool isLocal = !result->starts_with("http");
|
||||
if (!openSlot(*slot, *result, isLocal)) {
|
||||
// A non-local URL that won't open (expired, IP-locked
|
||||
// googlevideo under SOCKS5, dead instance): retry once via
|
||||
// download-to-file before giving up on this track.
|
||||
if (!isLocal && retryViaDownload(*slot)) {
|
||||
continue;
|
||||
}
|
||||
host_.onPlaybackError(
|
||||
Api::Error{Api::ErrorCode::AudioError,
|
||||
"Failed to open resolved stream"},
|
||||
slot->entry);
|
||||
const bool wasCurrent = (slot == ¤t_);
|
||||
slot->closeAndReset();
|
||||
if (wasCurrent) {
|
||||
if (++consecutiveFailures_ >= MAX_CONSECUTIVE_FAILURES ||
|
||||
!beginNextFromQueue()) {
|
||||
playing_ = false;
|
||||
clock_.stop();
|
||||
publishCurrent(std::nullopt);
|
||||
host_.onEngineIdle();
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (slot == ¤t_) {
|
||||
activateSlot(current_);
|
||||
} else {
|
||||
slot->state = DecoderSlot::State::Warming;
|
||||
Void::Log::info("PlaybackEngine", "{}",
|
||||
"Next track warmed for gapless handoff");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void PlaybackEngine::beginCrossfade()
|
||||
{
|
||||
// Bound the tail: what's already in the ring plus at most the
|
||||
// crossfade duration from the decoder (it is within crossfadeMs of
|
||||
// EOF, so its remaining queue is small and already buffered).
|
||||
const auto maxTailSamples = static_cast<std::size_t>(
|
||||
crossfadeMs_.load() * SAMPLE_RATE * CHANNELS / 1000);
|
||||
|
||||
fadeTail_.clear();
|
||||
fadePos_ = 0;
|
||||
fadeTail_.reserve(ring_.size() + maxTailSamples);
|
||||
for (std::size_t i = 0; i < ring_.size(); ++i) {
|
||||
fadeTail_.push_back(ring_[i]);
|
||||
}
|
||||
// NOT clearFade() here — the tail was just built from the ring.
|
||||
ring_.clear();
|
||||
while (fadeTail_.size() < maxTailSamples + SHORTS_PER_CHUNK &&
|
||||
current_.decoder->getNextChunk(incomingChunk_)) {
|
||||
fadeTail_.insert(fadeTail_.end(), incomingChunk_.begin(),
|
||||
incomingChunk_.end());
|
||||
}
|
||||
|
||||
if (current_.entry) {
|
||||
host_.onTrackFinished(*current_.entry, clock_.position());
|
||||
}
|
||||
if (current_.isLocalFile && !current_.openUrl.empty()) {
|
||||
host_.onLocalFileDone(current_.openUrl);
|
||||
}
|
||||
|
||||
// Commit the warm slot (same stale-peek protocol as the EOF
|
||||
// handoff).
|
||||
current_.closeAndReset();
|
||||
std::swap(current_, next_);
|
||||
if (!current_.entry ||
|
||||
!host_.takeNextTrack(current_.entry->queueId)) {
|
||||
// Queue changed under the peek: put the tail back as normal
|
||||
// output and advance conventionally later.
|
||||
Void::Log::info("PlaybackEngine", "{}",
|
||||
"Queue changed during crossfade; aborting fade");
|
||||
current_.closeAndReset();
|
||||
ring_.append(std::span<const short>(fadeTail_.data(),
|
||||
fadeTail_.size()));
|
||||
clearFade();
|
||||
if (!beginNextFromQueue()) {
|
||||
playing_ = false;
|
||||
clock_.stop();
|
||||
publishCurrent(std::nullopt);
|
||||
host_.onEngineIdle();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
activateSlot(current_);
|
||||
Void::Log::info(
|
||||
"PlaybackEngine", "{}",
|
||||
std::format("Crossfading over {} samples", fadeTail_.size()));
|
||||
}
|
||||
|
||||
void PlaybackEngine::handleTrackEnd()
|
||||
{
|
||||
if (current_.entry) {
|
||||
host_.onTrackFinished(*current_.entry, clock_.position());
|
||||
}
|
||||
if (current_.isLocalFile && !current_.openUrl.empty()) {
|
||||
host_.onLocalFileDone(current_.openUrl);
|
||||
}
|
||||
consecutiveFailures_ = 0;
|
||||
|
||||
// Repeat: reopen the same source (decoder EOF'd, so reopen).
|
||||
if (host_.repeatEnabled() && current_.entry) {
|
||||
const std::string url = current_.openUrl;
|
||||
const bool isLocal = current_.isLocalFile;
|
||||
auto entry = *current_.entry;
|
||||
// The warm slot may hold the same track (prefetch prefers the
|
||||
// current entry under repeat) — use it if so.
|
||||
if (next_.state == DecoderSlot::State::Warming && next_.entry &&
|
||||
next_.entry->queueId == entry.queueId) {
|
||||
current_.closeAndReset();
|
||||
std::swap(current_, next_);
|
||||
activateSlot(current_);
|
||||
return;
|
||||
}
|
||||
current_.closeAndReset();
|
||||
current_.entry = entry;
|
||||
if (!url.empty() && openSlot(current_, url, isLocal)) {
|
||||
activateSlot(current_);
|
||||
return;
|
||||
}
|
||||
// Fall through to queue advance when the reopen failed.
|
||||
}
|
||||
|
||||
// Gapless handoff to the warm slot.
|
||||
if (next_.state == DecoderSlot::State::Warming) {
|
||||
current_.closeAndReset();
|
||||
std::swap(current_, next_);
|
||||
if (current_.entry) {
|
||||
// Commit the pop; if the queue changed since the peek the
|
||||
// warm track is stale — drop it and advance normally.
|
||||
auto committed = host_.takeNextTrack(current_.entry->queueId);
|
||||
if (!committed) {
|
||||
Void::Log::info(
|
||||
"PlaybackEngine", "{}",
|
||||
"Queue changed during prefetch; re-resolving");
|
||||
current_.closeAndReset();
|
||||
if (!beginNextFromQueue()) {
|
||||
playing_ = false;
|
||||
clock_.stop();
|
||||
publishCurrent(std::nullopt);
|
||||
host_.onEngineIdle();
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
activateSlot(current_);
|
||||
return;
|
||||
}
|
||||
|
||||
// Next still resolving: keep its future, move it into current_ and
|
||||
// let the silence-grace path in run() wait for it.
|
||||
if (next_.state == DecoderSlot::State::Resolving) {
|
||||
current_.closeAndReset();
|
||||
std::swap(current_, next_);
|
||||
// The peeked entry must be consumed from the queue now; if the
|
||||
// queue changed the in-flight resolve is stale — drop it.
|
||||
if (!current_.entry ||
|
||||
!host_.takeNextTrack(current_.entry->queueId)) {
|
||||
current_.closeAndReset();
|
||||
if (!beginNextFromQueue()) {
|
||||
playing_ = false;
|
||||
clock_.stop();
|
||||
publishCurrent(std::nullopt);
|
||||
host_.onEngineIdle();
|
||||
}
|
||||
return;
|
||||
}
|
||||
silenceSince_ = std::chrono::steady_clock::now();
|
||||
return;
|
||||
}
|
||||
|
||||
// Nothing prefetched: advance from the queue.
|
||||
current_.closeAndReset();
|
||||
if (!beginNextFromQueue()) {
|
||||
playing_ = false;
|
||||
clock_.stop();
|
||||
publishCurrent(std::nullopt);
|
||||
currentDurationMs_ = 0;
|
||||
host_.onEngineIdle();
|
||||
}
|
||||
}
|
||||
|
||||
bool PlaybackEngine::openSlot(DecoderSlot& slot, const std::string& url,
|
||||
bool isLocalFile)
|
||||
{
|
||||
auto result = slot.decoder->openSource(url);
|
||||
if (!result) {
|
||||
Void::Log::error("PlaybackEngine", "{}",
|
||||
std::format("Failed to open source: {}",
|
||||
result.error().message));
|
||||
return false;
|
||||
}
|
||||
slot.openUrl = url;
|
||||
slot.isLocalFile = isLocalFile;
|
||||
return true;
|
||||
}
|
||||
|
||||
void PlaybackEngine::activateSlot(DecoderSlot& slot,
|
||||
std::chrono::milliseconds startAt)
|
||||
{
|
||||
slot.state = DecoderSlot::State::Active;
|
||||
consecutiveFailures_ = 0;
|
||||
silenceSince_ = {};
|
||||
clock_.seekTo(startAt);
|
||||
clock_.resume();
|
||||
|
||||
if (slot.entry) {
|
||||
slot.entry->isPlaying = true;
|
||||
slot.entry->position = startAt;
|
||||
}
|
||||
publishCurrent(slot.entry);
|
||||
|
||||
if (auto info = slot.decoder->getStreamInfo()) {
|
||||
currentDurationMs_ = info->duration.count();
|
||||
} else {
|
||||
currentDurationMs_ = 0;
|
||||
}
|
||||
|
||||
if (slot.entry) {
|
||||
host_.onTrackStarted(*slot.entry);
|
||||
}
|
||||
}
|
||||
|
||||
void PlaybackEngine::publishCurrent(
|
||||
const std::optional<Api::QueueEntry>& entry)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(currentEntryMutex_);
|
||||
publishedEntry_ = entry;
|
||||
}
|
||||
|
||||
void PlaybackEngine::emitChunk(bool fromRing)
|
||||
{
|
||||
if (fromRing) {
|
||||
const size_t available = std::min(ring_.size(), SHORTS_PER_CHUNK);
|
||||
const bool fading =
|
||||
!fadeTail_.empty() && fadePos_ < fadeTail_.size();
|
||||
|
||||
// The number of output samples we actually fill: during a fade
|
||||
// we emit a FULL chunk even when the incoming ring is still
|
||||
// short (the outgoing tail covers the gap), so a track handoff
|
||||
// never leaves the TS3 device starved. Otherwise it's just what
|
||||
// the ring holds.
|
||||
const size_t filled = fading ? SHORTS_PER_CHUNK : available;
|
||||
|
||||
if (fading) {
|
||||
// Equal-power blend: incoming (ring, or 0 if not ready yet)
|
||||
// rises while the outgoing tail falls, across the whole
|
||||
// chunk.
|
||||
const auto fadeLen = static_cast<float>(fadeTail_.size());
|
||||
for (size_t i = 0; i < SHORTS_PER_CHUNK; ++i) {
|
||||
const float incoming =
|
||||
i < available ? static_cast<float>(ring_[i]) : 0.0f;
|
||||
float mixed = incoming;
|
||||
if (fadePos_ < fadeTail_.size()) {
|
||||
const float theta =
|
||||
(static_cast<float>(fadePos_) / fadeLen) *
|
||||
1.57079632679f; // pi/2
|
||||
mixed = incoming * std::sin(theta) +
|
||||
static_cast<float>(fadeTail_[fadePos_]) *
|
||||
std::cos(theta);
|
||||
++fadePos_;
|
||||
}
|
||||
outChunk_[i] = static_cast<short>(std::clamp(
|
||||
static_cast<int>(mixed), -32768, 32767));
|
||||
}
|
||||
if (fadePos_ >= fadeTail_.size()) {
|
||||
clearFade();
|
||||
}
|
||||
} else {
|
||||
for (size_t i = 0; i < available; ++i) {
|
||||
outChunk_[i] = ring_[i];
|
||||
}
|
||||
}
|
||||
|
||||
// Loudness AGC (before user volume) + cubic user volume.
|
||||
float gain = std::pow(volume_.load(), 3.0f);
|
||||
if (normalizeEnabled_.load()) {
|
||||
gain *= agcGainFor(filled);
|
||||
}
|
||||
if (gain != 1.0f) {
|
||||
for (size_t i = 0; i < filled; ++i) {
|
||||
const int sample = static_cast<int>(
|
||||
static_cast<float>(outChunk_[i]) * gain);
|
||||
outChunk_[i] = static_cast<short>(
|
||||
std::clamp(sample, -32768, 32767));
|
||||
}
|
||||
}
|
||||
|
||||
// Zero-pad the remainder of a short chunk.
|
||||
std::fill(outChunk_.begin() +
|
||||
static_cast<std::ptrdiff_t>(filled),
|
||||
outChunk_.end(), 0);
|
||||
ring_.popFront(available);
|
||||
} else {
|
||||
std::fill(outChunk_.begin(), outChunk_.end(), 0);
|
||||
}
|
||||
|
||||
host_.emitAudio(
|
||||
std::span<const short>(outChunk_.data(), outChunk_.size()));
|
||||
}
|
||||
|
||||
float PlaybackEngine::agcGainFor(std::size_t samples)
|
||||
{
|
||||
if (samples == 0) {
|
||||
return 1.0f;
|
||||
}
|
||||
|
||||
// Mean square of the (pre-gain) chunk, folded into a ~400ms EMA.
|
||||
double sum = 0.0;
|
||||
for (std::size_t i = 0; i < samples; ++i) {
|
||||
const double v = static_cast<double>(outChunk_[i]);
|
||||
sum += v * v;
|
||||
}
|
||||
const double chunkMs = sum / static_cast<double>(samples);
|
||||
|
||||
// Don't chase silence — hold the gain through quiet passages.
|
||||
constexpr double kSilenceFloor = 32768.0 * 32768.0 * 1e-6; // -60dB
|
||||
if (chunkMs > kSilenceFloor) {
|
||||
constexpr double alpha = 0.05; // ~400ms at 20ms chunks
|
||||
agcMeanSquare_ =
|
||||
agcMeanSquare_ <= 0.0
|
||||
? chunkMs
|
||||
: agcMeanSquare_ + alpha * (chunkMs - agcMeanSquare_);
|
||||
|
||||
const float rmsDb = static_cast<float>(
|
||||
10.0 * std::log10(agcMeanSquare_ /
|
||||
(32768.0 * 32768.0)));
|
||||
const float wantedDb = normalizeTargetDb_.load() - rmsDb;
|
||||
|
||||
// Slew: fast attack (turn down), slow release (turn up).
|
||||
constexpr float kAttackPerChunk = 0.4f; // 20 dB/s
|
||||
constexpr float kReleasePerChunk = 0.06f; // 3 dB/s
|
||||
const float delta = wantedDb - agcGainDb_;
|
||||
if (delta < 0.0f) {
|
||||
agcGainDb_ += std::max(delta, -kAttackPerChunk);
|
||||
} else {
|
||||
agcGainDb_ += std::min(delta, kReleasePerChunk);
|
||||
}
|
||||
agcGainDb_ = std::clamp(agcGainDb_, -20.0f, 12.0f);
|
||||
}
|
||||
|
||||
return std::clamp(std::pow(10.0f, agcGainDb_ / 20.0f), 0.1f, 4.0f);
|
||||
}
|
||||
|
||||
void PlaybackEngine::positionTick()
|
||||
{
|
||||
if (current_.state != DecoderSlot::State::Active ||
|
||||
!current_.entry) {
|
||||
return;
|
||||
}
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
if (now - lastPositionTick_ < std::chrono::seconds(1)) {
|
||||
return;
|
||||
}
|
||||
lastPositionTick_ = now;
|
||||
host_.onPositionTick(*current_.entry, clock_.position(),
|
||||
std::chrono::milliseconds(
|
||||
currentDurationMs_.load()));
|
||||
}
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,311 @@
|
||||
#include "echoion/core/playback/QueueService.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
Api::Result<uint64_t> QueueService::enqueue(const Api::TrackInfo& track,
|
||||
std::string addedBy,
|
||||
std::size_t maxSize)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
if (entries_.size() >= maxSize) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument, "Queue is full");
|
||||
}
|
||||
|
||||
const uint64_t queueId = nextQueueId_++;
|
||||
entries_.push_back(
|
||||
Entry{.queueId = queueId,
|
||||
.track = track,
|
||||
.addedAt = std::chrono::system_clock::now(),
|
||||
.addedBy = std::move(addedBy),
|
||||
.isPlaying = false,
|
||||
.position = std::nullopt});
|
||||
|
||||
if (shuffle_) {
|
||||
// Insert the new position at a random spot among the remaining
|
||||
// (not yet played) shuffled picks.
|
||||
const std::size_t newPos = entries_.size() - 1;
|
||||
if (shuffleIndex_ < shuffledIndices_.size()) {
|
||||
std::uniform_int_distribution<std::size_t> dist(
|
||||
shuffleIndex_, shuffledIndices_.size());
|
||||
shuffledIndices_.insert(
|
||||
shuffledIndices_.begin() +
|
||||
static_cast<std::ptrdiff_t>(dist(rng_)),
|
||||
newPos);
|
||||
} else {
|
||||
shuffledIndices_.push_back(newPos);
|
||||
}
|
||||
}
|
||||
|
||||
return queueId;
|
||||
}
|
||||
|
||||
Api::Result<QueueService::Entry> QueueService::removeAt(uint32_t position)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
if (position >= entries_.size()) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"Invalid position");
|
||||
}
|
||||
|
||||
Entry removed = entries_[position];
|
||||
entries_.erase(entries_.begin() + position);
|
||||
|
||||
if (shuffle_ && !shuffledIndices_.empty()) {
|
||||
auto it = std::find(shuffledIndices_.begin(),
|
||||
shuffledIndices_.end(), position);
|
||||
if (it != shuffledIndices_.end()) {
|
||||
const std::size_t removedShuffleIndex = static_cast<std::size_t>(
|
||||
std::distance(shuffledIndices_.begin(), it));
|
||||
shuffledIndices_.erase(it);
|
||||
if (removedShuffleIndex < shuffleIndex_) {
|
||||
--shuffleIndex_;
|
||||
}
|
||||
}
|
||||
for (auto& idx : shuffledIndices_) {
|
||||
if (idx > position) {
|
||||
--idx;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return removed;
|
||||
}
|
||||
|
||||
uint32_t QueueService::clear()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
const auto previous = static_cast<uint32_t>(entries_.size());
|
||||
entries_.clear();
|
||||
shuffledIndices_.clear();
|
||||
shuffleIndex_ = 0;
|
||||
return previous;
|
||||
}
|
||||
|
||||
Api::Result<uint64_t> QueueService::move(uint32_t from, uint32_t to)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
if (from >= entries_.size() || to >= entries_.size()) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"Invalid position");
|
||||
}
|
||||
|
||||
Entry entry = entries_[from];
|
||||
entries_.erase(entries_.begin() + from);
|
||||
entries_.insert(entries_.begin() + to, entry);
|
||||
|
||||
if (shuffle_ && !shuffledIndices_.empty()) {
|
||||
for (auto& idx : shuffledIndices_) {
|
||||
if (from < to) {
|
||||
// Moving forward: positions in (from, to] shift down.
|
||||
if (idx > from && idx <= to) {
|
||||
--idx;
|
||||
} else if (idx == from) {
|
||||
idx = to;
|
||||
}
|
||||
} else if (from > to) {
|
||||
// Moving backward: positions in [to, from) shift up.
|
||||
if (idx >= to && idx < from) {
|
||||
++idx;
|
||||
} else if (idx == from) {
|
||||
idx = to;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return entry.queueId;
|
||||
}
|
||||
|
||||
std::optional<QueueService::Entry> QueueService::popNext()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return popNextLocked();
|
||||
}
|
||||
|
||||
std::optional<QueueService::Entry> QueueService::popIfNext(uint64_t queueId)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
auto pos = nextPositionLocked();
|
||||
if (!pos || entries_[*pos].queueId != queueId) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return popNextLocked();
|
||||
}
|
||||
|
||||
void QueueService::replaceAll(std::vector<Entry> entries)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
entries_ = std::move(entries);
|
||||
// Keep queue ids unique after a restore.
|
||||
for (const auto& entry : entries_) {
|
||||
nextQueueId_ = std::max(nextQueueId_, entry.queueId + 1);
|
||||
}
|
||||
if (shuffle_ && !entries_.empty()) {
|
||||
rebuildShuffledIndicesLocked();
|
||||
} else {
|
||||
shuffledIndices_.clear();
|
||||
shuffleIndex_ = 0;
|
||||
}
|
||||
}
|
||||
|
||||
void QueueService::shuffleInPlace()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
std::shuffle(entries_.begin(), entries_.end(), rng_);
|
||||
if (shuffle_) {
|
||||
rebuildShuffledIndicesLocked();
|
||||
}
|
||||
}
|
||||
|
||||
bool QueueService::toggleShuffle()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
shuffle_ = !shuffle_;
|
||||
if (shuffle_) {
|
||||
rebuildShuffledIndicesLocked();
|
||||
} else {
|
||||
shuffledIndices_.clear();
|
||||
shuffleIndex_ = 0;
|
||||
}
|
||||
return shuffle_;
|
||||
}
|
||||
|
||||
void QueueService::setShuffle(bool enabled)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (shuffle_ == enabled) {
|
||||
return;
|
||||
}
|
||||
shuffle_ = enabled;
|
||||
if (shuffle_) {
|
||||
rebuildShuffledIndicesLocked();
|
||||
} else {
|
||||
shuffledIndices_.clear();
|
||||
shuffleIndex_ = 0;
|
||||
}
|
||||
}
|
||||
|
||||
bool QueueService::shuffleEnabled() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return shuffle_;
|
||||
}
|
||||
|
||||
bool QueueService::toggleRepeat()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
repeat_ = !repeat_;
|
||||
return repeat_;
|
||||
}
|
||||
|
||||
void QueueService::setRepeat(bool enabled)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
repeat_ = enabled;
|
||||
}
|
||||
|
||||
bool QueueService::repeatEnabled() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return repeat_;
|
||||
}
|
||||
|
||||
std::optional<QueueService::Entry> QueueService::peekNext() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
auto pos = nextPositionLocked();
|
||||
if (!pos) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return entries_[*pos];
|
||||
}
|
||||
|
||||
std::vector<QueueService::Entry> QueueService::snapshot() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return entries_;
|
||||
}
|
||||
|
||||
std::size_t QueueService::size() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return entries_.size();
|
||||
}
|
||||
|
||||
bool QueueService::empty() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return entries_.empty();
|
||||
}
|
||||
|
||||
uint64_t QueueService::allocateQueueId()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return nextQueueId_++;
|
||||
}
|
||||
|
||||
void QueueService::rebuildShuffledIndicesLocked()
|
||||
{
|
||||
shuffledIndices_.clear();
|
||||
shuffledIndices_.reserve(entries_.size());
|
||||
for (std::size_t i = 0; i < entries_.size(); ++i) {
|
||||
shuffledIndices_.push_back(i);
|
||||
}
|
||||
std::shuffle(shuffledIndices_.begin(), shuffledIndices_.end(), rng_);
|
||||
shuffleIndex_ = 0;
|
||||
}
|
||||
|
||||
std::optional<std::size_t> QueueService::nextPositionLocked() const
|
||||
{
|
||||
if (entries_.empty()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
if (shuffle_ && !shuffledIndices_.empty() &&
|
||||
shuffleIndex_ < shuffledIndices_.size()) {
|
||||
const std::size_t pos = shuffledIndices_[shuffleIndex_];
|
||||
if (pos < entries_.size()) {
|
||||
return pos;
|
||||
}
|
||||
// Permutation out of sync (defensive) — fall through to front.
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
std::optional<QueueService::Entry> QueueService::popNextLocked()
|
||||
{
|
||||
auto posOpt = nextPositionLocked();
|
||||
if (!posOpt) {
|
||||
return std::nullopt;
|
||||
}
|
||||
const std::size_t pos = *posOpt;
|
||||
Entry entry = entries_[pos];
|
||||
entries_.erase(entries_.begin() + static_cast<std::ptrdiff_t>(pos));
|
||||
|
||||
if (shuffle_ && !shuffledIndices_.empty() &&
|
||||
shuffleIndex_ < shuffledIndices_.size()) {
|
||||
++shuffleIndex_;
|
||||
if (shuffleIndex_ >= shuffledIndices_.size()) {
|
||||
rebuildShuffledIndicesLocked();
|
||||
} else {
|
||||
// Fix up remaining picks for the removed position.
|
||||
for (std::size_t i = shuffleIndex_;
|
||||
i < shuffledIndices_.size(); ++i) {
|
||||
if (shuffledIndices_[i] > pos) {
|
||||
--shuffledIndices_[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return entry;
|
||||
}
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,74 @@
|
||||
#include "echoion/core/sources/DirectUrlSource.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <string>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
namespace
|
||||
{
|
||||
bool looksLikeAudioUrl(const std::string& query)
|
||||
{
|
||||
if (query.find("://") == std::string::npos) {
|
||||
return false;
|
||||
}
|
||||
// Strip query string before checking the extension.
|
||||
std::string path = query;
|
||||
if (auto q = path.find('?'); q != std::string::npos) {
|
||||
path.resize(q);
|
||||
}
|
||||
std::transform(path.begin(), path.end(), path.begin(),
|
||||
[](unsigned char c) {
|
||||
return static_cast<char>(std::tolower(c));
|
||||
});
|
||||
|
||||
static const char* extensions[] = {
|
||||
".mp3", ".ogg", ".opus", ".m4a", ".aac",
|
||||
".wav", ".flac", ".m3u8", ".m3u", ".pls"};
|
||||
for (const char* ext : extensions) {
|
||||
if (path.ends_with(ext)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
// Icecast/shoutcast mounts commonly live under /stream.
|
||||
return path.ends_with("/stream") || path.ends_with("/listen");
|
||||
}
|
||||
} // namespace
|
||||
|
||||
bool DirectUrlSource::canHandle(const std::string& query) const
|
||||
{
|
||||
return looksLikeAudioUrl(query);
|
||||
}
|
||||
|
||||
Api::Result<Api::SearchResult> DirectUrlSource::search(std::string_view)
|
||||
{
|
||||
return Api::fail(Api::ErrorCode::NotSupported,
|
||||
"direct-url does not search");
|
||||
}
|
||||
|
||||
Api::Result<Api::TrackInfo> DirectUrlSource::resolve(const std::string& urlOrId)
|
||||
{
|
||||
Api::TrackInfo t;
|
||||
t.id = urlOrId;
|
||||
t.title = urlOrId;
|
||||
t.source = Api::TrackSource::URL;
|
||||
t.originalUrl = urlOrId;
|
||||
t.streamUrl = urlOrId;
|
||||
t.addedAt = std::chrono::system_clock::now();
|
||||
return t;
|
||||
}
|
||||
|
||||
Api::Result<StreamHandle>
|
||||
DirectUrlSource::getStream(const Api::TrackInfo& track)
|
||||
{
|
||||
const std::string& url = track.streamUrl.value_or(track.originalUrl);
|
||||
if (url.empty()) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument, "No URL");
|
||||
}
|
||||
return StreamHandle{.url = url,
|
||||
.isLocalFile = false,
|
||||
.sourceName = "direct-url"};
|
||||
}
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,400 @@
|
||||
#include "echoion/core/sources/InnertubeSource.hpp"
|
||||
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
#include <regex>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
namespace
|
||||
{
|
||||
constexpr const char* kDefaultEndpoint = "https://www.youtube.com";
|
||||
constexpr const char* kIosVersion = "19.45.4";
|
||||
constexpr const char* kWebVersion = "2.20241126.01.00";
|
||||
|
||||
std::optional<std::string> extractVideoId(const std::string& query)
|
||||
{
|
||||
static const std::regex patterns[] = {
|
||||
std::regex(R"([?&]v=([A-Za-z0-9_-]{11}))"),
|
||||
std::regex(R"(youtu\.be/([A-Za-z0-9_-]{11}))"),
|
||||
std::regex(R"(/shorts/([A-Za-z0-9_-]{11}))"),
|
||||
std::regex(R"(/embed/([A-Za-z0-9_-]{11}))"),
|
||||
std::regex(R"(^([A-Za-z0-9_-]{11})$)"),
|
||||
};
|
||||
std::smatch match;
|
||||
for (const auto& pattern : patterns) {
|
||||
if (std::regex_search(query, match, pattern)) {
|
||||
return match[1].str();
|
||||
}
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
std::string str(const Void::Json::Value& v, const char* key)
|
||||
{
|
||||
const auto* f = v.find(key);
|
||||
return (f && f->is_string()) ? f->as_string() : std::string{};
|
||||
}
|
||||
|
||||
int64_t num(const Void::Json::Value& v, const char* key)
|
||||
{
|
||||
const auto* f = v.find(key);
|
||||
if (!f) {
|
||||
return 0;
|
||||
}
|
||||
if (f->is_number()) {
|
||||
return static_cast<int64_t>(f->as_number());
|
||||
}
|
||||
// innertube returns some numerics as strings ("lengthSeconds")
|
||||
if (f->is_string()) {
|
||||
try {
|
||||
return std::stoll(f->as_string());
|
||||
} catch (const std::exception&) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
std::string playerRequestBody(const std::string& videoId,
|
||||
bool webClient)
|
||||
{
|
||||
// Built via the JSON model so the video id is safely escaped.
|
||||
using Void::Json::Value;
|
||||
Value client = Void::Json::object();
|
||||
auto& c = client.as_object();
|
||||
if (webClient) {
|
||||
c.emplace_back("clientName", Value{"WEB"});
|
||||
c.emplace_back("clientVersion", Value{kWebVersion});
|
||||
} else {
|
||||
c.emplace_back("clientName", Value{"IOS"});
|
||||
c.emplace_back("clientVersion", Value{kIosVersion});
|
||||
c.emplace_back("deviceMake", Value{"Apple"});
|
||||
c.emplace_back("deviceModel", Value{"iPhone16,2"});
|
||||
c.emplace_back("osName", Value{"iOS"});
|
||||
c.emplace_back("osVersion", Value{"18.1.0.22B83"});
|
||||
}
|
||||
c.emplace_back("hl", Value{"en"});
|
||||
c.emplace_back("gl", Value{"US"});
|
||||
|
||||
Value context = Void::Json::object();
|
||||
context.as_object().emplace_back("client", std::move(client));
|
||||
|
||||
Value root = Void::Json::object();
|
||||
auto& r = root.as_object();
|
||||
r.emplace_back("videoId", Value{videoId});
|
||||
r.emplace_back("context", std::move(context));
|
||||
r.emplace_back("contentCheckOk", Value{true});
|
||||
r.emplace_back("racyCheckOk", Value{true});
|
||||
return Void::Json::serialize(root, {});
|
||||
}
|
||||
|
||||
// Pick the best audio-only format: prefer Opus (251/250/249) then
|
||||
// AAC (140), falling back to the highest audio bitrate.
|
||||
const Void::Json::Value*
|
||||
pickAudioFormat(const Void::Json::Value& formats)
|
||||
{
|
||||
const Void::Json::Value* best = nullptr;
|
||||
int64_t bestScore = -1;
|
||||
for (const auto& fmt : formats.as_array()) {
|
||||
const auto mime = str(fmt, "mimeType");
|
||||
if (!mime.starts_with("audio/")) {
|
||||
continue;
|
||||
}
|
||||
const auto itag = num(fmt, "itag");
|
||||
int64_t score = num(fmt, "bitrate");
|
||||
if (itag == 251) {
|
||||
score += 10'000'000;
|
||||
} else if (itag == 250 || itag == 249) {
|
||||
score += 5'000'000;
|
||||
} else if (itag == 140) {
|
||||
score += 1'000'000;
|
||||
}
|
||||
if (score > bestScore) {
|
||||
bestScore = score;
|
||||
best = &fmt;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
std::string urlDecode(std::string_view text)
|
||||
{
|
||||
std::string out;
|
||||
out.reserve(text.size());
|
||||
for (size_t i = 0; i < text.size(); ++i) {
|
||||
if (text[i] == '%' && i + 2 < text.size()) {
|
||||
const auto hex = std::string(text.substr(i + 1, 2));
|
||||
out.push_back(static_cast<char>(
|
||||
std::stoi(hex, nullptr, 16)));
|
||||
i += 2;
|
||||
} else if (text[i] == '+') {
|
||||
out.push_back(' ');
|
||||
} else {
|
||||
out.push_back(text[i]);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
InnertubeSource::InnertubeSource(std::shared_ptr<NetworkClient> network,
|
||||
std::string endpointOverride) :
|
||||
network_(std::move(network)),
|
||||
endpoint_(endpointOverride.empty() ? kDefaultEndpoint
|
||||
: std::move(endpointOverride))
|
||||
{
|
||||
}
|
||||
|
||||
void InnertubeSource::configure(bool enabled, bool requireProxy)
|
||||
{
|
||||
enabled_ = enabled;
|
||||
requireProxy_ = requireProxy;
|
||||
}
|
||||
|
||||
bool InnertubeSource::canHandle(const std::string& query) const
|
||||
{
|
||||
if (!enabled_.load()) {
|
||||
return false;
|
||||
}
|
||||
// URLs/ids only; free-text search stays on the frontend sources.
|
||||
return extractVideoId(query).has_value();
|
||||
}
|
||||
|
||||
bool InnertubeSource::isAvailable() const
|
||||
{
|
||||
if (!enabled_.load()) {
|
||||
return false;
|
||||
}
|
||||
if (requireProxy_.load() && !network_->getProxy().has_value()) {
|
||||
// youtubei is ISP-blocked without a proxy — don't waste attempts.
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
Api::Result<Api::SearchResult> InnertubeSource::search(std::string_view)
|
||||
{
|
||||
return Api::fail(Api::ErrorCode::NotSupported,
|
||||
"innertube does not search");
|
||||
}
|
||||
|
||||
Api::Result<InnertubeSource::PlayerResponse>
|
||||
InnertubeSource::callPlayer(const std::string& videoId,
|
||||
bool webClient)
|
||||
{
|
||||
const std::string url =
|
||||
endpoint_ + "/youtubei/v1/player?prettyPrint=false";
|
||||
|
||||
std::vector<Void::Net::Header> headers = {
|
||||
{"Content-Type", "application/json"},
|
||||
};
|
||||
if (webClient) {
|
||||
headers.push_back({"X-YouTube-Client-Name", "1"});
|
||||
headers.push_back({"X-YouTube-Client-Version", kWebVersion});
|
||||
} else {
|
||||
headers.push_back({"X-YouTube-Client-Name", "5"});
|
||||
headers.push_back({"X-YouTube-Client-Version", kIosVersion});
|
||||
headers.push_back(
|
||||
{"User-Agent",
|
||||
std::format("com.google.ios.youtube/{} (iPhone16,2; U; CPU "
|
||||
"iOS 18_1_0 like Mac OS X;)",
|
||||
kIosVersion)});
|
||||
}
|
||||
|
||||
auto resp = network_->post(url, playerRequestBody(videoId, webClient),
|
||||
headers);
|
||||
if (!resp) {
|
||||
return std::unexpected(resp.error());
|
||||
}
|
||||
if (resp->status != 200) {
|
||||
return Api::fail(
|
||||
Api::ErrorCode::NetworkError,
|
||||
std::format("innertube player returned HTTP {}",
|
||||
resp->status));
|
||||
}
|
||||
|
||||
auto parsed = Void::Json::parse(resp->body);
|
||||
if (!parsed) {
|
||||
return Api::fail(Api::ErrorCode::ParseError,
|
||||
"Invalid innertube player response");
|
||||
}
|
||||
|
||||
if (const auto* status = parsed->find("playabilityStatus")) {
|
||||
const auto state = str(*status, "status");
|
||||
if (state != "OK") {
|
||||
return Api::fail(
|
||||
Api::ErrorCode::NotFound,
|
||||
std::format("Video not playable: {} ({})", state,
|
||||
str(*status, "reason")));
|
||||
}
|
||||
}
|
||||
|
||||
PlayerResponse out;
|
||||
if (const auto* details = parsed->find("videoDetails")) {
|
||||
out.title = str(*details, "title");
|
||||
out.author = str(*details, "author");
|
||||
out.lengthSeconds = num(*details, "lengthSeconds");
|
||||
if (const auto* thumb = details->find("thumbnail")) {
|
||||
if (const auto* thumbs = thumb->find("thumbnails");
|
||||
thumbs && thumbs->is_array() &&
|
||||
!thumbs->as_array().empty()) {
|
||||
out.thumbnailUrl =
|
||||
str(thumbs->as_array().back(), "url");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const auto* streaming = parsed->find("streamingData");
|
||||
const auto* formats =
|
||||
streaming ? streaming->find("adaptiveFormats") : nullptr;
|
||||
if (formats && formats->is_array()) {
|
||||
if (const auto* best = pickAudioFormat(*formats)) {
|
||||
out.streamUrl = str(*best, "url");
|
||||
out.signatureCipher = str(*best, "signatureCipher");
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
Api::Result<Api::TrackInfo>
|
||||
InnertubeSource::resolve(const std::string& urlOrId)
|
||||
{
|
||||
auto videoId = extractVideoId(urlOrId);
|
||||
if (!videoId) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"Not a YouTube video");
|
||||
}
|
||||
|
||||
auto player = callPlayer(*videoId, false);
|
||||
if (!player) {
|
||||
return std::unexpected(player.error());
|
||||
}
|
||||
|
||||
Api::TrackInfo t;
|
||||
t.id = *videoId;
|
||||
t.title = player->title;
|
||||
t.artist = player->author;
|
||||
t.source = Api::TrackSource::YouTube;
|
||||
t.originalUrl = "https://www.youtube.com/watch?v=" + *videoId;
|
||||
if (player->lengthSeconds > 0) {
|
||||
t.duration =
|
||||
std::chrono::milliseconds(player->lengthSeconds * 1000);
|
||||
}
|
||||
if (!player->thumbnailUrl.empty()) {
|
||||
t.thumbnailUrl = player->thumbnailUrl;
|
||||
}
|
||||
t.addedAt = std::chrono::system_clock::now();
|
||||
return t;
|
||||
}
|
||||
|
||||
Api::Result<StreamHandle>
|
||||
InnertubeSource::getStream(const Api::TrackInfo& track)
|
||||
{
|
||||
auto videoId = extractVideoId(track.originalUrl);
|
||||
if (!videoId && !track.id.empty()) {
|
||||
videoId = extractVideoId(track.id);
|
||||
}
|
||||
if (!videoId) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"Not a YouTube track");
|
||||
}
|
||||
|
||||
auto player = callPlayer(*videoId, false);
|
||||
if (!player) {
|
||||
return std::unexpected(player.error());
|
||||
}
|
||||
|
||||
if (!player->streamUrl.empty()) {
|
||||
Void::Log::info(
|
||||
"InnertubeSource", "{}",
|
||||
std::format("Resolved stream for {} via IOS client",
|
||||
*videoId));
|
||||
return StreamHandle{.url = player->streamUrl,
|
||||
.isLocalFile = false,
|
||||
.sourceName = "innertube"};
|
||||
}
|
||||
|
||||
if (!player->signatureCipher.empty()) {
|
||||
auto deciphered =
|
||||
decipherWithWebPlayer(*videoId, player->signatureCipher);
|
||||
if (deciphered) {
|
||||
return StreamHandle{.url = std::move(*deciphered),
|
||||
.isLocalFile = false,
|
||||
.sourceName = "innertube"};
|
||||
}
|
||||
return std::unexpected(deciphered.error());
|
||||
}
|
||||
|
||||
return Api::fail(Api::ErrorCode::NotFound,
|
||||
"innertube returned no audio formats");
|
||||
}
|
||||
|
||||
Api::Result<std::string> InnertubeSource::decipherWithWebPlayer(
|
||||
const std::string& videoId, const std::string& signatureCipher)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(cipherMutex_);
|
||||
|
||||
// Locate the current player JS from the watch page and feed the
|
||||
// solver once per player version.
|
||||
auto watch = network_->get(endpoint_ + "/watch?v=" + videoId);
|
||||
if (!watch || watch->status != 200) {
|
||||
return Api::fail(Api::ErrorCode::NetworkError,
|
||||
"Failed to fetch watch page for player JS");
|
||||
}
|
||||
std::smatch match;
|
||||
static const std::regex playerRe(
|
||||
R"delim("(/s/player/[^"]+/base\.js)")delim");
|
||||
if (!std::regex_search(watch->body, match, playerRe)) {
|
||||
return Api::fail(Api::ErrorCode::ParseError,
|
||||
"Player JS URL not found in watch page");
|
||||
}
|
||||
const std::string playerUrl = endpoint_ + match[1].str();
|
||||
|
||||
if (!cipher_) {
|
||||
cipher_ = std::make_unique<SignatureCipher>();
|
||||
cipher_->initialize();
|
||||
}
|
||||
if (loadedPlayerJsUrl_ != playerUrl) {
|
||||
auto playerJs = network_->get(playerUrl);
|
||||
if (!playerJs || playerJs->status != 200) {
|
||||
return Api::fail(Api::ErrorCode::NetworkError,
|
||||
"Failed to fetch player JS");
|
||||
}
|
||||
if (!cipher_->setPlayerJs(playerJs->body)) {
|
||||
return Api::fail(Api::ErrorCode::ServiceUnavailable,
|
||||
"Signature solver rejected player JS");
|
||||
}
|
||||
loadedPlayerJsUrl_ = playerUrl;
|
||||
}
|
||||
|
||||
auto url = cipher_->decipher(signatureCipher);
|
||||
if (url.empty()) {
|
||||
return Api::fail(Api::ErrorCode::ServiceUnavailable,
|
||||
"Failed to decipher signature");
|
||||
}
|
||||
|
||||
// The n query parameter throttles undecoded downloads to ~50 KB/s;
|
||||
// solve and substitute it when present.
|
||||
static const std::regex nRe(R"([?&]n=([^&]+))");
|
||||
std::smatch nMatch;
|
||||
if (std::regex_search(url, nMatch, nRe)) {
|
||||
const std::string original = nMatch[1].str();
|
||||
auto solved = cipher_->decipherNParam(urlDecode(original));
|
||||
if (!solved.empty() && solved != original) {
|
||||
url = url.substr(0, static_cast<size_t>(
|
||||
nMatch.position(1))) +
|
||||
solved +
|
||||
url.substr(static_cast<size_t>(nMatch.position(1)) +
|
||||
original.size());
|
||||
}
|
||||
}
|
||||
|
||||
Void::Log::info(
|
||||
"InnertubeSource", "{}",
|
||||
std::format("Deciphered WEB stream for {}", videoId));
|
||||
return url;
|
||||
}
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,340 @@
|
||||
#include "echoion/core/sources/SourceRouter.hpp"
|
||||
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <condition_variable>
|
||||
#include <format>
|
||||
#include <optional>
|
||||
#include <thread>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
namespace
|
||||
{
|
||||
// Locally-downloaded files are stable; googlevideo URLs (yt-dlp /
|
||||
// innertube) are good for hours before their signature expires.
|
||||
std::chrono::milliseconds ttlFor(const StreamHandle& handle)
|
||||
{
|
||||
if (handle.isLocalFile) {
|
||||
return std::chrono::hours(24);
|
||||
}
|
||||
if (handle.sourceName == "invidious" ||
|
||||
handle.sourceName == "piped") {
|
||||
return std::chrono::minutes(30);
|
||||
}
|
||||
return std::chrono::hours(4);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
void SourceRouter::setSources(
|
||||
std::vector<std::shared_ptr<ITrackSource>> sources)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
allSources_ = std::move(sources);
|
||||
chain_.clear();
|
||||
for (auto& source : allSources_) {
|
||||
chain_.push_back(SourceState{.source = source});
|
||||
}
|
||||
}
|
||||
|
||||
void SourceRouter::setOrder(const std::vector<std::string>& order)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
std::vector<SourceState> reordered;
|
||||
for (const auto& name : order) {
|
||||
for (auto& source : allSources_) {
|
||||
if (source->name() == name) {
|
||||
reordered.push_back(SourceState{.source = source});
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (reordered.empty()) {
|
||||
Void::Log::warn("SourceRouter", "{}",
|
||||
"sources.order matched nothing; keeping all "
|
||||
"sources in registration order");
|
||||
return;
|
||||
}
|
||||
chain_ = std::move(reordered);
|
||||
}
|
||||
|
||||
void SourceRouter::setFailureCooldown(std::chrono::milliseconds cooldown)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (cooldown.count() > 0) {
|
||||
cooldown_ = cooldown;
|
||||
}
|
||||
}
|
||||
|
||||
void SourceRouter::setHedgeDelay(std::chrono::milliseconds delay)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
hedgeDelay_ = std::max(delay, std::chrono::milliseconds(0));
|
||||
}
|
||||
|
||||
std::vector<SourceRouter::SourceState*>
|
||||
SourceRouter::candidatesFor(const std::string& query, bool needSearch)
|
||||
{
|
||||
// Callers hold mutex_.
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
std::vector<SourceState*> eligible;
|
||||
std::vector<SourceState*> coolingDown;
|
||||
|
||||
for (auto& state : chain_) {
|
||||
if (needSearch && !state.source->supportsSearch()) {
|
||||
continue;
|
||||
}
|
||||
if (!state.source->canHandle(query)) {
|
||||
continue;
|
||||
}
|
||||
if (state.cooldownUntil > now) {
|
||||
coolingDown.push_back(&state);
|
||||
continue;
|
||||
}
|
||||
eligible.push_back(&state);
|
||||
}
|
||||
// A source on cooldown is still tried when nothing else matched —
|
||||
// better a likely-failing attempt than an immediate error.
|
||||
if (eligible.empty()) {
|
||||
return coolingDown;
|
||||
}
|
||||
return eligible;
|
||||
}
|
||||
|
||||
void SourceRouter::reportFailure(SourceState& state)
|
||||
{
|
||||
state.cooldownUntil = std::chrono::steady_clock::now() + cooldown_;
|
||||
Void::Log::info(
|
||||
"SourceRouter", "{}",
|
||||
std::format("Source '{}' on cooldown for {}s",
|
||||
state.source->name(), cooldown_.count() / 1000));
|
||||
}
|
||||
|
||||
Api::Result<Api::SearchResult> SourceRouter::search(std::string_view query)
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(mutex_);
|
||||
auto candidates = candidatesFor(std::string(query), true);
|
||||
lock.unlock();
|
||||
|
||||
Api::Error lastError{Api::ErrorCode::ServiceUnavailable,
|
||||
"No source can search"};
|
||||
for (auto* state : candidates) {
|
||||
if (!state->source->isAvailable()) {
|
||||
continue;
|
||||
}
|
||||
auto result = state->source->search(query);
|
||||
if (result) {
|
||||
return result;
|
||||
}
|
||||
lastError = result.error();
|
||||
std::lock_guard<std::mutex> relock(mutex_);
|
||||
reportFailure(*state);
|
||||
}
|
||||
return std::unexpected(lastError);
|
||||
}
|
||||
|
||||
Api::Result<Api::TrackInfo> SourceRouter::resolve(const std::string& query)
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(mutex_);
|
||||
auto candidates = candidatesFor(query, false);
|
||||
lock.unlock();
|
||||
|
||||
Api::Error lastError{Api::ErrorCode::NotFound,
|
||||
"No source can resolve this query"};
|
||||
for (auto* state : candidates) {
|
||||
if (!state->source->isAvailable()) {
|
||||
continue;
|
||||
}
|
||||
Void::Log::debug(
|
||||
"SourceRouter", "{}",
|
||||
std::format("Resolving '{}' via {}", query,
|
||||
state->source->name()));
|
||||
auto result = state->source->resolve(query);
|
||||
if (result) {
|
||||
return result;
|
||||
}
|
||||
lastError = result.error();
|
||||
std::lock_guard<std::mutex> relock(mutex_);
|
||||
reportFailure(*state);
|
||||
}
|
||||
return std::unexpected(lastError);
|
||||
}
|
||||
|
||||
Api::Result<StreamHandle>
|
||||
SourceRouter::getStream(const Api::TrackInfo& track)
|
||||
{
|
||||
const std::string cacheKey =
|
||||
track.id.empty() ? track.originalUrl : track.id;
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
auto it = streamCache_.find(cacheKey);
|
||||
if (it != streamCache_.end()) {
|
||||
if (it->second.expiry > std::chrono::steady_clock::now()) {
|
||||
Void::Log::debug(
|
||||
"SourceRouter", "{}",
|
||||
std::format("Stream cache hit for {}", cacheKey));
|
||||
return it->second.handle;
|
||||
}
|
||||
streamCache_.erase(it);
|
||||
}
|
||||
}
|
||||
|
||||
// Which query represents this track for canHandle()? The original
|
||||
// URL (or the id for search-resolved YouTube tracks).
|
||||
const std::string query =
|
||||
!track.originalUrl.empty() ? track.originalUrl : track.id;
|
||||
|
||||
std::unique_lock<std::mutex> lock(mutex_);
|
||||
auto candidates = candidatesFor(query, false);
|
||||
const auto hedgeDelay = hedgeDelay_;
|
||||
lock.unlock();
|
||||
|
||||
std::vector<SourceState*> eligible;
|
||||
for (auto* state : candidates) {
|
||||
if (state->source->isAvailable()) {
|
||||
eligible.push_back(state);
|
||||
}
|
||||
}
|
||||
|
||||
Api::Error lastError{Api::ErrorCode::NotFound,
|
||||
"No source produced a stream"};
|
||||
const auto finish =
|
||||
[&](Api::Result<StreamHandle> handle)
|
||||
-> Api::Result<StreamHandle> {
|
||||
std::lock_guard<std::mutex> relock(mutex_);
|
||||
// Local files are single-use (deleted after playback) — do
|
||||
// not serve them from cache.
|
||||
if (handle && !handle->isLocalFile) {
|
||||
streamCache_[cacheKey] = CachedStream{
|
||||
.handle = *handle,
|
||||
.expiry = std::chrono::steady_clock::now() +
|
||||
ttlFor(*handle)};
|
||||
}
|
||||
return handle;
|
||||
};
|
||||
|
||||
std::size_t index = 0;
|
||||
|
||||
// Hedge the first two candidates: run A, and if it hasn't answered
|
||||
// within hedgeDelay, race B against it — first success wins. Cuts
|
||||
// tail latency when an instance is slow or dying instead of waiting
|
||||
// out its full timeout.
|
||||
if (hedgeDelay.count() > 0 && eligible.size() >= 2) {
|
||||
struct HedgeState {
|
||||
std::mutex m;
|
||||
std::condition_variable cv;
|
||||
std::optional<Api::Result<StreamHandle>> winner;
|
||||
std::array<bool, 2> failed{false, false};
|
||||
std::array<Api::Error, 2> errors{};
|
||||
int finished = 0;
|
||||
};
|
||||
auto state = std::make_shared<HedgeState>();
|
||||
auto trackCopy = track;
|
||||
|
||||
// Detached workers own shared_ptrs to the source and the state
|
||||
// only — nothing that can dangle if a straggler outlives us.
|
||||
const auto launch = [&state, &trackCopy](
|
||||
std::shared_ptr<ITrackSource> source,
|
||||
int slot) {
|
||||
std::thread([source, state, trackCopy, slot]() {
|
||||
auto result = source->getStream(trackCopy);
|
||||
std::lock_guard<std::mutex> lk(state->m);
|
||||
++state->finished;
|
||||
if (result && !state->winner) {
|
||||
state->winner = std::move(result);
|
||||
} else if (!result) {
|
||||
state->failed[static_cast<size_t>(slot)] = true;
|
||||
state->errors[static_cast<size_t>(slot)] =
|
||||
result.error();
|
||||
}
|
||||
state->cv.notify_all();
|
||||
}).detach();
|
||||
};
|
||||
|
||||
launch(eligible[0]->source, 0);
|
||||
int launched = 1;
|
||||
std::optional<Api::Result<StreamHandle>> winner;
|
||||
std::array<bool, 2> failed{false, false};
|
||||
std::array<Api::Error, 2> errors{};
|
||||
{
|
||||
std::unique_lock<std::mutex> lk(state->m);
|
||||
state->cv.wait_for(lk, hedgeDelay, [&] {
|
||||
return state->winner.has_value() ||
|
||||
state->finished >= 1;
|
||||
});
|
||||
if (!state->winner) {
|
||||
// A is slow or already failed: bring in B.
|
||||
lk.unlock();
|
||||
launch(eligible[1]->source, 1);
|
||||
launched = 2;
|
||||
lk.lock();
|
||||
state->cv.wait(lk, [&] {
|
||||
return state->winner.has_value() ||
|
||||
state->finished >= launched;
|
||||
});
|
||||
}
|
||||
winner = state->winner;
|
||||
failed = state->failed;
|
||||
errors = state->errors;
|
||||
}
|
||||
|
||||
// Cooldown accounting for candidates that failed by now
|
||||
// (stragglers that fail later are simply not recorded).
|
||||
{
|
||||
std::lock_guard<std::mutex> relock(mutex_);
|
||||
for (int slot = 0; slot < launched; ++slot) {
|
||||
if (failed[static_cast<size_t>(slot)]) {
|
||||
lastError = errors[static_cast<size_t>(slot)];
|
||||
Void::Log::warn(
|
||||
"SourceRouter", "{}",
|
||||
std::format(
|
||||
"Source '{}' failed stream for '{}': {}",
|
||||
eligible[static_cast<size_t>(slot)]
|
||||
->source->name(),
|
||||
cacheKey, lastError.message));
|
||||
reportFailure(
|
||||
*eligible[static_cast<size_t>(slot)]);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (winner) {
|
||||
return finish(std::move(*winner));
|
||||
}
|
||||
index = 2;
|
||||
}
|
||||
|
||||
// Sequential pass over the remaining candidates (or all of them
|
||||
// when hedging is disabled).
|
||||
for (; index < eligible.size(); ++index) {
|
||||
auto* state = eligible[index];
|
||||
auto handle = state->source->getStream(track);
|
||||
if (handle) {
|
||||
return finish(std::move(handle));
|
||||
}
|
||||
lastError = handle.error();
|
||||
Void::Log::warn(
|
||||
"SourceRouter", "{}",
|
||||
std::format("Source '{}' failed stream for '{}': {}",
|
||||
state->source->name(), cacheKey,
|
||||
handle.error().message));
|
||||
std::lock_guard<std::mutex> relock(mutex_);
|
||||
reportFailure(*state);
|
||||
}
|
||||
return std::unexpected(lastError);
|
||||
}
|
||||
|
||||
void SourceRouter::invalidate(const std::string& trackId)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (auto it = streamCache_.find(trackId); it != streamCache_.end()) {
|
||||
Void::Log::info(
|
||||
"SourceRouter", "{}",
|
||||
std::format("Invalidated cached stream for {} (source {})",
|
||||
trackId, it->second.handle.sourceName));
|
||||
streamCache_.erase(it);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,485 @@
|
||||
#include "echoion/core/sources/YandexMusicSource.hpp"
|
||||
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
#include <openssl/evp.h>
|
||||
#include <regex>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
namespace
|
||||
{
|
||||
constexpr const char* kDefaultEndpoint = "https://api.music.yandex.net";
|
||||
// The signing salt of the classic get-mp3 scheme (public knowledge,
|
||||
// same value every unofficial client uses).
|
||||
constexpr const char* kSignSalt = "XGRlBW9FXlekgbPrRHuSiA";
|
||||
|
||||
std::string md5hex(const std::string& data)
|
||||
{
|
||||
unsigned char digest[EVP_MAX_MD_SIZE];
|
||||
unsigned int length = 0;
|
||||
if (EVP_Digest(data.data(), data.size(), digest, &length, EVP_md5(),
|
||||
nullptr) != 1) {
|
||||
return {};
|
||||
}
|
||||
static constexpr char hex[] = "0123456789abcdef";
|
||||
std::string out;
|
||||
out.reserve(length * 2);
|
||||
for (unsigned int i = 0; i < length; ++i) {
|
||||
out.push_back(hex[digest[i] >> 4]);
|
||||
out.push_back(hex[digest[i] & 0xF]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// music.yandex.ru/album/123/track/456 and friends.
|
||||
std::optional<std::string> extractTrackId(const std::string& url)
|
||||
{
|
||||
static const std::regex albumTrack(
|
||||
R"(music\.yandex\.[a-z]+/album/\d+/track/(\d+))");
|
||||
static const std::regex bareTrack(
|
||||
R"(music\.yandex\.[a-z]+/track/(\d+))");
|
||||
std::smatch match;
|
||||
if (std::regex_search(url, match, albumTrack) ||
|
||||
std::regex_search(url, match, bareTrack)) {
|
||||
return match[1].str();
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
bool isAlbumUrl(const std::string& url)
|
||||
{
|
||||
static const std::regex albumOnly(
|
||||
R"(music\.yandex\.[a-z]+/album/\d+/?($|\?))");
|
||||
return std::regex_search(url, albumOnly);
|
||||
}
|
||||
|
||||
bool isPlaylistUrl(const std::string& url)
|
||||
{
|
||||
static const std::regex playlist(
|
||||
R"(music\.yandex\.[a-z]+/users/[^/]+/playlists/\d+)");
|
||||
return std::regex_search(url, playlist);
|
||||
}
|
||||
|
||||
std::string percentEncode(std::string_view text)
|
||||
{
|
||||
static constexpr char hex[] = "0123456789ABCDEF";
|
||||
std::string out;
|
||||
out.reserve(text.size() * 3);
|
||||
for (unsigned char c : text) {
|
||||
const bool unreserved = (c >= 'A' && c <= 'Z') ||
|
||||
(c >= 'a' && c <= 'z') ||
|
||||
(c >= '0' && c <= '9') || c == '-' ||
|
||||
c == '_' || c == '.' || c == '~';
|
||||
if (unreserved) {
|
||||
out.push_back(static_cast<char>(c));
|
||||
} else {
|
||||
out.push_back('%');
|
||||
out.push_back(hex[c >> 4]);
|
||||
out.push_back(hex[c & 0xF]);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string str(const Void::Json::Value& v, const char* key)
|
||||
{
|
||||
const auto* f = v.find(key);
|
||||
return (f && f->is_string()) ? f->as_string() : std::string{};
|
||||
}
|
||||
|
||||
int64_t num(const Void::Json::Value& v, const char* key)
|
||||
{
|
||||
const auto* f = v.find(key);
|
||||
if (!f) {
|
||||
return 0;
|
||||
}
|
||||
if (f->is_number()) {
|
||||
return static_cast<int64_t>(f->as_number());
|
||||
}
|
||||
if (f->is_string()) {
|
||||
try {
|
||||
return std::stoll(f->as_string());
|
||||
} catch (const std::exception&) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
Api::TrackInfo toTrackInfo(const Void::Json::Value& track)
|
||||
{
|
||||
Api::TrackInfo t;
|
||||
t.id = "yandex:" + std::format("{}", num(track, "id"));
|
||||
if (const auto* idField = track.find("id");
|
||||
idField && idField->is_string()) {
|
||||
t.id = "yandex:" + idField->as_string();
|
||||
}
|
||||
t.title = str(track, "title");
|
||||
if (const auto* artists = track.find("artists");
|
||||
artists && artists->is_array()) {
|
||||
for (const auto& artist : artists->as_array()) {
|
||||
if (!t.artist.empty()) {
|
||||
t.artist += ", ";
|
||||
}
|
||||
t.artist += str(artist, "name");
|
||||
}
|
||||
}
|
||||
const auto durationMs = num(track, "durationMs");
|
||||
if (durationMs > 0) {
|
||||
t.duration = std::chrono::milliseconds(durationMs);
|
||||
}
|
||||
auto cover = str(track, "coverUri");
|
||||
if (!cover.empty()) {
|
||||
if (auto pos = cover.find("%%"); pos != std::string::npos) {
|
||||
cover.replace(pos, 2, "200x200");
|
||||
}
|
||||
t.thumbnailUrl = "https://" + cover;
|
||||
}
|
||||
// Track id is enough to rebuild a canonical URL.
|
||||
std::string plainId = t.id.substr(std::string("yandex:").size());
|
||||
int64_t albumId = 0;
|
||||
if (const auto* albums = track.find("albums");
|
||||
albums && albums->is_array() && !albums->as_array().empty()) {
|
||||
albumId = num(albums->as_array().front(), "id");
|
||||
}
|
||||
t.originalUrl =
|
||||
albumId > 0
|
||||
? std::format("https://music.yandex.com/album/{}/track/{}",
|
||||
albumId, plainId)
|
||||
: std::format("https://music.yandex.com/track/{}", plainId);
|
||||
t.source = Api::TrackSource::Yandex;
|
||||
t.addedAt = std::chrono::system_clock::now();
|
||||
return t;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
YandexMusicSource::YandexMusicSource(std::shared_ptr<NetworkClient> network,
|
||||
std::string endpointOverride)
|
||||
: network_(std::move(network)),
|
||||
endpoint_(endpointOverride.empty() ? kDefaultEndpoint
|
||||
: std::move(endpointOverride))
|
||||
{
|
||||
}
|
||||
|
||||
void YandexMusicSource::configure(bool enabled, std::string token)
|
||||
{
|
||||
enabled_ = enabled;
|
||||
std::lock_guard<std::mutex> lock(tokenMutex_);
|
||||
token_ = std::move(token);
|
||||
}
|
||||
|
||||
std::string YandexMusicSource::tokenSnapshot() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(tokenMutex_);
|
||||
return token_;
|
||||
}
|
||||
|
||||
bool YandexMusicSource::canHandle(const std::string& query) const
|
||||
{
|
||||
if (!isAvailable()) {
|
||||
return false;
|
||||
}
|
||||
return extractTrackId(query).has_value() || isAlbumUrl(query) ||
|
||||
isPlaylistUrl(query);
|
||||
}
|
||||
|
||||
bool YandexMusicSource::isAvailable() const
|
||||
{
|
||||
return enabled_.load() && !tokenSnapshot().empty();
|
||||
}
|
||||
|
||||
Api::Result<Api::SearchResult>
|
||||
YandexMusicSource::search(std::string_view query)
|
||||
{
|
||||
if (!isAvailable()) {
|
||||
return Api::fail(Api::ErrorCode::ServiceUnavailable,
|
||||
"Yandex Music not configured");
|
||||
}
|
||||
|
||||
auto body =
|
||||
apiGet("/search?type=track&page=0&text=" + percentEncode(query));
|
||||
if (!body) {
|
||||
return std::unexpected(body.error());
|
||||
}
|
||||
auto parsed = Void::Json::parse(*body);
|
||||
if (!parsed) {
|
||||
return Api::fail(Api::ErrorCode::ParseError,
|
||||
"Invalid Yandex search response");
|
||||
}
|
||||
|
||||
Api::SearchResult result;
|
||||
result.query = std::string(query);
|
||||
const auto* root = parsed->find("result");
|
||||
const auto* tracks = root ? root->find("tracks") : nullptr;
|
||||
const auto* items = tracks ? tracks->find("results") : nullptr;
|
||||
if (items && items->is_array()) {
|
||||
for (const auto& item : items->as_array()) {
|
||||
auto track = toTrackInfo(item);
|
||||
if (!track.title.empty()) {
|
||||
result.tracks.push_back(std::move(track));
|
||||
}
|
||||
}
|
||||
}
|
||||
result.totalResults = static_cast<uint32_t>(result.tracks.size());
|
||||
return result;
|
||||
}
|
||||
|
||||
Api::Result<std::vector<Api::TrackInfo>>
|
||||
YandexMusicSource::related(const std::string& trackId, size_t limit)
|
||||
{
|
||||
if (!isAvailable()) {
|
||||
return Api::fail(Api::ErrorCode::ServiceUnavailable,
|
||||
"Yandex Music not configured");
|
||||
}
|
||||
|
||||
// /tracks/{id}/similar returns result.similarTracks[] — the same
|
||||
// track shape toTrackInfo already understands.
|
||||
auto body = apiGet("/tracks/" + trackId + "/similar");
|
||||
if (!body) {
|
||||
return std::unexpected(body.error());
|
||||
}
|
||||
auto parsed = Void::Json::parse(*body);
|
||||
if (!parsed) {
|
||||
return Api::fail(Api::ErrorCode::ParseError,
|
||||
"Invalid Yandex similar-tracks response");
|
||||
}
|
||||
|
||||
std::vector<Api::TrackInfo> tracks;
|
||||
const auto* root = parsed->find("result");
|
||||
const auto* items = root ? root->find("similarTracks") : nullptr;
|
||||
if (items && items->is_array()) {
|
||||
for (const auto& item : items->as_array()) {
|
||||
if (tracks.size() >= limit) {
|
||||
break;
|
||||
}
|
||||
auto track = toTrackInfo(item);
|
||||
if (!track.title.empty()) {
|
||||
track.requestedBy = "radio\\autoplay";
|
||||
tracks.push_back(std::move(track));
|
||||
}
|
||||
}
|
||||
}
|
||||
return tracks;
|
||||
}
|
||||
|
||||
std::optional<std::string>
|
||||
YandexMusicSource::trackIdFromUrl(const std::string& url) const
|
||||
{
|
||||
return extractTrackId(url);
|
||||
}
|
||||
|
||||
Api::Result<std::string> YandexMusicSource::apiGet(const std::string& path)
|
||||
{
|
||||
// Deliberately proxy-less (getDirect): Yandex may geo-block foreign
|
||||
// proxy exits, and it is reachable directly here.
|
||||
auto resp = network_->getDirect(
|
||||
endpoint_ + path, {{"Authorization", "OAuth " + tokenSnapshot()}});
|
||||
if (!resp) {
|
||||
return std::unexpected(resp.error());
|
||||
}
|
||||
if (resp->status != 200) {
|
||||
return Api::fail(
|
||||
Api::ErrorCode::NetworkError,
|
||||
std::format("Yandex API returned HTTP {}", resp->status));
|
||||
}
|
||||
return resp->body;
|
||||
}
|
||||
|
||||
Api::Result<Api::TrackInfo>
|
||||
YandexMusicSource::resolve(const std::string& urlOrId)
|
||||
{
|
||||
auto trackId = extractTrackId(urlOrId);
|
||||
if (!trackId) {
|
||||
// Collections resolve to their first track (the router contract
|
||||
// wants one TrackInfo; full import goes through playlistTracks).
|
||||
if (isCollectionUrl(urlOrId)) {
|
||||
auto tracks = playlistTracks(urlOrId);
|
||||
if (!tracks) {
|
||||
return std::unexpected(tracks.error());
|
||||
}
|
||||
if (tracks->empty()) {
|
||||
return Api::fail(Api::ErrorCode::NotFound,
|
||||
"Collection is empty");
|
||||
}
|
||||
return tracks->front();
|
||||
}
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"Not a Yandex Music URL");
|
||||
}
|
||||
|
||||
auto body = apiGet("/tracks/" + *trackId);
|
||||
if (!body) {
|
||||
return std::unexpected(body.error());
|
||||
}
|
||||
auto parsed = Void::Json::parse(*body);
|
||||
if (!parsed) {
|
||||
return Api::fail(Api::ErrorCode::ParseError,
|
||||
"Invalid Yandex track response");
|
||||
}
|
||||
const auto* result = parsed->find("result");
|
||||
if (!result || !result->is_array() || result->as_array().empty()) {
|
||||
return Api::fail(Api::ErrorCode::NotFound, "Track not found");
|
||||
}
|
||||
return toTrackInfo(result->as_array().front());
|
||||
}
|
||||
|
||||
Api::Result<StreamHandle>
|
||||
YandexMusicSource::getStream(const Api::TrackInfo& track)
|
||||
{
|
||||
auto trackId = extractTrackId(track.originalUrl);
|
||||
if (!trackId && track.id.starts_with("yandex:")) {
|
||||
trackId = track.id.substr(std::string("yandex:").size());
|
||||
}
|
||||
if (!trackId) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"Not a Yandex track");
|
||||
}
|
||||
|
||||
// 1) Pick the best MP3 download option.
|
||||
auto infoBody = apiGet("/tracks/" + *trackId + "/download-info");
|
||||
if (!infoBody) {
|
||||
return std::unexpected(infoBody.error());
|
||||
}
|
||||
auto parsed = Void::Json::parse(*infoBody);
|
||||
if (!parsed) {
|
||||
return Api::fail(Api::ErrorCode::ParseError,
|
||||
"Invalid download-info response");
|
||||
}
|
||||
const auto* result = parsed->find("result");
|
||||
if (!result || !result->is_array()) {
|
||||
return Api::fail(Api::ErrorCode::NotFound, "No download options");
|
||||
}
|
||||
std::string infoUrl;
|
||||
int64_t bestBitrate = -1;
|
||||
for (const auto& option : result->as_array()) {
|
||||
if (str(option, "codec") != "mp3") {
|
||||
continue;
|
||||
}
|
||||
const auto bitrate = num(option, "bitrateInKbps");
|
||||
if (bitrate > bestBitrate) {
|
||||
bestBitrate = bitrate;
|
||||
infoUrl = str(option, "downloadInfoUrl");
|
||||
}
|
||||
}
|
||||
if (infoUrl.empty()) {
|
||||
return Api::fail(Api::ErrorCode::NotFound,
|
||||
"No MP3 download option");
|
||||
}
|
||||
|
||||
// 2) Fetch the XML descriptor and build the signed URL.
|
||||
auto xmlResp = network_->getDirect(infoUrl);
|
||||
if (!xmlResp || xmlResp->status != 200) {
|
||||
return Api::fail(Api::ErrorCode::NetworkError,
|
||||
"Failed to fetch download descriptor");
|
||||
}
|
||||
const std::string& xml = xmlResp->body;
|
||||
auto field = [&xml](const char* tag) -> std::string {
|
||||
const std::regex re(std::format("<{0}>([^<]*)</{0}>", tag));
|
||||
std::smatch match;
|
||||
if (std::regex_search(xml, match, re)) {
|
||||
return match[1].str();
|
||||
}
|
||||
return {};
|
||||
};
|
||||
const std::string host = field("host");
|
||||
const std::string path = field("path");
|
||||
const std::string ts = field("ts");
|
||||
const std::string s = field("s");
|
||||
if (host.empty() || path.empty() || s.empty()) {
|
||||
return Api::fail(Api::ErrorCode::ParseError,
|
||||
"Malformed download descriptor");
|
||||
}
|
||||
|
||||
const std::string sign = md5hex(kSignSalt + path.substr(1) + s);
|
||||
if (sign.empty()) {
|
||||
return Api::fail(Api::ErrorCode::UnknownError, "MD5 failed");
|
||||
}
|
||||
|
||||
std::string url =
|
||||
std::format("https://{}/get-mp3/{}/{}{}", host, sign, ts, path);
|
||||
Void::Log::info("YandexMusicSource", "{}",
|
||||
std::format("Resolved stream for track {}", *trackId));
|
||||
return StreamHandle{.url = std::move(url),
|
||||
.isLocalFile = false,
|
||||
.sourceName = "yandex"};
|
||||
}
|
||||
|
||||
bool YandexMusicSource::isCollectionUrl(const std::string& url) const
|
||||
{
|
||||
return isAlbumUrl(url) || isPlaylistUrl(url);
|
||||
}
|
||||
|
||||
Api::Result<std::vector<Api::TrackInfo>>
|
||||
YandexMusicSource::playlistTracks(const std::string& url)
|
||||
{
|
||||
std::vector<Api::TrackInfo> tracks;
|
||||
|
||||
if (isAlbumUrl(url)) {
|
||||
static const std::regex albumRe(
|
||||
R"(music\.yandex\.[a-z]+/album/(\d+))");
|
||||
std::smatch match;
|
||||
if (!std::regex_search(url, match, albumRe)) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"Bad album URL");
|
||||
}
|
||||
auto body = apiGet("/albums/" + match[1].str() + "/with-tracks");
|
||||
if (!body) {
|
||||
return std::unexpected(body.error());
|
||||
}
|
||||
auto parsed = Void::Json::parse(*body);
|
||||
if (!parsed) {
|
||||
return Api::fail(Api::ErrorCode::ParseError,
|
||||
"Invalid album response");
|
||||
}
|
||||
const auto* result = parsed->find("result");
|
||||
const auto* volumes = result ? result->find("volumes") : nullptr;
|
||||
if (volumes && volumes->is_array()) {
|
||||
for (const auto& volume : volumes->as_array()) {
|
||||
if (!volume.is_array()) {
|
||||
continue;
|
||||
}
|
||||
for (const auto& track : volume.as_array()) {
|
||||
tracks.push_back(toTrackInfo(track));
|
||||
}
|
||||
}
|
||||
}
|
||||
return tracks;
|
||||
}
|
||||
|
||||
if (isPlaylistUrl(url)) {
|
||||
static const std::regex playlistRe(
|
||||
R"(music\.yandex\.[a-z]+/users/([^/]+)/playlists/(\d+))");
|
||||
std::smatch match;
|
||||
if (!std::regex_search(url, match, playlistRe)) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"Bad playlist URL");
|
||||
}
|
||||
auto body = apiGet("/users/" + match[1].str() + "/playlists/" +
|
||||
match[2].str());
|
||||
if (!body) {
|
||||
return std::unexpected(body.error());
|
||||
}
|
||||
auto parsed = Void::Json::parse(*body);
|
||||
if (!parsed) {
|
||||
return Api::fail(Api::ErrorCode::ParseError,
|
||||
"Invalid playlist response");
|
||||
}
|
||||
const auto* result = parsed->find("result");
|
||||
const auto* items = result ? result->find("tracks") : nullptr;
|
||||
if (items && items->is_array()) {
|
||||
for (const auto& item : items->as_array()) {
|
||||
if (const auto* track = item.find("track")) {
|
||||
tracks.push_back(toTrackInfo(*track));
|
||||
}
|
||||
}
|
||||
}
|
||||
return tracks;
|
||||
}
|
||||
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"Not a Yandex collection URL");
|
||||
}
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,132 @@
|
||||
#include "echoion/core/sources/YtDlpSource.hpp"
|
||||
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <algorithm>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
namespace
|
||||
{
|
||||
bool isYouTubeQuery(const std::string& query)
|
||||
{
|
||||
return query.find("youtube.com") != std::string::npos ||
|
||||
query.find("youtu.be") != std::string::npos;
|
||||
}
|
||||
|
||||
bool isUrl(const std::string& query)
|
||||
{
|
||||
return query.find("://") != std::string::npos;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
YtDlpSource::YtDlpSource(std::shared_ptr<YouTubeClient> client, Mode mode,
|
||||
std::string tempDir) :
|
||||
client_(std::move(client)), mode_(mode), tempDir_(std::move(tempDir))
|
||||
{
|
||||
}
|
||||
|
||||
bool YtDlpSource::canHandle(const std::string& query) const
|
||||
{
|
||||
if (mode_ == Mode::Direct) {
|
||||
// Only extractor page URLs that are NOT YouTube (native YouTube
|
||||
// resolution is what the innertube source is for).
|
||||
return isUrl(query) && !isYouTubeQuery(query);
|
||||
}
|
||||
// Proxied: anything — YouTube URLs, other URLs, text search.
|
||||
return true;
|
||||
}
|
||||
|
||||
bool YtDlpSource::isAvailable() const
|
||||
{
|
||||
return client_ && client_->isAvailable();
|
||||
}
|
||||
|
||||
Api::Result<Api::SearchResult> YtDlpSource::search(std::string_view query)
|
||||
{
|
||||
if (mode_ == Mode::Direct) {
|
||||
return Api::fail(Api::ErrorCode::NotSupported,
|
||||
"ytdlp-direct does not search");
|
||||
}
|
||||
return client_->search(query);
|
||||
}
|
||||
|
||||
Api::Result<Api::TrackInfo> YtDlpSource::resolve(const std::string& urlOrId)
|
||||
{
|
||||
if (mode_ == Mode::Proxied) {
|
||||
if (isYouTubeQuery(urlOrId)) {
|
||||
if (auto videoId = client_->extractVideoId(urlOrId)) {
|
||||
return client_->getVideoInfo(*videoId);
|
||||
}
|
||||
}
|
||||
if (!isUrl(urlOrId)) {
|
||||
auto results = client_->search(urlOrId);
|
||||
if (!results) {
|
||||
return std::unexpected(results.error());
|
||||
}
|
||||
if (results->tracks.empty()) {
|
||||
return Api::fail(Api::ErrorCode::NotFound,
|
||||
"No results found");
|
||||
}
|
||||
return results->tracks.front();
|
||||
}
|
||||
}
|
||||
|
||||
// Non-YouTube page URL: synthesise minimal metadata; the stream
|
||||
// resolution does the heavy lifting.
|
||||
Api::TrackInfo t;
|
||||
t.id = urlOrId;
|
||||
t.title = urlOrId;
|
||||
t.source = Api::TrackSource::URL;
|
||||
t.originalUrl = urlOrId;
|
||||
t.addedAt = std::chrono::system_clock::now();
|
||||
return t;
|
||||
}
|
||||
|
||||
Api::Result<StreamHandle> YtDlpSource::getStream(const Api::TrackInfo& track)
|
||||
{
|
||||
if (mode_ == Mode::Proxied &&
|
||||
track.source == Api::TrackSource::YouTube) {
|
||||
if (auto videoId = client_->extractVideoId(track.originalUrl)) {
|
||||
auto url = client_->getStreamUrl(*videoId);
|
||||
if (url) {
|
||||
return StreamHandle{.url = std::move(*url),
|
||||
.isLocalFile = false,
|
||||
.sourceName =
|
||||
std::string(name())};
|
||||
}
|
||||
return std::unexpected(url.error());
|
||||
}
|
||||
}
|
||||
|
||||
const std::string& pageUrl =
|
||||
!track.originalUrl.empty() ? track.originalUrl : track.id;
|
||||
auto url = client_->getStreamUrlForPage(pageUrl,
|
||||
mode_ == Mode::Proxied);
|
||||
if (!url) {
|
||||
return std::unexpected(url.error());
|
||||
}
|
||||
return StreamHandle{.url = std::move(*url),
|
||||
.isLocalFile = false,
|
||||
.sourceName = std::string(name())};
|
||||
}
|
||||
|
||||
Api::Result<StreamHandle>
|
||||
YtDlpSource::getStreamViaDownload(const Api::TrackInfo& track)
|
||||
{
|
||||
const std::string idOrUrl =
|
||||
!track.originalUrl.empty() ? track.originalUrl : track.id;
|
||||
if (idOrUrl.empty()) {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"Track has no id/URL to download");
|
||||
}
|
||||
auto path = client_->downloadAudioToFile(idOrUrl, tempDir_);
|
||||
if (!path) {
|
||||
return std::unexpected(path.error());
|
||||
}
|
||||
return StreamHandle{.url = std::move(*path),
|
||||
.isLocalFile = true,
|
||||
.sourceName = std::string(name())};
|
||||
}
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -119,7 +119,7 @@ namespace Echoion::Core
|
||||
try {
|
||||
return static_cast<uint32_t>(
|
||||
std::stoul(jsonStr.substr(pos)));
|
||||
} catch (...) {
|
||||
} catch (const std::exception&) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user