Release 1.0.0

Signed-off-by: faumaray <faumaray@gmail.com>
This commit is contained in:
faumaray committed 2026-07-04 01:49:28 +03:00
1 parent df99b6ea7f
commit d146f11f02
63 files changed
+8331 -2709

No files matched your search

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