diff --git a/CMakeLists.txt b/CMakeLists.txt index dfa6973..7595aa2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -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 + + + + + + + + + + + + ) +endif() + set_target_properties(EchoionCore PROPERTIES OUTPUT_NAME "Echoion" PREFIX "" diff --git a/include/echoion/core/AudioDecoder.hpp b/include/echoion/core/AudioDecoder.hpp index 3c642e1..fedecad 100644 --- a/include/echoion/core/AudioDecoder.hpp +++ b/include/echoion/core/AudioDecoder.hpp @@ -5,11 +5,11 @@ #include #include #include +#include #include #include -#include -#include #include +#include // 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 - initialize(const Api::HwAccelConfig& hwConfig = {}); + Api::Result initialize(); void shutdown(); // Open audio source (URL or file path) Api::Result openSource(const std::string& url); void closeSource(); - // Decode audio - returns zero-copy pooled buffer - [[nodiscard]] Api::Result decodeFrame(); - // Seek to position Api::Result seek(std::chrono::milliseconds position); @@ -50,50 +48,19 @@ namespace Echoion::Core [[nodiscard]] Api::Result 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& 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& outChunk, bool blocking = false); @@ -103,18 +70,12 @@ namespace Echoion::Core private: void decodeThread(); - Api::Result readPacket(); - Api::Result 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 acquireChunkBuffer(size_t samples); void cleanupFfmpeg(); - // Hardware acceleration setup - Api::Result - initializeHardwareAccel(const Api::HwAccelConfig& config); - void cleanupHardwareAccel(); - - // Frame conversion (returns int16 for direct playback) - Api::Result 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 decodedQueue_; - static constexpr size_t MAX_QUEUE_SIZE = 50; // S16 audio queue (like reference) - avoids float conversion std::deque> 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> recycledChunks_; + // State std::atomic initialized_{false}; std::atomic decoding_{false}; std::atomic eof_{false}; std::atomic 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 currentPositionMs_{0}; std::string currentUrl_; std::atomic streamSampleRate_{48000}; std::optional proxyConfig_; - - // Statistics - mutable std::mutex statsMutex_; - Stats stats_; }; } // namespace Echoion::Core diff --git a/include/echoion/core/MusicManager.hpp b/include/echoion/core/MusicManager.hpp index 6cbb90d..7946b86 100644 --- a/include/echoion/core/MusicManager.hpp +++ b/include/echoion/core/MusicManager.hpp @@ -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 #include #include #include #include #include -#include -#include -#include +#include +#include #include -#include -#include +#include #include #include -#include +#include +#include #include +#include 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 initialize(std::shared_ptr 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 play(const std::string& query, uint64_t clientId); [[nodiscard]] Api::Result 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 - 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(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 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 + 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 database() const + { + return database_; + } + private: + // ---- IPlaybackHost (called from the engine) -------------------- + + void emitAudio(std::span samples) override; + Api::Result + resolveStream(const Api::QueueEntry& entry, + bool preferDownload) override; + std::optional peekNextTrack() override; + std::optional + takeNextTrack(uint64_t expectedQueueId) override; + std::optional 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& entry) + override; + + // ---- helpers --------------------------------------------------- + // Publish a domain event on the injected bus (no-op until set). template 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 resolveQuery(const std::string& query); [[nodiscard]] Api::Result 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 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 tempFiles_; mutable std::shared_mutex tempFilesMutex_; - // Prefetch state for seamless playback - struct PrefetchState { - std::future> streamUrlFuture; - std::atomic isPrefetching{false}; - std::atomic hasPrefetched{false}; - std::optional prefetchedUrl; - } prefetchState_; - // Async playlist loading (background thread owned by the loader). std::unique_ptr 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_; + std::shared_ptr 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_; - std::unique_ptr audioDecoder_; - std::unique_ptr subscriptionManager_; + std::shared_ptr youTubeClient_; + + // Source-resolution chain (proxy-free first, proxied last). + std::unique_ptr router_; + std::shared_ptr innertubeSource_; + std::shared_ptr yandexSource_; + std::shared_ptr ytdlpProxied_; Api::BotConfig config_; - // Playback queue + shuffle state (driven under mutex_). - QueueManager queueMgr_; - std::optional currentTrack_; - std::atomic isPlaying_{false}; - std::atomic isPaused_{false}; - std::atomic wasPausedForNoSubscribers_{ - false}; // Track if we auto-paused + std::atomic autoStartOnSubscribe_{true}; + std::atomic autoplay_{false}; + QueueService queue_; + std::unique_ptr 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 volume_{0.5f}; - std::atomic shuffle_{false}; - std::atomic 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 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> + autoplaySeedFromHistory() const; - std::jthread playbackThread_; - mutable std::shared_mutex mutex_; - std::condition_variable_any cv_; - std::atomic playbackThreadRunning_{ - false}; // True while thread is actively running + // Spotify/Yandex collection imports (background metadata fetch; + // enqueue itself is instant). + std::atomic importRunning_{false}; + std::jthread importThread_; + std::unique_ptr engine_; + std::unique_ptr subscriptions_; // Pending search results per client (for select command) std::unordered_map> 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 diff --git a/include/echoion/core/NetworkClient.hpp b/include/echoion/core/NetworkClient.hpp index fda82e9..e0bccee 100644 --- a/include/echoion/core/NetworkClient.hpp +++ b/include/echoion/core/NetworkClient.hpp @@ -41,6 +41,15 @@ namespace Echoion::Core [[nodiscard]] Api::Result 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 + getDirect(std::string_view url, + const std::vector& headers = {}); + // Proxy configuration void setProxy( const std::optional& proxy) override; diff --git a/include/echoion/core/QueueManager.hpp b/include/echoion/core/QueueManager.hpp deleted file mode 100644 index 355e2e6..0000000 --- a/include/echoion/core/QueueManager.hpp +++ /dev/null @@ -1,53 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include - -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& entries() noexcept - { - return entries_; - } - [[nodiscard]] const std::vector& entries() const noexcept - { - return entries_; - } - [[nodiscard]] std::vector& 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 entries_; - std::vector shuffledIndices_; - std::size_t shuffleIndex_ = 0; - std::uint64_t nextQueueId_ = 1; - std::mt19937 rng_{std::random_device{}()}; - }; - -} // namespace Echoion::Core diff --git a/include/echoion/core/RpcDtos.hpp b/include/echoion/core/RpcDtos.hpp index 2b7ee53..bf11b69 100644 --- a/include/echoion/core/RpcDtos.hpp +++ b/include/echoion/core/RpcDtos.hpp @@ -30,6 +30,53 @@ namespace Echoion::Core::Dto std::optional 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 uid; + }; + // ── RPC handler responses ─────────────────────────────────────────────── struct Track { @@ -39,6 +86,8 @@ namespace Echoion::Core::Dto std::string album; std::optional duration; // milliseconds int source = 0; + std::optional thumbnailUrl; + std::optional url; // originalUrl (play-by-url) }; [[nodiscard]] inline Track toTrack(const Api::TrackInfo& t) @@ -51,7 +100,11 @@ namespace Echoion::Core::Dto ? std::optional( t.duration->count()) : std::nullopt, - .source = static_cast(t.source)}; + .source = static_cast(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 tracks; + }; + + struct PlaylistBrief { + std::string id; + std::string name; + std::string description; + std::uint32_t trackCount = 0; + }; + + struct PlaylistList { + std::vector playlists; + }; + + struct PlaylistContents { + std::string id; + std::string name; + std::string description; + std::vector tracks; + }; + + struct HistoryRequest { + std::uint32_t limit = 20; + }; + + struct HistoryResponse { + std::vector tracks; + }; + + struct StatsResponse { + std::uint64_t totalPlays = 0; + std::uint64_t totalTracks = 0; + std::uint64_t totalPlaytimeMs = 0; + std::optional 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 entries; + }; + + struct SubscriberDto { + std::string uid; + std::string nickname; + }; + + struct UsersResponse { + std::vector users; + }; + // ── Event-broadcast payloads ──────────────────────────────────────────── struct TrackBrief { diff --git a/include/echoion/core/RpcServer.hpp b/include/echoion/core/RpcServer.hpp index a18b32e..731f533 100644 --- a/include/echoion/core/RpcServer.hpp +++ b/include/echoion/core/RpcServer.hpp @@ -8,12 +8,15 @@ #include #include #include +#include +#include #include #include #include #include #include #include +#include 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 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>> clients_; - std::mutex clientsMutex_; + mutable std::mutex clientsMutex_; std::atomic 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 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 handlers_; std::mutex handlersMutex_; diff --git a/include/echoion/core/SignatureCipher.hpp b/include/echoion/core/SignatureCipher.hpp index 360fcff..c7b8162 100644 --- a/include/echoion/core/SignatureCipher.hpp +++ b/include/echoion/core/SignatureCipher.hpp @@ -8,7 +8,10 @@ #include #include -#include +// Opaque quickjs handles — only the .cpp needs , and keeping it +// out of this header keeps the quickjs include dir private to EchoionCore. +struct JSRuntime; +struct JSContext; namespace Echoion::Core { diff --git a/include/echoion/core/SubscriptionService.hpp b/include/echoion/core/SubscriptionService.hpp new file mode 100644 index 0000000..3eece09 --- /dev/null +++ b/include/echoion/core/SubscriptionService.hpp @@ -0,0 +1,115 @@ +#pragma once + +#include "SubscriptionManager.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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>(uint64_t clientId)>; + using UidToClientIdCallback = + std::function(const std::string& uid)>; + using ChangeCallback = std::function; + // requestPause returns true when playback was actually paused by + // this policy (so a returning subscriber should resume it). + using RequestPause = std::function; + using RequestResume = std::function; + + Api::Result + initialize(std::shared_ptr 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 subscribe(uint64_t clientId); + [[nodiscard]] Api::Result + unsubscribe(uint64_t clientId); + [[nodiscard]] Api::Result + unsubscribeByUid(const std::string& uid); + [[nodiscard]] Api::Result clearAllSubscriptions(); + + [[nodiscard]] bool isSubscribed(uint64_t clientId) const; + [[nodiscard]] bool hasSubscribers() const; + [[nodiscard]] bool hasOnlineSubscribers() const; + [[nodiscard]] std::set getSubscribedClients() const; + [[nodiscard]] std::set getOnlineSubscriberUids() const; + [[nodiscard]] std::vector + 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 void emit(T event) + { + if (eventBus_) { + eventBus_->publish(std::move(event)); + } + } + + // Pause playback if the audience vanished; remember that WE + // paused so the next returning subscriber resumes. + void pauseIfAudienceGone(); + + std::unique_ptr manager_; + Void::EventBus::EventBus* eventBus_ = nullptr; + ClientInfoCallback clientInfo_; + UidToClientIdCallback uidToClientId_; + ChangeCallback onChange_; + RequestPause requestPause_; + RequestResume requestResume_; + std::atomic pausedForNoSubscribers_{false}; + std::atomic pauseOnEmpty_{true}; + std::atomic resumeOnReturn_{true}; + }; + +} // namespace Echoion::Core diff --git a/include/echoion/core/TrackCache.hpp b/include/echoion/core/TrackCache.hpp new file mode 100644 index 0000000..59811b2 --- /dev/null +++ b/include/echoion/core/TrackCache.hpp @@ -0,0 +1,74 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +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 + 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 diff --git a/include/echoion/core/YouTubeClient.hpp b/include/echoion/core/YouTubeClient.hpp index 33a140d..8fbbe0d 100644 --- a/include/echoion/core/YouTubeClient.hpp +++ b/include/echoion/core/YouTubeClient.hpp @@ -49,6 +49,12 @@ namespace Echoion::Core search(std::string_view query, std::optional pageToken = std::nullopt); + // Related tracks for radio autoplay: lists the YouTube "mix" + // playlist (RD) via yt-dlp --flat-playlist. Runs through + // the proxy like every yt-dlp call, so it works under SOCKS5. + [[nodiscard]] Api::Result> + radioMix(const std::string& videoId, size_t limit = 10); + // Get video details including stream URLs using yt-dlp [[nodiscard]] Api::Result getVideoInfo(std::string_view videoId); @@ -101,6 +107,13 @@ namespace Echoion::Core [[nodiscard]] Api::Result 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 + 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: diff --git a/include/echoion/core/YtDlpManager.hpp b/include/echoion/core/YtDlpManager.hpp index 6048458..8bd71ed 100644 --- a/include/echoion/core/YtDlpManager.hpp +++ b/include/echoion/core/YtDlpManager.hpp @@ -34,6 +34,13 @@ namespace Echoion::Core // Initialize - checks for yt-dlp and downloads if needed Api::Result 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_; std::filesystem::path executablePath_; std::atomic initialized_{false}; + std::atomic autoUpdateEnabled_{true}; + // Background download/verify (joined in the destructor). + std::jthread initThread_; mutable std::mutex mutex_; // Cookie configuration for YouTube authentication diff --git a/include/echoion/core/commands/AnnounceCommand.hpp b/include/echoion/core/commands/AnnounceCommand.hpp new file mode 100644 index 0000000..92da64b --- /dev/null +++ b/include/echoion/core/commands/AnnounceCommand.hpp @@ -0,0 +1,55 @@ +#pragma once + +#include "../MusicManager.hpp" +#include "Command.hpp" +#include + +namespace Echoion::Core +{ + + // !announce — 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 ", 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 ""; } + + CommandCategory getCategory() const override + { + return CommandCategory::Admin; + } + + bool requiresAdmin() const override { return true; } + }; + +} // namespace Echoion::Core diff --git a/include/echoion/core/commands/AutoplayCommand.hpp b/include/echoion/core/commands/AutoplayCommand.hpp new file mode 100644 index 0000000..a2c6ca3 --- /dev/null +++ b/include/echoion/core/commands/AutoplayCommand.hpp @@ -0,0 +1,81 @@ +#pragma once + +#include "../MusicManager.hpp" +#include "Command.hpp" +#include +#include +#include +#include + +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(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 getAliases() const override + { + return {"radio"}; + } + }; + +} // namespace Echoion::Core diff --git a/include/echoion/core/commands/Command.hpp b/include/echoion/core/commands/Command.hpp index e57aa9b..56b33db 100644 --- a/include/echoion/core/commands/Command.hpp +++ b/include/echoion/core/commands/Command.hpp @@ -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 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. diff --git a/include/echoion/core/commands/Commands.hpp b/include/echoion/core/commands/Commands.hpp index a95ffd0..feaa9cb 100644 --- a/include/echoion/core/commands/Commands.hpp +++ b/include/echoion/core/commands/Commands.hpp @@ -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" diff --git a/include/echoion/core/commands/FavoriteCommand.hpp b/include/echoion/core/commands/FavoriteCommand.hpp new file mode 100644 index 0000000..2eb2588 --- /dev/null +++ b/include/echoion/core/commands/FavoriteCommand.hpp @@ -0,0 +1,206 @@ +#pragma once + +#include "../MusicManager.hpp" +#include "Command.hpp" +#include +#include +#include +#include + +namespace Echoion::Core +{ + + // !fav add | list | play | remove — 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(); + 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 | remove ", + ctx.prefix)); + } + } + + std::string_view getDescription() const override + { + return "Manage your favorite tracks"; + } + + std::string_view getUsage() const override + { + return "add | list | play | remove "; + } + + CommandCategory getCategory() const override + { + return CommandCategory::Music; + } + + std::vector 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 + 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 + 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 (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 (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 diff --git a/include/echoion/core/commands/HistoryCommand.hpp b/include/echoion/core/commands/HistoryCommand.hpp new file mode 100644 index 0000000..6a372d7 --- /dev/null +++ b/include/echoion/core/commands/HistoryCommand.hpp @@ -0,0 +1,72 @@ +#pragma once + +#include "../MusicManager.hpp" +#include "Command.hpp" +#include +#include +#include + +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(); + 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(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 getAliases() const override + { + return {"recent"}; + } + }; + +} // namespace Echoion::Core diff --git a/include/echoion/core/commands/NowPlayingCommand.hpp b/include/echoion/core/commands/NowPlayingCommand.hpp index 87744cb..434825e 100644 --- a/include/echoion/core/commands/NowPlayingCommand.hpp +++ b/include/echoion/core/commands/NowPlayingCommand.hpp @@ -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). diff --git a/include/echoion/core/commands/PlayCommand.hpp b/include/echoion/core/commands/PlayCommand.hpp index 09c9f7b..c362c5f 100644 --- a/include/echoion/core/commands/PlayCommand.hpp +++ b/include/echoion/core/commands/PlayCommand.hpp @@ -1,5 +1,6 @@ #pragma once +#include "../MusicManager.hpp" #include "Command.hpp" #include #include @@ -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 \nExample: " - "play never gonna give you up"); + ctx.reply(std::format( + "Usage: {} \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 ""; - } - CommandCategory getCategory() const override { - return CommandCategory::Music; + return CommandCategory::Play; } - std::vector 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 ""; + } + std::vector 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 diff --git a/include/echoion/core/commands/QueueCommand.hpp b/include/echoion/core/commands/QueueCommand.hpp index 5987385..2f7520a 100644 --- a/include/echoion/core/commands/QueueCommand.hpp +++ b/include/echoion/core/commands/QueueCommand.hpp @@ -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, diff --git a/include/echoion/core/commands/SearchCommand.hpp b/include/echoion/core/commands/SearchCommand.hpp index e76dc45..45d853f 100644 --- a/include/echoion/core/commands/SearchCommand.hpp +++ b/include/echoion/core/commands/SearchCommand.hpp @@ -1,5 +1,6 @@ #pragma once +#include "../MusicManager.hpp" #include "Command.hpp" #include #include @@ -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 \nExample: search " - "never gonna give you up"); + ctx.reply(std::format("Usage: {} ", 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 ""; } - CommandCategory getCategory() const override { - return CommandCategory::Music; + return CommandCategory::Search; } - std::vector 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 ""; } + std::vector 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 diff --git a/include/echoion/core/commands/StatsCommand.hpp b/include/echoion/core/commands/StatsCommand.hpp new file mode 100644 index 0000000..83ce9d5 --- /dev/null +++ b/include/echoion/core/commands/StatsCommand.hpp @@ -0,0 +1,55 @@ +#pragma once + +#include "Command.hpp" +#include +#include + +namespace Echoion::Core +{ + + // !stats — global playback statistics. + class StatsCommand : public Command + { + public: + + void execute(const CommandContext& ctx) override + { + auto db = ctx.service(); + 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 diff --git a/include/echoion/core/commands/YandexPlayCommand.hpp b/include/echoion/core/commands/YandexPlayCommand.hpp new file mode 100644 index 0000000..d5ddb16 --- /dev/null +++ b/include/echoion/core/commands/YandexPlayCommand.hpp @@ -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 ""; + } + std::vector 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 diff --git a/include/echoion/core/commands/YandexSearchCommand.hpp b/include/echoion/core/commands/YandexSearchCommand.hpp new file mode 100644 index 0000000..5b73a9e --- /dev/null +++ b/include/echoion/core/commands/YandexSearchCommand.hpp @@ -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 ""; } + std::vector 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 diff --git a/include/echoion/core/commands/YoutubePlayCommand.hpp b/include/echoion/core/commands/YoutubePlayCommand.hpp new file mode 100644 index 0000000..d0b5018 --- /dev/null +++ b/include/echoion/core/commands/YoutubePlayCommand.hpp @@ -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 ""; + } + std::vector 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 diff --git a/include/echoion/core/commands/YoutubeSearchCommand.hpp b/include/echoion/core/commands/YoutubeSearchCommand.hpp new file mode 100644 index 0000000..28e75cb --- /dev/null +++ b/include/echoion/core/commands/YoutubeSearchCommand.hpp @@ -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 ""; } + std::vector 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 diff --git a/include/echoion/core/playback/AudioRingBuffer.hpp b/include/echoion/core/playback/AudioRingBuffer.hpp new file mode 100644 index 0000000..c4ffb2c --- /dev/null +++ b/include/echoion/core/playback/AudioRingBuffer.hpp @@ -0,0 +1,93 @@ +#pragma once + +#include +#include +#include +#include + +namespace Echoion::Core +{ + + // Fixed-capacity ring buffer of audio samples for the playback thread. + // + // A std::vector 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 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 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 storage_; + std::size_t head_ = 0; + std::size_t count_ = 0; + }; + +} // namespace Echoion::Core diff --git a/include/echoion/core/playback/PlaybackEngine.hpp b/include/echoion/core/playback/PlaybackEngine.hpp new file mode 100644 index 0000000..c3bd766 --- /dev/null +++ b/include/echoion/core/playback/PlaybackEngine.hpp @@ -0,0 +1,331 @@ +#pragma once + +#include "../AudioDecoder.hpp" +#include "AudioRingBuffer.hpp" +#include "PositionClock.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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 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 + resolveStream(const Api::QueueEntry& entry, + bool preferDownload) = 0; + + // Queue access: peek what would play next / pop it if unchanged. + virtual std::optional peekNextTrack() = 0; + virtual std::optional + takeNextTrack(uint64_t expectedQueueId) = 0; + // Unconditional pop (fallback when the peeked entry vanished). + virtual std::optional 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& 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(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 initialize( + const std::optional& proxy); + void shutdown(); + + void setProxyConfig( + const std::optional& 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 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; + + 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 decoder; + std::optional entry; + std::future> 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& entry); + void emitChunk(bool fromRing); + void positionTick(); + + IPlaybackHost& host_; + + // Mailbox + std::mutex mailboxMutex_; + std::deque mailbox_; + std::condition_variable mailboxCv_; + + // Engine-thread-only state + DecoderSlot current_; + DecoderSlot next_; + AudioRingBuffer ring_; + std::vector outChunk_; + std::vector 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 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 playing_{false}; + std::atomic paused_{false}; + std::atomic volume_{0.5f}; + std::atomic resolveGraceMs_{10000}; + std::atomic crossfadeMs_{0}; + std::atomic normalizeEnabled_{false}; + std::atomic normalizeTargetDb_{-14.0f}; + PositionClock clock_; + mutable std::mutex currentEntryMutex_; + std::optional publishedEntry_; + std::atomic currentDurationMs_{0}; + + std::optional proxy_; + std::jthread thread_; + std::atomic initialized_{false}; + }; + +} // namespace Echoion::Core diff --git a/include/echoion/core/playback/PositionClock.hpp b/include/echoion/core/playback/PositionClock.hpp new file mode 100644 index 0000000..95cd19b --- /dev/null +++ b/include/echoion/core/playback/PositionClock.hpp @@ -0,0 +1,89 @@ +#pragma once + +#include +#include +#include + +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::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 baseMs_{0}; + std::atomic startedAtNs_{0}; + std::atomic running_{false}; + }; + +} // namespace Echoion::Core diff --git a/include/echoion/core/playback/QueueService.hpp b/include/echoion/core/playback/QueueService.hpp new file mode 100644 index 0000000..e3b2e74 --- /dev/null +++ b/include/echoion/core/playback/QueueService.hpp @@ -0,0 +1,97 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +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 enqueue(const Api::TrackInfo& track, + std::string addedBy, + std::size_t maxSize); + + // Removes the entry at `position`; returns it for event payloads. + Api::Result removeAt(uint32_t position); + + // Returns the number of entries removed. + uint32_t clear(); + + // Moves an entry; returns its queueId for event payloads. + Api::Result move(uint32_t from, uint32_t to); + + // Pops the next entry honouring shuffle order. + std::optional 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 popIfNext(uint64_t queueId); + + // Replace the whole queue (hot-reload restore). + void replaceAll(std::vector 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 peekNext() const; + [[nodiscard]] std::vector 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 nextPositionLocked() const; + std::optional popNextLocked(); + + mutable std::mutex mutex_; + std::vector entries_; + std::vector 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 diff --git a/include/echoion/core/sources/DirectUrlSource.hpp b/include/echoion/core/sources/DirectUrlSource.hpp new file mode 100644 index 0000000..2d15469 --- /dev/null +++ b/include/echoion/core/sources/DirectUrlSource.hpp @@ -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 + search(std::string_view query) override; + Api::Result + resolve(const std::string& urlOrId) override; + Api::Result + getStream(const Api::TrackInfo& track) override; + }; + +} // namespace Echoion::Core diff --git a/include/echoion/core/sources/InnertubeSource.hpp b/include/echoion/core/sources/InnertubeSource.hpp new file mode 100644 index 0000000..d5d8ed7 --- /dev/null +++ b/include/echoion/core/sources/InnertubeSource.hpp @@ -0,0 +1,86 @@ +#pragma once + +#include "../NetworkClient.hpp" +#include "../SignatureCipher.hpp" +#include "TrackSource.hpp" +#include +#include +#include + +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 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 + search(std::string_view query) override; + Api::Result + resolve(const std::string& urlOrId) override; + Api::Result + 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 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 + decipherWithWebPlayer(const std::string& videoId, + const std::string& signatureCipher); + + std::shared_ptr network_; + std::string endpoint_; + std::atomic enabled_{true}; + std::atomic requireProxy_{true}; + + // Lazy cipher state (only the WEB fallback needs it). + std::mutex cipherMutex_; + std::unique_ptr cipher_; + std::string loadedPlayerJsUrl_; + }; + +} // namespace Echoion::Core diff --git a/include/echoion/core/sources/SourceRouter.hpp b/include/echoion/core/sources/SourceRouter.hpp new file mode 100644 index 0000000..843e39b --- /dev/null +++ b/include/echoion/core/sources/SourceRouter.hpp @@ -0,0 +1,74 @@ +#pragma once + +#include "TrackSource.hpp" +#include +#include +#include +#include +#include +#include + +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> sources); + + // Reorder/enable per config; names not found are ignored, sources + // not named are dropped from the chain. + void setOrder(const std::vector& 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 + search(std::string_view query); + + // URL/id/text -> track metadata. + [[nodiscard]] Api::Result + resolve(const std::string& query); + + // Track -> playable stream handle (cached). + [[nodiscard]] Api::Result + 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 source; + std::chrono::steady_clock::time_point cooldownUntil{}; + }; + + [[nodiscard]] std::vector + candidatesFor(const std::string& query, bool needSearch); + void reportFailure(SourceState& state); + + mutable std::mutex mutex_; + std::vector> allSources_; + std::vector chain_; + std::chrono::milliseconds cooldown_{std::chrono::minutes(5)}; + std::chrono::milliseconds hedgeDelay_{std::chrono::milliseconds(300)}; + std::unordered_map streamCache_; + }; + +} // namespace Echoion::Core diff --git a/include/echoion/core/sources/TrackSource.hpp b/include/echoion/core/sources/TrackSource.hpp new file mode 100644 index 0000000..9b3d305 --- /dev/null +++ b/include/echoion/core/sources/TrackSource.hpp @@ -0,0 +1,57 @@ +#pragma once + +#include +#include +#include +#include + +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 + search(std::string_view query) = 0; + + // Resolve metadata for a URL or id this source canHandle(). + virtual Api::Result + resolve(const std::string& urlOrId) = 0; + + // Produce a playable handle for a resolved track. + virtual Api::Result + getStream(const Api::TrackInfo& track) = 0; + }; + +} // namespace Echoion::Core diff --git a/include/echoion/core/sources/YandexMusicSource.hpp b/include/echoion/core/sources/YandexMusicSource.hpp new file mode 100644 index 0000000..45afe68 --- /dev/null +++ b/include/echoion/core/sources/YandexMusicSource.hpp @@ -0,0 +1,79 @@ +#pragma once + +#include "../NetworkClient.hpp" +#include "TrackSource.hpp" +#include +#include +#include +#include +#include +#include + +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 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 + search(std::string_view query) override; + Api::Result + resolve(const std::string& urlOrId) override; + Api::Result + getStream(const Api::TrackInfo& track) override; + + // Album/playlist track listing for queue imports. + [[nodiscard]] bool isCollectionUrl(const std::string& url) const; + Api::Result> + playlistTracks(const std::string& url); + + // Related/similar tracks for radio autoplay. trackId is the bare + // Yandex numeric id (no "yandex:" prefix). + Api::Result> + 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 + trackIdFromUrl(const std::string& url) const; + + private: + + Api::Result apiGet(const std::string& path); + [[nodiscard]] std::string tokenSnapshot() const; + + std::shared_ptr network_; + std::string endpoint_; + std::atomic enabled_{true}; + mutable std::mutex tokenMutex_; + std::string token_; + }; + +} // namespace Echoion::Core diff --git a/include/echoion/core/sources/YtDlpSource.hpp b/include/echoion/core/sources/YtDlpSource.hpp new file mode 100644 index 0000000..6649329 --- /dev/null +++ b/include/echoion/core/sources/YtDlpSource.hpp @@ -0,0 +1,58 @@ +#pragma once + +#include "../YouTubeClient.hpp" +#include "TrackSource.hpp" +#include + +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 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 + search(std::string_view query) override; + Api::Result + resolve(const std::string& urlOrId) override; + Api::Result + 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 + getStreamViaDownload(const Api::TrackInfo& track); + + private: + + std::shared_ptr client_; + Mode mode_; + std::string tempDir_; + }; + +} // namespace Echoion::Core diff --git a/src/AudioDecoder.cpp b/src/AudioDecoder.cpp index 8cd256d..995c403 100644 --- a/src/AudioDecoder.cpp +++ b/src/AudioDecoder.cpp @@ -4,7 +4,6 @@ extern "C" { #include #include #include -#include #include #include #include @@ -23,78 +22,22 @@ namespace Echoion::Core { shutdown(); cleanupFfmpeg(); - cleanupHardwareAccel(); } - Api::Result - AudioDecoder::initialize(const Api::HwAccelConfig& hwConfig) + Api::Result 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 - 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 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(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(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( 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(outputSampleRate_), &codecContext_->ch_layout, codecContext_->sample_fmt, codecContext_->sample_rate, 0, nullptr); - if (codecContext_->sample_rate != outputSampleRate_) { + if (codecContext_->sample_rate != + static_cast(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 AudioDecoder::decodeFrame() + bool AudioDecoder::getNextChunk(std::vector& outChunk, + bool blocking) { std::unique_lock 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 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& outChunk, bool blocking) - { - callCount++; - - std::unique_lock 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& 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 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 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 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 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 AudioDecoder::acquireChunkBuffer(size_t samples) { - std::lock_guard lock(statsMutex_); - return stats_; + std::vector chunk; + { + std::lock_guard 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(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 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(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 chunk = acquireChunkBuffer(chunkSamples); std::memcpy(chunk.data(), outputBuffer_, - outSamples * outputChannels_ * sizeof(int16_t)); + chunkSamples * sizeof(int16_t)); { std::lock_guard 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(frame_->data), frame_->nb_samples); + const uint8_t** inData = + const_cast(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 chunk(outSamples * outputChannels_); + const size_t chunkSamples = outSamples * outputChannels_; + std::vector chunk = acquireChunkBuffer(chunkSamples); std::memcpy(chunk.data(), outputBuffer_, - outSamples * outputChannels_ * sizeof(int16_t)); + chunkSamples * sizeof(int16_t)); { std::lock_guard 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 chunk = acquireChunkBuffer(chunkSamples); + std::memcpy(chunk.data(), outputBuffer_, + chunkSamples * sizeof(int16_t)); + { + std::lock_guard 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 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 audio; - - if (zeroCopyEnabled_) { - audio = convertFramePooled(); - } else { - audio = convertFrame(); - } - - if (audio) { - std::lock_guard lock(mutex_); - decodedQueue_.push(std::move(*audio)); - cv_.notify_one(); - } - } - - return {}; - } - - Api::Result AudioDecoder::convertFrame() - { - int outSamples = swr_get_out_samples(swrContext_, frame_->nb_samples); - // Use int16_t for direct output (no float conversion) - std::vector outputBuffer(outSamples * outputChannels_); - - uint8_t* outData = reinterpret_cast(outputBuffer.data()); - const uint8_t** inData = - const_cast(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 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_) { diff --git a/src/CommandManager.cpp b/src/CommandManager.cpp index 33324c5..b6bdf7c 100644 --- a/src/CommandManager.cpp +++ b/src/CommandManager.cpp @@ -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 - //
/). Blank lines around the inner - // content let the Markdown render inside the block. - helpMsg += std::format( - "
\n{} {} Commands\n\n", - categoryEmoji(cat), toString(cat)); + // Collapsible section per category. TeamSpeak uses the + // markdown-it container syntax ":::details " … + // ":::" (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() diff --git a/src/ConfigLoader.cpp b/src/ConfigLoader.cpp index 5a18899..c2765fa 100644 --- a/src/ConfigLoader.cpp +++ b/src/ConfigLoader.cpp @@ -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; diff --git a/src/ConfigManager.cpp b/src/ConfigManager.cpp index e3de584..2739f6e 100644 --- a/src/ConfigManager.cpp +++ b/src/ConfigManager.cpp @@ -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_); diff --git a/src/Core.cpp b/src/Core.cpp index c7e5109..e1c5cd3 100644 --- a/src/Core.cpp +++ b/src/Core.cpp @@ -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 {}; } diff --git a/src/CoreEventRelay.cpp b/src/CoreEventRelay.cpp index de525d5..ab640a3 100644 --- a/src/CoreEventRelay.cpp +++ b/src/CoreEventRelay.cpp @@ -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"); } diff --git a/src/CoreRpcHandlers.cpp b/src/CoreRpcHandlers.cpp index 83ff45a..be4e682 100644 --- a/src/CoreRpcHandlers.cpp +++ b/src/CoreRpcHandlers.cpp @@ -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"); } diff --git a/src/Database.cpp b/src/Database.cpp index ad05452..1d3eb72 100644 --- a/src/Database.cpp +++ b/src/Database.cpp @@ -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 diff --git a/src/MemoryPool.cpp b/src/MemoryPool.cpp deleted file mode 100644 index ab2024e..0000000 --- a/src/MemoryPool.cpp +++ /dev/null @@ -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 diff --git a/src/MusicManager.cpp b/src/MusicManager.cpp index 5c0ab0c..97407b8 100644 --- a/src/MusicManager.cpp +++ b/src/MusicManager.cpp @@ -1,13 +1,12 @@ #include "ConfigManager.hpp" -#include <Void/Log/Log.hpp> #include "echoion/core/MusicManager.hpp" #include "echoion/core/PlaylistLoader.hpp" +#include "echoion/core/sources/DirectUrlSource.hpp" #include <Events.hpp> +#include <Void/Log/Log.hpp> #include <algorithm> -#include <execution> #include <filesystem> #include <format> -#include <fstream> #include <optional> #include <thread> @@ -30,6 +29,7 @@ namespace Echoion::Core config_ = botConfig; networkClient_ = std::move(networkClient); + database_ = database; // NetworkClient is already initialized by Core, just update proxy if // needed @@ -41,7 +41,7 @@ namespace Echoion::Core networkConfig.proxy->host, networkConfig.proxy->port)); } - youTubeClient_ = std::make_unique<YouTubeClient>(networkClient_); + youTubeClient_ = std::make_shared<YouTubeClient>(networkClient_); // Playlist loading runs off the audio path: it enqueues resolved // tracks via queueTrack and pokes the playback loop on the first one. @@ -60,7 +60,7 @@ namespace Echoion::Core } else if (youtubeConfig.cookiesFromBrowser.has_value()) { youTubeClient_->setCookiesFromBrowser( *youtubeConfig.cookiesFromBrowser); - Void::Log::info("MusicManager", "{}", + Void::Log::info("MusicManager", "{}", std::format("Using YouTube cookies from browser: {}", *youtubeConfig.cookiesFromBrowser)); } @@ -88,41 +88,98 @@ namespace Echoion::Core auto ytResult = youTubeClient_->initialize(); if (!ytResult) { - Void::Log::warn("MusicManager", "{}", + Void::Log::warn("MusicManager", "{}", std::format("Failed to initialize YouTube client: {}", ytResult.error().message)); } - audioDecoder_ = std::make_unique<AudioDecoder>(); - auto decoderResult = audioDecoder_->initialize(); - if (!decoderResult) { - return std::unexpected(decoderResult.error()); + // Persistent audio cache (advanced.cache*): downloaded files are + // reused across plays and restarts instead of re-downloading. + const auto& advanced = configManager_->getAdvanced(); + trackCache_ = std::make_unique<TrackCache>(TrackCache::Config{ + .enabled = advanced.cacheEnabled, + .maxBytes = std::max<uint64_t>( + TrackCache::parseSize(advanced.cacheMaxSize), 64ull << 20), + .ttl = std::chrono::seconds(advanced.cacheTTL)}); + + // Source-resolution chain: native innertube YouTube path and + // Yandex Music first, direct audio URLs, direct yt-dlp for + // non-YouTube extractors, proxied yt-dlp as the last resort. + const auto tempDir = + (std::filesystem::temp_directory_path() / "echoion_audio") + .string(); + innertubeSource_ = std::make_shared<InnertubeSource>(networkClient_); + yandexSource_ = std::make_shared<YandexMusicSource>(networkClient_); + auto directUrl = std::make_shared<DirectUrlSource>(); + auto ytdlpDirect = std::make_shared<YtDlpSource>( + youTubeClient_, YtDlpSource::Mode::Direct, tempDir); + ytdlpProxied_ = std::make_shared<YtDlpSource>( + youTubeClient_, YtDlpSource::Mode::Proxied, tempDir); + + router_ = std::make_unique<SourceRouter>(); + router_->setSources({innertubeSource_, yandexSource_, directUrl, + ytdlpDirect, ytdlpProxied_}); + applySourcesConfig(configManager_->getSources()); + + // Playback engine owns both decoders and the audio thread. + engine_ = std::make_unique<PlaybackEngine>( + static_cast<IPlaybackHost&>(*this)); + auto engineResult = engine_->initialize( + (networkConfig.proxy.has_value() && networkConfig.proxy->enabled()) + ? networkConfig.proxy + : std::nullopt); + if (!engineResult) { + return engineResult; } + engine_->setVolume(botConfig.defaultVolume); + engine_->setResolveGrace(botConfig.trackTimeout); + engine_->setCrossfade(botConfig.crossfade); - audioDecoder_->setOutputFormat(TEAMSPEAK_SAMPLE_RATE, - TEAMSPEAK_CHANNELS); - - // Set proxy config from NetworkConfig if enabled - if (networkConfig.proxy.has_value() && networkConfig.proxy->enabled()) { - audioDecoder_->setProxyConfig(networkConfig.proxy); - Void::Log::info("MusicManager", "{}", - std::format("AudioDecoder using {} proxy: {}:{}", - (networkConfig.proxy->kind == Void::Net::ProxyConfig::Kind::Socks5) ? "SOCKS5" : "HTTP", - networkConfig.proxy->host, - networkConfig.proxy->port)); + // Subscription service: audience bookkeeping + pause-on-empty policy. + subscriptions_ = std::make_unique<SubscriptionService>(); + subscriptions_->setEventBus(eventBus_); + if (clientInfoCallback_) { + subscriptions_->setClientInfoCallback(clientInfoCallback_); } - - // Initialize subscription manager with database - subscriptionManager_ = std::make_unique<SubscriptionManager>(); - auto subResult = subscriptionManager_->initialize(database); + if (uidToClientIdCallback_) { + subscriptions_->setUidToClientIdCallback(uidToClientIdCallback_); + } + if (subscriptionChangeCallback_) { + subscriptions_->setChangeCallback(subscriptionChangeCallback_); + } + subscriptions_->setPauseResumeHooks( + [this]() { + if (!engine_ || !engine_->isPlaying() || + engine_->isPaused()) { + return false; + } + engine_->pause(); + emitPauseState(true); + return true; + }, + [this]() { + if (!engine_ || !engine_->isPaused()) { + return false; + } + engine_->resume(); + emitPauseState(false); + return true; + }); + auto subResult = subscriptions_->initialize(database); if (!subResult) { - Void::Log::warn("MusicManager", "{}", + Void::Log::warn("MusicManager", "{}", std::format("Failed to initialize subscription manager: {}", subResult.error().message)); // Not fatal - continue without subscriptions } - volume_ = botConfig.defaultVolume; + // Feature toggles: policy flags may change on reload; the initial + // shuffle/repeat state is cold-start only (runtime toggles win). + const auto& features = configManager_->getFeatures(); + applyFeaturesConfig(features); + queue_.setShuffle(features.shuffleMode == "random"); + queue_.setRepeat(features.repeatMode != "off" && + !features.repeatMode.empty()); Void::Log::info("MusicManager", "{}", "MusicManager initialized"); return {}; @@ -142,8 +199,8 @@ namespace Echoion::Core if (youTubeClient_) { youTubeClient_->setProxyConfig(proxy); } - if (audioDecoder_) { - audioDecoder_->setProxyConfig(proxy); + if (engine_) { + engine_->setProxyConfig(proxy); } if (enabled) { @@ -187,38 +244,108 @@ namespace Echoion::Core hasKey ? "set" : "none (yt-dlp)")); } + void MusicManager::applyBotConfig(const Api::BotConfig& bot) + { + config_ = bot; + if (engine_) { + engine_->setResolveGrace(bot.trackTimeout); + engine_->setCrossfade(bot.crossfade); + } + } + + void MusicManager::applyFeaturesConfig(const Api::FeaturesConfig& features) + { + autoStartOnSubscribe_ = features.autoStartOnSubscribe; + // A runtime !autoplay toggle (persisted in kv) always wins over the + // config default, so a reload doesn't silently flip radio back. + bool autoplayPref = features.autoplay; + if (database_) { + if (auto stored = database_->getKv("autoplay.enabled")) { + autoplayPref = (*stored == "1"); + } + } + autoplay_ = autoplayPref; + if (engine_) { + engine_->setNormalization(features.normalizeLoudness, + features.targetLoudnessDb); + } + if (subscriptions_) { + subscriptions_->setPolicy(features.pauseOnEmptySubscribers, + features.resumeOnSubscriberReturn); + } + if (youTubeClient_) { + youTubeClient_->setAutoUpdateEnabled( + features.enableAutoUpdateCheck); + } + Void::Log::info("MusicManager", "{}", "Features config applied"); + } + + void MusicManager::setAutoplay(bool enabled) + { + autoplay_ = enabled; + if (database_) { + (void)database_->setKv("autoplay.enabled", enabled ? "1" : "0"); + } + Void::Log::info("MusicManager", "{}", + std::format("Autoplay {}", enabled ? "enabled" : "disabled")); + // Enabling while nothing is playing: kick an immediate refill so the + // radio starts without waiting for the next track to finish. + if (enabled && engine_ && !engine_->isPlaying()) { + onEngineIdle(); + } + } + + void MusicManager::applySourcesConfig(const Api::SourcesConfig& sources) + { + if (!router_) { + return; + } + router_->setOrder(sources.order); + router_->setFailureCooldown(sources.failureCooldown); + if (innertubeSource_) { + innertubeSource_->configure(sources.innertubeEnabled, + sources.innertubeRequireProxy); + } + if (yandexSource_) { + yandexSource_->configure(sources.yandexEnabled, + sources.yandexToken.value_or("")); + } + router_->setHedgeDelay(sources.hedgeDelay); + Void::Log::info("MusicManager", "{}", + "Sources config applied"); + } + void MusicManager::shutdown() { - isPlaying_ = false; - cv_.notify_all(); - - if (playbackThread_.joinable()) { - playbackThread_.join(); + // Background fetch threads touch queue_/engine_/sources; join them + // before tearing anything down. + if (autoplayThread_.joinable()) { + autoplayThread_.join(); + } + if (importThread_.joinable()) { + importThread_.join(); } // Stop playlist loading (the loader joins its background thread). playlistLoader_.reset(); - // Join auto-start thread if still running - if (playlistAutoStartThread_.joinable()) { - playlistAutoStartThread_.join(); - } - - if (audioDecoder_) { - audioDecoder_->shutdown(); + if (engine_) { + engine_->shutdown(); } // Clean up temp files - std::unique_lock<std::shared_mutex> lock(tempFilesMutex_); - for (const auto& filepath : tempFiles_) { - std::error_code ec; - std::filesystem::remove(filepath, ec); - if (!ec) { - Void::Log::debug("MusicManager", "{}", - std::format("Cleaned up temp file: {}", filepath)); + { + std::unique_lock<std::shared_mutex> lock(tempFilesMutex_); + for (const auto& filepath : tempFiles_) { + std::error_code ec; + std::filesystem::remove(filepath, ec); + if (!ec) { + Void::Log::debug("MusicManager", "{}", + std::format("Cleaned up temp file: {}", filepath)); + } } + tempFiles_.clear(); } - tempFiles_.clear(); // Also clean up any remaining files in temp directory auto cacheDir = @@ -234,160 +361,64 @@ namespace Echoion::Core Void::Log::info("MusicManager", "{}", "MusicManager shutdown"); } + // ---- playback commands --------------------------------------------- + Api::Result<std::string> MusicManager::play(const std::string& query, uint64_t clientId) { - Void::Log::info("MusicManager", "{}", + Void::Log::info("MusicManager", "{}", std::format("Play request: '{}' from client {}", query, clientId)); - auto startTime = std::chrono::steady_clock::now(); - // Get nickname for the client - std::string nickname = std::to_string(clientId); - if (nicknameCallback_) { - if (auto n = nicknameCallback_(clientId)) { - nickname = *n; + // Yandex collections dropped into !play import the whole collection + // (tracks enqueue as their metadata lands). + const bool isCollection = + (yandexSource_ && yandexSource_->canHandle(query) && + yandexSource_->isCollectionUrl(query)); + if (isCollection) { + auto import = loadPlaylist(query, clientId); + if (!import) { + return std::unexpected(import.error()); } + return std::string("Importing the collection — tracks are being " + "added to the queue..."); } auto track = resolveQuery(query); - auto afterResolve = std::chrono::steady_clock::now(); - Void::Log::debug("MusicManager", "{}", - std::format("resolveQuery took {} ms", - std::chrono::duration_cast<std::chrono::milliseconds>( - afterResolve - startTime) - .count())); if (!track) { Void::Log::error("MusicManager", "{}", std::format("Failed to resolve query '{}': {}", query, track.error().message)); return std::unexpected(track.error()); } - Void::Log::info("MusicManager", "{}", std::format( - "Resolved track: {} - {} ({}:{}", track->title, track->artist, - track->source == Api::TrackSource::YouTube ? "YouTube" : "Unknown", - track->streamUrl.has_value() ? "direct" : "needs extraction")); + const std::string nickname = nicknameFor(clientId); - if (!isPlaying_ && !currentTrack_.has_value()) { - currentTrack_ = - Api::QueueEntry{.queueId = queueMgr_.nextQueueId()++, - .track = *track, - .addedAt = std::chrono::system_clock::now(), - .addedBy = nickname, - .isPlaying = true, - .position = std::chrono::milliseconds(0)}; + // Idle: play immediately. Resolution happens here on the command + // thread so failures surface to the user synchronously. + if (engine_ && !engine_->isPlaying() && !engine_->currentEntry()) { + Api::QueueEntry entry{ + .queueId = queue_.allocateQueueId(), + .track = *track, + .addedAt = std::chrono::system_clock::now(), + .addedBy = nickname, + .isPlaying = true, + .position = std::chrono::milliseconds(0)}; - Void::Log::debug("MusicManager", "{}", "Getting stream URL..."); - auto streamStart = std::chrono::steady_clock::now(); - auto streamUrl = getStreamUrl(*track); - Void::Log::debug("MusicManager", "{}", std::format( - "getStreamUrl took {} ms", - std::chrono::duration_cast<std::chrono::milliseconds>( - std::chrono::steady_clock::now() - streamStart) - .count())); + auto streamUrl = resolveStream(entry, false); if (!streamUrl) { - Void::Log::error("MusicManager", "{}", std::format("Failed to get stream URL: {}", - streamUrl.error().message)); - currentTrack_.reset(); + Void::Log::error("MusicManager", "{}", + std::format("Failed to get stream URL: {}", + streamUrl.error().message)); return std::unexpected(streamUrl.error()); } - Void::Log::debug("MusicManager", "{}", "Opening audio source..."); + const bool isLocal = !streamUrl->starts_with("http"); + engine_->playNow(std::move(entry), *streamUrl, isLocal); - const auto& networkConfig = configManager_->getNetwork(); - const bool socks5Proxy = - networkConfig.proxy.has_value() && - networkConfig.proxy->enabled() && - networkConfig.proxy->kind == - Void::Net::ProxyConfig::Kind::Socks5; - - // Download the audio via yt-dlp and open the resulting local file. - auto downloadAndOpen = [&]() -> Api::Result<void> { - auto downloadedPath = - downloadAudioForPlayback(currentTrack_->track); - if (!downloadedPath) { - Void::Log::warn( - "MusicManager", "{}", - std::format("Failed to download audio: {}", - downloadedPath.error().message)); - return std::unexpected(downloadedPath.error()); - } - Void::Log::info("MusicManager", "{}", - std::format("Downloaded audio to: {}", - *downloadedPath)); - auto opened = audioDecoder_->openSource(*downloadedPath); - if (opened) { - std::unique_lock<std::shared_mutex> lock(tempFilesMutex_); - tempFiles_.insert(*downloadedPath); - } - return opened; - }; - - Api::Result<void> openResult; - if (socks5Proxy) { - // ffmpeg can't use a SOCKS5 proxy for the IP-locked stream URL; - // go straight to the yt-dlp download (which can). - Void::Log::info( - "MusicManager", "{}", - "SOCKS5 proxy configured: downloading audio via yt-dlp..."); - openResult = downloadAndOpen(); - } else { - openResult = audioDecoder_->openSource(*streamUrl); - // HTTP/no proxy: if a direct open fails but a proxy is set, - // fall back to a yt-dlp download through it. - if (!openResult && networkConfig.proxy.has_value() && - networkConfig.proxy->enabled()) { - Void::Log::info("MusicManager", "{}", - "Direct open failed, trying download via " - "yt-dlp through proxy..."); - openResult = downloadAndOpen(); - } - } - - if (!openResult) { - Void::Log::error("MusicManager", "{}", std::format("Failed to open audio source: {}", - openResult.error().message)); - currentTrack_.reset(); - return std::unexpected(openResult.error()); - } - - isPlaying_ = true; - isPaused_ = false; - - // Initialize time-based position tracking - playbackPosition_ = std::chrono::milliseconds(0); - playbackBasePosition_ = std::chrono::milliseconds(0); - playbackStartTime_ = std::chrono::steady_clock::now(); - - // Reset prefetch state for this new track - prefetchState_.hasPrefetched = false; - prefetchState_.isPrefetching = false; - - // Send initial silence to prime the audio stream and prevent - // whisper glitch This ensures the audio callback is active before - // real audio data arrives - sendSilenceChunk(); - - // Notify that playback is starting (updates whisper list) + // Update the whisper list before audio starts flowing. if (playbackStartCallback_) { playbackStartCallback_(); } - // Start playback thread if not running (check both joinable and - // running flag) - if (!playbackThread_.joinable() || !playbackThreadRunning_) { - // Join old thread if it exists but isn't running - if (playbackThread_.joinable()) { - Void::Log::info("MusicManager", "{}", "Joining old playback thread before " - "starting new one..."); - playbackThread_.join(); - } - playbackThread_ = - std::jthread(&MusicManager::playbackThread, this); - Void::Log::info("MusicManager", "{}", "Playback thread started"); - } - - cv_.notify_one(); - Void::Log::info("MusicManager", "{}", std::format("Now playing: {} - {}", track->title, track->artist)); return std::format("{} - {}", track->title, track->artist); @@ -405,169 +436,82 @@ namespace Echoion::Core Api::Result<void> MusicManager::pause() { - std::shared_lock<std::shared_mutex> lock(mutex_); - - if (!isPlaying_ || isPaused_) { + if (!engine_ || !engine_->isPlaying() || engine_->isPaused()) { return Api::fail(Api::ErrorCode::InvalidArgument, "Nothing is playing"); } - - // Capture current position before pausing - playbackPosition_ = getPlaybackPosition(); - isPaused_ = true; - Void::Log::info("MusicManager", "{}", - std::format("Playback paused at {}ms", playbackPosition_.count())); + engine_->pause(); + emitPauseState(true); + Void::Log::info("MusicManager", "{}", + std::format("Playback paused at {}ms", + engine_->position().count())); return {}; } Api::Result<void> MusicManager::resume() { - std::shared_lock<std::shared_mutex> lock(mutex_); - - if (!isPlaying_ || !isPaused_) { + if (!engine_ || !engine_->isPaused()) { return Api::fail(Api::ErrorCode::InvalidArgument, "Not paused"); } - - // Reset time tracking from current position - playbackBasePosition_ = playbackPosition_; - playbackStartTime_ = std::chrono::steady_clock::now(); - isPaused_ = false; - bool needToStartThread = false; - if (playbackThread_.joinable() && !playbackThreadRunning_) { - Void::Log::info("MusicManager", "{}", - "Joining finished playback thread before starting new one..."); - playbackThread_.join(); - Void::Log::info("MusicManager", "{}", "Old thread joined"); - needToStartThread = true; + engine_->resume(); + emitPauseState(false); + if (playbackStartCallback_) { + playbackStartCallback_(); } - - if (needToStartThread || - (!playbackThreadRunning_ && - (!queueMgr_.entries().empty() || currentTrack_.has_value()))) { - // Start the playback thread - isPlaying_ = true; - isPaused_ = false; - - // Initialize time-based position tracking - playbackPosition_ = std::chrono::milliseconds(0); - playbackBasePosition_ = std::chrono::milliseconds(0); - playbackStartTime_ = std::chrono::steady_clock::now(); - - // Notify that playback is starting (updates whisper list) - if (playbackStartCallback_) { - playbackStartCallback_(); - } - - playbackThread_ = std::jthread(&MusicManager::playbackThread, this); - Void::Log::info("MusicManager", "{}", "Started playback thread"); - } - - // Notify the thread to process - cv_.notify_one(); - - Void::Log::info("MusicManager", "{}", std::format("Playback resumed from {}ms", - playbackPosition_.count())); + Void::Log::info("MusicManager", "{}", + std::format("Playback resumed from {}ms", + engine_->position().count())); return {}; } Api::Result<void> MusicManager::stop() { - std::shared_lock<std::shared_mutex> lock(mutex_); + // Capture before stopping: the PlaybackStopped event reports which + // track was interrupted. + std::optional<Api::TrackInfo> lastTrack; + std::chrono::milliseconds finalPosition{0}; + if (engine_) { + if (auto entry = engine_->currentEntry()) { + lastTrack = entry->track; + } + finalPosition = engine_->position(); + engine_->stopPlayback(); + } + queue_.clear(); - isPlaying_ = false; - isPaused_ = false; - currentTrack_.reset(); - queueMgr_.entries().clear(); - - if (audioDecoder_) { - audioDecoder_->closeSource(); + // An explicit stop also ends radio mode: no seed, no refill. + { + std::lock_guard<std::mutex> lock(autoplaySeedMutex_); + autoplaySeedId_.clear(); } - cv_.notify_one(); Void::Log::info("MusicManager", "{}", "Playback stopped"); - // Publish playback stopped event emit(Api::Events::PlaybackStopped{ - .lastTrack = currentTrack_ ? std::optional(currentTrack_->track) - : std::nullopt, - .finalPosition = playbackPosition_}); + .lastTrack = lastTrack, + .finalPosition = finalPosition}); return {}; } Api::Result<void> MusicManager::skip(uint32_t count) { - std::shared_lock<std::shared_mutex> lock(mutex_); - - if (!isPlaying_) { + if (!engine_ || !engine_->isPlaying()) { return Api::fail(Api::ErrorCode::InvalidArgument, "Nothing is playing"); } - - for (uint32_t i = 0; i < count; ++i) { - if (queueMgr_.entries().empty()) { - if (repeat_ && currentTrack_.has_value()) { - continue; - } - isPlaying_ = false; - currentTrack_.reset(); - audioDecoder_->closeSource(); - break; - } - - auto nextTrack = getNextTrack(); - currentTrack_ = - Api::QueueEntry{.queueId = queueMgr_.nextQueueId()++, - .track = nextTrack, - .addedAt = std::chrono::system_clock::now(), - .addedBy = currentTrack_->addedBy, - .isPlaying = true, - .position = std::chrono::milliseconds(0)}; - - // Reset position tracking for new track - playbackPosition_ = std::chrono::milliseconds(0); - playbackBasePosition_ = std::chrono::milliseconds(0); - playbackStartTime_ = std::chrono::steady_clock::now(); - - auto streamUrl = getStreamUrl(nextTrack); - if (streamUrl) { - audioDecoder_->closeSource(); - auto openResult = audioDecoder_->openSource(*streamUrl); - if (!openResult) { - Void::Log::error("MusicManager", "{}", std::format("Failed to open stream: {}", - openResult.error().message)); - } - } - } - - cv_.notify_one(); + engine_->skip(count); Void::Log::info("MusicManager", "{}", std::format("Skipped {} track(s)", count)); return {}; } Api::Result<void> MusicManager::seek(std::chrono::milliseconds position) { - if (!isPlaying_) { + if (!engine_ || !engine_->isPlaying()) { return Api::fail(Api::ErrorCode::InvalidArgument, "Nothing is playing"); } - - auto result = audioDecoder_->seek(position); - if (!result) { - return std::unexpected(result.error()); - } - - // Update time-based tracking - playbackPosition_ = position; - playbackBasePosition_ = position; - if (!isPaused_) { - playbackStartTime_ = std::chrono::steady_clock::now(); - } - - if (currentTrack_) { - currentTrack_->position = position; - } - + engine_->seekTo(position); Void::Log::info("MusicManager", "{}", std::format("Seeked to {} ms", position.count())); return {}; } @@ -579,11 +523,12 @@ namespace Echoion::Core "Volume must be 0.0-1.0"); } - float oldVolume = volume_; - volume_ = volume; + float oldVolume = engine_ ? engine_->volume() : 0.0f; + if (engine_) { + engine_->setVolume(volume); + } Void::Log::info("MusicManager", "{}", std::format("Volume set to {}", volume)); - // Publish volume changed event emit(Api::Events::VolumeChanged{ .oldVolume = oldVolume, .newVolume = volume, @@ -593,124 +538,34 @@ namespace Echoion::Core return {}; } + // ---- queue commands --------------------------------------------------- + Api::Result<uint64_t> MusicManager::queueTrack(const Api::TrackInfo& track, uint64_t clientId) { - // Validate track before adding to queue - check if we can get a stream - // URL - Void::Log::info("MusicManager", "{}", - std::format("Validating track before queueing: {} - {}", - track.title, track.artist)); - auto streamUrl = getStreamUrl(track); - if (!streamUrl) { - Void::Log::warn("MusicManager", "{}", std::format( - "Track validation failed for '{} - {}': {}", track.title, - track.artist, streamUrl.error().message)); - return Api::fail(Api::ErrorCode::ServiceUnavailable, - std::format("Cannot play this track: {}", - streamUrl.error().message)); + // No synchronous stream validation here: enqueue is instant. The + // engine resolves the stream during its prefetch window; a dead + // track surfaces at play time and the failure budget advances past + // it automatically. + auto queueId = + queue_.enqueue(track, nicknameFor(clientId), config_.maxQueueSize); + if (!queueId) { + return queueId; } - uint64_t queueId; - bool shouldStart = false; - bool needToStartThread = false; + Void::Log::info("MusicManager", "{}", + std::format("Queued: {} - {}", track.title, track.artist)); - // Get nickname for the client - std::string nickname = std::to_string(clientId); - if (nicknameCallback_) { - if (auto n = nicknameCallback_(clientId)) { - nickname = *n; + // Auto-start when idle with an online audience. + if (autoStartOnSubscribe_.load() && engine_ && + !engine_->isPlaying() && !engine_->currentEntry() && + hasOnlineSubscribers()) { + Void::Log::info("MusicManager", "{}", + "Auto-starting playback for queued track"); + if (playbackStartCallback_) { + playbackStartCallback_(); } - } - - { - std::shared_lock<std::shared_mutex> lock(mutex_); - - if (queueMgr_.entries().size() >= config_.maxQueueSize) { - return Api::fail( - Api::ErrorCode::InvalidArgument, "Queue is full"); - } - - queueId = queueMgr_.nextQueueId()++; - queueMgr_.entries().push_back( - Api::QueueEntry{.queueId = queueId, - .track = track, - .addedAt = std::chrono::system_clock::now(), - .addedBy = nickname, - .isPlaying = false, - .position = std::nullopt}); - - // If shuffle is enabled, add the new track to shuffled indices - if (shuffle_) { - // Insert at a random position among the remaining tracks - if (queueMgr_.shuffleIndex() < queueMgr_.shuffledIndices().size()) { - std::uniform_int_distribution<size_t> dist( - queueMgr_.shuffleIndex(), queueMgr_.shuffledIndices().size()); - size_t insertPos = dist(queueMgr_.rng()); - queueMgr_.shuffledIndices().insert(queueMgr_.shuffledIndices().begin() + - insertPos, - queueMgr_.entries().size() - 1); - } else { - queueMgr_.shuffledIndices().push_back(queueMgr_.entries().size() - 1); - } - } - - Void::Log::info("MusicManager", "{}", - std::format("Queued: {} - {}", track.title, track.artist)); - - // Check if we should auto-start playback - // Conditions: not playing, not paused, has ONLINE subscribers, and - // this was the first track - shouldStart = !isPlaying_ && !isPaused_ && - !currentTrack_.has_value() && - hasOnlineSubscribers() && queueMgr_.entries().size() > 0; - needToStartThread = - !playbackThread_.joinable() && !playbackThreadRunning_; - - Void::Log::debug("MusicManager", "{}", std::format( - "queueTrack debug: shouldStart={}, " - "needToStartThread={}, isPlaying_={}, " - "thread_joinable={}, thread_running={}, queue_size={}", - shouldStart, needToStartThread, isPlaying_.load(), - playbackThread_.joinable(), playbackThreadRunning_.load(), - queueMgr_.entries().size())); - } - - if (shouldStart) { - Void::Log::info("MusicManager", "{}", "Auto-starting playback for first track in queue"); - - // Check if we need to handle an old thread that's done but still - // joinable - if (playbackThread_.joinable() && !playbackThreadRunning_) { - Void::Log::info("MusicManager", "{}", "Joining finished playback thread before " - "starting new one..."); - playbackThread_.join(); - Void::Log::info("MusicManager", "{}", "Old thread joined"); - needToStartThread = true; - } - - if (needToStartThread) { - // Start the playback thread - isPlaying_ = true; - isPaused_ = false; - - // Initialize time-based position tracking - playbackPosition_ = std::chrono::milliseconds(0); - playbackBasePosition_ = std::chrono::milliseconds(0); - playbackStartTime_ = std::chrono::steady_clock::now(); - - // Notify that playback is starting (updates whisper list) - if (playbackStartCallback_) { - playbackStartCallback_(); - } - - playbackThread_ = - std::jthread(&MusicManager::playbackThread, this); - Void::Log::info("MusicManager", "{}", "Started playback thread for auto-play"); - } - - // Notify the thread to process - cv_.notify_one(); + engine_->start(); } return queueId; @@ -718,66 +573,27 @@ namespace Echoion::Core Api::Result<void> MusicManager::removeFromQueue(uint32_t position) { - std::shared_lock<std::shared_mutex> lock(mutex_); - - if (position >= queueMgr_.entries().size()) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "Invalid position"); - } - - auto removedTrack = queueMgr_.entries()[position]; - queueMgr_.entries().erase(queueMgr_.entries().begin() + position); - - // Update shuffled indices if shuffle is enabled - if (shuffle_ && !queueMgr_.shuffledIndices().empty()) { - // Remove the index from shuffledIndices - auto it = std::find(queueMgr_.shuffledIndices().begin(), - queueMgr_.shuffledIndices().end(), position); - if (it != queueMgr_.shuffledIndices().end()) { - size_t removedShuffleIndex = - std::distance(queueMgr_.shuffledIndices().begin(), it); - queueMgr_.shuffledIndices().erase(it); - // If we removed an index before the current shuffle position, - // decrement it - if (removedShuffleIndex < queueMgr_.shuffleIndex()) { - queueMgr_.shuffleIndex()--; - } - } - // Decrement indices that were after the removed position - for (auto& idx : queueMgr_.shuffledIndices()) { - if (idx > position) { - idx--; - } - } + auto removed = queue_.removeAt(position); + if (!removed) { + return std::unexpected(removed.error()); } Void::Log::info("MusicManager", "{}", std::format("Removed track at position {}", position)); - // Publish track removed event emit(Api::Events::TrackRemoved{ - .track = removedTrack.track, - .queueId = removedTrack.queueId, + .track = removed->track, + .queueId = removed->queueId, .removedByClientId = 0, - .queueLength = static_cast<uint32_t>(queueMgr_.entries().size())}); + .queueLength = static_cast<uint32_t>(queue_.size())}); return {}; } Api::Result<void> MusicManager::clearQueue() { - std::shared_lock<std::shared_mutex> lock(mutex_); - uint32_t previousLength = static_cast<uint32_t>(queueMgr_.entries().size()); - queueMgr_.entries().clear(); - - // Clear shuffle state - if (shuffle_) { - queueMgr_.shuffledIndices().clear(); - queueMgr_.shuffleIndex() = 0; - } - + const uint32_t previousLength = queue_.clear(); Void::Log::info("MusicManager", "{}", "Queue cleared"); - // Publish queue cleared event emit(Api::Events::QueueCleared{ .clearedByClientId = 0, .previousLength = previousLength}); @@ -786,51 +602,20 @@ namespace Echoion::Core Api::Result<std::vector<Api::QueueEntry>> MusicManager::getQueue() const { - std::shared_lock<std::shared_mutex> lock(mutex_); - return queueMgr_.entries(); + return queue_.snapshot(); } Api::Result<void> MusicManager::moveInQueue(uint32_t from, uint32_t to) { - std::shared_lock<std::shared_mutex> lock(mutex_); - - if (from >= queueMgr_.entries().size() || to >= queueMgr_.entries().size()) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "Invalid position"); - } - - auto entry = queueMgr_.entries()[from]; - queueMgr_.entries().erase(queueMgr_.entries().begin() + from); - queueMgr_.entries().insert(queueMgr_.entries().begin() + to, entry); - - // Update shuffled indices if shuffle is enabled - if (shuffle_ && !queueMgr_.shuffledIndices().empty()) { - // Find and update indices that are affected by the move - for (auto& idx : queueMgr_.shuffledIndices()) { - if (from < to) { - // Moving forward: indices in (from, to] decrement - if (idx > from && idx <= to) { - idx--; - } else if (idx == from) { - idx = to; - } - } else if (from > to) { - // Moving backward: indices in [to, from) increment - if (idx >= to && idx < from) { - idx++; - } else if (idx == from) { - idx = to; - } - } - // If from == to, nothing changes - } + auto moved = queue_.move(from, to); + if (!moved) { + return std::unexpected(moved.error()); } Void::Log::info("MusicManager", "{}", std::format("Moved track from {} to {}", from, to)); - // Publish queue reordered event emit( - Api::Events::QueueReordered{.queueId = entry.queueId, + Api::Events::QueueReordered{.queueId = *moved, .oldPosition = from, .newPosition = to, .changedByClientId = 0}); @@ -840,82 +625,87 @@ namespace Echoion::Core Api::Result<bool> MusicManager::toggleShuffle() { - std::shared_lock<std::shared_mutex> lock(mutex_); + const bool enabled = queue_.toggleShuffle(); + Void::Log::info("MusicManager", "{}", + enabled ? "Shuffle enabled" : "Shuffle disabled"); - shuffle_ = !shuffle_; - - if (shuffle_) { - // Build shuffled indices for current queue - rebuildShuffledIndices(); - queueMgr_.shuffleIndex() = 0; - Void::Log::info("MusicManager", "{}", - std::format("Shuffle enabled - queue shuffled with {} tracks", - queueMgr_.shuffledIndices().size())); - } else { - // Clear shuffle state - queueMgr_.shuffledIndices().clear(); - queueMgr_.shuffleIndex() = 0; - Void::Log::info("MusicManager", "{}", "Shuffle disabled"); - } - - // Publish shuffle changed event emit(Api::Events::ShuffleChanged{ - .enabled = shuffle_, .changedByClientId = 0}); + .enabled = enabled, .changedByClientId = 0}); - return shuffle_; - } - - void MusicManager::rebuildShuffledIndices() - { - queueMgr_.shuffledIndices().clear(); - queueMgr_.shuffledIndices().reserve(queueMgr_.entries().size()); - - // Create indices 0 to queue_size-1 - for (size_t i = 0; i < queueMgr_.entries().size(); ++i) { - queueMgr_.shuffledIndices().push_back(i); - } - - // Shuffle the indices using Fisher-Yates algorithm - std::shuffle(queueMgr_.shuffledIndices().begin(), queueMgr_.shuffledIndices().end(), queueMgr_.rng()); - queueMgr_.shuffleIndex() = 0; - - Void::Log::debug("MusicManager", "{}", std::format("Rebuilt shuffled indices: {} tracks", - queueMgr_.shuffledIndices().size())); - } - - void MusicManager::reshuffleRemaining() - { - if (queueMgr_.shuffledIndices().empty() || - queueMgr_.shuffleIndex() >= queueMgr_.shuffledIndices().size()) { - return; - } - - // Only reshuffle the remaining indices (from queueMgr_.shuffleIndex() onwards) - // This preserves the already-played tracks order but reshuffles what's - // left - std::shuffle(queueMgr_.shuffledIndices().begin() + queueMgr_.shuffleIndex(), - queueMgr_.shuffledIndices().end(), queueMgr_.rng()); - - Void::Log::debug("MusicManager", "{}", std::format("Reshuffled remaining {} tracks", - queueMgr_.shuffledIndices().size() - queueMgr_.shuffleIndex())); + return enabled; } Api::Result<bool> MusicManager::toggleRepeat() { - repeat_ = !repeat_; - Void::Log::info("MusicManager", "{}", repeat_ ? "Repeat enabled" : "Repeat disabled"); + const bool enabled = queue_.toggleRepeat(); + Void::Log::info("MusicManager", "{}", + enabled ? "Repeat enabled" : "Repeat disabled"); - // Publish repeat changed event emit(Api::Events::RepeatChanged{ - .enabled = repeat_, .changedByClientId = 0}); + .enabled = enabled, .changedByClientId = 0}); - return repeat_; + return enabled; } + Api::Result<void> MusicManager::shuffleQueue() + { + queue_.shuffleInPlace(); + emit(Api::Events::QueueShuffled{.triggeredByClientId = 0}); + return {}; + } + + // ---- playlist / state --------------------------------------------------- + Api::Result<void> MusicManager::loadPlaylist(const std::string& playlistIdOrUrl, uint64_t clientId) { + if (!config_.allowPlaylistImports) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "Playlist imports are disabled"); + } + + // Yandex collections import through the source: the metadata fetch + // runs in the background, each track enqueues instantly, and stream + // resolution happens lazily in the engine. + const bool yandexCollection = + yandexSource_ && yandexSource_->canHandle(playlistIdOrUrl) && + yandexSource_->isCollectionUrl(playlistIdOrUrl); + if (yandexCollection) { + bool expected = false; + if (!importRunning_.compare_exchange_strong(expected, true)) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "A playlist import is already running"); + } + if (importThread_.joinable()) { + importThread_.join(); // previous import already finished + } + importThread_ = std::jthread([this, playlistIdOrUrl, clientId]() { + auto tracks = yandexSource_->playlistTracks(playlistIdOrUrl); + if (!tracks) { + Void::Log::warn("MusicManager", "{}", + std::format("Collection import failed: {}", + tracks.error().message)); + importRunning_ = false; + return; + } + size_t queued = 0; + for (const auto& track : *tracks) { + if (queueTrack(track, clientId)) { + ++queued; + } + } + Void::Log::info("MusicManager", "{}", + std::format("Imported {} track(s) from collection", + queued)); + if (queued > 0 && engine_) { + engine_->start(); + } + importRunning_ = false; + }); + return {}; + } + if (!playlistLoader_) { return Api::fail(Api::ErrorCode::ServiceUnavailable, "Playlist loader not available"); @@ -925,99 +715,133 @@ namespace Echoion::Core void MusicManager::requestPlaybackStart() { - // Start playback in a background thread so streaming isn't blocked. - if (playlistAutoStartThread_.joinable()) { - playlistAutoStartThread_.join(); - } - playlistAutoStartThread_ = std::thread([this]() { - // Small delay to ensure the queue is updated. - std::this_thread::sleep_for(std::chrono::milliseconds(100)); - - std::shared_lock<std::shared_mutex> lock(mutex_); - if (!isPlaying_ && !queueMgr_.entries().empty()) { - cv_.notify_one(); - Void::Log::info("MusicManager", "{}", - "Playback started from playlist"); + // The engine's Start command is idempotent and cheap: if the queue is + // still empty (streaming race) the engine just stays idle and the + // next queueTrack pokes it again — no delay thread needed. + if (autoStartOnSubscribe_.load() && engine_ && + hasOnlineSubscribers()) { + if (playbackStartCallback_) { + playbackStartCallback_(); } - }); + engine_->start(); + } } Api::Result<std::vector<Api::PlaylistInfo>> MusicManager::getPlaylists() const { - return std::vector<Api::PlaylistInfo>{}; + if (!database_) { + return std::vector<Api::PlaylistInfo>{}; + } + auto playlists = database_->getAllPlaylists(); + if (!playlists) { + return std::unexpected(playlists.error()); + } + std::vector<Api::PlaylistInfo> result; + result.reserve(playlists->size()); + for (const auto& p : *playlists) { + Api::PlaylistInfo info; + info.id = std::to_string(p.id); + info.name = p.name; + info.description = p.description; + info.owner = std::to_string(p.createdBy); + info.tracks = p.tracks; + info.createdAt = p.createdAt; + info.updatedAt = p.updatedAt; + result.push_back(std::move(info)); + } + return result; } Api::Result<std::optional<Api::QueueEntry>> MusicManager::getCurrentTrack() const { - std::shared_lock<std::shared_mutex> lock(mutex_); - return currentTrack_; + if (!engine_) { + return std::optional<Api::QueueEntry>{}; + } + auto entry = engine_->currentEntry(); + if (entry) { + entry->position = engine_->position(); + } + return entry; } std::chrono::milliseconds MusicManager::getPlaybackPosition() const { - std::shared_lock<std::shared_mutex> lock(mutex_); - - if (!isPlaying_) { - return std::chrono::milliseconds(0); - } - - if (isPaused_) { - return playbackPosition_; - } - - // Safety check: if playbackStartTime_ is not initialized, return base - // position - if (playbackStartTime_.time_since_epoch().count() == 0) { - Void::Log::debug("MusicManager", "{}", - "getPlaybackPosition: playbackStartTime_ not initialized"); - return playbackBasePosition_; - } - - // Calculate elapsed time since last start/resume - auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>( - std::chrono::steady_clock::now() - playbackStartTime_); - auto position = playbackBasePosition_ + elapsed; - - // Sanity check: position shouldn't be negative or more than 24 hours - if (position.count() < 0 || position.count() > 86400000) { - Void::Log::warn("MusicManager", "{}", - std::format("getPlaybackPosition: Invalid position: {}ms", - position.count())); - return std::chrono::milliseconds(0); - } - - return position; + return engine_ ? engine_->position() : std::chrono::milliseconds(0); } Api::Result<Api::PlaybackState> MusicManager::getPlaybackState() const { - std::shared_lock<std::shared_mutex> lock(mutex_); - Api::PlaybackState state; - state.currentTrack = currentTrack_; - state.queue = queueMgr_.entries(); - state.isPlaying = isPlaying_; - state.isPaused = isPaused_; + state.currentTrack = + engine_ ? engine_->currentEntry() : std::nullopt; + state.queue = queue_.snapshot(); + state.isPlaying = engine_ && engine_->isPlaying(); + state.isPaused = engine_ && engine_->isPaused(); state.position = getPlaybackPosition(); - state.volume = volume_; - state.repeat = repeat_; - state.shuffle = shuffle_; + state.volume = engine_ ? engine_->volume() : 0.0f; + state.repeat = queue_.repeatEnabled(); + state.shuffle = queue_.shuffleEnabled(); state.lastUpdate = std::chrono::system_clock::now(); return state; } Api::Result<Api::SearchResult> - MusicManager::search(const std::string& query) + MusicManager::search(const std::string& query, SearchScope scope) { - if (!youTubeClient_) { + // YouTube search goes through the router (Invidious/Piped/ytdlp); + // Yandex is called directly (its canHandle rejects text, so the + // router never routes bare queries to it). + const auto youtube = [&]() -> Api::Result<Api::SearchResult> { + if (router_) { + return router_->search(query); + } + if (youTubeClient_) { + return youTubeClient_->search(query); + } return Api::fail(Api::ErrorCode::ServiceUnavailable, - "YouTube client not available"); + "YouTube search unavailable"); + }; + const auto yandex = [&]() -> Api::Result<Api::SearchResult> { + if (yandexSource_ && yandexSource_->isAvailable()) { + return yandexSource_->search(query); + } + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "Yandex Music not configured"); + }; + + if (scope == SearchScope::YouTube) { + return youtube(); + } + if (scope == SearchScope::Yandex) { + return yandex(); } - return youTubeClient_->search(query); + // All: merge both catalogs (YouTube first). Succeed if either does. + Api::SearchResult merged; + merged.query = query; + std::optional<Api::Error> lastError; + if (auto yt = youtube()) { + for (auto& t : yt->tracks) { + merged.tracks.push_back(std::move(t)); + } + } else { + lastError = yt.error(); + } + if (auto ya = yandex()) { + for (auto& t : ya->tracks) { + merged.tracks.push_back(std::move(t)); + } + } else if (!lastError) { + lastError = ya.error(); + } + if (merged.tracks.empty() && lastError) { + return std::unexpected(*lastError); + } + merged.totalResults = static_cast<uint32_t>(merged.tracks.size()); + return merged; } void MusicManager::storePendingSearch( @@ -1087,35 +911,15 @@ namespace Echoion::Core Api::HotReloadState MusicManager::getStateForHotReload() const { - std::shared_lock<std::shared_mutex> lock(mutex_); - Api::HotReloadState state; - // Build playback state directly (don't call getPlaybackState to avoid - // double-lock) - state.playback.currentTrack = currentTrack_; - state.playback.queue = queueMgr_.entries(); - state.playback.isPlaying = isPlaying_; - state.playback.isPaused = isPaused_; - // Calculate position directly using time-based tracking - if (isPlaying_ && !isPaused_) { - auto elapsed = - std::chrono::duration_cast<std::chrono::milliseconds>( - std::chrono::steady_clock::now() - playbackStartTime_); - state.playback.position = playbackBasePosition_ + elapsed; - } else { - state.playback.position = - isPaused_ ? playbackPosition_ : std::chrono::milliseconds(0); - } - state.playback.volume = volume_; - state.playback.repeat = repeat_; - state.playback.shuffle = shuffle_; - state.playback.lastUpdate = std::chrono::system_clock::now(); + state.playback = getPlaybackState().value_or(Api::PlaybackState{}); + state.queue = state.playback.queue; - state.queue = queueMgr_.entries(); - - if (currentTrack_ && currentTrack_->track.streamUrl) { - state.currentStreamUrl = currentTrack_->track.streamUrl; + if (state.playback.currentTrack && + state.playback.currentTrack->track.streamUrl) { + state.currentStreamUrl = + state.playback.currentTrack->track.streamUrl; } state.playbackPosition = state.playback.position; @@ -1128,17 +932,14 @@ namespace Echoion::Core MusicManager::restoreFromHotReload(const Api::HotReloadState& state) { config_ = state.config; - queueMgr_.entries() = state.queue; - volume_ = state.playback.volume; - shuffle_ = state.playback.shuffle; - repeat_ = state.playback.repeat; - - // Rebuild shuffle state if shuffle is enabled - if (shuffle_ && !queueMgr_.entries().empty()) { - rebuildShuffledIndices(); + queue_.setShuffle(state.playback.shuffle); + queue_.setRepeat(state.playback.repeat); + queue_.replaceAll(state.queue); + if (engine_) { + engine_->setVolume(state.playback.volume); } - Void::Log::info("MusicManager", "{}", + Void::Log::info("MusicManager", "{}", std::format("restoreFromHotReload: shouldPreservePlayback={}, " "hasStreamUrl={}, isPlaying={}, hasCurrentTrack={}", state.shouldPreservePlayback(), @@ -1146,95 +947,32 @@ namespace Echoion::Core state.playback.isPlaying, state.playback.currentTrack.has_value())); - if (state.shouldPreservePlayback() && state.currentStreamUrl) { - Void::Log::info("MusicManager", "{}", + if (engine_ && state.shouldPreservePlayback() && + state.currentStreamUrl && state.playback.currentTrack) { + Void::Log::info("MusicManager", "{}", std::format("Restoring playback from position {}ms", state.playbackPosition.count())); - auto openResult = - audioDecoder_->openSource(*state.currentStreamUrl); - if (openResult) { - auto seekResult = audioDecoder_->seek(state.playbackPosition); - if (seekResult) { - currentTrack_ = state.playback.currentTrack; - isPlaying_ = true; - isPaused_ = state.playback.isPaused; - - // Initialize position tracking from restored state - playbackPosition_ = state.playbackPosition; - playbackBasePosition_ = state.playbackPosition; - if (!isPaused_) { - playbackStartTime_ = std::chrono::steady_clock::now(); - } - - // Start thread if not running (check both joinable and - // running flag) - if (!playbackThread_.joinable() || - !playbackThreadRunning_) { - if (playbackThread_.joinable()) { - playbackThread_.join(); - } - playbackThread_ = - std::jthread(&MusicManager::playbackThread, this); - } - - cv_.notify_one(); - Void::Log::info("MusicManager", "{}", "Playback restored successfully"); - } else { - Void::Log::error("MusicManager", "{}", - std::format("Failed to seek to position {}ms: {}", - state.playbackPosition.count(), - seekResult.error().message)); - } - } else { - Void::Log::error("MusicManager", "{}", std::format("Failed to open stream URL: {}", - openResult.error().message)); - } - } else { - Void::Log::info("MusicManager", "{}", - std::format("Playback not restored: conditions not met " - "(isPlaying={}, hasTrack={}, hasUrl={})", - state.playback.isPlaying, - state.playback.currentTrack.has_value(), - state.currentStreamUrl.has_value())); - } - if (!currentTrack_.has_value() && !queueMgr_.entries().empty() && - hasOnlineSubscribers()) { - Void::Log::info("MusicManager", "{}", - "Playback not restored but queue has items, starting " - "thread for auto-start"); - if (playbackThread_.joinable()) { - playbackThread_.join(); - } - // Start the playback thread - isPlaying_ = true; - isPaused_ = false; - - // Initialize time-based position tracking - playbackPosition_ = std::chrono::milliseconds(0); - playbackBasePosition_ = std::chrono::milliseconds(0); - playbackStartTime_ = std::chrono::steady_clock::now(); - - // Notify that playback is starting (updates whisper list) + engine_->restore(*state.playback.currentTrack, + *state.currentStreamUrl, state.playbackPosition, + state.playback.isPaused); if (playbackStartCallback_) { playbackStartCallback_(); } - - if (!playbackThread_.joinable() || !playbackThreadRunning_) { - - playbackThread_ = - std::jthread(&MusicManager::playbackThread, this); + } else if (engine_ && !queue_.empty() && hasOnlineSubscribers()) { + Void::Log::info("MusicManager", "{}", + "Playback not restored but queue has items, auto-starting"); + if (playbackStartCallback_) { + playbackStartCallback_(); } - cv_.notify_one(); - } else if (state.playback.isPlaying && !queueMgr_.entries().empty()) { - isPaused_ = true; - isPlaying_ = true; - currentTrack_.reset(); + engine_->start(); } Void::Log::info("MusicManager", "{}", "State restored from hot reload"); return {}; } + // ---- callbacks --------------------------------------------------------- + void MusicManager::setAudioDataCallback(const AudioDataCallback& callback) { audioCallback_ = callback; @@ -1244,6 +982,9 @@ namespace Echoion::Core const SubscriptionChangeCallback& callback) { subscriptionChangeCallback_ = callback; + if (subscriptions_) { + subscriptions_->setChangeCallback(callback); + } } void MusicManager::setPlaybackStartCallback( @@ -1255,12 +996,18 @@ namespace Echoion::Core void MusicManager::setClientInfoCallback(const ClientInfoCallback& callback) { clientInfoCallback_ = callback; + if (subscriptions_) { + subscriptions_->setClientInfoCallback(callback); + } } void MusicManager::setUidToClientIdCallback( const UidToClientIdCallback& callback) { uidToClientIdCallback_ = callback; + if (subscriptions_) { + subscriptions_->setUidToClientIdCallback(callback); + } } void MusicManager::setNicknameCallback(const NicknameCallback& callback) @@ -1268,382 +1015,352 @@ namespace Echoion::Core nicknameCallback_ = callback; } - void MusicManager::playbackThread() + // ---- IPlaybackHost ------------------------------------------------- + + void MusicManager::emitAudio(std::span<const short> samples) { - Void::Log::debug("MusicManager", "{}", "Playback thread started"); - playbackThreadRunning_ = true; + if (audioCallback_) { + audioCallback_(samples); + } + } - // Constants for 192kHz 20ms chunks (like reference) - constexpr int CHUNK_MS = 20; - constexpr size_t SHORTS_PER_CHUNK = - (TEAMSPEAK_SAMPLE_RATE * TEAMSPEAK_CHANNELS * CHUNK_MS) / 1000; - constexpr size_t MAX_BUFFER_SHORTS = SHORTS_PER_CHUNK * 50; + Api::Result<std::string> + MusicManager::resolveStream(const Api::QueueEntry& entry, + bool preferDownload) + { + const std::string cacheKey = + entry.track.id.empty() ? entry.track.originalUrl + : entry.track.id; - std::vector<short> localAudioBuffer; - auto next = std::chrono::steady_clock::now(); - int chunksSent = 0; - - while (true) { - { - std::unique_lock<std::shared_mutex> lock(mutex_); - cv_.wait(lock, [this] { - return !isPlaying_ || !isPaused_ || - (hasOnlineSubscribers() && !queueMgr_.entries().empty() && - !currentTrack_.has_value()); - }); - - // Auto-start if we have ONLINE subscribers and queue but no - // current track - if (hasOnlineSubscribers() && !queueMgr_.entries().empty() && - !currentTrack_.has_value() && !wasPausedForNoSubscribers_) { - if (!isPlaying_) { - isPlaying_ = true; - isPaused_ = false; - - // Initialize time-based position tracking - playbackPosition_ = std::chrono::milliseconds(0); - playbackBasePosition_ = std::chrono::milliseconds(0); - playbackStartTime_ = std::chrono::steady_clock::now(); - - // Notify that playback is starting (updates whisper - // list) - if (playbackStartCallback_) { - playbackStartCallback_(); - } - } - // Start first track from queue - auto firstTrack = queueMgr_.entries().front(); - queueMgr_.entries().erase(queueMgr_.entries().begin()); - - auto streamUrl = getStreamUrl(firstTrack.track); - if (streamUrl) { - currentTrack_ = Api::QueueEntry{ - .queueId = firstTrack.queueId, - .track = firstTrack.track, - .addedAt = firstTrack.addedAt, - .addedBy = firstTrack.addedBy, - .isPlaying = true, - .position = std::chrono::milliseconds(0)}; - - lock.unlock(); - - // Send silence before opening source to keep audio - // stream alive - sendSilenceChunk(); - - auto openResult = audioDecoder_->openSource(*streamUrl); - if (!openResult) { - Void::Log::error("MusicManager", "{}", - std::format("Failed to open first track: {}", - openResult.error().message)); - lock.lock(); - currentTrack_.reset(); - isPlaying_ = false; - continue; - } - lock.lock(); - - Void::Log::info("MusicManager", "{}", std::format( - "Auto-started playback: {} - {}", - firstTrack.track.title, firstTrack.track.artist)); - } - } - - if (!isPlaying_) { - break; - } - } - - if (isPaused_.load()) { - continue; - } - - // Pull data from decoder (like reference) - if (localAudioBuffer.size() < MAX_BUFFER_SHORTS) { - std::vector<short> incomingChunk; - if (audioDecoder_->getNextChunk(incomingChunk)) { - localAudioBuffer.insert(localAudioBuffer.end(), - incomingChunk.begin(), - incomingChunk.end()); - if (chunksSent == 0) { - Void::Log::debug("MusicManager", "{}", - std::format("First chunk received: {} samples", - incomingChunk.size())); - } - } - } - // Update current position periodically (every ~2 seconds) - if (chunksSent == 0 && currentTrack_.has_value()) { - std::shared_lock<std::shared_mutex> lock(mutex_); - playbackPosition_ = std::chrono::milliseconds(0); - playbackBasePosition_ = std::chrono::milliseconds(0); - playbackStartTime_ = std::chrono::steady_clock::now(); - currentTrack_->position = getPlaybackPosition(); - } - // Check if we should prefetch next track for seamless transition - if (shouldPrefetch()) { - prefetchNextTrack(); - } - - // Note: Position is calculated on-demand via getPlaybackPosition() - // No need to periodically update currentTrack_->position - - // Publish position update periodically - if (currentTrack_.has_value()) { - auto now = std::chrono::steady_clock::now(); - if (now - lastPositionUpdate_ >= POSITION_UPDATE_INTERVAL) { - auto position = getPlaybackPosition(); - auto streamInfo = audioDecoder_->getStreamInfo(); - - float progress = 0.0f; - if (streamInfo && streamInfo->duration.count() > 0) { - progress = - (static_cast<float>(position.count()) / - static_cast<float>(streamInfo->duration.count())) * - 100.0f; - } - - emit( - Api::Events::PlaybackPositionChanged{ - .track = currentTrack_->track, - .position = position, - .duration = streamInfo - ? streamInfo->duration - : std::chrono::milliseconds(0), - .progressPercent = progress}); - lastPositionUpdate_ = now; - } - } - - // Send audio when we have enough - if (localAudioBuffer.size() >= SHORTS_PER_CHUNK) { - // Apply volume (squared for better perception, not cubed to - // avoid over-amplification) - float volMult = std::pow(volume_.load(), 3.0f); - std::vector<short> audioChunk(SHORTS_PER_CHUNK); - - // Debug: Check if audio data is valid (first chunk only) - if (chunksSent == 0) { - int nonZeroCount = 0; - int maxSample = 0; - for (size_t i = 0; - i < std::min(size_t(100), localAudioBuffer.size()); - ++i) { - if (localAudioBuffer[i] != 0) { - nonZeroCount++; - } - maxSample = std::max( - maxSample, - std::abs(static_cast<int>(localAudioBuffer[i]))); - } - Void::Log::debug("MusicManager", "{}", std::format( - "Audio debug: volume={:.3f}, volMult={:.3f}, " - "nonZero={}/100, maxSample={}", - volume_.load(), volMult, nonZeroCount, maxSample)); - } - - for (size_t i = 0; i < SHORTS_PER_CHUNK; ++i) { - // Apply volume with soft limiting to prevent clipping - int sample = - static_cast<int>(localAudioBuffer[i] * volMult); - audioChunk[i] = - static_cast<short>(std::clamp(sample, -32768, 32767)); - } - - localAudioBuffer.erase(localAudioBuffer.begin(), - localAudioBuffer.begin() + - SHORTS_PER_CHUNK); - - // Send audio to callback - if (audioCallback_) { - audioCallback_(std::span<const short>(audioChunk.data(), - audioChunk.size())); - - chunksSent++; - if (chunksSent == 1 || chunksSent % 100 == 0) { - Void::Log::debug("MusicManager", "{}", - std::format("Sent {} chunks, buffer: {}", - chunksSent, - localAudioBuffer.size())); - } - } else if (chunksSent == 0) { - Void::Log::warn("MusicManager", "{}", "No audio callback set!"); - } - - // Precision timing (like reference) - next += std::chrono::milliseconds(CHUNK_MS); - std::this_thread::sleep_until(next); - } else { - // Buffer underrun - wait for more data - if (chunksSent == 0) { - Void::Log::debug("MusicManager", "{}", std::format("Waiting for data: {} < {}", - localAudioBuffer.size(), - SHORTS_PER_CHUNK)); - } - - std::vector<short> incoming; - if (audioDecoder_->getNextChunk(incoming, - true)) { // Blocking wait - localAudioBuffer.insert(localAudioBuffer.end(), - incoming.begin(), incoming.end()); - continue; - } - - // Check if finished - bool decoderFinished = audioDecoder_->isFinished(); - - if (decoderFinished) { - // Send ALL remaining data in multiple chunks if needed - // (LAST FLUSH) - size_t totalFlushed = 0; - while (!localAudioBuffer.empty()) { - size_t toSend = - std::min(localAudioBuffer.size(), SHORTS_PER_CHUNK); - totalFlushed += toSend; - - float volMult = std::pow(volume_.load(), 3.0f); - - std::vector<short> audioChunk(SHORTS_PER_CHUNK, 0); - - // Copy actual data, rest is silence - for (size_t i = 0; i < toSend; ++i) { - // Apply volume with soft limiting - int sample = - static_cast<int>(localAudioBuffer[i] * volMult); - // Soft limiting to prevent clipping - audioChunk[i] = static_cast<short>( - std::clamp(sample, -32768, 32767)); - } - - if (audioCallback_) { - audioCallback_(std::span<const short>( - audioChunk.data(), audioChunk.size())); - chunksSent++; - - // Small delay to let audio play - std::this_thread::sleep_for( - std::chrono::milliseconds(CHUNK_MS)); - } - - // Remove sent samples from buffer - localAudioBuffer.erase(localAudioBuffer.begin(), - localAudioBuffer.begin() + - toSend); - } - - if (totalFlushed > 0) { - Void::Log::info("MusicManager", "{}", - std::format("Playback finished with last flush, " - "sent {} chunks, flushed {} samples", - chunksSent, totalFlushed)); - } else { - Void::Log::info("MusicManager", "{}", std::format( - "Playback finished, sent {} chunks", chunksSent)); - } - - onTrackFinished(); - - // Send low-level white noise during track transition to - // prevent audio glitch and keep microphone active - Void::Log::debug("MusicManager", "{}", - "Sending transition noise during track transition..."); - auto transitionStart = std::chrono::steady_clock::now(); - constexpr auto MAX_TRANSITION_TIME = - std::chrono::seconds(5); - - // Random number generator for white noise - static std::random_device rd; - static std::mt19937 gen(rd()); - // Very low amplitude noise (-60dB = ~0.001 in 16-bit range) - std::uniform_int_distribution<int> noiseDist(-20, 20); - - while (std::chrono::steady_clock::now() - transitionStart < - MAX_TRANSITION_TIME) { - // Check if next track is ready - std::vector<short> incoming; - if (audioDecoder_->getNextChunk(incoming, false)) { - // Next track is ready, add to buffer and break - localAudioBuffer.insert(localAudioBuffer.end(), - incoming.begin(), - incoming.end()); - Void::Log::debug("MusicManager", "{}", - "Next track ready, resuming playback"); - break; - } - - // Send low-level white noise to keep audio stream alive - // and microphone active (silence doesn't work) - if (audioCallback_) { - std::vector<short> noiseChunk(SHORTS_PER_CHUNK); - for (size_t i = 0; i < SHORTS_PER_CHUNK; ++i) { - noiseChunk[i] = - static_cast<short>(noiseDist(gen)); - } - audioCallback_(std::span<const short>( - noiseChunk.data(), noiseChunk.size())); - } - - // Small delay to prevent busy-waiting - std::this_thread::sleep_for( - std::chrono::milliseconds(CHUNK_MS)); - - // Check if playback should stop - { - std::shared_lock<std::shared_mutex> lock(mutex_); - if (!isPlaying_) { - Void::Log::info("MusicManager", "{}", - "Playback stopped during transition"); - break; - } - } - } - - // Check if playback should continue (more tracks available) - { - std::shared_lock<std::shared_mutex> lock(mutex_); - Void::Log::debug("MusicManager", "{}", std::format( - "Playback thread: isPlaying_={}, queue_size={}, " - "currentTrack.has_value={}", - isPlaying_.load(), queueMgr_.entries().size(), - currentTrack_.has_value())); - if (!isPlaying_) { - Void::Log::info("MusicManager", "{}", - "Playback thread exiting: isPlaying_ is false"); - break; // Exit thread if no more tracks - } - } - - // Reset for next track - chunksSent = 0; - next = std::chrono::steady_clock::now(); - Void::Log::debug("MusicManager", "{}", "Continuing to next track..."); - continue; - } + // A previously downloaded copy trumps every source: instant start, + // works offline. + if (trackCache_ && !preferDownload) { + if (auto cached = trackCache_->lookup(cacheKey)) { + Void::Log::info("MusicManager", "{}", + std::format("Track cache hit for {}", cacheKey)); + return *cached; } } - Void::Log::debug("MusicManager", "{}", "Playback thread exiting"); - playbackThreadRunning_ = false; + // yt-dlp downloads the audio to a local file through the configured + // proxy (it handles SOCKS5, which ffmpeg cannot) — the shared path + // for both the explicit retry and the proactive SOCKS5 case below. + const auto downloadToFile = + [this, &entry, &cacheKey]() -> Api::Result<std::string> { + auto downloaded = downloadAudioForPlayback(entry.track); + if (downloaded) { + if (trackCache_ && trackCache_->enabled()) { + // Cache-owned files persist; nothing to track. + return trackCache_->store(cacheKey, *downloaded); + } + std::unique_lock<std::shared_mutex> lock(tempFilesMutex_); + tempFiles_.insert(*downloaded); + } + return downloaded; + }; + + // Retry after a failed open: the served URL was bad (expired cache + // entry, dead instance, or ffmpeg can't stream it through the + // configured SOCKS5 proxy). Evict the cache and download instead. + if (preferDownload) { + if (router_) { + router_->invalidate(cacheKey); + } + return downloadToFile(); + } + + if (router_) { + auto handle = router_->getStream(entry.track); + if (!handle) { + return std::unexpected(handle.error()); + } + + // ffmpeg cannot route an IP-locked googlevideo URL through a + // SOCKS5 proxy (it silently ignores socks5:// and times out at + // -110). Under SOCKS5, take the download path proactively for + // such URLs instead of eating a ~15s ffmpeg timeout per track. + // Instance-proxied URLs (Invidious local=true, Piped + // pipedproxy.*), Yandex CDN and local files are reachable and + // left untouched. + if (!handle->isLocalFile && socksProxyActive() && + handle->url.find("googlevideo.com") != std::string::npos) { + Void::Log::info("MusicManager", "{}", + "SOCKS5 proxy: downloading googlevideo audio (ffmpeg " + "cannot stream it directly)"); + if (auto downloaded = downloadToFile()) { + return downloaded; + } + // Download failed — fall back to the (likely doomed) direct + // URL rather than nothing; the engine retry covers it. + } + + if (handle->isLocalFile) { + std::unique_lock<std::shared_mutex> lock(tempFilesMutex_); + tempFiles_.insert(handle->url); + } + return handle->url; + } + + return getStreamUrl(entry.track); + } + + bool MusicManager::socksProxyActive() const + { + if (!configManager_) { + return false; + } + const auto& proxy = configManager_->getNetwork().proxy; + return proxy.has_value() && proxy->enabled() && + proxy->kind == Void::Net::ProxyConfig::Kind::Socks5; + } + + std::optional<Api::QueueEntry> MusicManager::peekNextTrack() + { + return queue_.peekNext(); + } + + std::optional<Api::QueueEntry> + MusicManager::takeNextTrack(uint64_t expectedQueueId) + { + return queue_.popIfNext(expectedQueueId); + } + + std::optional<Api::QueueEntry> MusicManager::takeAnyNextTrack() + { + return queue_.popNext(); + } + + bool MusicManager::repeatEnabled() const { return queue_.repeatEnabled(); } + + void MusicManager::onTrackStarted(const Api::QueueEntry& entry) + { + Void::Log::info("MusicManager", "{}", + std::format("Now playing: {} - {}", entry.track.title, + entry.track.artist)); + emit(Api::Events::PlaybackStarted{ + .track = entry.track, + .clientId = 0, + .position = std::chrono::milliseconds(0)}); + } + + void MusicManager::onTrackFinished(const Api::QueueEntry& entry, + std::chrono::milliseconds finalPosition) + { + // Remember the last YouTube or Yandex track as the autoplay seed; + // radio pulls related tracks from whichever catalog it came from. + if (entry.track.source == Api::TrackSource::YouTube && + !entry.track.id.empty()) { + std::lock_guard<std::mutex> lock(autoplaySeedMutex_); + autoplaySeedId_ = entry.track.id; + autoplaySeedSource_ = AutoplaySeedSource::YouTube; + } else if (entry.track.source == Api::TrackSource::Yandex && + entry.track.id.starts_with("yandex:")) { + std::lock_guard<std::mutex> lock(autoplaySeedMutex_); + // Store the bare provider id; related() expects it unprefixed. + autoplaySeedId_ = + entry.track.id.substr(std::string("yandex:").size()); + autoplaySeedSource_ = AutoplaySeedSource::Yandex; + } + + emit(Api::Events::TrackFinished{ + .track = entry.track, + .autoSkipped = false, + .finalPosition = finalPosition}); + } + + void MusicManager::onPositionTick(const Api::QueueEntry& entry, + std::chrono::milliseconds position, + std::chrono::milliseconds duration) + { + float progress = 0.0f; + if (duration.count() > 0) { + progress = (static_cast<float>(position.count()) / + static_cast<float>(duration.count())) * + 100.0f; + } + + emit(Api::Events::PlaybackPositionChanged{ + .track = entry.track, + .position = position, + .duration = duration, + .progressPercent = progress}); + } + + std::optional<std::pair<std::string, MusicManager::AutoplaySeedSource>> + MusicManager::autoplaySeedFromHistory() const + { + if (!database_) { + return std::nullopt; + } + // Scan history newest-first for the first track that belongs to a + // catalog we can pull related tracks from — the most recent play may + // be a direct URL / other extractor with no radio. + auto recent = database_->getRecentlyPlayed(0, 50); + if (!recent) { + return std::nullopt; + } + for (const auto& track : *recent) { + const std::string& url = track.originalUrl; + if (youTubeClient_ && YouTubeClient::isYouTubeUrl(url)) { + if (auto id = youTubeClient_->extractVideoId(url); + id && !id->empty()) { + return std::make_pair(*id, AutoplaySeedSource::YouTube); + } + } + if (yandexSource_) { + if (auto id = yandexSource_->trackIdFromUrl(url); + id && !id->empty()) { + return std::make_pair(*id, AutoplaySeedSource::Yandex); + } + } + } + return std::nullopt; + } + + void MusicManager::onEngineIdle() + { + Void::Log::info("MusicManager", "{}", "Queue empty, playback stopped"); + + // Radio mode: refill the queue with tracks related to the last + // played one. Runs on its own thread — this callback fires on the + // engine thread and the fetch does network I/O. + if (!autoplay_.load() || !queue_.empty() || !hasOnlineSubscribers()) { + return; + } + std::string seed; + AutoplaySeedSource seedSource = AutoplaySeedSource::None; + { + std::lock_guard<std::mutex> lock(autoplaySeedMutex_); + seed = autoplaySeedId_; + seedSource = autoplaySeedSource_; + } + // Nothing played this session (or the last track wasn't a + // YouTube/Yandex track): fall back to the most recent history entry + // so radio can still start. + if (seed.empty() || seedSource == AutoplaySeedSource::None) { + if (auto fromHistory = autoplaySeedFromHistory()) { + seed = fromHistory->first; + seedSource = fromHistory->second; + } + } + if (seed.empty() || seedSource == AutoplaySeedSource::None) { + return; + } + bool expected = false; + if (!autoplayFetching_.compare_exchange_strong(expected, true)) { + return; // fetch already in flight + } + + if (autoplayThread_.joinable()) { + autoplayThread_.join(); // previous fetch already finished + } + autoplayThread_ = std::jthread([this, seed, seedSource]() { + // Related tracks come from the same catalog as the seed: + // YouTube via a yt-dlp radio mix, Yandex via its similar-tracks + // endpoint. + Api::Result<std::vector<Api::TrackInfo>> related = + Api::fail(Api::ErrorCode::ServiceUnavailable, + "Autoplay source unavailable"); + if (seedSource == AutoplaySeedSource::Yandex) { + if (yandexSource_) { + related = yandexSource_->related(seed, 10); + } + } else if (youTubeClient_) { + related = youTubeClient_->radioMix(seed, 10); + } + if (related && !related->empty()) { + // Skip anything played recently to avoid radio loops. + std::set<std::string> recentUrls; + if (database_) { + if (auto recent = database_->getRecentlyPlayed(0, 50)) { + for (const auto& t : *recent) { + recentUrls.insert(t.originalUrl); + } + } + } + size_t queued = 0; + for (const auto& track : *related) { + if (recentUrls.contains(track.originalUrl)) { + continue; + } + if (queueTrack(track, 0)) { + ++queued; + } + } + if (queued > 0) { + Void::Log::info( + "MusicManager", "{}", + std::format("Autoplay queued {} related track(s)", + queued)); + if (engine_) { + engine_->start(); + } + } + } else { + Void::Log::debug("MusicManager", "{}", + "Autoplay found no related tracks"); + } + autoplayFetching_ = false; + }); + } + + void MusicManager::onPlaybackError( + const Api::Error& error, const std::optional<Api::QueueEntry>& entry) + { + emit(Api::Events::PlaybackError{ + .code = error.code, + .message = error.message, + .track = entry ? std::optional(entry->track) : std::nullopt}); + } + + void MusicManager::emitPauseState(bool paused) + { + if (!engine_) { + return; + } + auto entry = engine_->currentEntry(); + if (!entry) { + return; + } + if (paused) { + emit(Api::Events::PlaybackPaused{ + .track = entry->track, .position = engine_->position()}); + } else { + emit(Api::Events::PlaybackResumed{ + .track = entry->track, .position = engine_->position()}); + } + } + + void MusicManager::onLocalFileDone(const std::string& path) + { + // Cache-owned files are the cache's to evict, not ours to delete. + if (trackCache_ && trackCache_->owns(path)) { + return; + } + cleanupTempFile(path); + } + + // ---- helpers ------------------------------------------------------- + + std::string MusicManager::nicknameFor(uint64_t clientId) const + { + if (nicknameCallback_) { + if (auto n = nicknameCallback_(clientId)) { + return *n; + } + } + return std::to_string(clientId); } Api::Result<Api::TrackInfo> MusicManager::resolveQuery(const std::string& query) { - if (YouTubeClient::isYouTubeUrl(query)) { - Void::Log::debug("MusicManager", "{}", - std::format("Extracting video ID from URL: {}", query)); - auto videoId = youTubeClient_->extractVideoId(query); - if (videoId) { - Void::Log::debug("MusicManager", "{}", - std::format("Extracted video ID: '{}'", *videoId)); - return youTubeClient_->getVideoInfo(*videoId); - } else { - Void::Log::warn("MusicManager", "{}", "Failed to extract video ID from URL"); - } - - auto playlistId = youTubeClient_->extractPlaylistId(query); - if (playlistId) { - Void::Log::debug("MusicManager", "{}", + // Playlist URLs are still resolved through the YouTube client (the + // router's sources resolve single tracks). + if (config_.allowPlaylistImports && YouTubeClient::isYouTubeUrl(query) && + !youTubeClient_->extractVideoId(query).has_value()) { + if (auto playlistId = YouTubeClient::extractPlaylistId(query)) { + Void::Log::debug("MusicManager", "{}", std::format("Extracted playlist ID: '{}'", *playlistId)); auto playlist = youTubeClient_->getPlaylist(*playlistId); if (playlist && !playlist->tracks.empty()) { @@ -1652,15 +1369,17 @@ namespace Echoion::Core } } + if (router_) { + return router_->resolve(query); + } + auto searchResult = youTubeClient_->search(query); if (!searchResult) { return std::unexpected(searchResult.error()); } - if (searchResult->tracks.empty()) { return Api::fail(Api::ErrorCode::NotFound, "No results found"); } - return searchResult->tracks[0]; } @@ -1672,174 +1391,19 @@ namespace Echoion::Core return *track.streamUrl; } - if (track.source == Api::TrackSource::YouTube) { - auto videoId = youTubeClient_->extractVideoId(track.originalUrl); - if (videoId) { - Void::Log::debug("MusicManager", "{}", std::format( - "Extracting stream URL for YouTube video: {}", *videoId)); - auto url = youTubeClient_->getStreamUrl(*videoId); - if (url) { - Void::Log::debug("MusicManager", "{}", - std::format("Got stream URL: {}", url->c_str())); - } else { - Void::Log::error("MusicManager", "{}", std::format( - "Failed to get stream URL: {}", url.error().message)); - } - return url; + // Route through the source chain; this also primes the router's + // stream cache, so the engine's later resolve is instant. + if (router_) { + auto handle = router_->getStream(track); + if (!handle) { + return std::unexpected(handle.error()); } - Void::Log::warn("MusicManager", "{}", "Could not extract video ID from URL"); + return handle->url; } return Api::fail(Api::ErrorCode::NotFound, "Could not get stream URL"); } - void MusicManager::onTrackFinished() - { - std::shared_lock<std::shared_mutex> lock(mutex_); - - // Publish track finished event - if (currentTrack_.has_value()) { - emit(Api::Events::TrackFinished{ - .track = currentTrack_->track, - .autoSkipped = false, - .finalPosition = getPlaybackPosition()}); - } - - // Reset prefetch state for next track - prefetchState_.hasPrefetched = false; - - if (repeat_ && currentTrack_.has_value()) { - auto streamUrl = getStreamUrl(currentTrack_->track); - if (streamUrl) { - audioDecoder_->closeSource(); - audioDecoder_->openSource(*streamUrl); - } - return; - } - - if (queueMgr_.entries().empty()) { - // Queue is empty - stop playback but keep thread running for next - // track - isPlaying_ = false; - currentTrack_.reset(); - audioDecoder_->closeSource(); - Void::Log::info("MusicManager", "{}", "Queue empty, playback stopped"); - return; - } - - // Play next track from queue - auto nextTrack = getNextTrack(); - Void::Log::info("MusicManager", "{}", std::format("Playing next track: {} - {}", - nextTrack.title, nextTrack.artist)); - - currentTrack_ = - Api::QueueEntry{.queueId = queueMgr_.nextQueueId()++, - .track = nextTrack, - .addedAt = std::chrono::system_clock::now(), - .addedBy = currentTrack_->addedBy, - .isPlaying = true, - .position = std::chrono::milliseconds(0)}; - - // Reset position tracking for new track - playbackPosition_ = std::chrono::milliseconds(0); - playbackBasePosition_ = std::chrono::milliseconds(0); - playbackStartTime_ = std::chrono::steady_clock::now(); - - // Try to use prefetched URL first (seamless transition) - std::optional<std::string> streamUrl; - if (prefetchState_.streamUrlFuture.valid()) { - auto status = prefetchState_.streamUrlFuture.wait_for( - std::chrono::seconds(0)); - if (status == std::future_status::ready) { - auto result = prefetchState_.streamUrlFuture.get(); - if (result) { - Void::Log::info("MusicManager", "{}", - "Using prefetched stream URL for seamless transition"); - streamUrl = *result; - } - } - } - - // If prefetch not ready or failed, fetch synchronously - if (!streamUrl) { - if (prefetchState_.isPrefetching) { - Void::Log::info("MusicManager", "{}", "Waiting for prefetch to complete..."); - auto result = prefetchState_.streamUrlFuture.get(); - if (result) { - streamUrl = *result; - } - } - - if (!streamUrl) { - Void::Log::debug("MusicManager", "{}", - "No prefetched URL available, fetching synchronously"); - auto result = getStreamUrl(nextTrack); - if (result) { - streamUrl = *result; - } - } - } - - if (streamUrl) { - audioDecoder_->closeSource(); - auto result = audioDecoder_->openSource(*streamUrl); - if (!result) { - Void::Log::error("MusicManager", "{}", std::format("Failed to open next track: {}", - result.error().message)); - // Remove the failed track and try next - queueMgr_.entries().erase(queueMgr_.entries().begin()); - onTrackFinished(); - } - } else { - Void::Log::error("MusicManager", "{}", "Failed to get stream URL for next track"); - queueMgr_.entries().erase(queueMgr_.entries().begin()); - onTrackFinished(); - } - } - - Api::TrackInfo MusicManager::getNextTrack() - { - if (queueMgr_.entries().empty()) { - return Api::TrackInfo{}; - } - - if (shuffle_ && !queueMgr_.shuffledIndices().empty()) { - // Use shuffled order - size_t queueIndex = queueMgr_.shuffledIndices()[queueMgr_.shuffleIndex()]; - auto track = queueMgr_.entries()[queueIndex].track; - - // Remove the track from queue and rebuild shuffled indices - queueMgr_.entries().erase(queueMgr_.entries().begin() + queueIndex); - queueMgr_.shuffleIndex()++; - - // If we've played all tracks, rebuild for next cycle - if (queueMgr_.shuffleIndex() >= queueMgr_.shuffledIndices().size()) { - rebuildShuffledIndices(); - } else { - // Rebuild indices to account for the removed track - // Decrement indices that were after the removed track - for (size_t i = queueMgr_.shuffleIndex(); i < queueMgr_.shuffledIndices().size(); - ++i) { - if (queueMgr_.shuffledIndices()[i] > queueIndex) { - queueMgr_.shuffledIndices()[i]--; - } - } - } - - return track; - } - - auto track = queueMgr_.entries().front().track; - queueMgr_.entries().erase(queueMgr_.entries().begin()); - return track; - } - - Api::Result<void> MusicManager::shuffleQueue() - { - std::shuffle(queueMgr_.entries().begin(), queueMgr_.entries().end(), queueMgr_.rng()); - return {}; - } - std::string MusicManager::getHelpText() const { return R"(Echoion Music Bot Commands: @@ -1848,9 +1412,15 @@ namespace Echoion::Core !resume - Resume playback !stop - Stop playback and clear queue !skip [n] - Skip current song (optionally skip n songs) +!seek <+/-secs> - Seek within the track (+30, -10, or absolute 60) !queue [page] - Show current queue (optionally specify page number) !volume <0-100> - Set volume level -!search <query> - Search for tracks +!search <query> - Search YouTube + Yandex Music +!youtube <query> - Search YouTube only (alias: yb, yt) +!yandex <query> - Search Yandex Music only (alias: ya) +!history [n] - Show recently played tracks +!stats - Show playback statistics +!fav add|list|play <n> - Manage your favorite tracks !subscribe - Subscribe to bot's audio output (whisper mode) !unsubscribe - Unsubscribe from bot's audio output !subscribers - List all subscribed users @@ -1860,311 +1430,178 @@ The bot only outputs audio to subscribed users. Subscribe to hear the music! Subscriptions are persistent across server reconnects.)"; } + // ---- subscriptions (delegated) -------------------------------------- + Api::Result<std::string> MusicManager::subscribe(uint64_t clientId) { - if (!subscriptionManager_) { + if (!subscriptions_) { return Api::fail(Api::ErrorCode::ServiceUnavailable, "Subscription manager not initialized"); } - - // Get client info (UID and nickname) from the callback - if (!clientInfoCallback_) { - return Api::fail(Api::ErrorCode::NotInitialized, - "Client info callback not set"); - } - - auto clientInfo = clientInfoCallback_(clientId); - if (!clientInfo) { - return Api::fail(Api::ErrorCode::NotFound, - "Could not get client info"); - } - - const auto& [uid, nickname] = *clientInfo; - bool added = subscriptionManager_->subscribe(uid, nickname); - - Void::Log::info("MusicManager", "{}", std::format("Subscribe: client {} ({}), added={}", - clientId, nickname, added)); - - // If we have subscribers now and were paused due to no subscribers, - // resume - if (added && wasPausedForNoSubscribers_ && isPaused_) { - auto result = resume(); - if (result) { - wasPausedForNoSubscribers_ = false; - } - } - - // Notify about subscription change - always trigger for subscribe to - // update whisper list This ensures offline->online transitions update - // the whisper list - if (subscriptionChangeCallback_) { - Void::Log::info("MusicManager", "{}", - "Subscribe: triggering subscriptionChangeCallback"); - subscriptionChangeCallback_(); - } - - // Publish subscription event - emit(Api::Events::UserSubscribed{ - .uid = uid, .nickname = nickname, .clientId = clientId}); - - if (added) { - return "You are now subscribed to the bot's audio output!"; - } else { - return "You are still subscribed (was already in database)."; - } + return subscriptions_->subscribe(clientId); } Api::Result<std::string> MusicManager::unsubscribe(uint64_t clientId) { - if (!subscriptionManager_) { + if (!subscriptions_) { return Api::fail(Api::ErrorCode::ServiceUnavailable, "Subscription manager not initialized"); } - - // Get client UID from the callback - if (!clientInfoCallback_) { - return Api::fail(Api::ErrorCode::NotInitialized, - "Client info callback not set"); - } - - auto clientInfo = clientInfoCallback_(clientId); - if (!clientInfo) { - return Api::fail(Api::ErrorCode::NotFound, - "Could not get client info"); - } - - const auto& [uid, nickname] = *clientInfo; - bool removed = subscriptionManager_->unsubscribe(uid); - - // If no online subscribers left and we're playing, pause - if (removed && !hasOnlineSubscribers() && isPlaying_ && !isPaused_) { - Void::Log::info("MusicManager", "{}", "No online subscribers left, pausing playback"); - auto result = pause(); - if (result) { - wasPausedForNoSubscribers_ = true; - } - } - - // Notify about subscription change - if (removed && subscriptionChangeCallback_) { - subscriptionChangeCallback_(); - } - - // Publish unsubscription event - if (removed) { - emit( - Api::Events::UserUnsubscribed{ - .uid = uid, .nickname = nickname, .clientId = clientId}); - return "You are now unsubscribed from the bot's audio output."; - } else { - return "You were not subscribed."; - } + return subscriptions_->unsubscribe(clientId); } Api::Result<std::string> MusicManager::unsubscribeByUid(const std::string& uid) { - if (!subscriptionManager_) { + if (!subscriptions_) { return Api::fail(Api::ErrorCode::ServiceUnavailable, "Subscription manager not initialized"); } - - bool removed = subscriptionManager_->unsubscribe(uid); - - // If no online subscribers left and we're playing, pause - if (removed && !hasOnlineSubscribers() && isPlaying_ && !isPaused_) { - Void::Log::info("MusicManager", "{}", "No online subscribers left, pausing playback"); - auto result = pause(); - if (result) { - wasPausedForNoSubscribers_ = true; - } - } - - // Notify about subscription change - if (removed && subscriptionChangeCallback_) { - subscriptionChangeCallback_(); - } - - if (removed) { - return "Subscriber removed successfully."; - } else { - return "Subscriber not found."; - } + return subscriptions_->unsubscribeByUid(uid); } Api::Result<std::string> MusicManager::clearAllSubscriptions() { - if (!subscriptionManager_) { + if (!subscriptions_) { return Api::fail(Api::ErrorCode::ServiceUnavailable, "Subscription manager not initialized"); } - - bool cleared = subscriptionManager_->clearAll(); - - // Pause playback if no subscribers - if (cleared && isPlaying_ && !isPaused_) { - Void::Log::info("MusicManager", "{}", "All subscriptions cleared, pausing playback"); - auto result = pause(); - if (result) { - wasPausedForNoSubscribers_ = true; - } - } - - // Notify about subscription change - if (cleared && subscriptionChangeCallback_) { - subscriptionChangeCallback_(); - } - - if (cleared) { - return "All subscriptions cleared."; - } else { - return "Failed to clear subscriptions."; - } + return subscriptions_->clearAllSubscriptions(); } bool MusicManager::isSubscribed(uint64_t clientId) const { - if (!subscriptionManager_ || !clientInfoCallback_) { - return false; - } - auto clientInfo = clientInfoCallback_(clientId); - if (!clientInfo) { - return false; - } - return subscriptionManager_->isSubscribed(clientInfo->first); + return subscriptions_ && subscriptions_->isSubscribed(clientId); } std::set<std::string> MusicManager::getOnlineSubscriberUids() const { - std::set<std::string> onlineUids; - if (!subscriptionManager_ || !uidToClientIdCallback_) { - return onlineUids; - } - - auto allUids = subscriptionManager_->getSubscribedUids(); - for (const auto& uid : allUids) { - // If we can resolve UID to a client ID, the user is online - if (uidToClientIdCallback_(uid).has_value()) { - onlineUids.insert(uid); - } - } - - return onlineUids; + return subscriptions_ ? subscriptions_->getOnlineSubscriberUids() + : std::set<std::string>{}; } std::set<uint64_t> MusicManager::getSubscribedClients() const { - if (!subscriptionManager_ || !uidToClientIdCallback_) { - return {}; - } - - // Resolve UIDs to current session client IDs - std::set<uint64_t> clientIds; - auto uids = subscriptionManager_->getSubscribedUids(); - - for (const auto& uid : uids) { - auto clientId = uidToClientIdCallback_(uid); - if (clientId) { - clientIds.insert(*clientId); - } - } - - return clientIds; + return subscriptions_ ? subscriptions_->getSubscribedClients() + : std::set<uint64_t>{}; } std::vector<SubscriptionManager::Subscriber> MusicManager::getSubscribers() const { - if (!subscriptionManager_) { - return {}; - } - return subscriptionManager_->getSubscribers(); + return subscriptions_ + ? subscriptions_->getSubscribers() + : std::vector<SubscriptionManager::Subscriber>{}; } bool MusicManager::hasSubscribers() const { - if (!subscriptionManager_) { - return false; - } - return subscriptionManager_->hasSubscribers(); + return subscriptions_ && subscriptions_->hasSubscribers(); } bool MusicManager::hasOnlineSubscribers() const { - if (!subscriptionManager_ || !uidToClientIdCallback_) { - return false; - } - - // Check if any subscribed UID can be resolved to a current client ID - auto uids = subscriptionManager_->getSubscribedUids(); - for (const auto& uid : uids) { - if (uidToClientIdCallback_(uid).has_value()) { - return true; - } - } - return false; + return subscriptions_ && subscriptions_->hasOnlineSubscribers(); } void MusicManager::onClientConnected(uint64_t clientId) { Void::Log::info("MusicManager", "{}", std::format("onClientConnected: client {}", clientId)); - if (!subscriptionManager_ || !clientInfoCallback_) { - Void::Log::warn("MusicManager", "{}", "onClientConnected: subscriptionManager or " - "clientInfoCallback not set"); + if (!subscriptions_) { return; } - // Get the client's UID - auto clientInfo = clientInfoCallback_(clientId); - if (!clientInfo) { - Void::Log::warn("MusicManager", "{}", std::format( - "onClientConnected: could not get client info for {}", - clientId)); - return; - } - - const auto& [uid, nickname] = *clientInfo; - - Void::Log::info("MusicManager", "{}", std::format( - "onClientConnected: client {} ({}), uid={}, isSubscribed={}", - clientId, nickname, uid, subscriptionManager_->isSubscribed(uid))); - - // Check if this user is subscribed (in offline subscribers) - if (subscriptionManager_->isSubscribed(uid)) { - Void::Log::info("MusicManager", "{}", std::format( - "Subscribed user {} ({}) connected, moving to online", nickname, - uid)); - - // Update their nickname in case it changed - subscriptionManager_->updateNickname(uid, nickname); - - // Update whisper list to include them - if (subscriptionChangeCallback_) { - Void::Log::info("MusicManager", "{}", - "onClientConnected: triggering subscriptionChangeCallback"); - subscriptionChangeCallback_(); + const bool mayAutoStart = subscriptions_->onClientConnected(clientId); + if (mayAutoStart && autoStartOnSubscribe_.load() && engine_ && + !engine_->isPlaying() && !engine_->currentEntry() && + !queue_.empty()) { + Void::Log::info("MusicManager", "{}", + "Online subscriber connected with tracks in queue, " + "auto-starting"); + if (playbackStartCallback_) { + playbackStartCallback_(); } + engine_->start(); + } - // If we were paused due to no online subscribers, resume playback - if (wasPausedForNoSubscribers_ && isPlaying_ && isPaused_) { - Void::Log::info("MusicManager", "{}", - "Online subscriber returned, resuming playback"); - auto result = resume(); - if (result) { - wasPausedForNoSubscribers_ = false; + // Deliver a pending announcement to this subscriber once. + if (auto uid = clientUid(clientId); + uid && subscriptions_->isSubscribed(clientId)) { + deliverAnnouncementTo(clientId, *uid); + } + } + + size_t MusicManager::setAnnouncement(const std::string& text) + { + if (!database_) { + return 0; + } + // Bump the announcement id so this fresh post reaches every + // subscriber once (the per-uid seen-id gate does the dedup). + int64_t id = 1; + if (auto stored = database_->getKv("announcement.id"); + stored && *stored) { + try { + id = std::stoll(**stored) + 1; + } catch (const std::exception&) { + id = 1; + } + } + (void)database_->setKv("announcement.text", text); + (void)database_->setKv("announcement.id", std::to_string(id)); + + // Deliver immediately to everyone currently online. + size_t reached = 0; + if (subscriptions_) { + for (uint64_t clientId : subscriptions_->getSubscribedClients()) { + if (auto uid = clientUid(clientId)) { + if (deliverAnnouncementTo(clientId, *uid)) { + ++reached; + } } } - // If we're not playing but have tracks in queue, auto-start - else if (!isPlaying_ && !currentTrack_.has_value() && - !queueMgr_.entries().empty()) { - Void::Log::info("MusicManager", "{}", "Online subscriber connected with tracks in " - "queue, auto-starting"); - // Notify playback thread to start - cv_.notify_one(); + } + return reached; + } + + bool MusicManager::deliverAnnouncementTo(uint64_t clientId, + const std::string& uid) + { + if (!database_ || !messageCallback_) { + return false; + } + auto textKv = database_->getKv("announcement.text"); + auto idKv = database_->getKv("announcement.id"); + if (!textKv || !*textKv || (*textKv)->empty() || !idKv || !*idKv) { + return false; + } + int64_t currentId = 0; + try { + currentId = std::stoll(**idKv); + } catch (const std::exception&) { + return false; + } + + const std::string seenKey = "announcement.seen." + uid; + int64_t seenId = 0; + if (auto seen = database_->getKv(seenKey); seen && *seen) { + try { + seenId = std::stoll(**seen); + } catch (const std::exception&) { + seenId = 0; } } - // If not subscribed, do nothing + if (seenId >= currentId) { + return false; // already delivered + } + + messageCallback_(clientId, **textKv); + (void)database_->setKv(seenKey, std::to_string(currentId)); + Void::Log::info("MusicManager", "{}", + std::format("Announcement (id {}) delivered to {}", currentId, + uid)); + return true; } void MusicManager::onClientDisconnected(uint64_t clientId) @@ -2175,41 +1612,13 @@ Subscriptions are persistent across server reconnects.)"; pendingSearches_.erase(clientId); } - if (!subscriptionManager_ || !clientInfoCallback_) { - return; - } - - // Get the client's UID - auto clientInfo = clientInfoCallback_(clientId); - if (!clientInfo) { - return; - } - - const auto& [uid, nickname] = *clientInfo; - - // If this was a subscribed user, update whisper list - if (subscriptionManager_->isSubscribed(uid)) { - Void::Log::info("MusicManager", "{}", std::format( - "Subscribed user {} ({}) disconnected, moving to offline", - nickname, uid)); - - // Update whisper list to remove them - if (subscriptionChangeCallback_) { - subscriptionChangeCallback_(); - } - - // If no more online subscribers and we're playing, pause - if (!hasOnlineSubscribers() && isPlaying_ && !isPaused_) { - Void::Log::info("MusicManager", "{}", - "No online subscribers left, pausing playback"); - auto result = pause(); - if (result) { - wasPausedForNoSubscribers_ = true; - } - } + if (subscriptions_) { + subscriptions_->onClientDisconnected(clientId); } } + // ---- temp files --------------------------------------------------------- + Api::Result<std::string> MusicManager::downloadAudioForPlayback(const Api::TrackInfo& track) { @@ -2245,154 +1654,9 @@ Subscriptions are persistent across server reconnects.)"; Void::Log::warn("MusicManager", "{}", std::format("Failed to remove temp file {}: {}", filepath, ec.message())); } else { - Void::Log::debug("MusicManager", "{}", + Void::Log::debug("MusicManager", "{}", std::format("Cleaned up temp file: {}", filepath)); } } - bool MusicManager::shouldPrefetch() const - { - std::shared_lock<std::shared_mutex> lock(mutex_); - - // Don't prefetch if not playing, no current track, or queue is empty - if (!isPlaying_ || !currentTrack_.has_value() || queueMgr_.entries().empty()) { - return false; - } - - // Don't prefetch if already prefetched or currently prefetching - if (prefetchState_.hasPrefetched.load() || - prefetchState_.isPrefetching.load()) { - return false; - } - - // Check if we're near the end of the current track - auto position = audioDecoder_->getPosition(); - auto streamInfo = audioDecoder_->getStreamInfo(); - - if (!streamInfo) { - Void::Log::debug("MusicManager", "{}", "Prefetch: No stream info available"); - return false; - } - - // Handle short tracks: if total duration is less than prefetch - // threshold, start prefetching after we've played at least 2 seconds - // (to avoid immediate prefetch) - if (streamInfo->duration <= PREFETCH_THRESHOLD) { - bool shouldPrefetch = position >= std::chrono::seconds(2); - if (shouldPrefetch) { - Void::Log::debug("MusicManager", "{}", std::format("Prefetch: Short track ({}s), " - "position {}s - should prefetch", - streamInfo->duration.count(), - position.count())); - } - return shouldPrefetch; - } - - // Normal case: Prefetch when we're within PREFETCH_THRESHOLD of the end - auto timeRemaining = streamInfo->duration - position; - bool shouldPrefetch = timeRemaining <= PREFETCH_THRESHOLD && - timeRemaining > std::chrono::seconds(0); - - // Log when we're getting close to prefetch threshold - if (timeRemaining <= std::chrono::seconds(20) && - timeRemaining > std::chrono::seconds(0)) { - Void::Log::debug("MusicManager", "{}", std::format( - "Prefetch: Time remaining {}s, threshold {}s - {}", - std::chrono::duration_cast<std::chrono::seconds>(timeRemaining) - .count(), - PREFETCH_THRESHOLD.count(), - shouldPrefetch ? "WILL PREFETCH" : "waiting")); - } - - return shouldPrefetch; - } - - void MusicManager::prefetchNextTrack() - { - // Check and set prefetching flag - bool expected = false; - if (!prefetchState_.isPrefetching.compare_exchange_strong(expected, - true)) { - return; // Already prefetching - } - - Void::Log::info("MusicManager", "{}", "Starting prefetch of next track stream URL"); - - // Get next track info (copy to avoid holding lock during async - // operation) - Api::TrackInfo nextTrack; - { - std::shared_lock<std::shared_mutex> lock(mutex_); - if (queueMgr_.entries().empty()) { - prefetchState_.isPrefetching = false; - return; - } - // Use shuffled order if shuffle is enabled - if (shuffle_ && !queueMgr_.shuffledIndices().empty() && - queueMgr_.shuffleIndex() < queueMgr_.shuffledIndices().size()) { - nextTrack = queueMgr_.entries()[queueMgr_.shuffledIndices()[queueMgr_.shuffleIndex()]].track; - } else { - nextTrack = queueMgr_.entries()[0].track; - } - } - - // Start async prefetch - prefetchState_.streamUrlFuture = std::async( - std::launch::async, - [this, nextTrack]() -> Api::Result<std::string> { - auto result = getStreamUrl(nextTrack); - if (result) { - Void::Log::info("MusicManager", "{}", "Prefetch completed successfully"); - } else { - Void::Log::warn("MusicManager", "{}", std::format("Prefetch failed: {}", - result.error().message)); - } - return result; - }); - - prefetchState_.hasPrefetched = true; - prefetchState_.isPrefetching = false; - } - - void MusicManager::generateTransitionAudio( - std::chrono::milliseconds duration) - { - if (!audioCallback_) { - return; - } - - constexpr int CHUNK_MS = 20; - constexpr size_t SHORTS_PER_CHUNK = - (TEAMSPEAK_SAMPLE_RATE * TEAMSPEAK_CHANNELS * CHUNK_MS) / 1000; - - // Generate silence chunks for the specified duration - auto chunksNeeded = duration.count() / CHUNK_MS; - std::vector<short> silenceChunk(SHORTS_PER_CHUNK, 0); - - Void::Log::debug("MusicManager", "{}", - std::format("Generating {}ms of transition silence ({} chunks)", - duration.count(), chunksNeeded)); - - for (int i = 0; i < chunksNeeded; ++i) { - audioCallback_(std::span<const short>(silenceChunk.data(), - silenceChunk.size())); - std::this_thread::sleep_for(std::chrono::milliseconds(CHUNK_MS)); - } - } - - void MusicManager::sendSilenceChunk() - { - if (!audioCallback_) { - return; - } - - constexpr int CHUNK_MS = 20; - constexpr size_t SHORTS_PER_CHUNK = - (TEAMSPEAK_SAMPLE_RATE * TEAMSPEAK_CHANNELS * CHUNK_MS) / 1000; - - std::vector<short> silenceChunk(SHORTS_PER_CHUNK, 0); - audioCallback_( - std::span<const short>(silenceChunk.data(), silenceChunk.size())); - } - } // namespace Echoion::Core diff --git a/src/NetworkClient.cpp b/src/NetworkClient.cpp index e691af9..2dc193e 100644 --- a/src/NetworkClient.cpp +++ b/src/NetworkClient.cpp @@ -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) diff --git a/src/RpcServer.cpp b/src/RpcServer.cpp index 8b3ba78..171d759 100644 --- a/src/RpcServer.cpp +++ b/src/RpcServer.cpp @@ -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_); diff --git a/src/SignatureCipher.cpp b/src/SignatureCipher.cpp index 7e99092..9e95b58 100644 --- a/src/SignatureCipher.cpp +++ b/src/SignatureCipher.cpp @@ -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> diff --git a/src/SubscriptionService.cpp b/src/SubscriptionService.cpp new file mode 100644 index 0000000..35ffd17 --- /dev/null +++ b/src/SubscriptionService.cpp @@ -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 diff --git a/src/TrackCache.cpp b/src/TrackCache.cpp new file mode 100644 index 0000000..00974c2 --- /dev/null +++ b/src/TrackCache.cpp @@ -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 diff --git a/src/YouTubeClient.cpp b/src/YouTubeClient.cpp index 1c3990b..ec809ac 100644 --- a/src/YouTubeClient.cpp +++ b/src/YouTubeClient.cpp @@ -1,6 +1,6 @@ -#include <Void/Log/Log.hpp> #include "echoion/core/YouTubeClient.hpp" #include <Void/Data/Json.hpp> +#include <Void/Log/Log.hpp> #include <Void/Text/Html.hpp> #include <Void/Text/Url.hpp> #include <Void/Time/Format.hpp> @@ -41,7 +41,8 @@ namespace Echoion::Core return {}; } - Void::Log::info("YouTubeClient", "{}", "Initializing YouTube client..."); + Void::Log::info("YouTubeClient", "{}", + "Initializing YouTube client..."); // Initialize yt-dlp manager (downloads if needed) auto result = ytDlpManager_->initialize(); @@ -53,7 +54,8 @@ namespace Echoion::Core ytDlpManager_->setThreadPoolSize(maxConcurrentResolutions_); initialized_ = true; - Void::Log::info("YouTubeClient", "{}", "YouTube client initialized successfully"); + Void::Log::info("YouTubeClient", "{}", + "YouTube client initialized successfully"); return {}; } @@ -80,9 +82,9 @@ namespace Echoion::Core std::lock_guard<std::mutex> lock(configMutex_); if (proxy.has_value() && proxy->enabled()) { - Void::Log::info("YouTubeClient", "{}", - std::format("YouTubeClient proxy configured: {}:{}", - proxy->host, proxy->port)); + Void::Log::info("YouTubeClient", "{}", + std::format("YouTubeClient proxy configured: {}:{}", + proxy->host, proxy->port)); } } @@ -98,7 +100,8 @@ namespace Echoion::Core { std::lock_guard<std::mutex> lock(configMutex_); apiKey_ = apiKey; - Void::Log::info("YouTubeClient", "{}", + Void::Log::info( + "YouTubeClient", "{}", "YouTube API key configured for enhanced playlist resolution"); } @@ -150,7 +153,7 @@ namespace Echoion::Core { if (!ytDlpManager_) { return Api::fail(Api::ErrorCode::ServiceUnavailable, - "yt-dlp manager not initialized"); + "yt-dlp manager not initialized"); } return ytDlpManager_->update(); } @@ -160,21 +163,22 @@ namespace Echoion::Core { if (!initialized_) { return Api::fail(Api::ErrorCode::ServiceUnavailable, - "YouTubeClient not initialized"); + "YouTubeClient not initialized"); } if (!ytDlpManager_->isAvailable()) { - return Api::fail( - Api::ErrorCode::ServiceUnavailable, "yt-dlp not available"); + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "yt-dlp not available"); } if (videoId.empty()) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Video ID is empty"); + "Video ID is empty"); } auto startTime = std::chrono::steady_clock::now(); - Void::Log::info("YouTubeClient", "{}", + Void::Log::info( + "YouTubeClient", "{}", std::format("Getting audio stream URL for video: {}", videoId)); // Use yt-dlp to get best audio URL - prefer AAC (m4a) over Opus (webm) @@ -182,27 +186,30 @@ namespace Echoion::Core // Pass just the video ID to yt-dlp std::string videoIdStr(videoId); - Void::Log::debug("YouTubeClient", "{}", "Starting yt-dlp audio URL extraction..."); + Void::Log::debug("YouTubeClient", "{}", + "Starting yt-dlp audio URL extraction..."); auto future = ytDlpManager_->executeAsync( {videoIdStr, "-f", "bestaudio/251/140", "-g", "--no-warnings"}); // Wait with timeout (30 seconds) - Void::Log::debug("YouTubeClient", "{}", "Waiting for yt-dlp audio URL (30s timeout)..."); + Void::Log::debug("YouTubeClient", "{}", + "Waiting for yt-dlp audio URL (30s timeout)..."); auto waitStatus = future.wait_for(std::chrono::seconds(30)); if (waitStatus == std::future_status::timeout) { - Void::Log::warn("YouTubeClient", "{}", - "yt-dlp audio URL extraction timed out after 30s"); + Void::Log::warn("YouTubeClient", "{}", + "yt-dlp audio URL extraction timed out after 30s"); return Api::fail(Api::ErrorCode::NetworkError, - "yt-dlp audio URL extraction timed out"); + "yt-dlp audio URL extraction timed out"); } auto ytdlpResult = future.get(); if (!ytdlpResult.success) { - Void::Log::warn("YouTubeClient", "{}", "yt-dlp audio URL extraction failed"); + Void::Log::warn("YouTubeClient", "{}", + "yt-dlp audio URL extraction failed"); return Api::fail(Api::ErrorCode::NetworkError, - "yt-dlp audio URL extraction failed"); + "yt-dlp audio URL extraction failed"); } std::string result = ytdlpResult.output; @@ -216,15 +223,67 @@ namespace Echoion::Core .count(); if (!result.empty() && result.find("http") == 0) { - Void::Log::info("YouTubeClient", "{}", std::format( - "Successfully got audio URL from yt-dlp in {} ms", elapsed)); + Void::Log::info( + "YouTubeClient", "{}", + std::format("Successfully got audio URL from yt-dlp in {} ms", + elapsed)); return result; } - Void::Log::warn("YouTubeClient", "{}", std::format( - "Failed to get audio URL from yt-dlp after {} ms", elapsed)); - return Api::fail( - Api::ErrorCode::NotFound, "Failed to get audio URL from yt-dlp"); + Void::Log::warn( + "YouTubeClient", "{}", + std::format("Failed to get audio URL from yt-dlp after {} ms", + elapsed)); + return Api::fail(Api::ErrorCode::NotFound, + "Failed to get audio URL from yt-dlp"); + } + + Api::Result<std::string> + YouTubeClient::getStreamUrlForPage(std::string_view pageUrl, + bool useProxy) + { + if (!initialized_ || !ytDlpManager_->isAvailable()) { + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "yt-dlp not available"); + } + if (pageUrl.empty()) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "Page URL is empty"); + } + + std::vector<std::string> args{std::string(pageUrl), "-f", + "bestaudio/best", "-g", + "--no-playlist", "--no-warnings"}; + if (!useProxy) { + // yt-dlp uses the LAST --proxy: an empty value overrides the + // manager-prepended proxy and forces a direct connection. + args.push_back("--proxy"); + args.push_back(""); + } + + auto future = ytDlpManager_->executeAsync(args); + if (future.wait_for(std::chrono::seconds(30)) == + std::future_status::timeout) { + return Api::fail(Api::ErrorCode::NetworkError, + "yt-dlp stream URL extraction timed out"); + } + + auto result = future.get(); + if (!result.success) { + return Api::fail(Api::ErrorCode::NetworkError, + "yt-dlp stream URL extraction failed"); + } + + std::string url = result.output; + // -g may print multiple lines (video+audio); take the first. + if (auto nl = url.find('\n'); nl != std::string::npos) { + url.resize(nl); + } + if (url.starts_with("http")) { + return url; + } + return Api::fail(Api::ErrorCode::NotFound, + "yt-dlp produced no stream URL"); } Api::Result<std::string> @@ -247,9 +306,8 @@ namespace Echoion::Core const std::string outTemplate = outDir + "/%(id)s.%(ext)s"; auto startTime = std::chrono::steady_clock::now(); - Void::Log::info( - "YouTubeClient", "{}", - std::format("Downloading audio via yt-dlp: {}", id)); + Void::Log::info("YouTubeClient", "{}", + std::format("Downloading audio via yt-dlp: {}", id)); // yt-dlp downloads through the configured proxy + cookies and writes to // disk; --print after_move:filepath emits the final path on stdout. @@ -292,9 +350,9 @@ namespace Echoion::Core auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::steady_clock::now() - startTime) .count(); - Void::Log::info("YouTubeClient", "{}", - std::format("Downloaded audio to {} in {} ms", path, - elapsed)); + Void::Log::info( + "YouTubeClient", "{}", + std::format("Downloaded audio to {} in {} ms", path, elapsed)); return path; } @@ -309,21 +367,22 @@ namespace Echoion::Core { if (!initialized_) { return Api::fail(Api::ErrorCode::ServiceUnavailable, - "YouTubeClient not initialized"); + "YouTubeClient not initialized"); } if (!ytDlpManager_->isAvailable()) { - return Api::fail( - Api::ErrorCode::ServiceUnavailable, "yt-dlp not available"); + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "yt-dlp not available"); } // Validate video ID if (videoId.empty()) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Video ID is empty"); + "Video ID is empty"); } - Void::Log::debug("YouTubeClient", "{}", + Void::Log::debug( + "YouTubeClient", "{}", std::format("Getting video info for ID: '{}'", videoId)); auto infoStart = std::chrono::steady_clock::now(); @@ -333,18 +392,21 @@ namespace Echoion::Core ytDlpManager_->executeAsync({videoIdStr, "-J", "--no-warnings"}); // Wait with timeout (30 seconds) - Void::Log::debug("YouTubeClient", "{}", "Waiting for yt-dlp video info (30s timeout)..."); + Void::Log::debug("YouTubeClient", "{}", + "Waiting for yt-dlp video info (30s timeout)..."); auto waitStatus = result.wait_for(std::chrono::seconds(30)); if (waitStatus == std::future_status::timeout) { - Void::Log::warn("YouTubeClient", "{}", "yt-dlp video info timed out after 30s"); + Void::Log::warn("YouTubeClient", "{}", + "yt-dlp video info timed out after 30s"); return Api::fail(Api::ErrorCode::NetworkError, - "yt-dlp video info timed out"); + "yt-dlp video info timed out"); } auto ytdlpResult = result.get(); - Void::Log::debug("YouTubeClient", "{}", + Void::Log::debug( + "YouTubeClient", "{}", std::format("yt-dlp video info completed in {} ms", std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::steady_clock::now() - infoStart) @@ -352,14 +414,14 @@ namespace Echoion::Core if (!ytdlpResult.success || ytdlpResult.output.empty()) { return Api::fail(Api::ErrorCode::NetworkError, - "yt-dlp failed to get video info"); + "yt-dlp failed to get video info"); } try { auto parsed = Void::Json::parse(ytdlpResult.output); if (!parsed) { return Api::fail(Api::ErrorCode::ParseError, - "Failed to parse yt-dlp output"); + "Failed to parse yt-dlp output"); } const JValue& json = *parsed; @@ -429,7 +491,7 @@ namespace Echoion::Core if (!initialized_) { return Api::fail(Api::ErrorCode::ServiceUnavailable, - "YouTubeClient not initialized"); + "YouTubeClient not initialized"); } auto startTime = std::chrono::steady_clock::now(); @@ -437,7 +499,8 @@ namespace Echoion::Core // Use YouTube Data API v3 if key is available if (hasApiKey()) { - Void::Log::info("YouTubeClient", "{}", + Void::Log::info( + "YouTubeClient", "{}", std::format("Searching YouTube via API: '{}'", query)); result = searchWithApi(query, pageToken); @@ -453,12 +516,14 @@ namespace Echoion::Core } } else { // Fallback to yt-dlp if no API key - Void::Log::warn("YouTubeClient", "{}", "No YouTube API key configured, falling back " - "to yt-dlp for search"); + Void::Log::warn("YouTubeClient", "{}", + "No YouTube API key configured, falling back " + "to yt-dlp for search"); result = searchWithYtDlp(query, pageToken); } - Void::Log::info("YouTubeClient", "{}", + Void::Log::info( + "YouTubeClient", "{}", std::format("YouTube search took {} ms", std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::steady_clock::now() - startTime) @@ -475,7 +540,7 @@ namespace Echoion::Core std::lock_guard<std::mutex> lock(configMutex_); if (!apiKey_.has_value() || apiKey_->empty()) { return Api::fail(Api::ErrorCode::ServiceUnavailable, - "YouTube API key not configured"); + "YouTube API key not configured"); } apiKey = *apiKey_; } @@ -491,73 +556,64 @@ namespace Echoion::Core } // Execute with timeout (10 seconds for API search) - Void::Log::debug("YouTubeClient", "{}", "Executing YouTube API search with 10s timeout..."); + Void::Log::debug("YouTubeClient", "{}", + "Executing YouTube API search with 10s timeout..."); - // Use shared promise so detached thread can safely complete - auto responsePromise = - std::make_shared<std::promise<Api::Result<Void::Net::Response>>>(); + // Run the blocking network GET on the shared thread pool. The pool's + // destructor joins in-flight tasks, so abandoning a timed-out future is + // safe — no detached thread racing this object's lifetime. std::future<Api::Result<Void::Net::Response>> responseFuture = - responsePromise->get_future(); - - std::thread apiThread( - [this, url = std::string(url), responsePromise]() { - Void::Log::debug("YouTubeClient", "{}", "API request thread started"); - try { - auto result = networkClient_->get(url); - responsePromise->set_value(std::move(result)); - } catch (...) { - responsePromise->set_exception(std::current_exception()); - } - Void::Log::debug("YouTubeClient", "{}", "API request thread completed"); + pool_.submit([this, url = std::string(url)]() { + return networkClient_->get(url); }); // Wait with timeout auto waitStatus = responseFuture.wait_for(std::chrono::seconds(20)); if (waitStatus == std::future_status::timeout) { - Void::Log::warn("YouTubeClient", "{}", "YouTube API search timed out after 10s"); - apiThread.detach(); // Thread owns shared_ptr, safe to detach + Void::Log::warn("YouTubeClient", "{}", + "YouTube API search timed out after 10s"); + // Task keeps running on the pool; its result is discarded. return Api::fail(Api::ErrorCode::NetworkError, - "YouTube API search timed out"); + "YouTube API search timed out"); } - Void::Log::debug("YouTubeClient", "{}", "Joining API request thread..."); - apiThread.join(); - Void::Log::debug("YouTubeClient", "{}", "API request thread joined"); - // Get the response Api::Result<Void::Net::Response> response; try { response = responseFuture.get(); } catch (const std::exception& e) { - Void::Log::error("YouTubeClient", "{}", + Void::Log::error( + "YouTubeClient", "{}", std::format("API request threw exception: {}", e.what())); return Api::fail(Api::ErrorCode::NetworkError, - std::format("API request failed: {}", e.what())); + std::format("API request failed: {}", e.what())); } // Log response status if (response) { - Void::Log::debug("YouTubeClient", "{}", + Void::Log::debug( + "YouTubeClient", "{}", std::format("API response status: {}", response->status)); } else { - Void::Log::warn("YouTubeClient", "{}", std::format("API request failed: {}", - response.error().message)); + Void::Log::warn("YouTubeClient", "{}", + std::format("API request failed: {}", + response.error().message)); } if (!response || !response->ok()) { - return Api::fail( - Api::ErrorCode::NetworkError, - std::format("YouTube API search failed: {}", - response ? std::to_string(response->status) - : "no response")); + return Api::fail(Api::ErrorCode::NetworkError, + std::format("YouTube API search failed: {}", + response + ? std::to_string(response->status) + : "no response")); } try { auto parsed = Void::Json::parse(response->body); if (!parsed) { return Api::fail(Api::ErrorCode::ParseError, - "Failed to parse YouTube API search response"); + "Failed to parse YouTube API search response"); } const JValue& json = *parsed; @@ -596,10 +652,11 @@ namespace Echoion::Core track.originalUrl = std::format( "https://www.youtube.com/watch?v={}", videoId); - if (const JValue* snippet = (item).child_object("snippet")) { + if (const JValue* snippet = + (item).child_object("snippet")) { if ((*snippet).has("title")) { - track.title = - Void::Text::html_unescape((*snippet).get_str("title")); + track.title = Void::Text::html_unescape( + (*snippet).get_str("title")); } if ((*snippet).has("channelTitle")) { track.artist = Void::Text::html_unescape( @@ -608,13 +665,16 @@ namespace Echoion::Core if (const JValue* thumbnails = (*snippet).child_object("thumbnails")) { // Get the highest quality thumbnail available - if (const JValue* t = (*thumbnails).child_object("high")) { + if (const JValue* t = + (*thumbnails).child_object("high")) { track.thumbnailUrl = (*t).get_str("url"); } else if (const JValue* m = - (*thumbnails).child_object("medium")) { + (*thumbnails) + .child_object("medium")) { track.thumbnailUrl = (*m).get_str("url"); } else if (const JValue* d = - (*thumbnails).child_object("default")) { + (*thumbnails) + .child_object("default")) { track.thumbnailUrl = (*d).get_str("url"); } } @@ -626,19 +686,23 @@ namespace Echoion::Core // Fetch duration for each video using videos endpoint (batch // request) if (!videoIds.empty()) { - Void::Log::debug("YouTubeClient", "{}", "Fetching video durations..."); + Void::Log::debug("YouTubeClient", "{}", + "Fetching video durations..."); fetchVideoDurations(result.tracks, videoIds); - Void::Log::debug("YouTubeClient", "{}", "Video durations fetched"); + Void::Log::debug("YouTubeClient", "{}", + "Video durations fetched"); } } - Void::Log::info("YouTubeClient", "{}", + Void::Log::info( + "YouTubeClient", "{}", std::format("YouTube API search returned {} results", result.tracks.size())); // Populate shortened URLs for all tracks (already non-blocking with // timeout) - Void::Log::debug("YouTubeClient", "{}", "Populating shortened URLs..."); + Void::Log::debug("YouTubeClient", "{}", + "Populating shortened URLs..."); populateShortenedUrls(result.tracks); Void::Log::debug("YouTubeClient", "{}", "Shortened URLs populated"); @@ -679,45 +743,36 @@ namespace Echoion::Core idList, *apiKey_); } - // Execute with timeout (5 seconds) to avoid blocking - // Use shared promise so detached thread can safely complete - auto responsePromise = - std::make_shared<std::promise<Api::Result<Void::Net::Response>>>(); + // Execute with timeout (5 seconds) to avoid blocking. Run on the shared + // pool — the pool destructor joins in-flight tasks, so abandoning a + // timed-out future is safe (no detached thread outliving this object). std::future<Api::Result<Void::Net::Response>> responseFuture = - responsePromise->get_future(); - - std::thread durationThread( - [this, url = std::string(url), responsePromise]() { - try { - auto result = networkClient_->get(url); - responsePromise->set_value(std::move(result)); - } catch (...) { - responsePromise->set_exception(std::current_exception()); - } + pool_.submit([this, url = std::string(url)]() { + return networkClient_->get(url); }); auto waitStatus = responseFuture.wait_for(std::chrono::seconds(5)); if (waitStatus == std::future_status::timeout) { - Void::Log::warn("YouTubeClient", "{}", "Video duration fetch timed out after 5s"); - durationThread.detach(); + Void::Log::warn("YouTubeClient", "{}", + "Video duration fetch timed out after 5s"); + // Task keeps running on the pool; its result is discarded. return; } - durationThread.join(); - Api::Result<Void::Net::Response> response; try { response = responseFuture.get(); } catch (const std::exception& e) { - Void::Log::warn("YouTubeClient", "{}", + Void::Log::warn( + "YouTubeClient", "{}", std::format("Video duration request failed: {}", e.what())); return; } if (!response || !response->ok()) { - Void::Log::warn("YouTubeClient", "{}", - "Failed to fetch video durations from YouTube API"); + Void::Log::warn("YouTubeClient", "{}", + "Failed to fetch video durations from YouTube API"); return; } @@ -744,9 +799,12 @@ namespace Echoion::Core if ((*contentDetails).has("duration")) { std::string durationStr = (*contentDetails).get_str("duration"); - auto duration = Void::Time::parse_iso8601_interval(durationStr).value_or(std::chrono::seconds{0}); + auto duration = + Void::Time::parse_iso8601_interval(durationStr) + .value_or(std::chrono::seconds{0}); if (duration.count() > 0) { - Void::Log::debug("YouTubeClient", "{}", + Void::Log::debug( + "YouTubeClient", "{}", std::format("Got duration: {}, parse as: {}", durationStr, duration)); durationMap[videoId] = duration; @@ -766,7 +824,8 @@ namespace Echoion::Core } } catch (const std::exception& e) { - Void::Log::warn("YouTubeClient", "{}", + Void::Log::warn( + "YouTubeClient", "{}", std::format("Failed to parse video durations: {}", e.what())); } } @@ -776,8 +835,8 @@ namespace Echoion::Core { if (!ytDlpManager_->isAvailable()) { - return Api::fail( - Api::ErrorCode::ServiceUnavailable, "yt-dlp not available"); + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "yt-dlp not available"); } Void::Log::debug("YouTubeClient", "{}", "Starting yt-dlp search..."); @@ -790,13 +849,15 @@ namespace Echoion::Core {searchQuery, "-J", "--flat-playlist", "--no-warnings"}); // Wait with timeout (30 seconds for yt-dlp search) - Void::Log::debug("YouTubeClient", "{}", "Waiting for yt-dlp search result (30s timeout)..."); + Void::Log::debug("YouTubeClient", "{}", + "Waiting for yt-dlp search result (30s timeout)..."); auto waitStatus = result.wait_for(std::chrono::seconds(30)); if (waitStatus == std::future_status::timeout) { - Void::Log::warn("YouTubeClient", "{}", "yt-dlp search timed out after 30s"); + Void::Log::warn("YouTubeClient", "{}", + "yt-dlp search timed out after 30s"); return Api::fail(Api::ErrorCode::NetworkError, - "yt-dlp search timed out"); + "yt-dlp search timed out"); } auto ytdlpResult = result.get(); @@ -804,19 +865,20 @@ namespace Echoion::Core auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::steady_clock::now() - searchStart) .count(); - Void::Log::debug("YouTubeClient", "{}", + Void::Log::debug( + "YouTubeClient", "{}", std::format("yt-dlp search completed in {} ms", elapsed)); if (!ytdlpResult.success || ytdlpResult.output.empty()) { return Api::fail(Api::ErrorCode::NetworkError, - "yt-dlp search failed"); + "yt-dlp search failed"); } try { auto parsed = Void::Json::parse(ytdlpResult.output); if (!parsed) { return Api::fail(Api::ErrorCode::ParseError, - "Failed to parse yt-dlp search output"); + "Failed to parse yt-dlp search output"); } const JValue& json = *parsed; @@ -836,13 +898,12 @@ namespace Echoion::Core Void::Text::html_unescape((entry).get_str("title")); } if ((entry).has("uploader")) { - track.artist = - Void::Text::html_unescape((entry).get_str("uploader")); + track.artist = Void::Text::html_unescape( + (entry).get_str("uploader")); } if ((entry).has("duration")) { - track.duration = - std::chrono::seconds(static_cast<int64_t>( - (entry).get_num("duration"))); + track.duration = std::chrono::seconds( + static_cast<int64_t>((entry).get_num("duration"))); } if ((entry).has("thumbnail")) { track.thumbnailUrl = (entry).get_str("thumbnail"); @@ -872,15 +933,102 @@ namespace Echoion::Core } } + Api::Result<std::vector<Api::TrackInfo>> + YouTubeClient::radioMix(const std::string& videoId, size_t limit) + { + if (!ytDlpManager_->isAvailable()) { + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "yt-dlp not available"); + } + + // YouTube's auto-generated "mix" playlist for a video is RD<videoId>. + // --flat-playlist lists it cheaply; each entry becomes a seed-free + // related track. Runs through the proxy like every yt-dlp call. + const std::string mixUrl = std::format( + "https://www.youtube.com/watch?v={}&list=RD{}", videoId, videoId); + auto future = ytDlpManager_->executeAsync( + {mixUrl, "-J", "--flat-playlist", "--no-warnings", "--playlist-end", + std::to_string(limit + 5)}); + + auto waitStatus = future.wait_for(std::chrono::seconds(30)); + if (waitStatus == std::future_status::timeout) { + return Api::fail(Api::ErrorCode::NetworkError, + "yt-dlp radio mix timed out"); + } + auto ytdlpResult = future.get(); + if (!ytdlpResult.success || ytdlpResult.output.empty()) { + return Api::fail(Api::ErrorCode::NetworkError, + "yt-dlp radio mix failed"); + } + + try { + auto parsed = Void::Json::parse(ytdlpResult.output); + if (!parsed) { + return Api::fail(Api::ErrorCode::ParseError, + "Failed to parse yt-dlp radio mix output"); + } + const JValue& json = *parsed; + + std::vector<Api::TrackInfo> tracks; + if (const JValue* entries = (json).child_array("entries")) { + for (const JValue& entry : entries->as_array()) { + if (tracks.size() >= limit) { + break; + } + if (!(entry).has("id")) { + continue; + } + Api::TrackInfo track; + track.id = (entry).get_str("id"); + // Skip the seed itself — the mix always leads with it. + if (track.id == videoId) { + continue; + } + if ((entry).has("title")) { + track.title = + Void::Text::html_unescape((entry).get_str("title")); + } + if ((entry).has("uploader")) { + track.artist = Void::Text::html_unescape( + (entry).get_str("uploader")); + } + if ((entry).has("duration")) { + track.duration = std::chrono::seconds( + static_cast<int64_t>((entry).get_num("duration"))); + } + if ((entry).has("thumbnail")) { + track.thumbnailUrl = (entry).get_str("thumbnail"); + } + track.requestedBy = "radio\\autoplay"; + track.addedAt = std::chrono::system_clock::now(); + track.originalUrl = std::format( + "https://www.youtube.com/watch?v={}", track.id); + track.source = Api::TrackSource::YouTube; + tracks.push_back(std::move(track)); + } + } + + populateShortenedUrls(tracks); + return tracks; + + } catch (const std::exception& e) { + return Api::fail( + Api::ErrorCode::ParseError, + std::format("Exception parsing yt-dlp radio mix: {}", + e.what())); + } + } + Api::Result<Api::PlaylistInfo> YouTubeClient::getPlaylist(std::string_view playlistId) { if (!initialized_) { return Api::fail(Api::ErrorCode::ServiceUnavailable, - "YouTubeClient not initialized"); + "YouTubeClient not initialized"); } - Void::Log::info("YouTubeClient", "{}", std::format("Fetching playlist: {}", playlistId)); + Void::Log::info("YouTubeClient", "{}", + std::format("Fetching playlist: {}", playlistId)); // Step 1: Fetch playlist items (via API v2 if key available, else // yt-dlp) @@ -897,9 +1045,11 @@ namespace Echoion::Core return emptyInfo; } - Void::Log::info("YouTubeClient", "{}", std::format( - "Found {} tracks in playlist, resolving individually...", - items.size())); + Void::Log::info( + "YouTubeClient", "{}", + std::format( + "Found {} tracks in playlist, resolving individually...", + items.size())); // Step 2: Resolve each track individually via yt-dlp (concurrently) Api::PlaylistInfo info; @@ -920,10 +1070,9 @@ namespace Echoion::Core // Launch concurrent resolutions for this batch for (size_t j = i; j < end; ++j) { - futures.push_back( - pool_.submit([this, &items, j]() { - return resolveTrackWithYtDlp(items[j]); - })); + futures.push_back(pool_.submit([this, &items, j]() { + return resolveTrackWithYtDlp(items[j]); + })); } // Collect results @@ -932,15 +1081,18 @@ namespace Echoion::Core if (result) { resolvedTracks.push_back(std::move(*result)); } else { - Void::Log::warn("YouTubeClient", "{}", std::format( - "Failed to resolve track: {}", result.error().message)); + Void::Log::warn("YouTubeClient", "{}", + std::format("Failed to resolve track: {}", + result.error().message)); } } - Void::Log::debug("YouTubeClient", "{}", std::format( - "Resolved batch {}/{} ({} tracks so far)", (i / batchSize) + 1, - (items.size() + batchSize - 1) / batchSize, - resolvedTracks.size())); + Void::Log::debug( + "YouTubeClient", "{}", + std::format("Resolved batch {}/{} ({} tracks so far)", + (i / batchSize) + 1, + (items.size() + batchSize - 1) / batchSize, + resolvedTracks.size())); } info.tracks = std::move(resolvedTracks); @@ -952,7 +1104,8 @@ namespace Echoion::Core info.name = std::format("Playlist ({} tracks)", info.tracks.size()); } - Void::Log::info("YouTubeClient", "{}", + Void::Log::info( + "YouTubeClient", "{}", std::format("Successfully resolved {}/{} tracks from playlist", info.tracks.size(), items.size())); @@ -986,12 +1139,14 @@ namespace Echoion::Core return; } - Void::Log::info("YouTubeClient", "{}", std::format("Streaming playlist: {}", playlistId)); + Void::Log::info("YouTubeClient", "{}", + std::format("Streaming playlist: {}", playlistId)); // Fetch playlist items first (quick operation) auto itemsResult = fetchPlaylistItems(playlistId); if (!itemsResult || itemsResult->empty()) { - Void::Log::warn("YouTubeClient", "{}", "No items found in playlist or fetch failed"); + Void::Log::warn("YouTubeClient", "{}", + "No items found in playlist or fetch failed"); if (onComplete) { onComplete(); } @@ -999,7 +1154,8 @@ namespace Echoion::Core } const auto& items = *itemsResult; - Void::Log::info("YouTubeClient", "{}", + Void::Log::info( + "YouTubeClient", "{}", std::format("Streaming {} tracks from playlist", items.size())); // Notify about total tracks @@ -1021,10 +1177,9 @@ namespace Echoion::Core // Launch concurrent resolutions for this batch for (size_t j = i; j < end; ++j) { - futures.push_back( - pool_.submit([this, &items, j]() { - return resolveTrackWithYtDlp(items[j]); - })); + futures.push_back(pool_.submit([this, &items, j]() { + return resolveTrackWithYtDlp(items[j]); + })); } // Collect results and immediately call callback for each @@ -1037,12 +1192,14 @@ namespace Echoion::Core // start trackCallback(std::move(*result)); } else { - Void::Log::warn("YouTubeClient", "{}", std::format( - "Failed to resolve track: {}", result.error().message)); + Void::Log::warn("YouTubeClient", "{}", + std::format("Failed to resolve track: {}", + result.error().message)); } } - Void::Log::debug("YouTubeClient", "{}", + Void::Log::debug( + "YouTubeClient", "{}", std::format("Processed batch {}/{}", (i / batchSize) + 1, (items.size() + batchSize - 1) / batchSize)); } @@ -1061,7 +1218,8 @@ namespace Echoion::Core // Try using YouTube Data API v3 if key is available if (hasApiKey()) { - Void::Log::info("YouTubeClient", "{}", "Using YouTube Data API v3 for playlist fetch"); + Void::Log::info("YouTubeClient", "{}", + "Using YouTube Data API v3 for playlist fetch"); std::optional<std::string> pageToken; do { @@ -1069,7 +1227,8 @@ namespace Echoion::Core auto response = networkClient_->get(apiUrl); if (!response || !response->ok()) { - Void::Log::warn("YouTubeClient", "{}", + Void::Log::warn( + "YouTubeClient", "{}", "YouTube API request failed, falling back to yt-dlp"); break; // Fall back to yt-dlp } @@ -1077,16 +1236,17 @@ namespace Echoion::Core try { auto parsed = Void::Json::parse(response->body); if (!parsed) { - Void::Log::warn("YouTubeClient", "{}", - "Failed to parse YouTube API response, " - "falling back to yt-dlp"); + Void::Log::warn("YouTubeClient", "{}", + "Failed to parse YouTube API response, " + "falling back to yt-dlp"); break; } const JValue& json = *parsed; if (const JValue* itemsArr = (json).child_array("items")) { for (const JValue& item : itemsArr->as_array()) { - const JValue* snippet = (item).child_object("snippet"); + const JValue* snippet = + (item).child_object("snippet"); const JValue* contentDetails = (item).child_object("contentDetails"); if (!snippet || !contentDetails) { @@ -1101,7 +1261,8 @@ namespace Echoion::Core } if ((*snippet).has("title")) { - playlistItem.title = (*snippet).get_str("title"); + playlistItem.title = + (*snippet).get_str("title"); } if (const JValue* thumbnails = @@ -1109,13 +1270,18 @@ namespace Echoion::Core // Get the highest quality thumbnail available if (const JValue* t = (*thumbnails).child_object("high")) { - playlistItem.thumbnailUrl = (*t).get_str("url"); + playlistItem.thumbnailUrl = + (*t).get_str("url"); } else if (const JValue* m = - (*thumbnails).child_object("medium")) { - playlistItem.thumbnailUrl = (*m).get_str("url"); + (*thumbnails) + .child_object("medium")) { + playlistItem.thumbnailUrl = + (*m).get_str("url"); } else if (const JValue* d = - (*thumbnails).child_object("default")) { - playlistItem.thumbnailUrl = (*d).get_str("url"); + (*thumbnails) + .child_object("default")) { + playlistItem.thumbnailUrl = + (*d).get_str("url"); } } @@ -1131,25 +1297,29 @@ namespace Echoion::Core } } catch (const std::exception& e) { - Void::Log::warn("YouTubeClient", "{}", std::format( - "Error parsing YouTube API response: {}", e.what())); + Void::Log::warn( + "YouTubeClient", "{}", + std::format("Error parsing YouTube API response: {}", + e.what())); break; // Fall back to yt-dlp } } while (pageToken.has_value()); if (!items.empty()) { - Void::Log::info("YouTubeClient", "{}", std::format( - "Fetched {} tracks via YouTube API", items.size())); + Void::Log::info("YouTubeClient", "{}", + std::format("Fetched {} tracks via YouTube API", + items.size())); return items; } } // Fallback: Use yt-dlp to fetch playlist items - Void::Log::info("YouTubeClient", "{}", "Using yt-dlp for playlist fetch"); + Void::Log::info("YouTubeClient", "{}", + "Using yt-dlp for playlist fetch"); if (!ytDlpManager_->isAvailable()) { - return Api::fail( - Api::ErrorCode::ServiceUnavailable, "yt-dlp not available"); + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "yt-dlp not available"); } std::string url = @@ -1162,14 +1332,14 @@ namespace Echoion::Core if (!ytdlpResult.success || ytdlpResult.output.empty()) { return Api::fail(Api::ErrorCode::NetworkError, - "Failed to fetch playlist via yt-dlp"); + "Failed to fetch playlist via yt-dlp"); } try { auto parsed = Void::Json::parse(ytdlpResult.output); if (!parsed) { return Api::fail(Api::ErrorCode::ParseError, - "Failed to parse yt-dlp playlist output"); + "Failed to parse yt-dlp playlist output"); } const JValue& json = *parsed; @@ -1182,9 +1352,11 @@ namespace Echoion::Core Api::YouTubePlaylistItem item; item.videoId = (entry).get_str("id"); if ((entry).has("title")) { - item.title = Void::Text::html_unescape((entry).get_str("title")); + item.title = + Void::Text::html_unescape((entry).get_str("title")); } - if (const JValue* thumbs = (entry).child_array("thumbnails")) { + if (const JValue* thumbs = + (entry).child_array("thumbnails")) { const auto& arr = thumbs->as_array(); if (!arr.empty() && arr.back().is_object() && arr.back().find("url")) { @@ -1196,7 +1368,8 @@ namespace Echoion::Core } } - Void::Log::info("YouTubeClient", "{}", + Void::Log::info( + "YouTubeClient", "{}", std::format("Fetched {} tracks via yt-dlp", items.size())); return items; @@ -1258,10 +1431,12 @@ namespace Echoion::Core Api::TrackInfo track; track.id = (json).get_str("id"); if ((json).has("title")) { - track.title = Void::Text::html_unescape((json).get_str("title")); + track.title = + Void::Text::html_unescape((json).get_str("title")); } if ((json).has("uploader")) { - track.artist = Void::Text::html_unescape((json).get_str("uploader")); + track.artist = + Void::Text::html_unescape((json).get_str("uploader")); } if ((json).has("duration")) { track.duration = std::chrono::seconds( @@ -1314,7 +1489,8 @@ namespace Echoion::Core // Handle faumaray.ru redirects using NetworkClient if (url_str.find("faumaray.ru") != std::string::npos && networkClient_) { - Void::Log::debug("YouTubeClient", "{}", + Void::Log::debug( + "YouTubeClient", "{}", std::format("Following redirect for: {}", url_str)); std::vector<Void::Net::Header> headers = { @@ -1330,7 +1506,8 @@ namespace Echoion::Core if (response->status >= 300 && response->status < 400) { auto location = response->header("location"); if (location.has_value()) { - Void::Log::debug("YouTubeClient", "{}", + Void::Log::debug( + "YouTubeClient", "{}", std::format("Redirected to: {}", *location)); url_str = std::string(*location); } @@ -1405,10 +1582,18 @@ namespace Echoion::Core { std::lock_guard<std::mutex> lock(configMutex_); urlShorteningEnabled_ = enabled; - Void::Log::info("YouTubeClient", "{}", + Void::Log::info( + "YouTubeClient", "{}", std::format("URL shortening {}", enabled ? "enabled" : "disabled")); } + void YouTubeClient::setAutoUpdateEnabled(bool enabled) + { + if (ytDlpManager_) { + ytDlpManager_->setAutoUpdateEnabled(enabled); + } + } + bool YouTubeClient::isUrlShorteningEnabled() const { std::lock_guard<std::mutex> lock(configMutex_); @@ -1426,49 +1611,37 @@ namespace Echoion::Core return; } - // Run URL shortening asynchronously with timeout to avoid blocking - // This is a best-effort feature - if it fails or times out, we still - // have the track. Use shared_ptr to ensure data lives for detached - // thread. + // Run URL shortening on the shared pool with a timeout. Best-effort: if + // it times out we keep the track unshortened. The future is only read + // on the ready path (which establishes happens-before), and on timeout + // the task keeps running on the pool with its result discarded — no + // detached thread and no busy-wait poll. auto trackId = track.id; - auto shortenedUrl = std::make_shared<std::optional<std::string>>(); - auto completed = std::make_shared<std::atomic<bool>>(false); - - std::thread shortenThread([this, trackId, shortenedUrl, completed]() { - try { - auto result = urlShortener_->shortenYouTubeUrl(trackId); - if (result) { - *shortenedUrl = *result; + auto future = + pool_.submit([this, trackId]() -> std::optional<std::string> { + try { + auto result = urlShortener_->shortenYouTubeUrl(trackId); + if (result) { + return *result; + } + } catch (...) { + // Ignore exceptions - this is best-effort } - } catch (...) { - // Ignore exceptions - this is best-effort - } - *completed = true; - }); + return std::nullopt; + }); - // Wait up to 3 seconds for URL shortening - auto start = std::chrono::steady_clock::now(); - while (!*completed && std::chrono::steady_clock::now() - start < - std::chrono::seconds(3)) { - std::this_thread::sleep_for(std::chrono::milliseconds(10)); - } - - if (*completed) { - // Thread completed, join it and apply result - if (shortenThread.joinable()) { - shortenThread.join(); - } - if (shortenedUrl->has_value()) { - track.shortenedUrl = *shortenedUrl; - Void::Log::debug("YouTubeClient", "{}", std::format("URL shortened for {}: {}", - track.title, - track.shortenedUrl.value())); + if (future.wait_for(std::chrono::seconds(3)) == + std::future_status::ready) { + if (auto shortened = future.get()) { + track.shortenedUrl = *shortened; + Void::Log::debug("YouTubeClient", "{}", + std::format("URL shortened for {}: {}", + track.title, + track.shortenedUrl.value())); } } else { - // Timeout - thread owns shared_ptr, safe to detach - Void::Log::warn("YouTubeClient", "{}", - "URL shortening timed out after 3s, detaching thread"); - shortenThread.detach(); + Void::Log::warn("YouTubeClient", "{}", + "URL shortening timed out after 3s"); } } @@ -1484,70 +1657,59 @@ namespace Echoion::Core return; } - // Shorten URLs in parallel using async with timeout - std::vector<std::future<void>> futures; - futures.reserve(tracks.size()); + // Shorten URLs in parallel on the shared pool. Each task writes its + // result into a shared optional (kept alive by the captured + // shared_ptr), so a task that outlives the overall timeout writes only + // to that shared slot — never to the caller's `tracks` vector. Results + // are applied on this thread, and only for tasks whose future is ready + // (which gives the needed happens-before for reading the slot). + // Replaces the previous nested std::async + std::thread + busy-wait + + // detach design. + struct Slot { + Api::TrackInfo* track; + std::shared_ptr<std::optional<std::string>> out; + std::future<void> future; + }; + std::vector<Slot> slots; + slots.reserve(tracks.size()); for (auto& track : tracks) { if (track.id.empty()) { continue; } - - // Best-effort wide-parallel shortening under a tight timeout — kept - // on std::async so each track gets its own thread rather than - // queueing behind the bounded resolution pool. - futures.push_back(std::async(std::launch::async, [this, &track]() { - // Each URL shortening has its own 3-second timeout - // Use shared_ptr for safe detached thread execution - auto trackId = track.id; - auto shortenedUrl = - std::make_shared<std::optional<std::string>>(); - auto completed = std::make_shared<std::atomic<bool>>(false); - - std::thread t([this, trackId, shortenedUrl, completed]() { - try { - auto result = urlShortener_->shortenYouTubeUrl(trackId); - if (result) { - *shortenedUrl = *result; - } - } catch (...) { - // Ignore exceptions + auto trackId = track.id; + auto out = std::make_shared<std::optional<std::string>>(); + auto future = pool_.submit([this, trackId, out]() { + try { + auto result = urlShortener_->shortenYouTubeUrl(trackId); + if (result) { + *out = *result; } - *completed = true; - }); - - // Wait for completion or timeout - auto start = std::chrono::steady_clock::now(); - while (!*completed && std::chrono::steady_clock::now() - start < - std::chrono::seconds(3)) { - std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } catch (...) { + // Ignore exceptions - best-effort } - - if (*completed) { - // Thread completed, join and apply result - if (t.joinable()) { - t.join(); - } - if (shortenedUrl->has_value()) { - track.shortenedUrl = *shortenedUrl; - } - } else { - // Timeout - thread owns shared_ptr, safe to detach - t.detach(); - } - })); + }); + slots.push_back({&track, std::move(out), std::move(future)}); } - // Wait for all with overall 5-second timeout + // Wait for all with an overall 5-second timeout. auto start = std::chrono::steady_clock::now(); - for (auto& f : futures) { + for (auto& slot : slots) { auto remaining = std::chrono::seconds(5) - - std::chrono::duration_cast<std::chrono::seconds>( - std::chrono::steady_clock::now() - start); - if (remaining.count() <= 0) { + (std::chrono::steady_clock::now() - start); + if (remaining <= std::chrono::seconds::zero()) { break; } - f.wait_for(remaining); + slot.future.wait_for(remaining); + } + + // Apply results for tasks that finished in time. + for (auto& slot : slots) { + if (slot.future.wait_for(std::chrono::seconds::zero()) == + std::future_status::ready && + slot.out->has_value()) { + slot.track->shortenedUrl = **slot.out; + } } } diff --git a/src/YtDlpManager.cpp b/src/YtDlpManager.cpp index a117620..31a470a 100644 --- a/src/YtDlpManager.cpp +++ b/src/YtDlpManager.cpp @@ -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 {}; } diff --git a/src/commands/RpcInfoCommand.cpp b/src/commands/RpcInfoCommand.cpp index 057071e..48bd531 100644 --- a/src/commands/RpcInfoCommand.cpp +++ b/src/commands/RpcInfoCommand.cpp @@ -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; } diff --git a/src/playback/PlaybackEngine.cpp b/src/playback/PlaybackEngine.cpp new file mode 100644 index 0000000..cc03aa6 --- /dev/null +++ b/src/playback/PlaybackEngine.cpp @@ -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 diff --git a/src/playback/QueueService.cpp b/src/playback/QueueService.cpp new file mode 100644 index 0000000..03e1e53 --- /dev/null +++ b/src/playback/QueueService.cpp @@ -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 diff --git a/src/sources/DirectUrlSource.cpp b/src/sources/DirectUrlSource.cpp new file mode 100644 index 0000000..1d5bfce --- /dev/null +++ b/src/sources/DirectUrlSource.cpp @@ -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 diff --git a/src/sources/InnertubeSource.cpp b/src/sources/InnertubeSource.cpp new file mode 100644 index 0000000..d7f5ce0 --- /dev/null +++ b/src/sources/InnertubeSource.cpp @@ -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 diff --git a/src/sources/SourceRouter.cpp b/src/sources/SourceRouter.cpp new file mode 100644 index 0000000..273e460 --- /dev/null +++ b/src/sources/SourceRouter.cpp @@ -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 diff --git a/src/sources/YandexMusicSource.cpp b/src/sources/YandexMusicSource.cpp new file mode 100644 index 0000000..8555e61 --- /dev/null +++ b/src/sources/YandexMusicSource.cpp @@ -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 diff --git a/src/sources/YtDlpSource.cpp b/src/sources/YtDlpSource.cpp new file mode 100644 index 0000000..ea897cf --- /dev/null +++ b/src/sources/YtDlpSource.cpp @@ -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 diff --git a/src/state/StateSerializer.cpp b/src/state/StateSerializer.cpp index 57e3456..2510bbd 100644 --- a/src/state/StateSerializer.cpp +++ b/src/state/StateSerializer.cpp @@ -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; } }