1 parent
df99b6ea7f
commit
d146f11f02
63 files changed
+8331
-2709
No files matched your search
+58
-14
@@ -68,21 +68,44 @@ if(quickjs_SOURCE_DIR)
|
||||
endforeach()
|
||||
endif()
|
||||
|
||||
set(AddBoost.cmake_VERSION 3.7.3)
|
||||
CPMAddPackage(
|
||||
NAME AddBoost.cmake
|
||||
VERSION "${AddBoost.cmake_VERSION}"
|
||||
URL "https://github.com/Arniiiii/AddBoost.cmake/archive/refs/tags/${AddBoost.cmake_VERSION}.tar.gz"
|
||||
)
|
||||
set(TRY_BOOST_VERSION "1.90.0")
|
||||
set(BOOST_MY_OPTIONS "BOOST_ENABLE_PYTHON ON;")
|
||||
set(BOOST_NOT_HEADER_ONLY_COMPONENTS_THAT_YOU_NEED "thread;system")
|
||||
set(BOOST_HEADER_ONLY_COMPONENTS_THAT_YOU_NEED "asio;beast;uuid;container;cobalt;url")
|
||||
# Boost: the process must contain exactly ONE copy of the compiled Boost
|
||||
# libraries. VoidLibrary links the SYSTEM Boost, so EchoionCore must use the
|
||||
# same one — vendoring a second copy (the old AddBoost path fetched 1.90
|
||||
# alongside the system 1.91) put two libboost_url.so versions into the
|
||||
# process and the cross-bound symbols corrupted every parsed URL
|
||||
# (SIGSEGV in boost::urls::url_view). Fall back to fetching only when no
|
||||
# usable system Boost exists (in which case Void fetched the same one).
|
||||
find_package(Boost 1.87 CONFIG QUIET COMPONENTS url thread container)
|
||||
if(Boost_FOUND)
|
||||
message(STATUS "EchoionCore using system Boost ${Boost_VERSION}")
|
||||
# Distros ship CMake configs only for the compiled Boost libraries;
|
||||
# header-only components (asio, beast, uuid) have none. Map the targets
|
||||
# EchoionCore links onto the installed headers.
|
||||
foreach(_hdr asio beast uuid system)
|
||||
if(NOT TARGET Boost::${_hdr})
|
||||
add_library(_boost_${_hdr}_hdr INTERFACE)
|
||||
add_library(Boost::${_hdr} ALIAS _boost_${_hdr}_hdr)
|
||||
target_include_directories(_boost_${_hdr}_hdr INTERFACE
|
||||
"${Boost_INCLUDE_DIRS}")
|
||||
endif()
|
||||
endforeach()
|
||||
else()
|
||||
set(AddBoost.cmake_VERSION 3.7.3)
|
||||
CPMAddPackage(
|
||||
NAME AddBoost.cmake
|
||||
VERSION "${AddBoost.cmake_VERSION}"
|
||||
URL "https://github.com/Arniiiii/AddBoost.cmake/archive/refs/tags/${AddBoost.cmake_VERSION}.tar.gz"
|
||||
)
|
||||
set(TRY_BOOST_VERSION "1.90.0")
|
||||
set(BOOST_MY_OPTIONS "BOOST_ENABLE_PYTHON ON;")
|
||||
set(BOOST_NOT_HEADER_ONLY_COMPONENTS_THAT_YOU_NEED "thread;system")
|
||||
set(BOOST_HEADER_ONLY_COMPONENTS_THAT_YOU_NEED "asio;beast;uuid;container;cobalt;url")
|
||||
|
||||
add_boost(
|
||||
TRY_BOOST_VERSION BOOST_HEADER_ONLY_COMPONENTS_THAT_YOU_NEED
|
||||
BOOST_NOT_HEADER_ONLY_COMPONENTS_THAT_YOU_NEED EchoionCore
|
||||
)
|
||||
add_boost(
|
||||
TRY_BOOST_VERSION BOOST_HEADER_ONLY_COMPONENTS_THAT_YOU_NEED
|
||||
BOOST_NOT_HEADER_ONLY_COMPONENTS_THAT_YOU_NEED EchoionCore
|
||||
)
|
||||
endif()
|
||||
|
||||
find_package(Threads REQUIRED)
|
||||
find_package(OpenSSL REQUIRED)
|
||||
@@ -126,6 +149,27 @@ else()
|
||||
target_compile_options(EchoionCore PRIVATE -Wall -Wextra -Wpedantic)
|
||||
endif()
|
||||
|
||||
# Precompiled headers for the heavy translation units (MusicManager.cpp ~2.4k
|
||||
# lines, Core.cpp, YouTubeClient.cpp). These pull in the same expensive standard
|
||||
# and Void headers, so compiling them once cuts a large slice off build time.
|
||||
# Disabled automatically under unity builds (CMake forbids combining the two).
|
||||
option(ECHOION_ENABLE_PCH "Use precompiled headers for EchoionCore" ON)
|
||||
if(ECHOION_ENABLE_PCH AND NOT CMAKE_UNITY_BUILD)
|
||||
target_precompile_headers(EchoionCore PRIVATE
|
||||
<string>
|
||||
<string_view>
|
||||
<vector>
|
||||
<memory>
|
||||
<optional>
|
||||
<chrono>
|
||||
<format>
|
||||
<mutex>
|
||||
<thread>
|
||||
<atomic>
|
||||
<functional>
|
||||
)
|
||||
endif()
|
||||
|
||||
set_target_properties(EchoionCore PROPERTIES
|
||||
OUTPUT_NAME "Echoion"
|
||||
PREFIX ""
|
||||
|
||||
@@ -5,11 +5,11 @@
|
||||
#include <Types.hpp>
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <deque>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <queue>
|
||||
#include <span>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
// Forward declarations for FFmpeg
|
||||
extern "C" {
|
||||
@@ -18,12 +18,15 @@ struct AVCodecContext;
|
||||
struct AVFrame;
|
||||
struct AVPacket;
|
||||
struct SwrContext;
|
||||
struct AVBufferRef;
|
||||
}
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// FFmpeg-backed streaming decoder. openSource() spawns a decode jthread
|
||||
// that resamples to interleaved S16 at the configured output format and
|
||||
// fills int16Queue_ (bounded, backpressured); the playback side drains it
|
||||
// chunk-by-chunk via getNextChunk().
|
||||
class AudioDecoder
|
||||
{
|
||||
public:
|
||||
@@ -31,18 +34,13 @@ namespace Echoion::Core
|
||||
AudioDecoder();
|
||||
~AudioDecoder();
|
||||
|
||||
// Initialize decoder with optional hardware acceleration
|
||||
Api::Result<void>
|
||||
initialize(const Api::HwAccelConfig& hwConfig = {});
|
||||
Api::Result<void> initialize();
|
||||
void shutdown();
|
||||
|
||||
// Open audio source (URL or file path)
|
||||
Api::Result<void> openSource(const std::string& url);
|
||||
void closeSource();
|
||||
|
||||
// Decode audio - returns zero-copy pooled buffer
|
||||
[[nodiscard]] Api::Result<Api::DecodedAudio> decodeFrame();
|
||||
|
||||
// Seek to position
|
||||
Api::Result<void> seek(std::chrono::milliseconds position);
|
||||
|
||||
@@ -50,50 +48,19 @@ namespace Echoion::Core
|
||||
[[nodiscard]] Api::Result<Api::AudioStreamInfo>
|
||||
getStreamInfo() const;
|
||||
|
||||
// Get current position
|
||||
// Get current decode position (runs ahead of playback by up to
|
||||
// the queued chunk depth; use MusicManager for playback position)
|
||||
[[nodiscard]] std::chrono::milliseconds getPosition() const;
|
||||
|
||||
// Check if decoder has more data
|
||||
[[nodiscard]] bool hasMoreData() const;
|
||||
|
||||
// Set output format
|
||||
void setOutputFormat(uint32_t sampleRate, uint32_t channels);
|
||||
|
||||
// Set proxy configuration for network requests
|
||||
void setProxyConfig(const std::optional<Void::Net::ProxyConfig>& proxy);
|
||||
|
||||
// Hardware acceleration
|
||||
[[nodiscard]] bool isHardwareAccelerated() const
|
||||
{
|
||||
return hwAccelEnabled_;
|
||||
}
|
||||
[[nodiscard]] Api::HwAccelType getHwAccelType() const
|
||||
{
|
||||
return hwAccelType_;
|
||||
}
|
||||
|
||||
// Enable/disable zero-copy mode
|
||||
void setZeroCopyEnabled(bool enabled)
|
||||
{
|
||||
zeroCopyEnabled_ = enabled;
|
||||
}
|
||||
[[nodiscard]] bool isZeroCopyEnabled() const
|
||||
{
|
||||
return zeroCopyEnabled_;
|
||||
}
|
||||
|
||||
// Get decoder statistics
|
||||
struct Stats {
|
||||
uint64_t framesDecoded = 0;
|
||||
uint64_t framesDropped = 0;
|
||||
uint64_t bytesDecoded = 0;
|
||||
std::chrono::milliseconds totalDecodeTime{0};
|
||||
double averageDecodeTimeMs = 0.0;
|
||||
bool hwAccelerationActive = false;
|
||||
};
|
||||
[[nodiscard]] Stats getStats() const;
|
||||
|
||||
// Get next S16 chunk (like reference implementation)
|
||||
// Get next S16 chunk. Swaps the caller's buffer for the queued
|
||||
// one, so the caller's previous storage is recycled into the
|
||||
// decode free-list — no per-chunk copy or allocation.
|
||||
bool getNextChunk(std::vector<int16_t>& outChunk,
|
||||
bool blocking = false);
|
||||
|
||||
@@ -103,18 +70,12 @@ namespace Echoion::Core
|
||||
private:
|
||||
|
||||
void decodeThread();
|
||||
Api::Result<void> readPacket();
|
||||
Api::Result<Api::DecodedAudio> convertFrame();
|
||||
// Borrow a chunk buffer of `samples` length from the recycle
|
||||
// free-list (reusing pooled storage), or allocate one if the
|
||||
// free-list is empty.
|
||||
std::vector<int16_t> acquireChunkBuffer(size_t samples);
|
||||
void cleanupFfmpeg();
|
||||
|
||||
// Hardware acceleration setup
|
||||
Api::Result<void>
|
||||
initializeHardwareAccel(const Api::HwAccelConfig& config);
|
||||
void cleanupHardwareAccel();
|
||||
|
||||
// Frame conversion (returns int16 for direct playback)
|
||||
Api::Result<Api::DecodedAudio> convertFramePooled();
|
||||
|
||||
// FFmpeg contexts
|
||||
AVFormatContext* formatContext_ = nullptr;
|
||||
AVCodecContext* codecContext_ = nullptr;
|
||||
@@ -123,13 +84,6 @@ namespace Echoion::Core
|
||||
SwrContext* swrContext_ = nullptr;
|
||||
uint8_t* outputBuffer_ = nullptr; // For S16 output like reference
|
||||
|
||||
// Hardware acceleration
|
||||
AVBufferRef* hwDeviceContext_ = nullptr;
|
||||
AVBufferRef* hwFramesContext_ = nullptr;
|
||||
bool hwAccelEnabled_ = false;
|
||||
Api::HwAccelType hwAccelType_ = Api::HwAccelType::None;
|
||||
bool zeroCopyEnabled_ = true;
|
||||
|
||||
// Stream info
|
||||
int audioStreamIndex_ = -1;
|
||||
Api::AudioStreamInfo streamInfo_;
|
||||
@@ -142,28 +96,30 @@ namespace Echoion::Core
|
||||
std::jthread decodeThread_;
|
||||
mutable std::mutex mutex_;
|
||||
std::condition_variable cv_;
|
||||
std::queue<Api::DecodedAudio> decodedQueue_;
|
||||
static constexpr size_t MAX_QUEUE_SIZE = 50;
|
||||
|
||||
// S16 audio queue (like reference) - avoids float conversion
|
||||
std::deque<std::vector<int16_t>> int16Queue_;
|
||||
static constexpr size_t MAX_INT16_QUEUE_SIZE = 100;
|
||||
|
||||
// Free-list of recycled chunk buffers. getNextChunk() swaps the
|
||||
// caller's previous buffer in here and decodeThread() reuses that
|
||||
// storage instead of allocating a fresh vector per frame.
|
||||
// Guarded by mutex_ (same as int16Queue_).
|
||||
std::vector<std::vector<int16_t>> recycledChunks_;
|
||||
|
||||
// State
|
||||
std::atomic<bool> initialized_{false};
|
||||
std::atomic<bool> decoding_{false};
|
||||
std::atomic<bool> eof_{false};
|
||||
std::atomic<bool> shouldExit_{
|
||||
false}; // For FFmpeg interrupt callback
|
||||
std::chrono::milliseconds currentPosition_{0};
|
||||
// Decode position in ms; written by the decode thread per frame,
|
||||
// read cross-thread by getPosition() (prefetch decisions).
|
||||
std::atomic<int64_t> currentPositionMs_{0};
|
||||
std::string currentUrl_;
|
||||
|
||||
std::atomic<uint32_t> streamSampleRate_{48000};
|
||||
std::optional<Void::Net::ProxyConfig> proxyConfig_;
|
||||
|
||||
// Statistics
|
||||
mutable std::mutex statsMutex_;
|
||||
Stats stats_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,39 +1,52 @@
|
||||
#pragma once
|
||||
|
||||
#include "AudioDecoder.hpp"
|
||||
#include "Database.hpp"
|
||||
#include "NetworkClient.hpp"
|
||||
#include "PlaylistLoader.hpp"
|
||||
#include "QueueManager.hpp"
|
||||
#include "RpcTypes.hpp"
|
||||
#include "SubscriptionManager.hpp"
|
||||
#include "SubscriptionService.hpp"
|
||||
#include "TrackCache.hpp"
|
||||
#include "YouTubeClient.hpp"
|
||||
#include "playback/PlaybackEngine.hpp"
|
||||
#include "playback/QueueService.hpp"
|
||||
#include "sources/InnertubeSource.hpp"
|
||||
#include "sources/YandexMusicSource.hpp"
|
||||
#include "sources/SourceRouter.hpp"
|
||||
#include "sources/YtDlpSource.hpp"
|
||||
#include <ConfigManager.hpp>
|
||||
#include <ConfigTypes.hpp>
|
||||
#include <TrackTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <Void/Async/EventBus.hpp>
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <filesystem>
|
||||
#include <future>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <queue>
|
||||
#include <random>
|
||||
#include <optional>
|
||||
#include <set>
|
||||
#include <shared_mutex>
|
||||
#include <thread>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class MusicManager
|
||||
// Facade over the playback services. Public surface is unchanged (Core,
|
||||
// the RPC handlers and ~27 commands call it); internally it wires:
|
||||
// - PlaybackEngine: real-time loop, both decoders, gapless handoff
|
||||
// - QueueService: queue + shuffle/repeat (self-locking)
|
||||
// - SubscriptionService: audience bookkeeping + pause-on-empty policy
|
||||
// and implements IPlaybackHost for the engine (stream resolution, queue
|
||||
// access, event publication).
|
||||
class MusicManager : private IPlaybackHost
|
||||
{
|
||||
public:
|
||||
|
||||
MusicManager();
|
||||
~MusicManager();
|
||||
~MusicManager() override;
|
||||
|
||||
Api::Result<void>
|
||||
initialize(std::shared_ptr<NetworkClient> networkClient,
|
||||
@@ -53,7 +66,7 @@ namespace Echoion::Core
|
||||
|
||||
// Re-apply network settings (proxy) to every outbound client:
|
||||
// the HTTP NetworkClient (YouTube Data API, URL shortener), the
|
||||
// yt-dlp subprocess, and the ffmpeg AudioDecoder. Call after a
|
||||
// yt-dlp subprocess, and the ffmpeg decoders. Call after a
|
||||
// config reload so proxy changes actually take effect everywhere
|
||||
// instead of only living in the config copy.
|
||||
void applyNetworkConfig(const Api::NetworkConfig& network);
|
||||
@@ -63,6 +76,20 @@ namespace Echoion::Core
|
||||
// an empty/absent API key clears it, restoring the yt-dlp fallback.
|
||||
void applyYouTubeConfig(const Api::YouTubeConfig& youtube);
|
||||
|
||||
// Re-apply the source-chain settings (order, cooldown, instance
|
||||
// lists) after a config reload.
|
||||
void applySourcesConfig(const Api::SourcesConfig& sources);
|
||||
|
||||
// Re-apply bot settings (queue size, track timeout, playlist
|
||||
// import gate) after a config reload. Does not touch the live
|
||||
// volume.
|
||||
void applyBotConfig(const Api::BotConfig& bot);
|
||||
|
||||
// Re-apply feature toggles (subscriber pause/resume policy,
|
||||
// auto-start, history size, autoplay) after a config reload.
|
||||
// shuffleMode/repeatMode are applied at cold start only.
|
||||
void applyFeaturesConfig(const Api::FeaturesConfig& features);
|
||||
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
play(const std::string& query, uint64_t clientId);
|
||||
[[nodiscard]] Api::Result<void> pause();
|
||||
@@ -106,8 +133,12 @@ namespace Echoion::Core
|
||||
getPlaybackState() const;
|
||||
[[nodiscard]] std::chrono::milliseconds getPlaybackPosition() const;
|
||||
|
||||
// Which catalog(s) a text search targets.
|
||||
enum class SearchScope { All, YouTube, Yandex };
|
||||
|
||||
[[nodiscard]] Api::Result<Api::SearchResult>
|
||||
search(const std::string& query);
|
||||
search(const std::string& query,
|
||||
SearchScope scope = SearchScope::All);
|
||||
|
||||
// Search result selection (client-specific)
|
||||
void storePendingSearch(uint64_t clientId,
|
||||
@@ -119,6 +150,14 @@ namespace Echoion::Core
|
||||
uint32_t index,
|
||||
const std::string& invokerName);
|
||||
|
||||
// Radio/autoplay toggle. Persisted in kv so it survives restart;
|
||||
// enabling while idle kicks an immediate related-track refill.
|
||||
void setAutoplay(bool enabled);
|
||||
[[nodiscard]] bool autoplayEnabled() const
|
||||
{
|
||||
return autoplay_.load();
|
||||
}
|
||||
|
||||
// Help command
|
||||
[[nodiscard]] std::string getHelpText() const;
|
||||
|
||||
@@ -179,11 +218,72 @@ namespace Echoion::Core
|
||||
std::function<std::optional<std::string>(uint64_t clientId)>;
|
||||
void setNicknameCallback(const NicknameCallback& callback);
|
||||
|
||||
// Callback to send a private text message to a client (wired by
|
||||
// Core to the plugin). Used for proactive announcements.
|
||||
using MessageCallback =
|
||||
std::function<void(uint64_t clientId, const std::string&)>;
|
||||
void setMessageCallback(const MessageCallback& callback)
|
||||
{
|
||||
messageCallback_ = callback;
|
||||
}
|
||||
|
||||
// Set the current announcement (admin !announce) and deliver it
|
||||
// to online subscribers now. Bumps the stored announcement id so
|
||||
// a fresh post reaches everyone once. Returns how many online
|
||||
// subscribers were reached immediately.
|
||||
[[nodiscard]] size_t setAnnouncement(const std::string& text);
|
||||
|
||||
// Called when a client leaves the server
|
||||
void onClientDisconnected(uint64_t clientId);
|
||||
|
||||
// Resolve the stable TS3 unique identifier for a session client
|
||||
// id (used to key per-user persistent data such as favorites).
|
||||
[[nodiscard]] std::optional<std::string>
|
||||
clientUid(uint64_t clientId) const
|
||||
{
|
||||
if (clientInfoCallback_) {
|
||||
if (auto info = clientInfoCallback_(clientId)) {
|
||||
return info->first;
|
||||
}
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
// Persistent storage shared with commands (may be null when the
|
||||
// database failed to open).
|
||||
[[nodiscard]] std::shared_ptr<Api::Database> database() const
|
||||
{
|
||||
return database_;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
// ---- IPlaybackHost (called from the engine) --------------------
|
||||
|
||||
void emitAudio(std::span<const short> samples) override;
|
||||
Api::Result<std::string>
|
||||
resolveStream(const Api::QueueEntry& entry,
|
||||
bool preferDownload) override;
|
||||
std::optional<Api::QueueEntry> peekNextTrack() override;
|
||||
std::optional<Api::QueueEntry>
|
||||
takeNextTrack(uint64_t expectedQueueId) override;
|
||||
std::optional<Api::QueueEntry> takeAnyNextTrack() override;
|
||||
bool repeatEnabled() const override;
|
||||
void onTrackStarted(const Api::QueueEntry& entry) override;
|
||||
void onTrackFinished(const Api::QueueEntry& entry,
|
||||
std::chrono::milliseconds finalPosition)
|
||||
override;
|
||||
void onPositionTick(const Api::QueueEntry& entry,
|
||||
std::chrono::milliseconds position,
|
||||
std::chrono::milliseconds duration) override;
|
||||
void onEngineIdle() override;
|
||||
void onLocalFileDone(const std::string& path) override;
|
||||
void onPlaybackError(const Api::Error& error,
|
||||
const std::optional<Api::QueueEntry>& entry)
|
||||
override;
|
||||
|
||||
// ---- helpers ---------------------------------------------------
|
||||
|
||||
// Publish a domain event on the injected bus (no-op until set).
|
||||
template <typename T> void emit(T event)
|
||||
{
|
||||
@@ -192,115 +292,101 @@ namespace Echoion::Core
|
||||
}
|
||||
}
|
||||
|
||||
void playbackThread();
|
||||
// Auto-start the playback loop when a playlist's first track lands.
|
||||
void requestPlaybackStart();
|
||||
// Publish PlaybackPaused/PlaybackResumed with the current track
|
||||
// and position (called from pause/resume and the subscriber
|
||||
// policy hooks so the Desktop sees every pause-state change).
|
||||
void emitPauseState(bool paused);
|
||||
[[nodiscard]] Api::Result<Api::TrackInfo>
|
||||
resolveQuery(const std::string& query);
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
getStreamUrl(const Api::TrackInfo& track);
|
||||
void onTrackFinished();
|
||||
[[nodiscard]] Api::TrackInfo getNextTrack();
|
||||
|
||||
// Generate silence/sine wave to keep audio stream alive during
|
||||
// transitions
|
||||
void generateTransitionAudio(std::chrono::milliseconds duration);
|
||||
void sendSilenceChunk();
|
||||
static constexpr auto TRANSITION_SILENCE_DURATION =
|
||||
std::chrono::milliseconds(100);
|
||||
static constexpr auto TRANSITION_FADE_DURATION =
|
||||
std::chrono::milliseconds(50);
|
||||
[[nodiscard]] std::string nicknameFor(uint64_t clientId) const;
|
||||
|
||||
// Download audio through proxy for playback
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
downloadAudioForPlayback(const Api::TrackInfo& track);
|
||||
void cleanupTempFile(const std::string& filepath);
|
||||
|
||||
// Prefetch next track for seamless transitions
|
||||
void prefetchNextTrack();
|
||||
[[nodiscard]] bool shouldPrefetch() const;
|
||||
static constexpr auto PREFETCH_THRESHOLD =
|
||||
std::chrono::seconds(15); // Start prefetch 15s before end
|
||||
// True when a SOCKS5 proxy is configured: ffmpeg cannot route
|
||||
// IP-locked googlevideo URLs through it, so those are downloaded.
|
||||
[[nodiscard]] bool socksProxyActive() const;
|
||||
|
||||
// ---- state -----------------------------------------------------
|
||||
|
||||
// Temporary file tracking
|
||||
std::set<std::string> tempFiles_;
|
||||
mutable std::shared_mutex tempFilesMutex_;
|
||||
|
||||
// Prefetch state for seamless playback
|
||||
struct PrefetchState {
|
||||
std::future<Api::Result<std::string>> streamUrlFuture;
|
||||
std::atomic<bool> isPrefetching{false};
|
||||
std::atomic<bool> hasPrefetched{false};
|
||||
std::optional<std::string> prefetchedUrl;
|
||||
} prefetchState_;
|
||||
|
||||
// Async playlist loading (background thread owned by the loader).
|
||||
std::unique_ptr<PlaylistLoader> playlistLoader_;
|
||||
|
||||
// Auto-start thread: pokes the playback loop when a playlist's
|
||||
// first track lands. Owned here because it touches the audio loop.
|
||||
std::thread playlistAutoStartThread_;
|
||||
|
||||
std::shared_ptr<NetworkClient> networkClient_;
|
||||
std::shared_ptr<Api::Database> database_;
|
||||
// Non-owning application event bus (provided by Core).
|
||||
Void::EventBus::EventBus* eventBus_ = nullptr;
|
||||
// Non-owning config holder (provided by Core).
|
||||
Api::ConfigManager* configManager_ = nullptr;
|
||||
std::unique_ptr<YouTubeClient> youTubeClient_;
|
||||
std::unique_ptr<AudioDecoder> audioDecoder_;
|
||||
std::unique_ptr<SubscriptionManager> subscriptionManager_;
|
||||
std::shared_ptr<YouTubeClient> youTubeClient_;
|
||||
|
||||
// Source-resolution chain (proxy-free first, proxied last).
|
||||
std::unique_ptr<SourceRouter> router_;
|
||||
std::shared_ptr<InnertubeSource> innertubeSource_;
|
||||
std::shared_ptr<YandexMusicSource> yandexSource_;
|
||||
std::shared_ptr<YtDlpSource> ytdlpProxied_;
|
||||
|
||||
Api::BotConfig config_;
|
||||
// Playback queue + shuffle state (driven under mutex_).
|
||||
QueueManager queueMgr_;
|
||||
std::optional<Api::QueueEntry> currentTrack_;
|
||||
std::atomic<bool> isPlaying_{false};
|
||||
std::atomic<bool> isPaused_{false};
|
||||
std::atomic<bool> wasPausedForNoSubscribers_{
|
||||
false}; // Track if we auto-paused
|
||||
std::atomic<bool> autoStartOnSubscribe_{true};
|
||||
std::atomic<bool> autoplay_{false};
|
||||
QueueService queue_;
|
||||
std::unique_ptr<TrackCache> trackCache_;
|
||||
|
||||
// Accurate playback position tracking
|
||||
std::chrono::milliseconds playbackPosition_{0}; // Current position
|
||||
std::chrono::steady_clock::time_point
|
||||
playbackStartTime_; // When current segment started
|
||||
std::chrono::milliseconds playbackBasePosition_{
|
||||
0}; // Position at start of current segment
|
||||
std::atomic<float> volume_{0.5f};
|
||||
std::atomic<bool> shuffle_{false};
|
||||
std::atomic<bool> repeat_{false};
|
||||
// Autoplay state: seed track for recommendations + re-entrancy
|
||||
// guard for the async fetch. The seed's catalog decides where
|
||||
// related tracks are pulled from (YouTube radio mix vs. Yandex
|
||||
// similar tracks).
|
||||
enum class AutoplaySeedSource { None, YouTube, Yandex };
|
||||
mutable std::mutex autoplaySeedMutex_;
|
||||
std::string autoplaySeedId_;
|
||||
AutoplaySeedSource autoplaySeedSource_ = AutoplaySeedSource::None;
|
||||
std::atomic<bool> autoplayFetching_{false};
|
||||
std::jthread autoplayThread_;
|
||||
|
||||
void rebuildShuffledIndices();
|
||||
void reshuffleRemaining();
|
||||
// Fallback seed for radio when nothing has been played this
|
||||
// session: derive one from the most recent history entry.
|
||||
[[nodiscard]] std::optional<
|
||||
std::pair<std::string, AutoplaySeedSource>>
|
||||
autoplaySeedFromHistory() const;
|
||||
|
||||
std::jthread playbackThread_;
|
||||
mutable std::shared_mutex mutex_;
|
||||
std::condition_variable_any cv_;
|
||||
std::atomic<bool> playbackThreadRunning_{
|
||||
false}; // True while thread is actively running
|
||||
// Spotify/Yandex collection imports (background metadata fetch;
|
||||
// enqueue itself is instant).
|
||||
std::atomic<bool> importRunning_{false};
|
||||
std::jthread importThread_;
|
||||
std::unique_ptr<PlaybackEngine> engine_;
|
||||
std::unique_ptr<SubscriptionService> subscriptions_;
|
||||
|
||||
// Pending search results per client (for select command)
|
||||
std::unordered_map<uint64_t, std::vector<Api::TrackInfo>>
|
||||
pendingSearches_;
|
||||
mutable std::mutex pendingSearchMutex_;
|
||||
|
||||
// Callbacks are stored here as well as forwarded to the
|
||||
// subscription service: Core may register them before
|
||||
// initialize() has created the service.
|
||||
AudioDataCallback audioCallback_;
|
||||
SubscriptionChangeCallback subscriptionChangeCallback_;
|
||||
PlaybackStartCallback playbackStartCallback_;
|
||||
NicknameCallback nicknameCallback_;
|
||||
MessageCallback messageCallback_;
|
||||
|
||||
// Deliver the current announcement to (clientId, uid) if that
|
||||
// subscriber hasn't seen it yet (per-uid seen-id in kv_store).
|
||||
// Returns true when a message was actually sent.
|
||||
bool deliverAnnouncementTo(uint64_t clientId,
|
||||
const std::string& uid);
|
||||
SubscriptionChangeCallback subscriptionChangeCallback_;
|
||||
ClientInfoCallback clientInfoCallback_;
|
||||
UidToClientIdCallback uidToClientIdCallback_;
|
||||
NicknameCallback nicknameCallback_;
|
||||
|
||||
// Position tracking for periodic event updates
|
||||
std::chrono::steady_clock::time_point lastPositionUpdate_{};
|
||||
static constexpr auto POSITION_UPDATE_INTERVAL =
|
||||
std::chrono::seconds(1);
|
||||
|
||||
static constexpr uint32_t TEAMSPEAK_SAMPLE_RATE =
|
||||
192000; // Match TeamSpeak CODEC_OPUS_MUSIC
|
||||
static constexpr uint32_t TEAMSPEAK_CHANNELS = 2;
|
||||
static constexpr size_t AUDIO_BUFFER_SIZE =
|
||||
7680; // 20ms @ 192kHz stereo
|
||||
static constexpr uint32_t CONCURRENT_LOAD_THREADS = 4;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -41,6 +41,15 @@ namespace Echoion::Core
|
||||
[[nodiscard]] Api::Result<Void::Net::Response>
|
||||
request(const Void::Net::Request& req) override;
|
||||
|
||||
// GET that never uses the configured proxy and does not retry —
|
||||
// for endpoints that must be reached directly and cheaply
|
||||
// (Invidious/Piped instance probes and API calls, public-IP
|
||||
// detection). Callers implement their own fallback across
|
||||
// instances, so retrying a dead one is counterproductive.
|
||||
[[nodiscard]] Api::Result<Void::Net::Response>
|
||||
getDirect(std::string_view url,
|
||||
const std::vector<Void::Net::Header>& headers = {});
|
||||
|
||||
// Proxy configuration
|
||||
void setProxy(
|
||||
const std::optional<Void::Net::ProxyConfig>& proxy) override;
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <TrackTypes.hpp>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
// Owns the playback queue and its shuffle state. NOT thread-safe by
|
||||
// design: the owning MusicManager serializes every access under its
|
||||
// playback mutex_, so the single-lock model of the real-time loop is
|
||||
// preserved. The containers are exposed by reference so the playback loop
|
||||
// keeps operating on them with identical semantics.
|
||||
class QueueManager
|
||||
{
|
||||
public:
|
||||
|
||||
using Entry = Api::QueueEntry;
|
||||
|
||||
[[nodiscard]] std::vector<Entry>& entries() noexcept
|
||||
{
|
||||
return entries_;
|
||||
}
|
||||
[[nodiscard]] const std::vector<Entry>& entries() const noexcept
|
||||
{
|
||||
return entries_;
|
||||
}
|
||||
[[nodiscard]] std::vector<std::size_t>& shuffledIndices() noexcept
|
||||
{
|
||||
return shuffledIndices_;
|
||||
}
|
||||
[[nodiscard]] std::size_t& shuffleIndex() noexcept
|
||||
{
|
||||
return shuffleIndex_;
|
||||
}
|
||||
[[nodiscard]] std::uint64_t& nextQueueId() noexcept
|
||||
{
|
||||
return nextQueueId_;
|
||||
}
|
||||
[[nodiscard]] std::mt19937& rng() noexcept { return rng_; }
|
||||
|
||||
private:
|
||||
|
||||
std::vector<Entry> entries_;
|
||||
std::vector<std::size_t> shuffledIndices_;
|
||||
std::size_t shuffleIndex_ = 0;
|
||||
std::uint64_t nextQueueId_ = 1;
|
||||
std::mt19937 rng_{std::random_device{}()};
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -30,6 +30,53 @@ namespace Echoion::Core::Dto
|
||||
std::optional<std::string> token;
|
||||
};
|
||||
|
||||
struct SeekRequest {
|
||||
std::int64_t position = 0; // milliseconds
|
||||
};
|
||||
|
||||
struct VolumeRequest {
|
||||
float volume = 0.5f; // normalised 0.0 - 1.0
|
||||
};
|
||||
|
||||
struct SkipRequest {
|
||||
std::uint32_t count = 1;
|
||||
};
|
||||
|
||||
struct QueueTrackRequest {
|
||||
std::string query;
|
||||
};
|
||||
|
||||
struct QueueIdRequest {
|
||||
std::uint64_t queueId = 0;
|
||||
};
|
||||
|
||||
struct MoveRequest {
|
||||
std::uint64_t queueId = 0;
|
||||
std::uint32_t newPosition = 0;
|
||||
};
|
||||
|
||||
struct SearchRequest {
|
||||
std::string query;
|
||||
};
|
||||
|
||||
struct TrackIdRequest {
|
||||
std::string id;
|
||||
};
|
||||
|
||||
struct PlaylistIdRequest {
|
||||
std::string playlistId;
|
||||
};
|
||||
|
||||
struct SavePlaylistRequest {
|
||||
std::string name;
|
||||
std::string description;
|
||||
};
|
||||
|
||||
struct ManageUsersRequest {
|
||||
std::string action; // "list" | "remove"
|
||||
std::optional<std::string> uid;
|
||||
};
|
||||
|
||||
// ── RPC handler responses ───────────────────────────────────────────────
|
||||
|
||||
struct Track {
|
||||
@@ -39,6 +86,8 @@ namespace Echoion::Core::Dto
|
||||
std::string album;
|
||||
std::optional<std::int64_t> duration; // milliseconds
|
||||
int source = 0;
|
||||
std::optional<std::string> thumbnailUrl;
|
||||
std::optional<std::string> url; // originalUrl (play-by-url)
|
||||
};
|
||||
|
||||
[[nodiscard]] inline Track toTrack(const Api::TrackInfo& t)
|
||||
@@ -51,7 +100,11 @@ namespace Echoion::Core::Dto
|
||||
? std::optional<std::int64_t>(
|
||||
t.duration->count())
|
||||
: std::nullopt,
|
||||
.source = static_cast<int>(t.source)};
|
||||
.source = static_cast<int>(t.source),
|
||||
.thumbnailUrl = t.thumbnailUrl,
|
||||
.url = t.originalUrl.empty()
|
||||
? std::nullopt
|
||||
: std::optional(t.originalUrl)};
|
||||
}
|
||||
|
||||
struct QueueItem {
|
||||
@@ -90,6 +143,76 @@ namespace Echoion::Core::Dto
|
||||
float volume = 0.0f;
|
||||
};
|
||||
|
||||
struct QueuedResponse {
|
||||
bool success = true;
|
||||
std::uint64_t queueId = 0;
|
||||
};
|
||||
|
||||
struct SearchResults {
|
||||
std::vector<Track> tracks;
|
||||
};
|
||||
|
||||
struct PlaylistBrief {
|
||||
std::string id;
|
||||
std::string name;
|
||||
std::string description;
|
||||
std::uint32_t trackCount = 0;
|
||||
};
|
||||
|
||||
struct PlaylistList {
|
||||
std::vector<PlaylistBrief> playlists;
|
||||
};
|
||||
|
||||
struct PlaylistContents {
|
||||
std::string id;
|
||||
std::string name;
|
||||
std::string description;
|
||||
std::vector<Track> tracks;
|
||||
};
|
||||
|
||||
struct HistoryRequest {
|
||||
std::uint32_t limit = 20;
|
||||
};
|
||||
|
||||
struct HistoryResponse {
|
||||
std::vector<Track> tracks;
|
||||
};
|
||||
|
||||
struct StatsResponse {
|
||||
std::uint64_t totalPlays = 0;
|
||||
std::uint64_t totalTracks = 0;
|
||||
std::uint64_t totalPlaytimeMs = 0;
|
||||
std::optional<std::string> mostPlayedTitle;
|
||||
std::uint64_t mostPlayedCount = 0;
|
||||
};
|
||||
|
||||
struct ServerInfo {
|
||||
std::string version;
|
||||
std::int64_t uptimeSeconds = 0;
|
||||
std::uint32_t connectedClients = 0;
|
||||
std::uint32_t subscribers = 0;
|
||||
std::uint32_t queueLength = 0;
|
||||
};
|
||||
|
||||
struct AuditEntryDto {
|
||||
std::uint64_t clientId = 0;
|
||||
int method = 0;
|
||||
std::int64_t timestamp = 0; // unix seconds
|
||||
};
|
||||
|
||||
struct AuditLogResponse {
|
||||
std::vector<AuditEntryDto> entries;
|
||||
};
|
||||
|
||||
struct SubscriberDto {
|
||||
std::string uid;
|
||||
std::string nickname;
|
||||
};
|
||||
|
||||
struct UsersResponse {
|
||||
std::vector<SubscriberDto> users;
|
||||
};
|
||||
|
||||
// ── Event-broadcast payloads ────────────────────────────────────────────
|
||||
|
||||
struct TrackBrief {
|
||||
|
||||
@@ -8,12 +8,15 @@
|
||||
#include <boost/asio.hpp>
|
||||
#include <boost/beast.hpp>
|
||||
#include <boost/beast/websocket.hpp>
|
||||
#include <chrono>
|
||||
#include <deque>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <set>
|
||||
#include <thread>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
@@ -50,6 +53,16 @@ namespace Echoion::Core
|
||||
void removeAuthenticatedClient(uint64_t clientId);
|
||||
[[nodiscard]] bool isClientAuthenticated(uint64_t clientId);
|
||||
|
||||
// Server introspection (for GetServerInfo / GetAuditLog).
|
||||
struct AuditEntry {
|
||||
uint64_t clientId = 0;
|
||||
int method = 0;
|
||||
std::chrono::system_clock::time_point timestamp;
|
||||
};
|
||||
[[nodiscard]] std::vector<AuditEntry> getAuditLog() const;
|
||||
[[nodiscard]] size_t getClientCount() const;
|
||||
[[nodiscard]] std::chrono::seconds getUptime() const;
|
||||
|
||||
// Broadcast events to all connected clients
|
||||
void broadcastEvent(const std::string& event,
|
||||
const std::string& data);
|
||||
@@ -80,7 +93,7 @@ namespace Echoion::Core
|
||||
uint64_t,
|
||||
std::shared_ptr<websocket::stream<asio::ip::tcp::socket>>>
|
||||
clients_;
|
||||
std::mutex clientsMutex_;
|
||||
mutable std::mutex clientsMutex_;
|
||||
std::atomic<uint64_t> nextClientId_{1};
|
||||
|
||||
// Per-client handlers run on a Void worker pool instead of one
|
||||
@@ -96,6 +109,13 @@ namespace Echoion::Core
|
||||
std::mutex authMutex_;
|
||||
std::string authToken_;
|
||||
|
||||
// Audit ring + uptime tracking
|
||||
mutable std::mutex auditMutex_;
|
||||
std::deque<AuditEntry> auditLog_;
|
||||
static constexpr size_t MAX_AUDIT_ENTRIES = 500;
|
||||
std::chrono::steady_clock::time_point startTime_{
|
||||
std::chrono::steady_clock::now()};
|
||||
|
||||
// Command handlers
|
||||
std::unordered_map<std::string, CommandHandler> handlers_;
|
||||
std::mutex handlersMutex_;
|
||||
|
||||
@@ -8,7 +8,10 @@
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
#include <quickjs.h>
|
||||
// Opaque quickjs handles — only the .cpp needs <quickjs.h>, and keeping it
|
||||
// out of this header keeps the quickjs include dir private to EchoionCore.
|
||||
struct JSRuntime;
|
||||
struct JSContext;
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
#pragma once
|
||||
|
||||
#include "SubscriptionManager.hpp"
|
||||
#include <Database.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <Void/Async/EventBus.hpp>
|
||||
#include <atomic>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// Subscription bookkeeping + audience policy, extracted from
|
||||
// MusicManager. Owns the persistent SubscriptionManager and the
|
||||
// client-resolution callbacks; drives the pause-on-empty /
|
||||
// resume-on-return policy through two injected hooks so it never touches
|
||||
// playback internals directly.
|
||||
class SubscriptionService
|
||||
{
|
||||
public:
|
||||
|
||||
using ClientInfoCallback = std::function<std::optional<
|
||||
std::pair<std::string, std::string>>(uint64_t clientId)>;
|
||||
using UidToClientIdCallback =
|
||||
std::function<std::optional<uint64_t>(const std::string& uid)>;
|
||||
using ChangeCallback = std::function<void()>;
|
||||
// requestPause returns true when playback was actually paused by
|
||||
// this policy (so a returning subscriber should resume it).
|
||||
using RequestPause = std::function<bool()>;
|
||||
using RequestResume = std::function<bool()>;
|
||||
|
||||
Api::Result<void>
|
||||
initialize(std::shared_ptr<Api::Database> database);
|
||||
|
||||
void setEventBus(Void::EventBus::EventBus* bus) { eventBus_ = bus; }
|
||||
void setClientInfoCallback(ClientInfoCallback cb)
|
||||
{
|
||||
clientInfo_ = std::move(cb);
|
||||
}
|
||||
void setUidToClientIdCallback(UidToClientIdCallback cb)
|
||||
{
|
||||
uidToClientId_ = std::move(cb);
|
||||
}
|
||||
void setChangeCallback(ChangeCallback cb)
|
||||
{
|
||||
onChange_ = std::move(cb);
|
||||
}
|
||||
void setPauseResumeHooks(RequestPause pause, RequestResume resume)
|
||||
{
|
||||
requestPause_ = std::move(pause);
|
||||
requestResume_ = std::move(resume);
|
||||
}
|
||||
|
||||
// Audience policy toggles (features.pauseOnEmptySubscribers /
|
||||
// features.resumeOnSubscriberReturn); re-applied on config
|
||||
// reload.
|
||||
void setPolicy(bool pauseOnEmpty, bool resumeOnReturn)
|
||||
{
|
||||
pauseOnEmpty_ = pauseOnEmpty;
|
||||
resumeOnReturn_ = resumeOnReturn;
|
||||
}
|
||||
|
||||
// Command surface (message strings go back to the chat user).
|
||||
[[nodiscard]] Api::Result<std::string> subscribe(uint64_t clientId);
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
unsubscribe(uint64_t clientId);
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
unsubscribeByUid(const std::string& uid);
|
||||
[[nodiscard]] Api::Result<std::string> clearAllSubscriptions();
|
||||
|
||||
[[nodiscard]] bool isSubscribed(uint64_t clientId) const;
|
||||
[[nodiscard]] bool hasSubscribers() const;
|
||||
[[nodiscard]] bool hasOnlineSubscribers() const;
|
||||
[[nodiscard]] std::set<uint64_t> getSubscribedClients() const;
|
||||
[[nodiscard]] std::set<std::string> getOnlineSubscriberUids() const;
|
||||
[[nodiscard]] std::vector<SubscriptionManager::Subscriber>
|
||||
getSubscribers() const;
|
||||
|
||||
// Presence events from the plugin. onClientConnected returns true
|
||||
// when a subscribed user came online and playback should
|
||||
// auto-start if tracks are queued.
|
||||
bool onClientConnected(uint64_t clientId);
|
||||
void onClientDisconnected(uint64_t clientId);
|
||||
|
||||
private:
|
||||
|
||||
template <typename T> void emit(T event)
|
||||
{
|
||||
if (eventBus_) {
|
||||
eventBus_->publish<T>(std::move(event));
|
||||
}
|
||||
}
|
||||
|
||||
// Pause playback if the audience vanished; remember that WE
|
||||
// paused so the next returning subscriber resumes.
|
||||
void pauseIfAudienceGone();
|
||||
|
||||
std::unique_ptr<SubscriptionManager> manager_;
|
||||
Void::EventBus::EventBus* eventBus_ = nullptr;
|
||||
ClientInfoCallback clientInfo_;
|
||||
UidToClientIdCallback uidToClientId_;
|
||||
ChangeCallback onChange_;
|
||||
RequestPause requestPause_;
|
||||
RequestResume requestResume_;
|
||||
std::atomic<bool> pausedForNoSubscribers_{false};
|
||||
std::atomic<bool> pauseOnEmpty_{true};
|
||||
std::atomic<bool> resumeOnReturn_{true};
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,74 @@
|
||||
#pragma once
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// Persistent on-disk cache of downloaded audio files, keyed by track id.
|
||||
// Survives restarts (lives under XDG_CACHE_HOME/echoion/tracks); evicts
|
||||
// least-recently-used files past maxBytes and entries older than the
|
||||
// TTL. Honors advanced.cacheEnabled / cacheMaxSize / cacheTTL.
|
||||
class TrackCache
|
||||
{
|
||||
public:
|
||||
|
||||
struct Config {
|
||||
bool enabled = true;
|
||||
uint64_t maxBytes = 1ull << 30; // 1 GiB
|
||||
std::chrono::seconds ttl{86400};
|
||||
};
|
||||
|
||||
// dirOverride points tests at a temp dir.
|
||||
explicit TrackCache(Config config,
|
||||
std::filesystem::path dirOverride = {});
|
||||
|
||||
// Parse "1GB"/"500MB"/"1024" (bytes) size strings; 0 on garbage.
|
||||
[[nodiscard]] static uint64_t
|
||||
parseSize(const std::string& text);
|
||||
|
||||
[[nodiscard]] bool enabled() const { return config_.enabled; }
|
||||
|
||||
// Cached file path for the track id, when present and fresh.
|
||||
// Bumps the file's LRU timestamp.
|
||||
[[nodiscard]] std::optional<std::string>
|
||||
lookup(const std::string& trackId);
|
||||
|
||||
// Move a downloaded file into the cache; returns the new path
|
||||
// (or the original on failure/disabled). Triggers eviction.
|
||||
[[nodiscard]] std::string store(const std::string& trackId,
|
||||
const std::string& filePath);
|
||||
|
||||
// True when the path lives inside the cache directory — such
|
||||
// files must NOT be deleted after playback.
|
||||
[[nodiscard]] bool owns(const std::string& filePath) const;
|
||||
|
||||
// Drop expired entries and evict LRU past the size budget.
|
||||
void sweep();
|
||||
|
||||
[[nodiscard]] const std::filesystem::path& directory() const
|
||||
{
|
||||
return dir_;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
[[nodiscard]] std::filesystem::path
|
||||
pathFor(const std::string& trackId,
|
||||
const std::string& extension) const;
|
||||
[[nodiscard]] static std::string
|
||||
sanitize(const std::string& trackId);
|
||||
// Eviction pass; caller holds mutex_.
|
||||
void sweepLocked();
|
||||
|
||||
Config config_;
|
||||
std::filesystem::path dir_;
|
||||
mutable std::mutex mutex_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -49,6 +49,12 @@ namespace Echoion::Core
|
||||
search(std::string_view query,
|
||||
std::optional<std::string> pageToken = std::nullopt);
|
||||
|
||||
// Related tracks for radio autoplay: lists the YouTube "mix"
|
||||
// playlist (RD<videoId>) via yt-dlp --flat-playlist. Runs through
|
||||
// the proxy like every yt-dlp call, so it works under SOCKS5.
|
||||
[[nodiscard]] Api::Result<std::vector<Api::TrackInfo>>
|
||||
radioMix(const std::string& videoId, size_t limit = 10);
|
||||
|
||||
// Get video details including stream URLs using yt-dlp
|
||||
[[nodiscard]] Api::Result<Api::TrackInfo>
|
||||
getVideoInfo(std::string_view videoId);
|
||||
@@ -101,6 +107,13 @@ namespace Echoion::Core
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
getAudioStreamUrl(std::string_view videoId);
|
||||
|
||||
// Resolve a stream URL for any yt-dlp-supported page URL
|
||||
// (SoundCloud, Bandcamp, VK, radio pages, ...). When useProxy is
|
||||
// false the configured proxy is explicitly bypassed with a
|
||||
// trailing --proxy "" (yt-dlp honours the last occurrence).
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
getStreamUrlForPage(std::string_view pageUrl, bool useProxy);
|
||||
|
||||
// Download the best audio to a file via yt-dlp (used when the
|
||||
// stream URL can't be opened directly — e.g. behind a SOCKS5 proxy
|
||||
// that ffmpeg can't use). yt-dlp applies the proxy + cookies and
|
||||
@@ -128,6 +141,10 @@ namespace Echoion::Core
|
||||
|
||||
// Enable/disable URL shortening for track links
|
||||
void setUrlShorteningEnabled(bool enabled);
|
||||
|
||||
// Gate yt-dlp's periodic background self-update
|
||||
// (features.enableAutoUpdateCheck). Set before initialize().
|
||||
void setAutoUpdateEnabled(bool enabled);
|
||||
[[nodiscard]] bool isUrlShorteningEnabled() const;
|
||||
|
||||
private:
|
||||
|
||||
@@ -34,6 +34,13 @@ namespace Echoion::Core
|
||||
// Initialize - checks for yt-dlp and downloads if needed
|
||||
Api::Result<void> initialize();
|
||||
|
||||
// Gate the periodic (7-day) background self-update. Configured
|
||||
// via features.enableAutoUpdateCheck; set BEFORE initialize().
|
||||
void setAutoUpdateEnabled(bool enabled)
|
||||
{
|
||||
autoUpdateEnabled_ = enabled;
|
||||
}
|
||||
|
||||
// Get the path to the yt-dlp executable
|
||||
[[nodiscard]] std::filesystem::path getExecutablePath() const;
|
||||
|
||||
@@ -109,6 +116,9 @@ namespace Echoion::Core
|
||||
std::shared_ptr<NetworkClient> networkClient_;
|
||||
std::filesystem::path executablePath_;
|
||||
std::atomic<bool> initialized_{false};
|
||||
std::atomic<bool> autoUpdateEnabled_{true};
|
||||
// Background download/verify (joined in the destructor).
|
||||
std::jthread initThread_;
|
||||
mutable std::mutex mutex_;
|
||||
|
||||
// Cookie configuration for YouTube authentication
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
#pragma once
|
||||
|
||||
#include "../MusicManager.hpp"
|
||||
#include "Command.hpp"
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// !announce <text> — admin-only. Stores the announcement and delivers it
|
||||
// as a private message to each subscriber exactly once: to those online
|
||||
// now, and to others the next time they connect. Persisted per-uid, so a
|
||||
// bot restart never re-sends, and re-running !announce with new text
|
||||
// reaches everyone once more.
|
||||
class AnnounceCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply("The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
if (ctx.args.empty()) {
|
||||
ctx.reply(std::format(
|
||||
"Usage: {}announce <message>", ctx.prefix));
|
||||
return;
|
||||
}
|
||||
|
||||
const size_t reached = manager->setAnnouncement(ctx.args);
|
||||
ctx.reply(std::format(
|
||||
"Announcement saved and delivered to {} online "
|
||||
"subscriber(s). Offline subscribers get it on their "
|
||||
"next connect.",
|
||||
reached));
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Send an announcement to all subscribers (admin).";
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override { return "<message>"; }
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Admin;
|
||||
}
|
||||
|
||||
bool requiresAdmin() const override { return true; }
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,81 @@
|
||||
#pragma once
|
||||
|
||||
#include "../MusicManager.hpp"
|
||||
#include "Command.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <algorithm>
|
||||
#include <format>
|
||||
#include <string>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// !autoplay [on|off] / !radio — toggle endless related-track playback.
|
||||
// With no argument it flips the current state. The choice is persisted so
|
||||
// it survives restarts. Related tracks come from the same catalog as the
|
||||
// last played track (YouTube radio mix or Yandex similar tracks).
|
||||
class AutoplayCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
|
||||
bool enable = !manager->autoplayEnabled();
|
||||
std::string arg(ctx.args);
|
||||
std::transform(arg.begin(), arg.end(), arg.begin(),
|
||||
[](unsigned char c) {
|
||||
return static_cast<char>(std::tolower(c));
|
||||
});
|
||||
if (arg == "on" || arg == "true" || arg == "1" ||
|
||||
arg == "enable") {
|
||||
enable = true;
|
||||
} else if (arg == "off" || arg == "false" || arg == "0" ||
|
||||
arg == "disable") {
|
||||
enable = false;
|
||||
}
|
||||
|
||||
manager->setAutoplay(enable);
|
||||
|
||||
if (enable) {
|
||||
ctx.reply(
|
||||
"\xf0\x9f\x93\xbb Autoplay is ON \xe2\x80\x94 I'll "
|
||||
"keep the music going with related tracks.");
|
||||
} else {
|
||||
ctx.reply("\xf0\x9f\x93\xbb Autoplay is OFF.");
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
Void::Log::error("AutoplayCommand", "{}",
|
||||
std::format("Autoplay command exception: {}",
|
||||
e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Toggles radio mode: auto-queues related tracks when "
|
||||
"the queue runs out.";
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override { return "[on|off]"; }
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Playback;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"radio"};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -18,11 +18,26 @@ namespace Echoion::Core
|
||||
|
||||
class MusicManager;
|
||||
|
||||
enum class CommandCategory { Music, Queue, Playback, Utility, Admin };
|
||||
// Declaration order also decides the order of the collapsible sections
|
||||
// in !help (the help map is keyed by this enum). Play and Search lead so
|
||||
// their related commands are grouped together up top.
|
||||
enum class CommandCategory {
|
||||
Play,
|
||||
Search,
|
||||
Music,
|
||||
Queue,
|
||||
Playback,
|
||||
Utility,
|
||||
Admin
|
||||
};
|
||||
|
||||
inline std::string toString(CommandCategory category)
|
||||
{
|
||||
switch (category) {
|
||||
case CommandCategory::Play:
|
||||
return "Play";
|
||||
case CommandCategory::Search:
|
||||
return "Search";
|
||||
case CommandCategory::Music:
|
||||
return "Music";
|
||||
case CommandCategory::Queue:
|
||||
@@ -78,6 +93,32 @@ namespace Echoion::Core
|
||||
return escapeMarkdown(text);
|
||||
}
|
||||
|
||||
// The best public link for a track: the shortened faumaray link when
|
||||
// available, otherwise the original source URL (e.g. the YouTube or
|
||||
// Yandex Music page). Used so every list — search, queue, history,
|
||||
// favorites, stats — links to the real track, never the CDN/stream URL.
|
||||
inline std::optional<std::string> trackLinkUrl(const Api::TrackInfo& track)
|
||||
{
|
||||
if (track.shortenedUrl.has_value() && !track.shortenedUrl->empty()) {
|
||||
return track.shortenedUrl;
|
||||
}
|
||||
if (!track.originalUrl.empty()) {
|
||||
return track.originalUrl;
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
// Render "Title by Artist" (or just Title) as a Markdown link to the
|
||||
// track's best public URL.
|
||||
inline std::string trackLink(const Api::TrackInfo& track)
|
||||
{
|
||||
std::string display = track.title;
|
||||
if (!track.artist.empty()) {
|
||||
display = std::format("{} by {}", track.title, track.artist);
|
||||
}
|
||||
return markdownLink(display, trackLinkUrl(track));
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Context passed to every command execution.
|
||||
* Wraps all dependencies required to perform an action.
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
#pragma once
|
||||
|
||||
// New command system - header-only commands
|
||||
#include "AnnounceCommand.hpp"
|
||||
#include "AutoplayCommand.hpp"
|
||||
#include "ClearCommand.hpp"
|
||||
#include "Command.hpp"
|
||||
#include "MoveCommand.hpp"
|
||||
@@ -19,8 +21,15 @@
|
||||
#include "SeekCommand.hpp"
|
||||
#include "SelectCommand.hpp"
|
||||
#include "ShuffleCommand.hpp"
|
||||
#include "FavoriteCommand.hpp"
|
||||
#include "HistoryCommand.hpp"
|
||||
#include "SkipCommand.hpp"
|
||||
#include "StatsCommand.hpp"
|
||||
#include "StopCommand.hpp"
|
||||
#include "YandexPlayCommand.hpp"
|
||||
#include "YandexSearchCommand.hpp"
|
||||
#include "YoutubePlayCommand.hpp"
|
||||
#include "YoutubeSearchCommand.hpp"
|
||||
#include "SubscribeCommand.hpp"
|
||||
#include "SubscribersCommand.hpp"
|
||||
#include "UnsubscribeAllCommand.hpp"
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
#pragma once
|
||||
|
||||
#include "../MusicManager.hpp"
|
||||
#include "Command.hpp"
|
||||
#include <Database.hpp>
|
||||
#include <charconv>
|
||||
#include <format>
|
||||
#include <string>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// !fav add | list | play <n> | remove <n> — per-user favorites keyed by
|
||||
// the stable TS3 unique identifier (hashed to the database's uint64
|
||||
// user key with FNV-1a; session client ids are NOT stable).
|
||||
class FavoriteCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
auto manager = ctx.musicManager.lock();
|
||||
auto db = ctx.service<Api::Database>();
|
||||
if (!manager || !db) {
|
||||
ctx.reply("Favorites are unavailable.");
|
||||
return;
|
||||
}
|
||||
|
||||
auto uid = manager->clientUid(ctx.clientId);
|
||||
if (!uid) {
|
||||
ctx.reply("Couldn't identify you on the server.");
|
||||
return;
|
||||
}
|
||||
const uint64_t userKey = fnv1a(*uid);
|
||||
|
||||
const auto [sub, rest] = splitFirstWord(ctx.args);
|
||||
|
||||
if (sub.empty() || sub == "list") {
|
||||
listFavorites(ctx, *db, userKey);
|
||||
} else if (sub == "add") {
|
||||
addCurrent(ctx, *manager, *db, userKey);
|
||||
} else if (sub == "play") {
|
||||
playFavorite(ctx, *manager, *db, userKey, rest);
|
||||
} else if (sub == "remove" || sub == "rm") {
|
||||
removeFavorite(ctx, *db, userKey, rest);
|
||||
} else {
|
||||
ctx.reply(std::format(
|
||||
"Usage: {}fav add | list | play <n> | remove <n>",
|
||||
ctx.prefix));
|
||||
}
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Manage your favorite tracks";
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override
|
||||
{
|
||||
return "add | list | play <n> | remove <n>";
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Music;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"favorite", "favorites"};
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
[[nodiscard]] static uint64_t fnv1a(std::string_view text)
|
||||
{
|
||||
uint64_t hash = 14695981039346656037ull;
|
||||
for (unsigned char c : text) {
|
||||
hash ^= c;
|
||||
hash *= 1099511628211ull;
|
||||
}
|
||||
return hash;
|
||||
}
|
||||
|
||||
[[nodiscard]] static std::pair<std::string, std::string>
|
||||
splitFirstWord(const std::string& text)
|
||||
{
|
||||
const auto start = text.find_first_not_of(' ');
|
||||
if (start == std::string::npos) {
|
||||
return {};
|
||||
}
|
||||
const auto end = text.find(' ', start);
|
||||
if (end == std::string::npos) {
|
||||
return {text.substr(start), {}};
|
||||
}
|
||||
const auto restStart = text.find_first_not_of(' ', end);
|
||||
return {text.substr(start, end - start),
|
||||
restStart == std::string::npos
|
||||
? std::string{}
|
||||
: text.substr(restStart)};
|
||||
}
|
||||
|
||||
[[nodiscard]] static std::optional<size_t>
|
||||
parseIndex(const std::string& text)
|
||||
{
|
||||
unsigned parsed = 0;
|
||||
auto [_, ec] = std::from_chars(
|
||||
text.data(), text.data() + text.size(), parsed);
|
||||
if (ec != std::errc{} || parsed == 0) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
static void listFavorites(const CommandContext& ctx,
|
||||
Api::Database& db, uint64_t userKey)
|
||||
{
|
||||
auto favorites = db.getFavorites(userKey);
|
||||
if (!favorites) {
|
||||
ctx.reply("Couldn't read your favorites.");
|
||||
return;
|
||||
}
|
||||
if (favorites->empty()) {
|
||||
ctx.reply(std::format(
|
||||
"You have no favorites yet. Save the current track "
|
||||
"with {}fav add",
|
||||
ctx.prefix));
|
||||
return;
|
||||
}
|
||||
std::string msg = "Your favorites:";
|
||||
size_t index = 1;
|
||||
for (const auto& fav : *favorites) {
|
||||
msg += std::format("\n{}. {}", index++,
|
||||
trackLink(fav.track));
|
||||
}
|
||||
ctx.reply(msg);
|
||||
}
|
||||
|
||||
static void addCurrent(const CommandContext& ctx,
|
||||
MusicManager& manager, Api::Database& db,
|
||||
uint64_t userKey)
|
||||
{
|
||||
auto current = manager.getCurrentTrack();
|
||||
if (!current || !current->has_value()) {
|
||||
ctx.reply("Nothing is playing right now.");
|
||||
return;
|
||||
}
|
||||
const auto& track = (*current)->track;
|
||||
if (db.addFavorite(userKey, track)) {
|
||||
ctx.reply(std::format("Added to favorites: {}",
|
||||
track.title));
|
||||
} else {
|
||||
ctx.reply("Couldn't save the favorite.");
|
||||
}
|
||||
}
|
||||
|
||||
static void playFavorite(const CommandContext& ctx,
|
||||
MusicManager& manager, Api::Database& db,
|
||||
uint64_t userKey, const std::string& arg)
|
||||
{
|
||||
auto index = parseIndex(arg);
|
||||
if (!index) {
|
||||
ctx.reply("Usage: fav play <number> (see fav list)");
|
||||
return;
|
||||
}
|
||||
auto favorites = db.getFavorites(userKey);
|
||||
if (!favorites || *index > favorites->size()) {
|
||||
ctx.reply("No favorite with that number.");
|
||||
return;
|
||||
}
|
||||
const auto& track = (*favorites)[*index - 1].track;
|
||||
auto result =
|
||||
manager.play(track.originalUrl, ctx.clientId);
|
||||
if (result) {
|
||||
ctx.reply(*result);
|
||||
} else {
|
||||
ctx.reply(std::format("Couldn't play it: {}",
|
||||
result.error().message));
|
||||
}
|
||||
}
|
||||
|
||||
static void removeFavorite(const CommandContext& ctx,
|
||||
Api::Database& db, uint64_t userKey,
|
||||
const std::string& arg)
|
||||
{
|
||||
auto index = parseIndex(arg);
|
||||
if (!index) {
|
||||
ctx.reply("Usage: fav remove <number> (see fav list)");
|
||||
return;
|
||||
}
|
||||
auto favorites = db.getFavorites(userKey);
|
||||
if (!favorites || *index > favorites->size()) {
|
||||
ctx.reply("No favorite with that number.");
|
||||
return;
|
||||
}
|
||||
const auto& fav = (*favorites)[*index - 1];
|
||||
if (db.removeFavorite(userKey, fav.track.originalUrl)) {
|
||||
ctx.reply(std::format("Removed from favorites: {}",
|
||||
fav.track.title));
|
||||
} else {
|
||||
ctx.reply("Couldn't remove the favorite.");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,72 @@
|
||||
#pragma once
|
||||
|
||||
#include "../MusicManager.hpp"
|
||||
#include "Command.hpp"
|
||||
#include <Database.hpp>
|
||||
#include <charconv>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// !history [n] — recently played tracks (global, deduplicated).
|
||||
class HistoryCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
auto db = ctx.service<Api::Database>();
|
||||
if (!db) {
|
||||
ctx.reply("History is unavailable (no database).");
|
||||
return;
|
||||
}
|
||||
|
||||
size_t limit = 10;
|
||||
if (!ctx.args.empty()) {
|
||||
unsigned parsed = 0;
|
||||
auto [_, ec] = std::from_chars(
|
||||
ctx.args.data(), ctx.args.data() + ctx.args.size(),
|
||||
parsed);
|
||||
if (ec == std::errc{} && parsed > 0) {
|
||||
limit = std::min<size_t>(parsed, 25);
|
||||
}
|
||||
}
|
||||
|
||||
auto recent = db->getRecentlyPlayed(0, limit);
|
||||
if (!recent) {
|
||||
ctx.reply("Couldn't read the playback history.");
|
||||
return;
|
||||
}
|
||||
if (recent->empty()) {
|
||||
ctx.reply("Nothing has been played yet.");
|
||||
return;
|
||||
}
|
||||
|
||||
std::string msg = "Recently played:";
|
||||
size_t index = 1;
|
||||
for (const auto& track : *recent) {
|
||||
msg += std::format("\n{}. {}", index++, trackLink(track));
|
||||
}
|
||||
ctx.reply(msg);
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Show recently played tracks";
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override { return "[count]"; }
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Music;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"recent"};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -46,7 +46,7 @@ namespace Echoion::Core
|
||||
}
|
||||
std::string msg = std::format(
|
||||
"\xf0\x9f\x8e\xb5 {}",
|
||||
markdownLink(displayText, trackInfo.shortenedUrl));
|
||||
markdownLink(displayText, trackLinkUrl(trackInfo)));
|
||||
|
||||
// Show current position / total duration after a middot
|
||||
// (no [] — TeamSpeak parses it as a link reference).
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#pragma once
|
||||
|
||||
#include "../MusicManager.hpp"
|
||||
#include "Command.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
@@ -7,7 +8,12 @@
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class PlayCommand : public Command
|
||||
// Shared play rendering. Concrete commands pick the catalog scope:
|
||||
// !play (both), !pyt (YouTube), !pya (Yandex). A bare URL always plays
|
||||
// directly regardless of scope; free text searches the chosen catalog(s)
|
||||
// and, when there is more than one hit, shows a !select list — the same
|
||||
// flow as the search commands.
|
||||
class PlayCommandBase : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
@@ -22,18 +28,20 @@ namespace Echoion::Core
|
||||
}
|
||||
|
||||
if (ctx.args.empty()) {
|
||||
ctx.reply("Usage: play <url or search query>\nExample: "
|
||||
"play never gonna give you up");
|
||||
ctx.reply(std::format(
|
||||
"Usage: {} <url or search query>\nExample: {} never "
|
||||
"gonna give you up",
|
||||
label(), label()));
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if it's a direct URL
|
||||
// Direct URL: hand straight to the player.
|
||||
if (ctx.args.find("http") == 0) {
|
||||
auto result = manager->play(ctx.args, ctx.clientId);
|
||||
if (!result) {
|
||||
Void::Log::error("PlayCommand", "{}",
|
||||
std::format("Play URL failed '{}': {}",
|
||||
ctx.args, result.error().message));
|
||||
Void::Log::error("PlayCommand", "{}",
|
||||
std::format("Play URL failed '{}': {}", ctx.args,
|
||||
result.error().message));
|
||||
|
||||
switch (result.error().code) {
|
||||
case Api::ErrorCode::NetworkError:
|
||||
@@ -52,15 +60,14 @@ namespace Echoion::Core
|
||||
return;
|
||||
}
|
||||
|
||||
// result contains the track title
|
||||
ctx.reply(std::format("Added to queue: {}", *result));
|
||||
return;
|
||||
}
|
||||
|
||||
// Otherwise, treat as search query
|
||||
auto searchResult = manager->search(ctx.args);
|
||||
// Otherwise, search the chosen catalog(s).
|
||||
auto searchResult = manager->search(ctx.args, scope());
|
||||
if (!searchResult) {
|
||||
Void::Log::error("PlayCommand", "{}",
|
||||
Void::Log::error("PlayCommand", "{}",
|
||||
std::format("Search failed for '{}': {}", ctx.args,
|
||||
searchResult.error().message));
|
||||
|
||||
@@ -79,13 +86,13 @@ namespace Echoion::Core
|
||||
return;
|
||||
}
|
||||
|
||||
// Single result - play immediately
|
||||
// Single result - queue immediately.
|
||||
if (searchResult->tracks.size() == 1) {
|
||||
const auto& track = searchResult->tracks[0];
|
||||
auto playResult =
|
||||
manager->queueTrack(track, ctx.clientId);
|
||||
if (!playResult) {
|
||||
Void::Log::error("PlayCommand", "{}",
|
||||
Void::Log::error("PlayCommand", "{}",
|
||||
std::format("Queue failed: {}",
|
||||
playResult.error().message));
|
||||
ctx.reply(
|
||||
@@ -100,11 +107,11 @@ namespace Echoion::Core
|
||||
}
|
||||
ctx.reply(std::format(
|
||||
"Added to queue: {}",
|
||||
markdownLink(displayText, track.shortenedUrl)));
|
||||
markdownLink(displayText, trackLinkUrl(track))));
|
||||
return;
|
||||
}
|
||||
|
||||
// Multiple results - store and show list
|
||||
// Multiple results - store and show list.
|
||||
manager->storePendingSearch(ctx.clientId,
|
||||
searchResult->tracks);
|
||||
|
||||
@@ -119,11 +126,9 @@ namespace Echoion::Core
|
||||
displayText = std::format("{} by {}", track.title,
|
||||
track.artist);
|
||||
}
|
||||
// [escaped title](url) · duration (no [] around the
|
||||
// duration: TeamSpeak parses [..] as a link reference).
|
||||
msg += std::format(
|
||||
"{}. {}", i + 1,
|
||||
markdownLink(displayText, track.shortenedUrl));
|
||||
markdownLink(displayText, trackLinkUrl(track)));
|
||||
if (track.duration.has_value()) {
|
||||
msg += std::format(" {} {}", kDot,
|
||||
formatDuration(*track.duration));
|
||||
@@ -134,33 +139,24 @@ namespace Echoion::Core
|
||||
ctx.reply(msg);
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
Void::Log::error("PlayCommand", "{}",
|
||||
Void::Log::error("PlayCommand", "{}",
|
||||
std::format("Play command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong while trying to play. "
|
||||
"Please try again.");
|
||||
}
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Plays a track from URL or searches and lets you "
|
||||
"select.";
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override
|
||||
{
|
||||
return "<url or search query>";
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Music;
|
||||
return CommandCategory::Play;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"p", "add"};
|
||||
}
|
||||
protected:
|
||||
|
||||
// The catalog(s) this command searches, and the command name used
|
||||
// in usage text.
|
||||
[[nodiscard]] virtual MusicManager::SearchScope scope() const = 0;
|
||||
[[nodiscard]] virtual std::string_view label() const = 0;
|
||||
|
||||
private:
|
||||
|
||||
@@ -179,4 +175,32 @@ namespace Echoion::Core
|
||||
}
|
||||
};
|
||||
|
||||
// !play — both YouTube and Yandex Music.
|
||||
class PlayCommand : public PlayCommandBase
|
||||
{
|
||||
public:
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Plays a track from URL, or searches YouTube and Yandex "
|
||||
"Music and lets you select.";
|
||||
}
|
||||
std::string_view getUsage() const override
|
||||
{
|
||||
return "<url or search query>";
|
||||
}
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"p", "add"};
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
MusicManager::SearchScope scope() const override
|
||||
{
|
||||
return MusicManager::SearchScope::All;
|
||||
}
|
||||
std::string_view label() const override { return "play"; }
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -41,7 +41,7 @@ namespace Echoion::Core
|
||||
if (page < 1) {
|
||||
page = 1;
|
||||
}
|
||||
} catch (...) {
|
||||
} catch (const std::exception&) {
|
||||
page = 1;
|
||||
}
|
||||
}
|
||||
@@ -96,7 +96,8 @@ namespace Echoion::Core
|
||||
}
|
||||
msg << std::format(
|
||||
"\n**Now Playing:** {}{}\n",
|
||||
markdownLink(displayText, trackInfo.shortenedUrl),
|
||||
markdownLink(displayText,
|
||||
trackLinkUrl(trackInfo)),
|
||||
timeStr);
|
||||
}
|
||||
|
||||
@@ -120,7 +121,7 @@ namespace Echoion::Core
|
||||
msg << std::format(
|
||||
"{}. {}", i + 1,
|
||||
markdownLink(displayText,
|
||||
trackInfo.shortenedUrl));
|
||||
trackLinkUrl(trackInfo)));
|
||||
if (trackInfo.duration.has_value()) {
|
||||
msg << std::format(
|
||||
" {} {}", kDot,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#pragma once
|
||||
|
||||
#include "../MusicManager.hpp"
|
||||
#include "Command.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
@@ -8,7 +9,9 @@
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class SearchCommand : public Command
|
||||
// Shared search rendering. Concrete commands pick the catalog scope:
|
||||
// !search (both), !youtube/!yb (YouTube), !ya/!yandex (Yandex).
|
||||
class SearchCommandBase : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
@@ -23,12 +26,11 @@ namespace Echoion::Core
|
||||
}
|
||||
|
||||
if (ctx.args.empty()) {
|
||||
ctx.reply("Usage: search <query>\nExample: search "
|
||||
"never gonna give you up");
|
||||
ctx.reply(std::format("Usage: {} <query>", label()));
|
||||
return;
|
||||
}
|
||||
|
||||
auto result = manager->search(ctx.args);
|
||||
auto result = manager->search(ctx.args, scope());
|
||||
if (!result) {
|
||||
Void::Log::error("SearchCommand", "{}",
|
||||
std::format("Search failed for '{}': {}", ctx.args,
|
||||
@@ -67,7 +69,7 @@ namespace Echoion::Core
|
||||
// duration: TeamSpeak parses [..] as a link reference).
|
||||
msg << std::format(
|
||||
"{}. {}", i + 1,
|
||||
markdownLink(displayText, track.shortenedUrl));
|
||||
markdownLink(displayText, trackLinkUrl(track)));
|
||||
if (track.duration.has_value()) {
|
||||
msg << " " << kDot << " "
|
||||
<< formatDuration(*track.duration);
|
||||
@@ -82,28 +84,23 @@ namespace Echoion::Core
|
||||
ctx.reply(msg.str());
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
Void::Log::error("SearchCommand", "{}",
|
||||
Void::Log::error("SearchCommand", "{}",
|
||||
std::format("Search command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Searches for tracks and shows results.";
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override { return "<query>"; }
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Music;
|
||||
return CommandCategory::Search;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"find", "s"};
|
||||
}
|
||||
protected:
|
||||
|
||||
// The catalog(s) this command searches, and the command name
|
||||
// used in usage text.
|
||||
[[nodiscard]] virtual MusicManager::SearchScope scope() const = 0;
|
||||
[[nodiscard]] virtual std::string_view label() const = 0;
|
||||
|
||||
private:
|
||||
|
||||
@@ -122,4 +119,28 @@ namespace Echoion::Core
|
||||
}
|
||||
};
|
||||
|
||||
// !search — both YouTube and Yandex Music.
|
||||
class SearchCommand : public SearchCommandBase
|
||||
{
|
||||
public:
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Search YouTube and Yandex Music for tracks.";
|
||||
}
|
||||
std::string_view getUsage() const override { return "<query>"; }
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"find", "s"};
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
MusicManager::SearchScope scope() const override
|
||||
{
|
||||
return MusicManager::SearchScope::All;
|
||||
}
|
||||
std::string_view label() const override { return "search"; }
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,55 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include <Database.hpp>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// !stats — global playback statistics.
|
||||
class StatsCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
auto db = ctx.service<Api::Database>();
|
||||
if (!db) {
|
||||
ctx.reply("Statistics are unavailable (no database).");
|
||||
return;
|
||||
}
|
||||
|
||||
auto stats = db->getStatistics(0);
|
||||
if (!stats) {
|
||||
ctx.reply("Couldn't read playback statistics.");
|
||||
return;
|
||||
}
|
||||
|
||||
const auto totalMinutes =
|
||||
stats->totalPlaytimeMs / 1000 / 60;
|
||||
std::string msg = std::format(
|
||||
"\xf0\x9f\x93\x8a Plays: {} {} Unique tracks: {} {} "
|
||||
"Playtime: {}h {}m",
|
||||
stats->totalPlays, kDot, stats->totalTracks, kDot,
|
||||
totalMinutes / 60, totalMinutes % 60);
|
||||
if (stats->mostPlayedTrack) {
|
||||
msg += std::format("\nMost played: {} ({}x)",
|
||||
trackLink(*stats->mostPlayedTrack),
|
||||
stats->mostPlayedCount);
|
||||
}
|
||||
ctx.reply(msg);
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Show playback statistics";
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Utility;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,35 @@
|
||||
#pragma once
|
||||
|
||||
#include "PlayCommand.hpp"
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// !pya / !playya — play from Yandex Music only.
|
||||
class YandexPlayCommand : public PlayCommandBase
|
||||
{
|
||||
public:
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Plays from Yandex Music only (URL or search).";
|
||||
}
|
||||
std::string_view getUsage() const override
|
||||
{
|
||||
return "<url or search query>";
|
||||
}
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"playya"};
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
MusicManager::SearchScope scope() const override
|
||||
{
|
||||
return MusicManager::SearchScope::Yandex;
|
||||
}
|
||||
std::string_view label() const override { return "pya"; }
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,32 @@
|
||||
#pragma once
|
||||
|
||||
#include "SearchCommand.hpp"
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// !yandex / !ya — search Yandex Music only.
|
||||
class YandexSearchCommand : public SearchCommandBase
|
||||
{
|
||||
public:
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Search Yandex Music only for tracks.";
|
||||
}
|
||||
std::string_view getUsage() const override { return "<query>"; }
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"ya"};
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
MusicManager::SearchScope scope() const override
|
||||
{
|
||||
return MusicManager::SearchScope::Yandex;
|
||||
}
|
||||
std::string_view label() const override { return "yandex"; }
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,35 @@
|
||||
#pragma once
|
||||
|
||||
#include "PlayCommand.hpp"
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// !pyt / !playyt — play from YouTube only.
|
||||
class YoutubePlayCommand : public PlayCommandBase
|
||||
{
|
||||
public:
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Plays from YouTube only (URL or search).";
|
||||
}
|
||||
std::string_view getUsage() const override
|
||||
{
|
||||
return "<url or search query>";
|
||||
}
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"playyt"};
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
MusicManager::SearchScope scope() const override
|
||||
{
|
||||
return MusicManager::SearchScope::YouTube;
|
||||
}
|
||||
std::string_view label() const override { return "pyt"; }
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,32 @@
|
||||
#pragma once
|
||||
|
||||
#include "SearchCommand.hpp"
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// !youtube / !yb — search YouTube only.
|
||||
class YoutubeSearchCommand : public SearchCommandBase
|
||||
{
|
||||
public:
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Search YouTube only for tracks.";
|
||||
}
|
||||
std::string_view getUsage() const override { return "<query>"; }
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"yb", "yt"};
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
MusicManager::SearchScope scope() const override
|
||||
{
|
||||
return MusicManager::SearchScope::YouTube;
|
||||
}
|
||||
std::string_view label() const override { return "youtube"; }
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,93 @@
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstddef>
|
||||
#include <span>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// Fixed-capacity ring buffer of audio samples for the playback thread.
|
||||
//
|
||||
// A std::vector<short> drained with erase(begin(), begin()+n) every 20ms
|
||||
// is an O(n) shift of the whole remaining buffer on the real-time audio
|
||||
// path. This ring buffer drains by advancing a head index (O(1)) and
|
||||
// reuses one contiguous allocation, so steady-state playback performs
|
||||
// zero per-frame allocations and no element shuffling. Capacity grows
|
||||
// only if a decoder hands back an unusually large chunk (rare); steady
|
||||
// state never reallocates.
|
||||
//
|
||||
// Single-threaded by design: owned and touched only by the playback
|
||||
// engine thread.
|
||||
class AudioRingBuffer
|
||||
{
|
||||
public:
|
||||
|
||||
void reserve(std::size_t capacity)
|
||||
{
|
||||
if (capacity > storage_.size()) {
|
||||
grow(capacity);
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t size() const { return count_; }
|
||||
[[nodiscard]] bool empty() const { return count_ == 0; }
|
||||
|
||||
// Read the i-th sample counting from the current head.
|
||||
short operator[](std::size_t i) const
|
||||
{
|
||||
return storage_[(head_ + i) % storage_.size()];
|
||||
}
|
||||
|
||||
void append(std::span<const short> data)
|
||||
{
|
||||
if (count_ + data.size() > storage_.size()) {
|
||||
grow(count_ + data.size());
|
||||
}
|
||||
const std::size_t cap = storage_.size();
|
||||
std::size_t tail = (head_ + count_) % cap;
|
||||
for (short sample : data) {
|
||||
storage_[tail] = sample;
|
||||
tail = (tail + 1) % cap;
|
||||
}
|
||||
count_ += data.size();
|
||||
}
|
||||
|
||||
// Drop the first n samples (advance head). O(1).
|
||||
void popFront(std::size_t n)
|
||||
{
|
||||
n = std::min(n, count_);
|
||||
head_ = (head_ + n) % storage_.size();
|
||||
count_ -= n;
|
||||
}
|
||||
|
||||
void clear()
|
||||
{
|
||||
head_ = 0;
|
||||
count_ = 0;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
void grow(std::size_t needed)
|
||||
{
|
||||
// Linearise existing samples into a fresh, larger buffer.
|
||||
std::size_t newCap = storage_.empty() ? 1 : storage_.size();
|
||||
while (newCap < needed) {
|
||||
newCap *= 2;
|
||||
}
|
||||
std::vector<short> next(newCap);
|
||||
for (std::size_t i = 0; i < count_; ++i) {
|
||||
next[i] = storage_[(head_ + i) % storage_.size()];
|
||||
}
|
||||
storage_ = std::move(next);
|
||||
head_ = 0;
|
||||
}
|
||||
|
||||
std::vector<short> storage_;
|
||||
std::size_t head_ = 0;
|
||||
std::size_t count_ = 0;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,331 @@
|
||||
#pragma once
|
||||
|
||||
#include "../AudioDecoder.hpp"
|
||||
#include "AudioRingBuffer.hpp"
|
||||
#include "PositionClock.hpp"
|
||||
#include <TrackTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <deque>
|
||||
#include <future>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <thread>
|
||||
#include <variant>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// Everything the engine needs from the outside world. Implemented by
|
||||
// MusicManager; keeps queue policy, source resolution and event
|
||||
// publication out of the real-time loop.
|
||||
class IPlaybackHost
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~IPlaybackHost() = default;
|
||||
|
||||
// Emit one 20ms PCM chunk to the audio sink (TeamSpeak).
|
||||
virtual void emitAudio(std::span<const short> samples) = 0;
|
||||
|
||||
// Resolve a playable URL / local file path for the entry.
|
||||
// Blocking; the engine calls it on a detached async, never on the
|
||||
// audio thread. preferDownload retries via the proxy-download
|
||||
// path after a direct open failed.
|
||||
virtual Api::Result<std::string>
|
||||
resolveStream(const Api::QueueEntry& entry,
|
||||
bool preferDownload) = 0;
|
||||
|
||||
// Queue access: peek what would play next / pop it if unchanged.
|
||||
virtual std::optional<Api::QueueEntry> peekNextTrack() = 0;
|
||||
virtual std::optional<Api::QueueEntry>
|
||||
takeNextTrack(uint64_t expectedQueueId) = 0;
|
||||
// Unconditional pop (fallback when the peeked entry vanished).
|
||||
virtual std::optional<Api::QueueEntry> takeAnyNextTrack() = 0;
|
||||
|
||||
virtual bool repeatEnabled() const = 0;
|
||||
|
||||
// Lifecycle notifications (called on the engine thread).
|
||||
virtual void onTrackStarted(const Api::QueueEntry& entry) = 0;
|
||||
virtual void
|
||||
onTrackFinished(const Api::QueueEntry& entry,
|
||||
std::chrono::milliseconds finalPosition) = 0;
|
||||
virtual void onPositionTick(const Api::QueueEntry& entry,
|
||||
std::chrono::milliseconds position,
|
||||
std::chrono::milliseconds duration) = 0;
|
||||
// Queue ran dry; engine went idle.
|
||||
virtual void onEngineIdle() = 0;
|
||||
// A resolved local temp file finished playing and can be deleted.
|
||||
virtual void onLocalFileDone(const std::string& path) = 0;
|
||||
// A track failed to resolve or open (before the engine advanced
|
||||
// past it). Called on the engine thread.
|
||||
virtual void
|
||||
onPlaybackError(const Api::Error& error,
|
||||
const std::optional<Api::QueueEntry>& entry) = 0;
|
||||
};
|
||||
|
||||
// Real-time playback engine with gapless track transitions.
|
||||
//
|
||||
// One fixed-cadence (20ms) loop owns BOTH AudioDecoder instances, the
|
||||
// ring buffer and the position clock; no other thread ever touches them.
|
||||
// Control arrives through a small command mailbox; state is published
|
||||
// through atomics. While the current track plays, the next one is
|
||||
// resolved asynchronously and its decoder pre-opened ("warm"), so at EOF
|
||||
// the engine swaps slots and PCM flows without interruption.
|
||||
class PlaybackEngine
|
||||
{
|
||||
public:
|
||||
|
||||
// Sample layout must match the TS3 custom device registration.
|
||||
static constexpr uint32_t SAMPLE_RATE = 192000;
|
||||
static constexpr uint32_t CHANNELS = 2;
|
||||
static constexpr int CHUNK_MS = 20;
|
||||
static constexpr size_t SHORTS_PER_CHUNK =
|
||||
(SAMPLE_RATE * CHANNELS * CHUNK_MS) / 1000;
|
||||
static constexpr auto PREFETCH_THRESHOLD =
|
||||
std::chrono::seconds(15);
|
||||
static constexpr int MAX_CONSECUTIVE_FAILURES = 5;
|
||||
|
||||
// How long the engine emits silence waiting for a late resolve
|
||||
// before it gives up on the track and advances. Configurable via
|
||||
// bot.trackTimeout.
|
||||
void setResolveGrace(std::chrono::milliseconds grace)
|
||||
{
|
||||
if (grace.count() > 0) {
|
||||
resolveGraceMs_.store(grace.count());
|
||||
}
|
||||
}
|
||||
|
||||
// Crossfade duration between tracks (bot.crossfadeMs);
|
||||
// 0 = plain gapless handoff.
|
||||
void setCrossfade(std::chrono::milliseconds duration)
|
||||
{
|
||||
crossfadeMs_.store(std::max<int64_t>(duration.count(), 0));
|
||||
}
|
||||
|
||||
// Loudness normalization (features.normalizeLoudness /
|
||||
// targetLoudnessDb): slow AGC toward the target RMS level,
|
||||
// applied before the user volume.
|
||||
void setNormalization(bool enabled, float targetDb)
|
||||
{
|
||||
normalizeTargetDb_.store(targetDb);
|
||||
normalizeEnabled_.store(enabled);
|
||||
}
|
||||
|
||||
explicit PlaybackEngine(IPlaybackHost& host);
|
||||
~PlaybackEngine();
|
||||
|
||||
Api::Result<void> initialize(
|
||||
const std::optional<Void::Net::ProxyConfig>& proxy);
|
||||
void shutdown();
|
||||
|
||||
void setProxyConfig(
|
||||
const std::optional<Void::Net::ProxyConfig>& proxy);
|
||||
|
||||
// ---- control (thread-safe, non-blocking) ---------------------
|
||||
|
||||
// Play this entry now, replacing whatever is playing. The URL was
|
||||
// already resolved by the caller (so resolution errors could be
|
||||
// reported to the user synchronously).
|
||||
void playNow(Api::QueueEntry entry, std::string streamUrl,
|
||||
bool isLocalFile);
|
||||
|
||||
// Wake the engine so it pulls from the queue if it is idle.
|
||||
void start();
|
||||
|
||||
void pause();
|
||||
void resume();
|
||||
void stopPlayback(); // stop + drop current track (engine idles)
|
||||
void skip(uint32_t count);
|
||||
void seekTo(std::chrono::milliseconds position);
|
||||
|
||||
// Restore after hot reload: open url, seek, optionally stay
|
||||
// paused.
|
||||
void restore(Api::QueueEntry entry, std::string streamUrl,
|
||||
std::chrono::milliseconds position, bool paused);
|
||||
|
||||
void setVolume(float volume) { volume_.store(volume); }
|
||||
[[nodiscard]] float volume() const { return volume_.load(); }
|
||||
|
||||
// ---- state (thread-safe reads) --------------------------------
|
||||
|
||||
[[nodiscard]] bool isPlaying() const { return playing_.load(); }
|
||||
[[nodiscard]] bool isPaused() const { return paused_.load(); }
|
||||
[[nodiscard]] std::chrono::milliseconds position() const
|
||||
{
|
||||
return clock_.position();
|
||||
}
|
||||
[[nodiscard]] std::optional<Api::QueueEntry> currentEntry() const;
|
||||
[[nodiscard]] std::chrono::milliseconds currentDuration() const;
|
||||
|
||||
private:
|
||||
|
||||
// ---- mailbox ---------------------------------------------------
|
||||
|
||||
struct CmdPlayNow {
|
||||
Api::QueueEntry entry;
|
||||
std::string url;
|
||||
bool isLocalFile = false;
|
||||
};
|
||||
struct CmdStart {};
|
||||
struct CmdPause {};
|
||||
struct CmdResume {};
|
||||
struct CmdStop {};
|
||||
struct CmdSkip {
|
||||
uint32_t count = 1;
|
||||
};
|
||||
struct CmdSeek {
|
||||
std::chrono::milliseconds position;
|
||||
};
|
||||
struct CmdRestore {
|
||||
Api::QueueEntry entry;
|
||||
std::string url;
|
||||
std::chrono::milliseconds position;
|
||||
bool paused = false;
|
||||
};
|
||||
using Command =
|
||||
std::variant<CmdPlayNow, CmdStart, CmdPause, CmdResume,
|
||||
CmdStop, CmdSkip, CmdSeek, CmdRestore>;
|
||||
|
||||
void post(Command cmd);
|
||||
|
||||
// ---- decoder slots --------------------------------------------
|
||||
|
||||
struct ResolvedStream {
|
||||
std::string url;
|
||||
bool isLocalFile = false;
|
||||
};
|
||||
|
||||
struct DecoderSlot {
|
||||
enum class State {
|
||||
Idle, // nothing assigned
|
||||
Resolving, // resolveFuture in flight
|
||||
Warming, // decoder open, pre-filling its queue
|
||||
Active, // currently feeding the ring buffer
|
||||
};
|
||||
|
||||
State state = State::Idle;
|
||||
std::unique_ptr<AudioDecoder> decoder;
|
||||
std::optional<Api::QueueEntry> entry;
|
||||
std::future<Api::Result<std::string>> resolveFuture;
|
||||
std::chrono::steady_clock::time_point resolveStartedAt{};
|
||||
std::string openUrl;
|
||||
bool isLocalFile = false;
|
||||
// Whether the download-to-file fallback was already tried
|
||||
// for this entry (bounds the retry to one attempt).
|
||||
bool triedDownload = false;
|
||||
|
||||
void closeAndReset()
|
||||
{
|
||||
if (decoder) {
|
||||
decoder->closeSource();
|
||||
}
|
||||
state = State::Idle;
|
||||
entry.reset();
|
||||
resolveFuture = {};
|
||||
openUrl.clear();
|
||||
isLocalFile = false;
|
||||
triedDownload = false;
|
||||
}
|
||||
};
|
||||
|
||||
// Kick off an async download-to-file retry for the slot's entry
|
||||
// (preferDownload=true). Returns false when no retry is possible
|
||||
// (already tried, or no entry).
|
||||
bool retryViaDownload(DecoderSlot& slot);
|
||||
|
||||
// ---- engine thread --------------------------------------------
|
||||
|
||||
void run(std::stop_token st);
|
||||
void drainMailbox();
|
||||
void handle(CmdPlayNow&& cmd);
|
||||
void handle(CmdStart&&);
|
||||
void handle(CmdPause&&);
|
||||
void handle(CmdResume&&);
|
||||
void handle(CmdStop&&);
|
||||
void handle(CmdSkip&& cmd);
|
||||
void handle(CmdSeek&& cmd);
|
||||
void handle(CmdRestore&& cmd);
|
||||
|
||||
// Try to begin playing the next queued track in the current slot
|
||||
// (used when idle). Returns true when a track started resolving
|
||||
// or playing.
|
||||
bool beginNextFromQueue();
|
||||
|
||||
// Kick off async resolution of the upcoming track into next_.
|
||||
void maybeStartPrefetch();
|
||||
// Move a finished resolve into an open, warming decoder.
|
||||
void pollNextResolve();
|
||||
// Current track hit EOF and drained: hand off or advance.
|
||||
void handleTrackEnd();
|
||||
// Crossfade: drain the current track's tail and swap to the warm
|
||||
// slot early so emitChunk can mix the two.
|
||||
void beginCrossfade();
|
||||
void clearFade()
|
||||
{
|
||||
fadeTail_.clear();
|
||||
fadePos_ = 0;
|
||||
}
|
||||
// AGC gain for one chunk (updates the internal RMS/gain state).
|
||||
[[nodiscard]] float agcGainFor(std::size_t samples);
|
||||
// Open `slot`'s decoder for `url`; false on failure.
|
||||
bool openSlot(DecoderSlot& slot, const std::string& url,
|
||||
bool isLocalFile);
|
||||
void activateSlot(DecoderSlot& slot,
|
||||
std::chrono::milliseconds startAt =
|
||||
std::chrono::milliseconds(0));
|
||||
void publishCurrent(const std::optional<Api::QueueEntry>& entry);
|
||||
void emitChunk(bool fromRing);
|
||||
void positionTick();
|
||||
|
||||
IPlaybackHost& host_;
|
||||
|
||||
// Mailbox
|
||||
std::mutex mailboxMutex_;
|
||||
std::deque<Command> mailbox_;
|
||||
std::condition_variable mailboxCv_;
|
||||
|
||||
// Engine-thread-only state
|
||||
DecoderSlot current_;
|
||||
DecoderSlot next_;
|
||||
AudioRingBuffer ring_;
|
||||
std::vector<short> outChunk_;
|
||||
std::vector<int16_t> incomingChunk_;
|
||||
std::chrono::steady_clock::time_point nextTick_{};
|
||||
std::chrono::steady_clock::time_point lastPositionTick_{};
|
||||
std::chrono::steady_clock::time_point silenceSince_{};
|
||||
int consecutiveFailures_ = 0;
|
||||
|
||||
// Crossfade state (engine thread only): the outgoing track's
|
||||
// remaining PCM, mixed into the incoming track equal-power.
|
||||
std::vector<short> fadeTail_;
|
||||
std::size_t fadePos_ = 0;
|
||||
|
||||
// AGC state (engine thread only): EMA of mean-square level and
|
||||
// the current smoothed gain in dB.
|
||||
double agcMeanSquare_ = 0.0;
|
||||
float agcGainDb_ = 0.0f;
|
||||
|
||||
// Published state
|
||||
std::atomic<bool> playing_{false};
|
||||
std::atomic<bool> paused_{false};
|
||||
std::atomic<float> volume_{0.5f};
|
||||
std::atomic<int64_t> resolveGraceMs_{10000};
|
||||
std::atomic<int64_t> crossfadeMs_{0};
|
||||
std::atomic<bool> normalizeEnabled_{false};
|
||||
std::atomic<float> normalizeTargetDb_{-14.0f};
|
||||
PositionClock clock_;
|
||||
mutable std::mutex currentEntryMutex_;
|
||||
std::optional<Api::QueueEntry> publishedEntry_;
|
||||
std::atomic<int64_t> currentDurationMs_{0};
|
||||
|
||||
std::optional<Void::Net::ProxyConfig> proxy_;
|
||||
std::jthread thread_;
|
||||
std::atomic<bool> initialized_{false};
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,89 @@
|
||||
#pragma once
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// Wall-clock based playback position. Replaces the playbackPosition_ /
|
||||
// playbackBasePosition_ / playbackStartTime_ triple whose reset logic was
|
||||
// duplicated across play/resume/skip/seek/track-finished/restore.
|
||||
//
|
||||
// Lock-free: the engine thread writes, any thread reads a consistent
|
||||
// position (worst case one field is a few ns stale, irrelevant at ms
|
||||
// granularity for UI display).
|
||||
class PositionClock
|
||||
{
|
||||
public:
|
||||
|
||||
using ms = std::chrono::milliseconds;
|
||||
|
||||
// Track started from zero (or restarted); clock runs.
|
||||
void restart()
|
||||
{
|
||||
seekTo(ms{0});
|
||||
running_.store(true);
|
||||
}
|
||||
|
||||
// Jump to a position and keep running/paused state.
|
||||
void seekTo(ms position)
|
||||
{
|
||||
baseMs_.store(position.count());
|
||||
startedAtNs_.store(nowNs());
|
||||
}
|
||||
|
||||
void pause()
|
||||
{
|
||||
if (!running_.exchange(false)) {
|
||||
return;
|
||||
}
|
||||
baseMs_.store(currentMs());
|
||||
}
|
||||
|
||||
void resume()
|
||||
{
|
||||
if (running_.load()) {
|
||||
return; // already running; resetting startedAt would
|
||||
// rewind the position
|
||||
}
|
||||
startedAtNs_.store(nowNs());
|
||||
running_.store(true);
|
||||
}
|
||||
|
||||
void stop()
|
||||
{
|
||||
running_.store(false);
|
||||
baseMs_.store(0);
|
||||
}
|
||||
|
||||
[[nodiscard]] bool running() const { return running_.load(); }
|
||||
|
||||
[[nodiscard]] ms position() const { return ms{currentMs()}; }
|
||||
|
||||
private:
|
||||
|
||||
[[nodiscard]] static int64_t nowNs()
|
||||
{
|
||||
return std::chrono::duration_cast<std::chrono::nanoseconds>(
|
||||
std::chrono::steady_clock::now().time_since_epoch())
|
||||
.count();
|
||||
}
|
||||
|
||||
[[nodiscard]] int64_t currentMs() const
|
||||
{
|
||||
const int64_t base = baseMs_.load();
|
||||
if (!running_.load()) {
|
||||
return base;
|
||||
}
|
||||
const int64_t elapsedNs = nowNs() - startedAtNs_.load();
|
||||
return base + elapsedNs / 1'000'000;
|
||||
}
|
||||
|
||||
std::atomic<int64_t> baseMs_{0};
|
||||
std::atomic<int64_t> startedAtNs_{0};
|
||||
std::atomic<bool> running_{false};
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,97 @@
|
||||
#pragma once
|
||||
|
||||
#include <TrackTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <cstdint>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// Owns the playback queue, shuffle order and repeat flag. Self-locking:
|
||||
// every public method takes the internal mutex, so callers never manage
|
||||
// queue locks (the old QueueManager exposed raw references and relied on
|
||||
// MusicManager's shared_mutex, which several writers acquired shared).
|
||||
//
|
||||
// Shuffle model: shuffledIndices_ is a permutation of positions into
|
||||
// entries_; shuffleIndex_ is the cursor of the next shuffled pick.
|
||||
// Removing/moving/adding entries fixes the permutation up in place, so
|
||||
// already-played order is preserved.
|
||||
class QueueService
|
||||
{
|
||||
public:
|
||||
|
||||
using Entry = Api::QueueEntry;
|
||||
|
||||
// ---- mutation -------------------------------------------------
|
||||
|
||||
// Appends a track. Fails when the queue is at maxSize.
|
||||
Api::Result<uint64_t> enqueue(const Api::TrackInfo& track,
|
||||
std::string addedBy,
|
||||
std::size_t maxSize);
|
||||
|
||||
// Removes the entry at `position`; returns it for event payloads.
|
||||
Api::Result<Entry> removeAt(uint32_t position);
|
||||
|
||||
// Returns the number of entries removed.
|
||||
uint32_t clear();
|
||||
|
||||
// Moves an entry; returns its queueId for event payloads.
|
||||
Api::Result<uint64_t> move(uint32_t from, uint32_t to);
|
||||
|
||||
// Pops the next entry honouring shuffle order.
|
||||
std::optional<Entry> popNext();
|
||||
|
||||
// Pops the next entry only if it is still the given one — the
|
||||
// gapless engine peeks, warms a decoder, and commits at the swap;
|
||||
// queue edits in between invalidate the warm slot.
|
||||
std::optional<Entry> popIfNext(uint64_t queueId);
|
||||
|
||||
// Replace the whole queue (hot-reload restore).
|
||||
void replaceAll(std::vector<Entry> entries);
|
||||
|
||||
// In-place random shuffle of the raw order (legacy !shufflequeue).
|
||||
void shuffleInPlace();
|
||||
|
||||
// ---- shuffle / repeat -----------------------------------------
|
||||
|
||||
bool toggleShuffle();
|
||||
void setShuffle(bool enabled);
|
||||
[[nodiscard]] bool shuffleEnabled() const;
|
||||
|
||||
bool toggleRepeat();
|
||||
void setRepeat(bool enabled);
|
||||
[[nodiscard]] bool repeatEnabled() const;
|
||||
|
||||
// ---- inspection -----------------------------------------------
|
||||
|
||||
[[nodiscard]] std::optional<Entry> peekNext() const;
|
||||
[[nodiscard]] std::vector<Entry> snapshot() const;
|
||||
[[nodiscard]] std::size_t size() const;
|
||||
[[nodiscard]] bool empty() const;
|
||||
|
||||
// Allocate a queue id for entries created outside the queue (the
|
||||
// immediately-played track in play()).
|
||||
[[nodiscard]] uint64_t allocateQueueId();
|
||||
|
||||
private:
|
||||
|
||||
// All *Locked helpers assume mutex_ is held.
|
||||
void rebuildShuffledIndicesLocked();
|
||||
[[nodiscard]] std::optional<std::size_t> nextPositionLocked() const;
|
||||
std::optional<Entry> popNextLocked();
|
||||
|
||||
mutable std::mutex mutex_;
|
||||
std::vector<Entry> entries_;
|
||||
std::vector<std::size_t> shuffledIndices_;
|
||||
std::size_t shuffleIndex_ = 0;
|
||||
uint64_t nextQueueId_ = 1;
|
||||
bool shuffle_ = false;
|
||||
bool repeat_ = false;
|
||||
std::mt19937 rng_{std::random_device{}()};
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,34 @@
|
||||
#pragma once
|
||||
|
||||
#include "TrackSource.hpp"
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// Pass-through for URLs that already point at an audio stream (radio
|
||||
// streams, .mp3/.ogg/.opus/.m3u8 files, icecast mounts). No network work
|
||||
// at resolve time — ffmpeg opens the URL directly.
|
||||
class DirectUrlSource : public ITrackSource
|
||||
{
|
||||
public:
|
||||
|
||||
[[nodiscard]] std::string_view name() const override
|
||||
{
|
||||
return "direct-url";
|
||||
}
|
||||
[[nodiscard]] bool canHandle(const std::string& query) const override;
|
||||
[[nodiscard]] bool isAvailable() const override { return true; }
|
||||
[[nodiscard]] bool supportsSearch() const override
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
Api::Result<Api::SearchResult>
|
||||
search(std::string_view query) override;
|
||||
Api::Result<Api::TrackInfo>
|
||||
resolve(const std::string& urlOrId) override;
|
||||
Api::Result<StreamHandle>
|
||||
getStream(const Api::TrackInfo& track) override;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,86 @@
|
||||
#pragma once
|
||||
|
||||
#include "../NetworkClient.hpp"
|
||||
#include "../SignatureCipher.hpp"
|
||||
#include "TrackSource.hpp"
|
||||
#include <atomic>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// Native YouTube resolution through the innertube player API — one HTTP
|
||||
// POST instead of a yt-dlp subprocess, so it is by far the fastest
|
||||
// YouTube path. Requests go through the configured proxy (NetworkClient
|
||||
// applies it); youtubei is ISP-blocked here, so with requireProxy=true
|
||||
// (default) the source reports unavailable when no proxy is set and the
|
||||
// router skips it.
|
||||
//
|
||||
// Client strategy: the IOS client historically returns direct
|
||||
// adaptiveFormats[].url with no signature deciphering. When it yields
|
||||
// nothing playable, the WEB client + SignatureCipher (quickjs solver)
|
||||
// deciphers signatureCipher/n-param challenges.
|
||||
class InnertubeSource : public ITrackSource
|
||||
{
|
||||
public:
|
||||
|
||||
// endpointOverride points tests at a StubHttpServer; production
|
||||
// passes nothing and talks to https://www.youtube.com.
|
||||
explicit InnertubeSource(std::shared_ptr<NetworkClient> network,
|
||||
std::string endpointOverride = "");
|
||||
|
||||
void configure(bool enabled, bool requireProxy);
|
||||
|
||||
[[nodiscard]] std::string_view name() const override
|
||||
{
|
||||
return "innertube";
|
||||
}
|
||||
[[nodiscard]] bool canHandle(const std::string& query) const override;
|
||||
[[nodiscard]] bool isAvailable() const override;
|
||||
[[nodiscard]] bool supportsSearch() const override
|
||||
{
|
||||
return false; // text search runs through the yt-dlp sources
|
||||
}
|
||||
|
||||
Api::Result<Api::SearchResult>
|
||||
search(std::string_view query) override;
|
||||
Api::Result<Api::TrackInfo>
|
||||
resolve(const std::string& urlOrId) override;
|
||||
Api::Result<StreamHandle>
|
||||
getStream(const Api::TrackInfo& track) override;
|
||||
|
||||
private:
|
||||
|
||||
struct PlayerResponse {
|
||||
std::string title;
|
||||
std::string author;
|
||||
int64_t lengthSeconds = 0;
|
||||
std::string thumbnailUrl;
|
||||
std::string streamUrl; // direct url when present
|
||||
std::string signatureCipher; // needs deciphering
|
||||
};
|
||||
|
||||
// POST youtubei/v1/player with the given client context; parses
|
||||
// the best audio format out of the response.
|
||||
Api::Result<PlayerResponse> callPlayer(const std::string& videoId,
|
||||
bool webClient);
|
||||
|
||||
// WEB fallback: fetch the watch page + player JS, feed the
|
||||
// cipher, decipher the signatureCipher/n-param challenge.
|
||||
Api::Result<std::string>
|
||||
decipherWithWebPlayer(const std::string& videoId,
|
||||
const std::string& signatureCipher);
|
||||
|
||||
std::shared_ptr<NetworkClient> network_;
|
||||
std::string endpoint_;
|
||||
std::atomic<bool> enabled_{true};
|
||||
std::atomic<bool> requireProxy_{true};
|
||||
|
||||
// Lazy cipher state (only the WEB fallback needs it).
|
||||
std::mutex cipherMutex_;
|
||||
std::unique_ptr<SignatureCipher> cipher_;
|
||||
std::string loadedPlayerJsUrl_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,74 @@
|
||||
#pragma once
|
||||
|
||||
#include "TrackSource.hpp"
|
||||
#include <chrono>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// Ordered chain of track sources with per-source failure cooldown and a
|
||||
// stream-URL cache. Resolution walks the configured order and takes the
|
||||
// first source that canHandle() the query, is available, and succeeds;
|
||||
// failures put a source on cooldown (skipped unless it is the last
|
||||
// candidate) and fall through to the next.
|
||||
class SourceRouter
|
||||
{
|
||||
public:
|
||||
|
||||
void setSources(std::vector<std::shared_ptr<ITrackSource>> sources);
|
||||
|
||||
// Reorder/enable per config; names not found are ignored, sources
|
||||
// not named are dropped from the chain.
|
||||
void setOrder(const std::vector<std::string>& order);
|
||||
void setFailureCooldown(std::chrono::milliseconds cooldown);
|
||||
// Hedged getStream: when the first candidate hasn't answered
|
||||
// within this delay, race the second one (first success wins).
|
||||
// 0 disables hedging.
|
||||
void setHedgeDelay(std::chrono::milliseconds delay);
|
||||
|
||||
// Text search across the first searching source that succeeds.
|
||||
[[nodiscard]] Api::Result<Api::SearchResult>
|
||||
search(std::string_view query);
|
||||
|
||||
// URL/id/text -> track metadata.
|
||||
[[nodiscard]] Api::Result<Api::TrackInfo>
|
||||
resolve(const std::string& query);
|
||||
|
||||
// Track -> playable stream handle (cached).
|
||||
[[nodiscard]] Api::Result<StreamHandle>
|
||||
getStream(const Api::TrackInfo& track);
|
||||
|
||||
// A cached/served handle failed to open: evict it and demote the
|
||||
// producing source so the next resolve tries elsewhere.
|
||||
void invalidate(const std::string& trackId);
|
||||
|
||||
private:
|
||||
|
||||
struct CachedStream {
|
||||
StreamHandle handle;
|
||||
std::chrono::steady_clock::time_point expiry;
|
||||
};
|
||||
|
||||
struct SourceState {
|
||||
std::shared_ptr<ITrackSource> source;
|
||||
std::chrono::steady_clock::time_point cooldownUntil{};
|
||||
};
|
||||
|
||||
[[nodiscard]] std::vector<SourceState*>
|
||||
candidatesFor(const std::string& query, bool needSearch);
|
||||
void reportFailure(SourceState& state);
|
||||
|
||||
mutable std::mutex mutex_;
|
||||
std::vector<std::shared_ptr<ITrackSource>> allSources_;
|
||||
std::vector<SourceState> chain_;
|
||||
std::chrono::milliseconds cooldown_{std::chrono::minutes(5)};
|
||||
std::chrono::milliseconds hedgeDelay_{std::chrono::milliseconds(300)};
|
||||
std::unordered_map<std::string, CachedStream> streamCache_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,57 @@
|
||||
#pragma once
|
||||
|
||||
#include <TrackTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// A playable handle produced by a source: either an http(s) URL the
|
||||
// decoder can stream, or a local file path (downloaded audio) the caller
|
||||
// must delete after playback.
|
||||
struct StreamHandle {
|
||||
std::string url;
|
||||
bool isLocalFile = false;
|
||||
std::string sourceName; // for logging / failure attribution
|
||||
};
|
||||
|
||||
// One catalog/stream backend in the resolution chain. Implementations:
|
||||
// InnertubeSource (native YouTube player API), YandexMusicSource (native
|
||||
// Yandex Music), DirectUrlSource (raw audio URLs), YtDlpSource (direct
|
||||
// and proxied yt-dlp).
|
||||
class ITrackSource
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~ITrackSource() = default;
|
||||
|
||||
[[nodiscard]] virtual std::string_view name() const = 0;
|
||||
|
||||
// Can this source resolve the query at all? URLs are matched by
|
||||
// host/scheme; bare text search is handled only by
|
||||
// YouTube-catalog sources.
|
||||
[[nodiscard]] virtual bool
|
||||
canHandle(const std::string& query) const = 0;
|
||||
|
||||
// Health gate — sources with no healthy instances report false
|
||||
// and are skipped by the router.
|
||||
[[nodiscard]] virtual bool isAvailable() const = 0;
|
||||
|
||||
// Does this source implement text search?
|
||||
[[nodiscard]] virtual bool supportsSearch() const = 0;
|
||||
|
||||
virtual Api::Result<Api::SearchResult>
|
||||
search(std::string_view query) = 0;
|
||||
|
||||
// Resolve metadata for a URL or id this source canHandle().
|
||||
virtual Api::Result<Api::TrackInfo>
|
||||
resolve(const std::string& urlOrId) = 0;
|
||||
|
||||
// Produce a playable handle for a resolved track.
|
||||
virtual Api::Result<StreamHandle>
|
||||
getStream(const Api::TrackInfo& track) = 0;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,79 @@
|
||||
#pragma once
|
||||
|
||||
#include "../NetworkClient.hpp"
|
||||
#include "TrackSource.hpp"
|
||||
#include <atomic>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// Native Yandex Music source (unofficial api.music.yandex.net). Full
|
||||
// tracks require a Yandex OAuth token (sources.yandexToken) from an
|
||||
// account with Plus; without one this source reports unavailable and
|
||||
// yandex URLs keep routing to ytdlp-direct.
|
||||
//
|
||||
// Yandex is reachable directly in this deployment's region and may
|
||||
// geo-block foreign proxy exits, so every request deliberately bypasses
|
||||
// the configured proxy (NetworkClient::getDirect).
|
||||
class YandexMusicSource : public ITrackSource
|
||||
{
|
||||
public:
|
||||
|
||||
// endpointOverride points tests at a StubHttpServer (it replaces
|
||||
// both the API base and the download-info hosts).
|
||||
explicit YandexMusicSource(std::shared_ptr<NetworkClient> network,
|
||||
std::string endpointOverride = "");
|
||||
|
||||
void configure(bool enabled, std::string token);
|
||||
|
||||
[[nodiscard]] std::string_view name() const override
|
||||
{
|
||||
return "yandex";
|
||||
}
|
||||
[[nodiscard]] bool canHandle(const std::string& query) const override;
|
||||
[[nodiscard]] bool isAvailable() const override;
|
||||
[[nodiscard]] bool supportsSearch() const override
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
Api::Result<Api::SearchResult>
|
||||
search(std::string_view query) override;
|
||||
Api::Result<Api::TrackInfo>
|
||||
resolve(const std::string& urlOrId) override;
|
||||
Api::Result<StreamHandle>
|
||||
getStream(const Api::TrackInfo& track) override;
|
||||
|
||||
// Album/playlist track listing for queue imports.
|
||||
[[nodiscard]] bool isCollectionUrl(const std::string& url) const;
|
||||
Api::Result<std::vector<Api::TrackInfo>>
|
||||
playlistTracks(const std::string& url);
|
||||
|
||||
// Related/similar tracks for radio autoplay. trackId is the bare
|
||||
// Yandex numeric id (no "yandex:" prefix).
|
||||
Api::Result<std::vector<Api::TrackInfo>>
|
||||
related(const std::string& trackId, size_t limit = 10);
|
||||
|
||||
// Extract the bare Yandex track id from a music.yandex.* URL, if it
|
||||
// is a single-track URL. Used to seed radio from history.
|
||||
[[nodiscard]] std::optional<std::string>
|
||||
trackIdFromUrl(const std::string& url) const;
|
||||
|
||||
private:
|
||||
|
||||
Api::Result<std::string> apiGet(const std::string& path);
|
||||
[[nodiscard]] std::string tokenSnapshot() const;
|
||||
|
||||
std::shared_ptr<NetworkClient> network_;
|
||||
std::string endpoint_;
|
||||
std::atomic<bool> enabled_{true};
|
||||
mutable std::mutex tokenMutex_;
|
||||
std::string token_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,58 @@
|
||||
#pragma once
|
||||
|
||||
#include "../YouTubeClient.hpp"
|
||||
#include "TrackSource.hpp"
|
||||
#include <memory>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// yt-dlp-backed source, in two router entries over the same
|
||||
// YouTubeClient:
|
||||
// - Direct ("ytdlp-direct", useProxy=false): non-YouTube extractor URLs
|
||||
// (SoundCloud, Bandcamp, VK, Yandex, radio pages) reachable without a
|
||||
// proxy. Never handles bare text search.
|
||||
// - Proxied ("ytdlp-proxied", useProxy=true): last-resort YouTube
|
||||
// resolution + text search through the configured proxy; also owns
|
||||
// the SOCKS5 download-to-file path.
|
||||
class YtDlpSource : public ITrackSource
|
||||
{
|
||||
public:
|
||||
|
||||
enum class Mode { Direct, Proxied };
|
||||
|
||||
YtDlpSource(std::shared_ptr<YouTubeClient> client, Mode mode,
|
||||
std::string tempDir);
|
||||
|
||||
[[nodiscard]] std::string_view name() const override
|
||||
{
|
||||
return mode_ == Mode::Direct ? "ytdlp-direct"
|
||||
: "ytdlp-proxied";
|
||||
}
|
||||
[[nodiscard]] bool canHandle(const std::string& query) const override;
|
||||
[[nodiscard]] bool isAvailable() const override;
|
||||
[[nodiscard]] bool supportsSearch() const override
|
||||
{
|
||||
return mode_ == Mode::Proxied;
|
||||
}
|
||||
|
||||
Api::Result<Api::SearchResult>
|
||||
search(std::string_view query) override;
|
||||
Api::Result<Api::TrackInfo>
|
||||
resolve(const std::string& urlOrId) override;
|
||||
Api::Result<StreamHandle>
|
||||
getStream(const Api::TrackInfo& track) override;
|
||||
|
||||
// Force the download-to-file path on the next getStream (set by
|
||||
// the router's preferDownload retry).
|
||||
Api::Result<StreamHandle>
|
||||
getStreamViaDownload(const Api::TrackInfo& track);
|
||||
|
||||
private:
|
||||
|
||||
std::shared_ptr<YouTubeClient> client_;
|
||||
Mode mode_;
|
||||
std::string tempDir_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
+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