Migrate to VoidLibrary (toolchain + API groundwork)

This commit is contained in:
faumaray committed 2026-06-22 15:53:18 +03:00
1 parent 5e1e3d66c4
commit e17cfed56f
38 files changed
+3077 -2505

No files matched your search

+272 -23
View File
@@ -1,4 +1,4 @@
cmake_minimum_required(VERSION 3.28)
cmake_minimum_required(VERSION 4.0.0)
project(EchoionApi VERSION 1.0.0 LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 26)
@@ -6,38 +6,287 @@ set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
# Create header-only interface library for API
add_library(EchoionApi INTERFACE)
find_package(Threads REQUIRED)
add_library(Echoion::Api ALIAS EchoionApi)
# ===== Granular API Libraries =====
# Directory structure:
# include/echoion/api/
# base/ - Types.hpp (Error, Result, LogLevel, LogEntry)
# audio/ - AudioTypes.hpp (AudioQuality, AudioFormat, AudioBuffer)
# track/ - TrackTypes.hpp (TrackInfo, QueueEntry, PlaybackState, etc.)
# network/ - NetworkTypes.hpp (HttpRequest, HttpResponse, ProxyConfig)
# plugin/ - PluginTypes.hpp (PluginEvent, ClientInfo, ChannelInfo, etc.)
# config/ - ConfigTypes.hpp (BotConfig, ServerConfig, AppConfig)
# rpc/ - RpcTypes.hpp (RpcMethod, RpcRequest, RpcResponse, HotReloadState)
# youtube/ - YouTubeTypes.hpp (YouTube types)
# logger/ - LoggerInterface.hpp (ILogger, LoggerRegistry)
# eventbus/ - EventBus.hpp (EventBus, all event types)
# database/ - Database.hpp (Database interface)
# interfaces/- CoreInterface.hpp, PluginInterface
# utils/ - Cache.hpp, MemoryPool.hpp
target_include_directories(EchoionApi INTERFACE
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>
# 1. Base Types
add_library(EchoionApiBase INTERFACE)
add_library(Echoion::ApiBase ALIAS EchoionApiBase)
target_include_directories(EchoionApiBase INTERFACE
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/api/base>
$<INSTALL_INTERFACE:include/echoion/api/base>
)
target_link_libraries(EchoionApiBase INTERFACE Void::Functional)
# 2. Audio Types
add_library(EchoionApiAudio INTERFACE)
add_library(Echoion::ApiAudio ALIAS EchoionApiAudio)
target_include_directories(EchoionApiAudio INTERFACE
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/api/audio>
$<INSTALL_INTERFACE:include/echoion/api/audio>
)
target_link_libraries(EchoionApiAudio INTERFACE Echoion::ApiBase Echoion::ApiUtils)
# 3. Track Types (depends on Audio)
add_library(EchoionApiTrack INTERFACE)
add_library(Echoion::ApiTrack ALIAS EchoionApiTrack)
target_include_directories(EchoionApiTrack INTERFACE
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/api/track>
$<INSTALL_INTERFACE:include/echoion/api/track>
)
target_link_libraries(EchoionApiTrack INTERFACE
Echoion::ApiBase
Echoion::ApiAudio
Void::Data
)
# Require glaze for JSON serialization (header-only)
find_package(glaze CONFIG REQUIRED)
target_link_libraries(EchoionApi INTERFACE glaze::glaze)
# 4. Network Types
add_library(EchoionApiNetwork INTERFACE)
add_library(Echoion::ApiNetwork ALIAS EchoionApiNetwork)
target_include_directories(EchoionApiNetwork INTERFACE
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/api/network>
$<INSTALL_INTERFACE:include/echoion/api/network>
)
target_link_libraries(EchoionApiNetwork INTERFACE Echoion::ApiBase)
find_package(Threads REQUIRED)
target_link_libraries(EchoionApi INTERFACE Threads::Threads)
# 5. Plugin Types
add_library(EchoionApiPlugin INTERFACE)
add_library(Echoion::ApiPlugin ALIAS EchoionApiPlugin)
target_include_directories(EchoionApiPlugin INTERFACE
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/api/plugin>
$<INSTALL_INTERFACE:include/echoion/api/plugin>
)
target_link_libraries(EchoionApiPlugin INTERFACE Echoion::ApiBase)
# Compiler-specific options (interface library, so use INTERFACE)
# 6. Config Types (depends on Network, Audio)
add_library(EchoionApiConfig INTERFACE)
add_library(Echoion::ApiConfig ALIAS EchoionApiConfig)
target_include_directories(EchoionApiConfig INTERFACE
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/api/config>
$<INSTALL_INTERFACE:include/echoion/api/config>
)
target_link_libraries(EchoionApiConfig INTERFACE
Echoion::ApiBase
Echoion::ApiNetwork
Echoion::ApiAudio
)
# 7. RPC Types (depends on Track)
add_library(EchoionApiRpc INTERFACE)
add_library(Echoion::ApiRpc ALIAS EchoionApiRpc)
target_include_directories(EchoionApiRpc INTERFACE
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/api/rpc>
$<INSTALL_INTERFACE:include/echoion/api/rpc>
)
target_link_libraries(EchoionApiRpc INTERFACE
Echoion::ApiBase
Echoion::ApiTrack
Echoion::ApiConfig
)
# 8. YouTube Types (depends on Track)
add_library(EchoionApiYouTube INTERFACE)
add_library(Echoion::ApiYouTube ALIAS EchoionApiYouTube)
target_include_directories(EchoionApiYouTube INTERFACE
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/api/youtube>
$<INSTALL_INTERFACE:include/echoion/api/youtube>
)
target_link_libraries(EchoionApiYouTube INTERFACE
Echoion::ApiBase
Echoion::ApiTrack
)
# 9. Logger (self-contained)
add_library(EchoionApiLogger INTERFACE)
add_library(Echoion::ApiLogger ALIAS EchoionApiLogger)
target_include_directories(EchoionApiLogger INTERFACE
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/api/logger>
$<INSTALL_INTERFACE:include/echoion/api/logger>
)
target_link_libraries(EchoionApiLogger INTERFACE
Echoion::ApiBase
Threads::Threads
)
# 10. EventBus (depends on Track, Config, Plugin)
add_library(EchoionApiEventBus INTERFACE)
add_library(Echoion::ApiEventBus ALIAS EchoionApiEventBus)
target_include_directories(EchoionApiEventBus INTERFACE
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/api/eventbus>
$<INSTALL_INTERFACE:include/echoion/api/eventbus>
)
target_link_libraries(EchoionApiEventBus INTERFACE
Echoion::ApiBase
Echoion::ApiTrack
Echoion::ApiConfig
Echoion::ApiPlugin
Threads::Threads
Void::Async
)
# 11. Database (depends on Track, Config)
add_library(EchoionApiDatabase INTERFACE)
add_library(Echoion::ApiDatabase ALIAS EchoionApiDatabase)
target_include_directories(EchoionApiDatabase INTERFACE
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/api/database>
$<INSTALL_INTERFACE:include/echoion/api/database>
)
target_link_libraries(EchoionApiDatabase INTERFACE
Echoion::ApiBase
Echoion::ApiTrack
Echoion::ApiConfig
Echoion::ApiEventBus
)
# 11b. OpaqueHandle (for breaking dependencies)
add_library(EchoionApiOpaque INTERFACE)
add_library(Echoion::ApiOpaque ALIAS EchoionApiOpaque)
target_include_directories(EchoionApiOpaque INTERFACE
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/api/interfaces>
$<INSTALL_INTERFACE:include/echoion/api/interfaces>
)
target_link_libraries(EchoionApiOpaque INTERFACE Echoion::ApiBase)
# 12a. PluginInterface only (minimal - for Plugin to implement)
add_library(EchoionApiPluginInterface INTERFACE)
add_library(Echoion::ApiPluginInterface ALIAS EchoionApiPluginInterface)
target_include_directories(EchoionApiPluginInterface INTERFACE
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/api/interfaces>
$<INSTALL_INTERFACE:include/echoion/api/interfaces>
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/api/plugin>
$<INSTALL_INTERFACE:include/echoion/api/plugin>
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/api/base>
$<INSTALL_INTERFACE:include/echoion/api/base>
)
target_link_libraries(EchoionApiPluginInterface INTERFACE
Echoion::ApiBase
Echoion::ApiPlugin
Echoion::ApiOpaque
)
# 12b. CoreInterface (decoupled - for Plugin to call Core)
add_library(EchoionApiCoreInterface INTERFACE)
add_library(Echoion::ApiCoreInterface ALIAS EchoionApiCoreInterface)
target_include_directories(EchoionApiCoreInterface INTERFACE
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/api/interfaces>
$<INSTALL_INTERFACE:include/echoion/api/interfaces>
)
target_link_libraries(EchoionApiCoreInterface INTERFACE
Echoion::ApiBase
Echoion::ApiPlugin
Echoion::ApiPluginInterface
Echoion::ApiOpaque
)
# 12c. Legacy Interfaces (both)
add_library(EchoionApiInterfaces INTERFACE)
add_library(Echoion::ApiInterfaces ALIAS EchoionApiInterfaces)
target_link_libraries(EchoionApiInterfaces INTERFACE
Echoion::ApiPluginInterface
Echoion::ApiCoreInterface
Echoion::ApiConfig
)
# 13. Utilities (Cache, MemoryPool)
add_library(EchoionApiUtils INTERFACE)
add_library(Echoion::ApiUtils ALIAS EchoionApiUtils)
target_include_directories(EchoionApiUtils INTERFACE
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/api/utils>
$<INSTALL_INTERFACE:include/echoion/api/utils>
)
target_link_libraries(EchoionApiUtils INTERFACE Echoion::ApiBase Void::Containers)
# 14. Full API (backward compatibility)
add_library(EchoionApi INTERFACE)
add_library(Echoion::Api ALIAS EchoionApi)
target_include_directories(EchoionApi INTERFACE
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/api>
$<INSTALL_INTERFACE:include/echoion/api>
)
target_link_libraries(EchoionApi INTERFACE
Echoion::ApiBase
Echoion::ApiAudio
Echoion::ApiTrack
Echoion::ApiNetwork
Echoion::ApiPlugin
Echoion::ApiConfig
Echoion::ApiRpc
Echoion::ApiYouTube
Echoion::ApiLogger
Echoion::ApiEventBus
Echoion::ApiDatabase
Echoion::ApiOpaque
Echoion::ApiPluginInterface
Echoion::ApiCoreInterface
Echoion::ApiUtils
)
# Compiler options
if(MSVC)
target_compile_options(EchoionApi INTERFACE /W4 /WX-)
target_compile_options(EchoionApiBase INTERFACE /W4 /WX-)
else()
target_compile_options(EchoionApi INTERFACE -Wall -Wextra -Wpedantic)
target_compile_options(EchoionApiBase INTERFACE -Wall -Wextra -Wpedantic)
endif()
# PackageProject.cmake configuration
packageProject(
NAME EchoionApi
# Install and export all modules
install(TARGETS
EchoionApiBase
EchoionApiAudio
EchoionApiTrack
EchoionApiNetwork
EchoionApiPlugin
EchoionApiConfig
EchoionApiRpc
EchoionApiYouTube
EchoionApiLogger
EchoionApiEventBus
EchoionApiDatabase
EchoionApiOpaque
EchoionApiPluginInterface
EchoionApiCoreInterface
EchoionApiInterfaces
EchoionApiUtils
EchoionApi
EXPORT EchoionApiTargets
INCLUDES DESTINATION include
)
install(EXPORT EchoionApiTargets
FILE EchoionApiTargets.cmake
NAMESPACE Echoion::
DESTINATION lib/cmake/EchoionApi
)
# Create package config files
include(CMakePackageConfigHelpers)
write_basic_package_version_file(
"${CMAKE_CURRENT_BINARY_DIR}/EchoionApiConfigVersion.cmake"
VERSION ${PROJECT_VERSION}
NAMESPACE Echoion
BINARY_DIR ${PROJECT_BINARY_DIR}
INCLUDE_DIR ${PROJECT_SOURCE_DIR}/include
INCLUDE_DESTINATION include
COMPATIBILITY SameMajorVersion
DISABLE_VERSION_SUFFIX YES
)
file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/EchoionApiConfig.cmake"
"include(\"\${CMAKE_CURRENT_LIST_DIR}/EchoionApiTargets.cmake\")
")
install(FILES
"${CMAKE_CURRENT_BINARY_DIR}/EchoionApiConfig.cmake"
"${CMAKE_CURRENT_BINARY_DIR}/EchoionApiConfigVersion.cmake"
DESTINATION lib/cmake/EchoionApi
)
+165
View File
@@ -0,0 +1,165 @@
# API Reorganization Guide
## Directory Structure to Create
```
EchoionApi/include/echoion/api/
├── base/
│ └── Types.hpp # Error, Result, LogLevel, LogEntry, version constants
├── audio/
│ └── AudioTypes.hpp # AudioQuality, AudioFormat, AudioBuffer
├── track/
│ └── TrackTypes.hpp # TrackInfo, QueueEntry, PlaybackState, SearchResult
├── network/
│ └── NetworkTypes.hpp # HttpHeader, HttpRequest, HttpResponse, ProxyConfig
├── plugin/
│ └── PluginTypes.hpp # PluginEventType, PluginEvent, ClientInfo, ChannelInfo
├── config/
│ └── ConfigTypes.hpp # BotConfig, ServerConfig, SecurityConfig, AppConfig
├── rpc/
│ └── RpcTypes.hpp # RpcMethod, RpcRequest, RpcResponse, HotReloadState
├── youtube/
│ └── YouTubeTypes.hpp # YouTubeVideoInfo, YouTubePlaylistInfo, etc.
├── logger/
│ └── LoggerInterface.hpp # ILogger, LoggerRegistry, macros
├── eventbus/
│ └── EventBus.hpp # EventBus, all event types
├── database/
│ └── Database.hpp # Database interface
├── interfaces/
│ ├── CoreInterface.hpp # ICoreInterface, INetworkClient
│ └── PluginInterface.hpp # IPluginInterface
└── utils/
├── Cache.hpp # Cache interface
└── MemoryPool.hpp # MemoryPool interface
```
## Files to Move
### From root `include/echoion/api/` to subfolders:
| Current Location | New Location |
|-----------------|--------------|
| `Types.hpp` | `base/Types.hpp` |
| `AudioTypes.hpp` | `audio/AudioTypes.hpp` |
| `TrackTypes.hpp` | `track/TrackTypes.hpp` |
| `NetworkTypes.hpp` | `network/NetworkTypes.hpp` |
| `PluginTypes.hpp` | `plugin/PluginTypes.hpp` |
| `ConfigTypes.hpp` | `config/ConfigTypes.hpp` |
| `RpcTypes.hpp` | `rpc/RpcTypes.hpp` |
| `YouTubeTypes.hpp` | `youtube/YouTubeTypes.hpp` |
| `LoggerInterface.hpp` | `logger/LoggerInterface.hpp` |
| `EventBus.hpp` | `eventbus/EventBus.hpp` |
| `Database.hpp` | `database/Database.hpp` |
| `CoreInterface.hpp` | `interfaces/CoreInterface.hpp` |
| `Cache.hpp` | `utils/Cache.hpp` |
| `MemoryPool.hpp` | `utils/MemoryPool.hpp` |
## Files to Delete
- `AudioTypesOnly.hpp`
- `ConfigTypesOnly.hpp`
- `LoggerTypesOnly.hpp`
- `NetworkTypesOnly.hpp`
- `PluginTypesOnly.hpp`
- `RpcTypesOnly.hpp`
- `TrackTypesOnly.hpp`
- `YouTubeTypesOnly.hpp`
- `BaseTypes.hpp`
## Include Path Changes
### For Plugin (minimal):
**Before:**
```cpp
#include <echoion/api.hpp>
```
**After:**
```cpp
#include <Types.hpp>
#include <PluginTypes.hpp>
#include <CoreInterface.hpp>
```
The CMake target `Echoion::ApiPlugin` will add the correct include paths.
### For Core:
**Before:**
```cpp
#include <echoion/api/EventBus.hpp>
```
**After:**
```cpp
#include <EventBus.hpp>
```
The CMake target `Echoion::ApiEventBus` adds `eventbus/` to the include path.
## CMake Usage
### Plugin only needs:
```cmake
target_link_libraries(EchoionPlugin PRIVATE
Echoion::ApiBase
Echoion::ApiPlugin
Echoion::ApiInterfaces
)
```
### Core uses everything:
```cmake
target_link_libraries(EchoionCore PUBLIC
Echoion::ApiBase
Echoion::ApiAudio
Echoion::ApiTrack
Echoion::ApiNetwork
Echoion::ApiPlugin
Echoion::ApiConfig
Echoion::ApiRpc
Echoion::ApiYouTube
Echoion::ApiLogger
Echoion::ApiEventBus
Echoion::ApiDatabase
Echoion::ApiInterfaces
Echoion::ApiUtils
)
```
## Commands to Execute
Run these commands in the project root:
```bash
# Create directory structure
cd EchoionApi/include/echoion/api
mkdir -p base audio track network plugin config rpc youtube logger eventbus database interfaces utils
# Move files
mv Types.hpp base/
mv AudioTypes.hpp audio/
mv TrackTypes.hpp track/
mv NetworkTypes.hpp network/
mv PluginTypes.hpp plugin/
mv ConfigTypes.hpp config/
mv RpcTypes.hpp rpc/
mv YouTubeTypes.hpp youtube/
mv LoggerInterface.hpp logger/
mv EventBus.hpp eventbus/
mv Database.hpp database/
mv CoreInterface.hpp interfaces/
mv Cache.hpp utils/
mv MemoryPool.hpp utils/
# Remove old files
rm -f *Only.hpp BaseTypes.hpp
# Go back to project root
cd ../../../../..
# Create Export.hpp in interfaces (if not exists)
touch EchoionApi/include/echoion/api/interfaces/Export.hpp
```
+30 -17
View File
@@ -1,20 +1,33 @@
#pragma once
// Main Echoion API header - includes all types
// Main Echoion API header - backward compatibility
// Includes all submodules
#include "echoion/api/Types.hpp"
#include "echoion/api/AudioTypes.hpp"
#include "echoion/api/TrackTypes.hpp"
#include "echoion/api/NetworkTypes.hpp"
#include "echoion/api/PluginTypes.hpp"
#include "echoion/api/ConfigTypes.hpp"
// Note: ConfigManager is deprecated - config is now passed from Plugin to Core via initialize()
#include "echoion/api/RpcTypes.hpp"
#include "echoion/api/YouTubeTypes.hpp"
#include "echoion/api/LoggerInterface.hpp"
#include "echoion/api/CoreInterface.hpp"
#include "echoion/api/MemoryPool.hpp"
#include "echoion/api/Cache.hpp"
#include "echoion/api/EventBus.hpp"
#include "echoion/api/Database.hpp"
#include "echoion/api/Export.hpp"
// Base types
#include "api/base/Types.hpp"
// Granular type modules
#include "api/audio/AudioTypes.hpp"
#include "api/config/ConfigTypes.hpp"
#include "api/logger/LoggerInterface.hpp"
#include "api/network/NetworkInterface.hpp"
#include "api/network/NetworkTypes.hpp"
#include "api/plugin/PluginTypes.hpp"
#include "api/rpc/RpcTypes.hpp"
#include "api/track/TrackTypes.hpp"
#include "api/youtube/YouTubeTypes.hpp"
// Interfaces (decoupled)
#include "api/interfaces/CoreInterface.hpp"
#include "api/interfaces/OpaqueHandle.hpp"
#include "api/interfaces/PluginInterface.hpp"
// Utilities
#include "api/utils/MemoryPool.hpp"
// Core systems (for Core implementation only)
#include "api/database/Database.hpp"
#include "api/eventbus/EventBus.hpp"
// Export macros
#include "api/interfaces/Export.hpp"
-118
View File
@@ -1,118 +0,0 @@
#pragma once
#include "Types.hpp"
#include "MemoryPool.hpp"
#include <vector>
#include <memory>
#include <span>
namespace Echoion::Api {
enum class AudioFormat : uint8_t {
Unknown = 0,
MP3,
AAC,
Opus,
Vorbis,
FLAC,
WAV
};
enum class AudioQuality : uint8_t {
Low = 0, // 64-96 kbps
Medium, // 128-160 kbps
High, // 192-256 kbps
VeryHigh, // 320 kbps
Lossless // FLAC or equivalent
};
// Hardware acceleration types
enum class HwAccelType : uint8_t {
None = 0,
CUDA, // NVIDIA CUDA
VAAPI, // Video Acceleration API (Linux)
DXVA2, // DirectX Video Acceleration 2 (Windows)
D3D11VA, // Direct3D 11 Video Acceleration
VideoToolbox, // Apple VideoToolbox
Vulkan // Vulkan Video
};
struct AudioFrame {
std::vector<uint8_t> data;
std::chrono::milliseconds pts;
std::chrono::milliseconds duration;
bool isKeyFrame;
};
struct AudioStreamInfo {
AudioFormat format;
uint32_t sampleRate;
uint32_t channels;
uint32_t bitrate;
std::chrono::milliseconds duration;
std::optional<AudioQuality> quality;
bool hwAccelerated = false;
HwAccelType hwAccelType = HwAccelType::None;
};
// Zero-copy decoded audio using pooled memory (int16 for direct playback)
struct DecodedAudio {
// Use pooled buffer instead of std::vector for zero-copy
// Now using int16_t for direct TeamSpeak compatibility (no float conversion)
std::vector<int16_t> samples;
// Non-owning view into the data
Int16AudioView view;
uint32_t sampleRate;
uint32_t channels;
std::chrono::milliseconds timestamp;
// Backwards compatibility - returns the samples
[[nodiscard]] std::vector<int16_t> getSamples() const {
return samples;
}
// Check if valid
[[nodiscard]] bool isValid() const {
return !samples.empty();
}
// Apply volume in-place (int16 version)
void applyVolume(float volume) {
if (samples.empty()) return;
int32_t volInt = static_cast<int32_t>(volume * 32768);
for (auto& sample : samples) {
int32_t scaled = (static_cast<int32_t>(sample) * volInt) / 32768;
sample = static_cast<int16_t>(std::clamp(scaled, -32768, 32767));
}
// Update view to point to new data
view = Int16AudioView(samples.data(), samples.size(), channels);
}
};
// Hardware acceleration configuration
struct HwAccelConfig {
HwAccelType type = HwAccelType::None;
int deviceIndex = -1; // -1 for auto-select
std::optional<std::string> deviceName;
[[nodiscard]] bool isEnabled() const {
return type != HwAccelType::None;
}
};
// Audio processing options
struct AudioProcessOptions {
float volume = 1.0f;
bool normalize = false;
bool highPassFilter = false; // Remove DC offset
float highPassFreq = 20.0f; // Hz
bool limiter = false; // Prevent clipping
float limiterThreshold = 0.95f;
};
using AudioBuffer = std::vector<uint8_t>;
using AudioFramePtr = std::shared_ptr<AudioFrame>;
} // namespace Echoion::Api
-389
View File
@@ -1,389 +0,0 @@
#pragma once
#include "Types.hpp"
#include "NetworkTypes.hpp"
#include "TrackTypes.hpp"
#include <string>
#include <unordered_map>
#include <mutex>
#include <shared_mutex>
#include <chrono>
#include <optional>
#include <functional>
#include <list>
#include <memory>
namespace Echoion::Api {
// Cache entry with metadata
template<typename T>
struct CacheEntry {
T value;
std::chrono::system_clock::time_point created;
std::chrono::system_clock::time_point lastAccessed;
std::chrono::milliseconds ttl;
uint64_t accessCount = 0;
size_t size = 0; // Approximate memory size
[[nodiscard]] bool isExpired() const {
auto now = std::chrono::system_clock::now();
return (now - created) > ttl;
}
};
// Cache statistics
struct CacheStats {
size_t hits = 0;
size_t misses = 0;
size_t evictions = 0;
size_t inserts = 0;
size_t currentSize = 0;
size_t maxSize = 0;
size_t memoryUsage = 0;
double hitRate() const {
auto total = hits + misses;
return total > 0 ? static_cast<double>(hits) / total : 0.0;
}
};
// Eviction policy
enum class EvictionPolicy {
LRU, // Least Recently Used
LFU, // Least Frequently Used
FIFO, // First In First Out
TTL // Time To Live only
};
// LRU Cache implementation
template<typename Key, typename Value>
class LruCache {
public:
using Entry = CacheEntry<Value>;
using Loader = std::function<std::optional<Value>(const Key&)>;
explicit LruCache(size_t maxSize = 1000,
std::chrono::milliseconds defaultTtl = std::chrono::minutes(5),
EvictionPolicy policy = EvictionPolicy::LRU)
: maxSize_(maxSize)
, defaultTtl_(defaultTtl)
, policy_(policy) {}
// Get value from cache (with optional loader for cache-aside pattern)
[[nodiscard]] std::optional<Value> get(const Key& key, Loader loader = nullptr) {
std::unique_lock<std::shared_mutex> lock(mutex_);
auto it = cache_.find(key);
if (it != cache_.end()) {
// Check if expired
if (it->second.entry.isExpired()) {
// Remove expired entry
memoryUsage_ -= it->second.entry.size;
removeFromOrder(it->second.orderIt);
cache_.erase(it);
stats_.evictions++;
lock.unlock();
stats_.misses++;
// Try to load if loader provided
if (loader) {
auto value = loader(key);
if (value) {
put(key, *value);
return value;
}
}
return std::nullopt;
}
// Update access info
it->second.entry.lastAccessed = std::chrono::system_clock::now();
it->second.entry.accessCount++;
// Move to front (MRU) for LRU policy
if (policy_ == EvictionPolicy::LRU) {
order_.splice(order_.begin(), order_, it->second.orderIt);
}
stats_.hits++;
return it->second.entry.value;
}
lock.unlock();
stats_.misses++;
// Try to load if loader provided
if (loader) {
auto value = loader(key);
if (value) {
put(key, *value);
return value;
}
}
return std::nullopt;
}
// Put value into cache
void put(const Key& key, const Value& value,
std::optional<std::chrono::milliseconds> ttl = std::nullopt,
size_t estimatedSize = 0) {
std::unique_lock<std::shared_mutex> lock(mutex_);
// Check if key already exists
auto it = cache_.find(key);
if (it != cache_.end()) {
// Update existing entry
memoryUsage_ -= it->second.entry.size;
it->second.entry.value = value;
it->second.entry.created = std::chrono::system_clock::now();
it->second.entry.lastAccessed = it->second.entry.created;
it->second.entry.ttl = ttl.value_or(defaultTtl_);
it->second.entry.size = estimatedSize;
memoryUsage_ += estimatedSize;
// Move to front for LRU
if (policy_ == EvictionPolicy::LRU) {
order_.splice(order_.begin(), order_, it->second.orderIt);
}
return;
}
// Evict entries if necessary
while (cache_.size() >= maxSize_ ||
(maxMemory_ > 0 && memoryUsage_ + estimatedSize > maxMemory_)) {
if (!evictOne()) {
break;
}
}
// Insert new entry
order_.push_front(key);
Entry entry{
.value = value,
.created = std::chrono::system_clock::now(),
.lastAccessed = entry.created,
.ttl = ttl.value_or(defaultTtl_),
.accessCount = 1,
.size = estimatedSize
};
cache_[key] = {
.entry = std::move(entry),
.orderIt = order_.begin()
};
memoryUsage_ += estimatedSize;
stats_.inserts++;
stats_.currentSize = cache_.size();
}
// Remove specific key
bool remove(const Key& key) {
std::unique_lock<std::shared_mutex> lock(mutex_);
auto it = cache_.find(key);
if (it == cache_.end()) {
return false;
}
memoryUsage_ -= it->second.entry.size;
removeFromOrder(it->second.orderIt);
cache_.erase(it);
stats_.currentSize = cache_.size();
return true;
}
// Clear all entries
void clear() {
std::unique_lock<std::shared_mutex> lock(mutex_);
cache_.clear();
order_.clear();
memoryUsage_ = 0;
stats_.currentSize = 0;
}
// Check if key exists (without updating access)
[[nodiscard]] bool contains(const Key& key) const {
std::shared_lock<std::shared_mutex> lock(mutex_);
return cache_.find(key) != cache_.end();
}
// Get cache statistics
[[nodiscard]] CacheStats getStats() const {
std::shared_lock<std::shared_mutex> lock(mutex_);
CacheStats stats = stats_;
stats.currentSize = cache_.size();
stats.maxSize = maxSize_;
stats.memoryUsage = memoryUsage_;
return stats;
}
// Reset statistics
void resetStats() {
std::unique_lock<std::shared_mutex> lock(mutex_);
stats_ = CacheStats{};
}
// Set max size
void setMaxSize(size_t maxSize) {
std::unique_lock<std::shared_mutex> lock(mutex_);
maxSize_ = maxSize;
// Evict if necessary
while (cache_.size() > maxSize_) {
if (!evictOne()) {
break;
}
}
}
// Set max memory (0 = unlimited)
void setMaxMemory(size_t maxMemory) {
std::unique_lock<std::shared_mutex> lock(mutex_);
maxMemory_ = maxMemory;
// Evict if necessary
if (maxMemory_ > 0) {
while (memoryUsage_ > maxMemory_) {
if (!evictOne()) {
break;
}
}
}
}
// Remove expired entries
size_t purgeExpired() {
std::unique_lock<std::shared_mutex> lock(mutex_);
size_t count = 0;
auto now = std::chrono::system_clock::now();
for (auto it = cache_.begin(); it != cache_.end();) {
if ((now - it->second.entry.created) > it->second.entry.ttl) {
memoryUsage_ -= it->second.entry.size;
removeFromOrder(it->second.orderIt);
it = cache_.erase(it);
count++;
} else {
++it;
}
}
stats_.evictions += count;
stats_.currentSize = cache_.size();
return count;
}
private:
struct Node {
Entry entry;
typename std::list<Key>::iterator orderIt;
};
bool evictOne() {
if (order_.empty()) {
return false;
}
Key keyToEvict;
switch (policy_) {
case EvictionPolicy::LRU:
case EvictionPolicy::FIFO:
// Evict from back (oldest/least recently used)
keyToEvict = order_.back();
break;
case EvictionPolicy::LFU: {
// Find least frequently used
auto minAccess = std::numeric_limits<uint64_t>::max();
for (const auto& [key, node] : cache_) {
if (node.entry.accessCount < minAccess) {
minAccess = node.entry.accessCount;
keyToEvict = key;
}
}
break;
}
case EvictionPolicy::TTL: {
// Find soonest to expire
auto now = std::chrono::system_clock::now();
auto minRemaining = std::chrono::milliseconds::max();
for (const auto& [key, node] : cache_) {
auto remaining = node.entry.ttl - (now - node.entry.created);
if (remaining < minRemaining) {
minRemaining = remaining;
keyToEvict = key;
}
}
break;
}
}
auto it = cache_.find(keyToEvict);
if (it != cache_.end()) {
memoryUsage_ -= it->second.entry.size;
removeFromOrder(it->second.orderIt);
cache_.erase(it);
stats_.evictions++;
return true;
}
return false;
}
void removeFromOrder(typename std::list<Key>::iterator it) {
order_.erase(it);
}
mutable std::shared_mutex mutex_;
std::unordered_map<Key, Node> cache_;
std::list<Key> order_; // For LRU/FIFO ordering
size_t maxSize_;
size_t maxMemory_ = 0;
size_t memoryUsage_ = 0;
std::chrono::milliseconds defaultTtl_;
EvictionPolicy policy_;
mutable CacheStats stats_;
};
// Type aliases for common cache types
using StringCache = LruCache<std::string, std::string>;
using HttpCache = LruCache<std::string, HttpResponse>;
using TrackCache = LruCache<std::string, TrackInfo>;
// Cache manager for multiple cache types
class CacheManager {
public:
static CacheManager& instance();
void initialize();
void shutdown();
// Get specific caches
[[nodiscard]] HttpCache& httpCache() { return httpCache_; }
[[nodiscard]] TrackCache& trackCache() { return trackCache_; }
[[nodiscard]] StringCache& metadataCache() { return metadataCache_; }
// Purge all expired entries
void purgeAllExpired();
// Clear all caches
void clearAll();
// Get combined stats
[[nodiscard]] std::unordered_map<std::string, CacheStats> getAllStats() const;
private:
CacheManager() = default;
HttpCache httpCache_{100, std::chrono::minutes(5)};
TrackCache trackCache_{500, std::chrono::hours(1)};
StringCache metadataCache_{1000, std::chrono::minutes(30)};
};
} // namespace Echoion::Api
-96
View File
@@ -1,96 +0,0 @@
#pragma once
#include "ConfigTypes.hpp"
#include <filesystem>
#include <mutex>
#include <shared_mutex>
#include <optional>
#include <functional>
namespace Echoion::Api {
/**
* @brief DEPRECATED: Global configuration manager
*
* This singleton pattern does NOT work across shared library boundaries.
* Each shared library (Plugin and Core) gets its own instance.
*
* NEW ARCHITECTURE:
* - Plugin loads config using ConfigLoader
- Plugin passes config to Core via CoreLoader::setConfig() -> Core::initialize()
* - Core stores config locally, updates via Core::updateConfig()
* - Config reload: Core calls plugin->reloadConfig() -> Core::updateConfig()
*
* This header is kept for backward compatibility but should not be used.
*/
class ConfigManager {
public:
using ConfigChangedCallback = std::function<void(const AppConfig&)>;
// Get singleton instance
static ConfigManager& instance();
// Delete copy/move
ConfigManager(const ConfigManager&) = delete;
ConfigManager& operator=(const ConfigManager&) = delete;
// Initialize with config file path (call once at startup)
[[nodiscard]] bool initialize(const std::filesystem::path& configPath);
// Initialize with default path (~/.config/echoion/config.json)
[[nodiscard]] bool initialize();
// Get current config (thread-safe)
[[nodiscard]] AppConfig getConfig() const;
// Get config by reference (faster, but hold lock briefly)
template<typename Func>
auto withConfig(Func&& func) const -> decltype(func(std::declval<const AppConfig&>())) {
std::shared_lock lock(mutex_);
return func(config_);
}
// Reload configuration from file
[[nodiscard]] bool reload();
// Save current configuration to file
[[nodiscard]] bool save();
// Update config (and optionally save)
void updateConfig(const AppConfig& config, bool saveToFile = true);
// Check if initialized
[[nodiscard]] bool isInitialized() const;
// Get config file path
[[nodiscard]] std::filesystem::path getConfigPath() const;
// Get default config path (~/.config/echoion/config.json)
[[nodiscard]] static std::filesystem::path getDefaultConfigPath();
// Subscribe to config changes
void onConfigChanged(ConfigChangedCallback callback);
// Create default config file if it doesn't exist
[[nodiscard]] bool createDefaultConfigIfNeeded();
private:
ConfigManager() = default;
~ConfigManager() = default;
mutable std::shared_mutex mutex_;
AppConfig config_;
std::filesystem::path configPath_;
std::atomic<bool> initialized_{false};
std::vector<ConfigChangedCallback> callbacks_;
mutable std::mutex callbackMutex_;
void notifyCallbacks();
[[nodiscard]] bool loadFromFileInternal();
[[nodiscard]] bool saveToFileInternal();
};
} // namespace Echoion::Api
// Convenience macro for accessing config
#define ECHOION_CONFIG (::Echoion::Api::ConfigManager::instance().getConfig())
-104
View File
@@ -1,104 +0,0 @@
#pragma once
#include "Types.hpp"
#include "NetworkTypes.hpp"
#include "echoion/api/AudioTypes.hpp"
#include <string>
#include <vector>
#include <map>
#include <optional>
#include <variant>
namespace Echoion::Api {
using ConfigValue = std::variant<
std::monostate,
bool,
int64_t,
double,
std::string,
std::vector<std::string>
>;
struct ConfigEntry {
std::string key;
ConfigValue value;
std::string description;
bool isSecret;
std::optional<ConfigValue> defaultValue;
std::optional<std::string> category;
};
struct BotConfig {
std::string botName = "Echoion";
std::string commandPrefix = "!";
float defaultVolume = 0.5f;
bool autoReconnect = true;
std::chrono::milliseconds reconnectDelay = 5000ms;
uint32_t maxReconnectAttempts = 5;
std::optional<ProxyConfig> proxy;
std::optional<std::string> youtubeApiKey;
AudioQuality preferredQuality = AudioQuality::High;
bool allowPlaylistImports = true;
uint32_t maxQueueSize = 100;
std::chrono::milliseconds trackTimeout = 30000ms;
uint16_t rpcPort = 8765; // WebSocket RPC server port for Desktop/API clients
// YouTube cookie file path for yt-dlp authentication
// See: https://github.com/yt-dlp/yt-dlp/wiki/Extractors#exporting-youtube-cookies
std::optional<std::string> youtubeCookiesPath;
// Alternative: use cookies from browser directly
// e.g., "chrome", "firefox", "safari", "edge"
std::optional<std::string> cookiesFromBrowser;
// yt-dlp concurrent resolution settings
// Number of concurrent yt-dlp processes for playlist track resolution (1-8, default: 4)
size_t ytDlpMaxConcurrent = 4;
// Enable async yt-dlp execution for better performance
bool ytDlpAsyncEnabled = true;
// URL shortening settings
bool enableUrlShortening = true; // Enable faumaray.ru link shortening
std::optional<std::string> urlShortenerApiUrl; // Custom URL shortener API endpoint
};
struct ServerConfig {
std::string address;
uint16_t port;
std::string serverPassword;
std::string nickname;
std::optional<std::string> defaultChannelId;
std::optional<std::string> channelPassword;
std::vector<uint64_t> adminGroups;
std::vector<uint64_t> djGroups;
std::vector<uint64_t> bannedGroups;
};
struct AdminCredentials {
std::string username;
std::string passwordHash;
std::optional<std::string> salt;
std::vector<std::string> permissions;
std::chrono::system_clock::time_point createdAt;
std::optional<std::chrono::system_clock::time_point> lastLogin;
bool isActive;
};
struct SecurityConfig {
bool requireAuthForAdmin = true;
uint32_t maxLoginAttempts = 5;
std::chrono::milliseconds lockoutDuration = 300000ms;
std::chrono::milliseconds sessionTimeout = 3600000ms;
bool enableAuditLog = true;
};
struct AppConfig {
BotConfig bot;
ServerConfig server;
SecurityConfig security;
std::map<std::string, ConfigEntry> custom;
};
} // namespace Echoion::Api
-164
View File
@@ -1,164 +0,0 @@
#pragma once
#include "Types.hpp"
#include "TrackTypes.hpp"
#include "PluginTypes.hpp"
#include "ConfigTypes.hpp"
#include "RpcTypes.hpp"
#include "NetworkTypes.hpp"
#include <filesystem>
#include <future>
#include <memory>
#include <functional>
#include <expected>
namespace Echoion::Api {
// Forward declarations
class IAudioDecoder;
class IMusicManager;
class ICommandManager;
class IPluginInterface;
class ICoreInterface;
// Network client interface
class INetworkClient {
public:
virtual ~INetworkClient() = default;
// Initialize with optional proxy
virtual Result<void> initialize(const std::optional<ProxyConfig>& proxy = std::nullopt) = 0;
virtual void shutdown() = 0;
// Synchronous requests
[[nodiscard]] virtual Result<HttpResponse> get(std::string_view url,
const std::vector<HttpHeader>& headers = {}) = 0;
[[nodiscard]] virtual Result<HttpResponse> post(std::string_view url,
std::string_view body, const std::vector<HttpHeader>& headers = {}) = 0;
[[nodiscard]] virtual Result<HttpResponse> request(const HttpRequest& req) = 0;
// Asynchronous requests
[[nodiscard]] virtual std::future<Result<HttpResponse>> getAsync(std::string_view url,
const std::vector<HttpHeader>& headers = {}) = 0;
[[nodiscard]] virtual std::future<Result<HttpResponse>> postAsync(std::string_view url,
std::string_view body, const std::vector<HttpHeader>& headers = {}) = 0;
[[nodiscard]] virtual std::future<Result<HttpResponse>> requestAsync(const HttpRequest& req) = 0;
// Proxy configuration
virtual void setProxy(const std::optional<ProxyConfig>& proxy) = 0;
[[nodiscard]] virtual std::optional<ProxyConfig> getProxy() const = 0;
virtual void clearProxy() = 0;
// Retry configuration
virtual void setRetryConfig(const RetryConfig& config) = 0;
[[nodiscard]] virtual RetryConfig getRetryConfig() const = 0;
};
// Plugin interface that the core will use
class IPluginInterface {
public:
virtual ~IPluginInterface() = default;
// Lifecycle
virtual Result<void> initialize() = 0;
virtual Result<void> shutdown() = 0;
// Client operations
[[nodiscard]] virtual Result<std::vector<ClientInfo>> getClients() = 0;
[[nodiscard]] virtual Result<std::optional<ClientInfo>>
getClient(uint64_t clientId) = 0;
virtual Result<void> moveClient(uint64_t clientId, uint64_t channelId) = 0;
virtual Result<void> kickClient(uint64_t clientId, const std::string& reason) = 0;
// Channel operations
[[nodiscard]] virtual Result<std::vector<ChannelInfo>> getChannels() const = 0;
[[nodiscard]] virtual Result<std::optional<ChannelInfo>> getChannel(uint64_t channelId) const = 0;
// Messaging
virtual Result<void> sendTextMessage(uint64_t targetId, const std::string& message) = 0;
virtual Result<void> sendChannelMessage(uint64_t channelId, const std::string& message) = 0;
virtual Result<void> sendServerMessage(const std::string& message) = 0;
// Audio
virtual Result<void> sendAudioData(const std::span<const short>& data) = 0;
virtual Result<void> setWhisperList(const std::vector<uint64_t>& clientIds) = 0;
// Server connection
virtual Result<void> connectToServer(const ServerConfig& config) = 0;
virtual Result<void> disconnectFromServer() = 0;
[[nodiscard]] virtual bool isConnected() const = 0;
virtual Result<void> reconnect() = 0;
// Event subscription
virtual void registerEventCallback(const EventCallback& callback) = 0;
virtual void unregisterEventCallback(const EventCallback& callback) = 0;
};
using PluginInterfacePtr = std::shared_ptr<IPluginInterface>;
// Core interface that the plugin will use to communicate with the core
class ICoreInterface {
public:
virtual ~ICoreInterface() = default;
// Lifecycle
// Plugin passes config file path, Core loads config internally (no AppConfig dependency in Plugin)
virtual Result<void> initialize(const std::filesystem::path& configPath) = 0;
virtual Result<void> shutdown() = 0;
virtual bool isInitialized() const noexcept = 0;
// Playback control
virtual Result<void> play(const TrackInfo& track) = 0;
virtual Result<void> pause() = 0;
virtual Result<void> resume() = 0;
virtual Result<void> stop() = 0;
virtual Result<void> skip(uint32_t count = 1) = 0;
virtual Result<void> seek(std::chrono::milliseconds position) = 0;
virtual Result<void> setVolume(float volume) = 0;
// Queue management
virtual Result<uint64_t> queueTrack(const TrackInfo& track, uint64_t clientId) = 0;
virtual Result<void> removeFromQueue(uint64_t queueId) = 0;
virtual Result<void> clearQueue() = 0;
[[nodiscard]] virtual Result<std::vector<QueueEntry>> getQueue() const = 0;
virtual Result<void> moveInQueue(uint64_t queueId, uint32_t newPosition) = 0;
// Track info
[[nodiscard]] virtual Result<std::optional<QueueEntry>> getCurrentTrack() const = 0;
[[nodiscard]] virtual Result<PlaybackState> getPlaybackState() const = 0;
// Playlist
virtual Result<void> loadPlaylist(const std::string& playlistId, uint64_t clientId) = 0;
virtual Result<std::vector<PlaylistInfo>> getPlaylists() const = 0;
// Configuration
virtual Result<void> updateConfig(const AppConfig& config) = 0;
[[nodiscard]] virtual Result<AppConfig> getConfig() const = 0;
// Hot reload
virtual Result<HotReloadState> prepareForHotReload() = 0;
virtual Result<void> restoreAfterHotReload(const HotReloadState& state) = 0;
// Event handling
virtual void registerEventCallback(const EventCallback& callback) = 0;
virtual void unregisterEventCallback(const EventCallback& callback) = 0;
// Plugin event processing
virtual Result<void> onPluginEvent(const PluginEvent& event) = 0;
// Status
[[nodiscard]] virtual std::string getVersion() const = 0;
[[nodiscard]] virtual std::chrono::system_clock::time_point getUptime() const = 0;
// Plugin interface
virtual void setPluginInterface(PluginInterfacePtr pluginInterface) = 0;
// Trigger auto-connect (call after setPluginInterface)
virtual void triggerAutoConnect() = 0;
};
using CoreInterfacePtr = std::shared_ptr<ICoreInterface>;
using CoreCreateFunc = std::function<CoreInterfacePtr()>;
using CoreDestroyFunc = std::function<void(ICoreInterface*)>;
} // namespace Echoion::Api
-225
View File
@@ -1,225 +0,0 @@
#pragma once
#include "Types.hpp"
#include "TrackTypes.hpp"
#include <string>
#include <vector>
#include <optional>
#include <functional>
#include <memory>
#include <mutex>
#include <shared_mutex>
#include <atomic>
namespace Echoion::Api {
// Forward declaration
class DatabaseImpl;
// Database configuration
struct DatabaseConfig {
std::string path = "echoion.db";
bool walMode = true; // Write-Ahead Logging for better concurrency
int maxConnections = 4;
std::chrono::seconds busyTimeout{5000};
};
// Playlist with tracks
struct Playlist {
uint64_t id;
std::string name;
std::string description;
uint64_t createdBy;
std::chrono::system_clock::time_point createdAt;
std::chrono::system_clock::time_point updatedAt;
std::vector<TrackInfo> tracks;
bool isPublic = false;
};
// Playback history entry
struct PlaybackHistoryEntry {
uint64_t id;
TrackInfo track;
uint64_t playedBy;
std::chrono::system_clock::time_point playedAt;
std::chrono::milliseconds duration; // How long it played
bool completed = false; // Did it play to the end
};
// User favorites
struct FavoriteTrack {
TrackInfo track;
uint64_t userId;
std::chrono::system_clock::time_point addedAt;
};
// Statistics
struct PlaybackStatistics {
uint64_t totalPlays = 0;
uint64_t totalTracks = 0;
uint64_t totalPlaytimeMs = 0;
std::optional<TrackInfo> mostPlayedTrack;
uint64_t mostPlayedCount = 0;
};
// Main database interface
class Database {
public:
Database();
~Database();
// Non-copyable
Database(const Database&) = delete;
Database& operator=(const Database&) = delete;
// Initialization
Api::Result<void> initialize(const DatabaseConfig& config = {});
void shutdown();
[[nodiscard]] bool isInitialized() const;
// Migrations
Api::Result<void> migrate(); // Run pending migrations
[[nodiscard]] int getCurrentVersion() const;
// ===== Playlists =====
// Create a new playlist
[[nodiscard]] Api::Result<uint64_t> createPlaylist(
const std::string& name,
const std::string& description,
uint64_t createdBy,
bool isPublic = false);
// Get playlist by ID
[[nodiscard]] Api::Result<std::optional<Playlist>> getPlaylist(uint64_t id);
// Get all playlists for a user
[[nodiscard]] Api::Result<std::vector<Playlist>> getUserPlaylists(uint64_t userId);
// Update playlist
Api::Result<void> updatePlaylist(uint64_t id,
const std::optional<std::string>& name = std::nullopt,
const std::optional<std::string>& description = std::nullopt,
const std::optional<bool>& isPublic = std::nullopt);
// Delete playlist
Api::Result<void> deletePlaylist(uint64_t id);
// Add track to playlist
Api::Result<void> addTrackToPlaylist(uint64_t playlistId,
const TrackInfo& track, uint32_t position = 0);
// Remove track from playlist
Api::Result<void> removeTrackFromPlaylist(uint64_t playlistId, uint64_t trackId);
// Reorder playlist tracks
Api::Result<void> reorderPlaylistTrack(uint64_t playlistId,
uint64_t trackId, uint32_t newPosition);
// ===== Playback History =====
// Record a playback
Api::Result<void> recordPlayback(const TrackInfo& track,
uint64_t playedBy,
std::chrono::milliseconds duration,
bool completed);
// Get playback history for a user
[[nodiscard]] Api::Result<std::vector<PlaybackHistoryEntry>> getPlaybackHistory(
uint64_t userId,
size_t limit = 100,
size_t offset = 0);
// Get recently played tracks
[[nodiscard]] Api::Result<std::vector<TrackInfo>> getRecentlyPlayed(
uint64_t userId,
size_t limit = 20);
// ===== Favorites =====
// Add track to favorites
Api::Result<void> addFavorite(uint64_t userId, const TrackInfo& track);
// Remove track from favorites
Api::Result<void> removeFavorite(uint64_t userId, const std::string& trackUrl);
// Check if track is favorited
[[nodiscard]] Api::Result<bool> isFavorite(uint64_t userId, const std::string& trackUrl);
// Get all favorites for a user
[[nodiscard]] Api::Result<std::vector<FavoriteTrack>> getFavorites(uint64_t userId);
// ===== Statistics =====
// Get playback statistics
[[nodiscard]] Api::Result<PlaybackStatistics> getStatistics(
uint64_t userId,
std::optional<std::chrono::system_clock::time_point> since = std::nullopt);
// Get most played tracks
[[nodiscard]] Api::Result<std::vector<std::pair<TrackInfo, uint64_t>>> getMostPlayed(
uint64_t userId,
size_t limit = 10);
// ===== Subscriptions =====
// Subscriber info
struct SubscriberInfo {
std::string uid;
std::string nickname;
std::chrono::system_clock::time_point subscribedAt;
};
// Add a subscriber (by UID)
Api::Result<void> addSubscriber(const std::string& uid, const std::string& nickname);
// Remove a subscriber (by UID)
Api::Result<void> removeSubscriber(const std::string& uid);
// Check if client is subscribed (by UID)
[[nodiscard]] Api::Result<bool> isSubscriber(const std::string& uid);
// Get all subscribers
[[nodiscard]] Api::Result<std::vector<SubscriberInfo>> getAllSubscribers();
// Get subscriber count
[[nodiscard]] Api::Result<size_t> getSubscriberCount();
// Clear all subscribers
Api::Result<void> clearAllSubscribers();
// ===== Cache Management =====
// Clear old history (keep last N entries)
Api::Result<void> trimHistory(size_t keepCount = 10000);
// Clear all data for a user
Api::Result<void> clearUserData(uint64_t userId);
// Vacuum database (reclaim space)
Api::Result<void> vacuum();
// ===== Raw Query (for advanced use) =====
using RowCallback = std::function<void(const std::vector<std::optional<std::string>>&)>;
Api::Result<void> executeQuery(const std::string& sql, RowCallback callback = nullptr);
private:
std::unique_ptr<DatabaseImpl> impl_;
mutable std::shared_mutex mutex_; // Shared mutex for read/write concurrency
std::atomic<bool> shutdown_{false}; // Flag to prevent operations after shutdown
};
// Database manager (singleton)
class DatabaseManager {
public:
static Database& instance();
static Api::Result<void> initialize(const DatabaseConfig& config = {});
static void shutdown();
private:
DatabaseManager() = default;
};
} // namespace Echoion::Api
-269
View File
@@ -1,269 +0,0 @@
#pragma once
#include "Types.hpp"
#include "echoion/api/ConfigTypes.hpp"
#include "echoion/api/PluginTypes.hpp"
#include "echoion/api/TrackTypes.hpp"
#include <functional>
#include <typeindex>
#include <unordered_map>
#include <vector>
#include <mutex>
#include <shared_mutex>
#include <queue>
#include <thread>
#include <condition_variable>
#include <atomic>
namespace Echoion::Api {
// Base event interface
struct IEvent {
virtual ~IEvent() = default;
virtual std::type_index getType() const = 0;
std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now();
};
// Typed event wrapper
template<typename T>
struct Event : IEvent {
T data;
explicit Event(T d) : data(std::move(d)) {}
std::type_index getType() const override {
return std::type_index(typeid(T));
}
};
// Event handler type
template<typename T>
using EventHandler = std::function<void(const T&)>;
// Subscription token for unsubscribing
class SubscriptionToken {
public:
using Id = uint64_t;
SubscriptionToken() = default;
explicit SubscriptionToken(Id id, std::type_index type,
std::weak_ptr<std::function<void(const std::shared_ptr<IEvent>&)>> handler)
: id_(id), type_(type), handler_(std::move(handler)) {}
[[nodiscard]] bool isValid() const { return id_ != 0; }
[[nodiscard]] Id getId() const { return id_; }
[[nodiscard]] std::type_index getType() const { return type_; }
private:
Id id_ = 0;
std::type_index type_ = std::type_index(typeid(void));
std::weak_ptr<std::function<void(const std::shared_ptr<IEvent>&)>> handler_;
friend class EventBus;
};
// Event bus for decoupled communication
class EventBus {
public:
EventBus();
~EventBus();
// Delete copy/move
EventBus(const EventBus&) = delete;
EventBus& operator=(const EventBus&) = delete;
EventBus(EventBus&&) = delete;
EventBus& operator=(EventBus&&) = delete;
// Start processing events
void start();
void stop();
// Publish an event (thread-safe)
template<typename T>
void publish(T event) {
auto evt = std::make_shared<Event<T>>(std::move(event));
{
std::lock_guard<std::mutex> lock(queueMutex_);
eventQueue_.push(evt);
}
queueCv_.notify_one();
}
// Subscribe to events (thread-safe)
template<typename T>
[[nodiscard]] SubscriptionToken subscribe(EventHandler<T> handler) {
auto wrappedHandler = std::make_shared<std::function<void(const std::shared_ptr<IEvent>&)>>(
[h = std::move(handler)](const std::shared_ptr<IEvent>& evt) {
if (auto typedEvt = std::dynamic_pointer_cast<Event<T>>(evt)) {
h(typedEvt->data);
}
}
);
std::type_index type(typeid(T));
auto id = nextId_++;
{
std::unique_lock<std::shared_mutex> lock(handlersMutex_);
handlers_[type][id] = wrappedHandler;
}
return SubscriptionToken(id, type, wrappedHandler);
}
// Unsubscribe from events
void unsubscribe(const SubscriptionToken& token);
// Process a single event immediately (for synchronous processing)
void processOne();
// Wait for and process one event (blocking)
bool waitAndProcessOne(std::chrono::milliseconds timeout);
// Clear all pending events
void clearQueue();
// Get number of pending events
[[nodiscard]] size_t getPendingEventCount() const;
private:
void processEvents();
mutable std::shared_mutex handlersMutex_;
std::unordered_map<std::type_index, std::unordered_map<SubscriptionToken::Id,
std::shared_ptr<std::function<void(const std::shared_ptr<IEvent>&)>>>> handlers_;
mutable std::mutex queueMutex_;
std::queue<std::shared_ptr<IEvent>> eventQueue_;
std::condition_variable queueCv_;
std::atomic<bool> running_{false};
std::atomic<bool> stopRequested_{false};
std::jthread eventThread_;
std::atomic<SubscriptionToken::Id> nextId_{1};
};
// Global event bus singleton
class GlobalEventBus {
public:
[[nodiscard]] static EventBus& instance();
private:
GlobalEventBus() = default;
};
// Common event types for Echoion
namespace Events {
// Playback events
struct PlaybackStarted {
TrackInfo track;
uint64_t clientId;
};
struct PlaybackPaused {
std::chrono::milliseconds position;
};
struct PlaybackResumed {
std::chrono::milliseconds position;
};
struct PlaybackStopped {};
struct TrackFinished {
TrackInfo track;
bool autoSkipped;
};
struct VolumeChanged {
float oldVolume;
float newVolume;
uint64_t changedByClientId;
};
// Queue events
struct TrackQueued {
TrackInfo track;
uint64_t queueId;
uint64_t addedByClientId;
uint32_t position;
};
struct TrackRemoved {
uint64_t queueId;
uint64_t removedByClientId;
};
struct QueueCleared {
uint64_t clearedByClientId;
};
struct QueueShuffled {
uint64_t triggeredByClientId;
};
// Connection events
struct ClientConnected {
ClientInfo client;
};
struct ClientDisconnected {
uint64_t clientId;
std::string reason;
};
struct ChannelChanged {
uint64_t clientId;
uint64_t oldChannelId;
uint64_t newChannelId;
};
// Error events
struct PlaybackError {
ErrorCode code;
std::string message;
std::optional<TrackInfo> track;
};
struct NetworkError {
std::string url;
ErrorCode code;
std::string message;
};
// Configuration events
struct ConfigReloaded {
BotConfig newConfig;
};
struct ConfigChanged {
std::string key;
std::string oldValue;
std::string newValue;
};
// Cache events
struct CacheHit {
std::string key;
std::string type;
};
struct CacheMiss {
std::string key;
std::string type;
};
struct CacheEvicted {
std::string key;
std::string reason;
};
} // namespace Events
// Helper macros for event publishing/subscribing
#define ECHOION_PUBLISH(event) Echoion::Api::GlobalEventBus::instance().publish(event)
#define ECHOION_SUBSCRIBE(type, handler) Echoion::Api::GlobalEventBus::instance().subscribe<type>(handler)
} // namespace Echoion::Api
-39
View File
@@ -1,39 +0,0 @@
#pragma once
#include "CoreInterface.hpp"
// Platform-specific export macros
#ifdef _WIN32
#ifdef ECHOION_API_EXPORT
#define ECHOION_API __declspec(dllexport)
#else
#define ECHOION_API __declspec(dllimport)
#endif
#else
#define ECHOION_API __attribute__((visibility("default")))
#endif
namespace Echoion::Api {
// Version information
constexpr uint32_t VERSION_MAJOR = 1;
constexpr uint32_t VERSION_MINOR = 0;
constexpr uint32_t VERSION_PATCH = 0;
constexpr const char* VERSION_STRING = "1.0.0";
// API export functions
extern "C" {
// Create a new core instance
ECHOION_API CoreInterfacePtr CreateCore();
// Destroy a core instance
ECHOION_API void DestroyCore(ICoreInterface* core);
// Get API version
ECHOION_API const char* GetApiVersion();
// Check if API is compatible
ECHOION_API bool IsApiCompatible(uint32_t major, uint32_t minor);
}
} // namespace Echoion::Api
-104
View File
@@ -1,104 +0,0 @@
#pragma once
#include "Types.hpp"
#include <string>
#include <functional>
#include <source_location>
#include <format>
namespace Echoion::Api {
// Logger interface for the user's custom logger implementation
class ILogger {
public:
virtual ~ILogger() = default;
// Core logging method
virtual void log(LogLevel level, std::string_view message,
std::source_location location = std::source_location::current()) = 0;
// Convenience methods
virtual void debug(std::string_view message,
std::source_location location = std::source_location::current()) {
log(LogLevel::Debug, message, location);
}
virtual void info(std::string_view message,
std::source_location location = std::source_location::current()) {
log(LogLevel::Info, message, location);
}
virtual void warning(std::string_view message,
std::source_location location = std::source_location::current()) {
log(LogLevel::Warning, message, location);
}
virtual void error(std::string_view message,
std::source_location location = std::source_location::current()) {
log(LogLevel::Error, message, location);
}
virtual void critical(std::string_view message,
std::source_location location = std::source_location::current()) {
log(LogLevel::Critical, message, location);
}
// Template method for formatted logging
template<typename... Args>
void logf(LogLevel level, std::format_string<Args...> fmt, Args&&... args,
std::source_location location = std::source_location::current()) {
log(level, std::format(fmt, std::forward<Args>(args)...), location);
}
// Set minimum log level
virtual void setMinLevel(LogLevel level) = 0;
[[nodiscard]] virtual LogLevel getMinLevel() const = 0;
// Register log callback
using LogCallback = std::function<void(const LogEntry&)>;
virtual void registerCallback(const LogCallback& callback) = 0;
virtual void unregisterCallback(const LogCallback& callback) = 0;
};
using LoggerPtr = std::shared_ptr<ILogger>;
// Global logger accessor
class LoggerRegistry {
public:
static LoggerRegistry& instance() {
static LoggerRegistry instance;
return instance;
}
void setLogger(LoggerPtr logger) { logger_ = std::move(logger); }
[[nodiscard]] LoggerPtr getLogger() const { return logger_; }
[[nodiscard]] bool hasLogger() const noexcept { return static_cast<bool>(logger_); }
private:
LoggerRegistry() = default;
LoggerPtr logger_;
};
// Convenience macros
#define ECHOION_LOG_DEBUG(msg) \
do { if (auto logger = Echoion::Api::LoggerRegistry::instance().getLogger()) \
logger->debug(msg); } while(0)
#define ECHOION_LOG_INFO(msg) \
do { if (auto logger = Echoion::Api::LoggerRegistry::instance().getLogger()) \
logger->info(msg); } while(0)
#define ECHOION_LOG_WARNING(msg) \
do { if (auto logger = Echoion::Api::LoggerRegistry::instance().getLogger()) \
logger->warning(msg); } while(0)
#define ECHOION_LOG_ERROR(msg) \
do { if (auto logger = Echoion::Api::LoggerRegistry::instance().getLogger()) \
logger->error(msg); } while(0)
#define ECHOION_LOG_CRITICAL(msg) \
do { if (auto logger = Echoion::Api::LoggerRegistry::instance().getLogger()) \
logger->critical(msg); } while(0)
} // namespace Echoion::Api
-292
View File
@@ -1,292 +0,0 @@
#pragma once
#include "Types.hpp"
#include <vector>
#include <memory>
#include <mutex>
#include <queue>
#include <atomic>
#include <cstring>
#include <cstdint>
namespace Echoion::Api {
// Custom allocator for audio buffers
template<typename T>
class MemoryPool {
public:
explicit MemoryPool(size_t blockSize, size_t initialBlocks = 64)
: blockSize_(blockSize)
, capacity_(initialBlocks) {
// Pre-allocate memory
storage_.resize(blockSize_ * capacity_);
// Initialize free list
for (size_t i = 0; i < capacity_; ++i) {
freeList_.push(&storage_[i * blockSize_]);
}
available_.store(capacity_, std::memory_order_relaxed);
}
~MemoryPool() = default;
// Non-copyable, non-movable
MemoryPool(const MemoryPool&) = delete;
MemoryPool& operator=(const MemoryPool&) = delete;
MemoryPool(MemoryPool&&) = delete;
MemoryPool& operator=(MemoryPool&&) = delete;
// Allocate a block
[[nodiscard]] T* acquire() {
std::lock_guard<std::mutex> lock(mutex_);
if (freeList_.empty()) {
// Grow pool if needed
grow();
}
if (freeList_.empty()) {
return nullptr; // Out of memory
}
T* block = freeList_.front();
freeList_.pop();
available_.fetch_sub(1, std::memory_order_relaxed);
return block;
}
// Release a block back to pool
void release(T* block) {
if (!block) return;
// Verify block belongs to this pool
if (!contains(block)) {
return; // Or assert/panic
}
std::lock_guard<std::mutex> lock(mutex_);
freeList_.push(block);
available_.fetch_add(1, std::memory_order_relaxed);
}
// Get available blocks count
[[nodiscard]] size_t available() const {
return available_.load(std::memory_order_relaxed);
}
// Get total capacity
[[nodiscard]] size_t capacity() const {
std::lock_guard<std::mutex> lock(mutex_);
return capacity_;
}
// Get block size
[[nodiscard]] size_t blockSize() const {
return blockSize_;
}
// Reserve additional blocks
void reserve(size_t additionalBlocks) {
std::lock_guard<std::mutex> lock(mutex_);
size_t oldCapacity = capacity_;
size_t newCapacity = capacity_ + additionalBlocks;
storage_.resize(blockSize_ * newCapacity);
// Add new blocks to free list
for (size_t i = oldCapacity; i < newCapacity; ++i) {
freeList_.push(&storage_[i * blockSize_]);
}
capacity_ = newCapacity;
available_.fetch_add(additionalBlocks, std::memory_order_relaxed);
}
private:
[[nodiscard]] bool contains(const T* block) const {
return block >= &storage_[0] &&
block <= &storage_[(capacity_ - 1) * blockSize_];
}
void grow() {
// Double the capacity
size_t additionalBlocks = capacity_;
reserve(additionalBlocks);
}
size_t blockSize_;
size_t capacity_;
std::vector<T> storage_;
std::queue<T*> freeList_;
mutable std::mutex mutex_;
std::atomic<size_t> available_;
};
// Smart pointer for pooled memory
template<typename T>
class PooledPtr {
public:
PooledPtr() = default;
PooledPtr(T* ptr, MemoryPool<T>* pool)
: ptr_(ptr), pool_(pool) {}
~PooledPtr() {
reset();
}
// Move semantics only
PooledPtr(PooledPtr&& other) noexcept
: ptr_(other.ptr_), pool_(other.pool_) {
other.ptr_ = nullptr;
other.pool_ = nullptr;
}
PooledPtr& operator=(PooledPtr&& other) noexcept {
if (this != &other) {
reset();
ptr_ = other.ptr_;
pool_ = other.pool_;
other.ptr_ = nullptr;
other.pool_ = nullptr;
}
return *this;
}
// Delete copy
PooledPtr(const PooledPtr&) = delete;
PooledPtr& operator=(const PooledPtr&) = delete;
[[nodiscard]] T* get() const { return ptr_; }
[[nodiscard]] T& operator*() const { return *ptr_; }
[[nodiscard]] T* operator->() const { return ptr_; }
[[nodiscard]] explicit operator bool() const { return ptr_ != nullptr; }
[[nodiscard]] T* release() {
T* tmp = ptr_;
ptr_ = nullptr;
pool_ = nullptr;
return tmp;
}
void reset() {
if (ptr_ && pool_) {
pool_->release(ptr_);
}
ptr_ = nullptr;
pool_ = nullptr;
}
private:
T* ptr_ = nullptr;
MemoryPool<T>* pool_ = nullptr;
};
// Specialized audio buffer pool for int16 (direct TeamSpeak compatibility)
class AudioBufferPool {
public:
static constexpr size_t DEFAULT_BUFFER_SIZE = 1920; // 48000Hz * 2ch * 20ms
static constexpr size_t DEFAULT_POOL_SIZE = 256; // ~1MB for int16 buffers
static AudioBufferPool& instance();
void initialize(size_t bufferSize = DEFAULT_BUFFER_SIZE,
size_t poolSize = DEFAULT_POOL_SIZE);
void shutdown();
// Get a buffer (returns nullptr if pool exhausted)
[[nodiscard]] PooledPtr<int16_t> acquireBuffer();
// Get buffer size
[[nodiscard]] size_t getBufferSize() const { return bufferSize_; }
// Get stats
[[nodiscard]] size_t getAvailableBuffers() const;
[[nodiscard]] size_t getTotalBuffers() const;
private:
AudioBufferPool() = default;
std::unique_ptr<MemoryPool<int16_t>> pool_;
size_t bufferSize_ = DEFAULT_BUFFER_SIZE;
};
// Zero-copy audio buffer view
template<typename T>
class AudioBufferView {
public:
AudioBufferView() = default;
AudioBufferView(T* data, size_t size, size_t channels = 2)
: data_(data), size_(size), channels_(channels) {}
[[nodiscard]] T* data() { return data_; }
[[nodiscard]] const T* data() const { return data_; }
[[nodiscard]] size_t size() const { return size_; }
[[nodiscard]] size_t channels() const { return channels_; }
[[nodiscard]] size_t samplesPerChannel() const { return size_ / channels_; }
[[nodiscard]] T* channel(size_t ch) {
return data_ + ch;
}
[[nodiscard]] T& sample(size_t frame, size_t ch) {
return data_[frame * channels_ + ch];
}
[[nodiscard]] const T& sample(size_t frame, size_t ch) const {
return data_[frame * channels_ + ch];
}
// Span for single channel
[[nodiscard]] std::span<T> getChannelSpan(size_t ch) {
return std::span<T>(data_ + ch, size_, channels_);
}
// Span for all data
[[nodiscard]] std::span<T> getSpan() {
return std::span<T>(data_, size_);
}
[[nodiscard]] bool empty() const { return data_ == nullptr || size_ == 0; }
void clear() {
if (data_) {
std::memset(data_, 0, size_ * sizeof(T));
}
}
// Apply gain in-place
void applyGain(float gain) {
if (!data_) return;
for (size_t i = 0; i < size_; ++i) {
data_[i] *= gain;
}
}
// Mix another buffer into this one
void mix(const AudioBufferView& other, float gain = 1.0f) {
if (!data_ || !other.data_) return;
size_t mixSize = std::min(size_, other.size_);
for (size_t i = 0; i < mixSize; ++i) {
data_[i] += other.data_[i] * gain;
}
}
private:
T* data_ = nullptr;
size_t size_ = 0;
size_t channels_ = 2;
};
// Audio buffer view types - using int16 (short) for direct TeamSpeak compatibility
using Int16AudioView = AudioBufferView<int16_t>;
// Deprecated: Float audio view is no longer used, all audio is int16
using FloatAudioView = AudioBufferView<float>;
} // namespace Echoion::Api
-145
View File
@@ -1,145 +0,0 @@
#pragma once
#include "Types.hpp"
#include <string>
#include <vector>
#include <map>
#include <optional>
#include <chrono>
#include <cctype>
namespace Echoion::Api {
enum class HttpMethod : uint8_t {
GET = 0,
POST,
PUT,
DELETE,
PATCH,
HEAD,
OPTIONS
};
enum class ProxyType : uint8_t {
HTTP = 0,
SOCKS5
};
struct ProxyConfig {
ProxyType type = ProxyType::HTTP;
std::string host;
uint16_t port;
std::optional<std::string> username;
std::optional<std::string> password;
std::optional<std::chrono::milliseconds> timeout;
[[nodiscard]] bool isValid() const noexcept {
return !host.empty() && port > 0;
}
[[nodiscard]] bool requiresAuth() const noexcept {
return username.has_value() && password.has_value();
}
[[nodiscard]] bool isSocks5() const noexcept {
return type == ProxyType::SOCKS5;
}
[[nodiscard]] bool operator==(const ProxyConfig& other) const = default;
[[nodiscard]] bool operator!=(const ProxyConfig& other) const = default;
};
struct HttpHeader {
std::string name;
std::string value;
};
struct HttpRequest {
std::string url;
HttpMethod method = HttpMethod::GET;
std::vector<HttpHeader> headers;
std::optional<std::vector<uint8_t>> body;
std::optional<ProxyConfig> proxy;
std::chrono::milliseconds timeout = 30000ms;
bool followRedirects = true;
uint32_t maxRedirects = 10;
};
struct HttpResponse {
int32_t statusCode;
// Using vector to support multiple headers with same name (e.g., Set-Cookie)
std::vector<std::pair<std::string, std::string>> headers;
std::string body;
std::chrono::milliseconds responseTime;
std::optional<std::string> contentType;
bool fromCache = false;
[[nodiscard]] bool isSuccess() const noexcept {
return statusCode >= 200 && statusCode < 300;
}
[[nodiscard]] bool isRedirect() const noexcept {
return statusCode >= 300 && statusCode < 400;
}
[[nodiscard]] bool isError() const noexcept {
return statusCode >= 400 || statusCode == 0;
}
[[nodiscard]] std::string bodyAsString() const {
return std::string(body.begin(), body.end());
}
// Helper to get first header value by name (case-insensitive)
[[nodiscard]] std::optional<std::string> getHeader(std::string_view name) const {
for (const auto& [key, value] : headers) {
if (key.size() == name.size()) {
bool match = true;
for (size_t i = 0; i < key.size(); ++i) {
if (std::tolower(static_cast<unsigned char>(key[i])) !=
std::tolower(static_cast<unsigned char>(name[i]))) {
match = false;
break;
}
}
if (match) return value;
}
}
return std::nullopt;
}
// Helper to get all header values by name (case-insensitive) - useful for Set-Cookie
[[nodiscard]] std::vector<std::string> getHeaders(std::string_view name) const {
std::vector<std::string> result;
for (const auto& [key, value] : headers) {
if (key.size() == name.size()) {
bool match = true;
for (size_t i = 0; i < key.size(); ++i) {
if (std::tolower(static_cast<unsigned char>(key[i])) !=
std::tolower(static_cast<unsigned char>(name[i]))) {
match = false;
break;
}
}
if (match) result.push_back(value);
}
}
return result;
}
};
struct RateLimitInfo {
uint32_t limit;
uint32_t remaining;
std::optional<std::chrono::system_clock::time_point> resetTime;
};
struct RetryConfig {
uint32_t maxRetries = 3;
std::chrono::milliseconds initialDelay = 1000ms;
std::chrono::milliseconds maxDelay = 30000ms;
float backoffMultiplier = 2.0f;
std::vector<int32_t> retryableStatusCodes = {408, 429, 500, 502, 503, 504};
};
} // namespace Echoion::Api
-107
View File
@@ -1,107 +0,0 @@
#pragma once
#include "Types.hpp"
#include "TrackTypes.hpp"
#include <string>
#include <vector>
#include <functional>
#include <memory>
namespace Echoion::Api {
enum class PluginEventType : uint8_t {
// Connection events
ClientConnected = 0,
ClientDisconnected,
ClientMoved,
// Chat events
TextMessageReceived,
// Audio events
VoiceDataReceived,
// Bot control events
PlayRequested,
PauseRequested,
SkipRequested,
StopRequested,
// Queue events
TrackQueued,
TrackRemoved,
QueueCleared,
QueueUpdated,
// State events
PlaybackStarted,
PlaybackPaused,
PlaybackResumed,
PlaybackStopped,
TrackFinished,
TrackSkipped,
VolumeChanged,
SeekPosition,
// System events
HotReloadRequested,
HotReloadCompleted,
ConfigurationChanged
};
struct PluginEvent {
PluginEventType type;
std::optional<std::string> clientName;
uint64_t clientId;
std::optional<uint64_t> targetChannelId;
std::optional<std::string> message;
std::optional<TrackInfo> trackInfo;
std::optional<float> volume;
std::optional<int> queuePosition;
std::chrono::system_clock::time_point timestamp;
};
struct ClientInfo {
uint64_t id;
std::string nickname;
std::optional<std::string> uniqueIdentifier;
uint64_t channelId;
bool isTalking;
bool isMuted;
bool isDeafened;
std::vector<uint64_t> serverGroups;
};
struct ChannelInfo {
uint64_t id;
std::string name;
std::optional<uint64_t> parentId;
uint64_t order;
bool isDefault;
bool hasPassword;
uint32_t maxClients;
uint32_t currentClients;
};
struct ServerInfo {
uint64_t id;
std::string name;
std::string welcomeMessage;
uint32_t maxClients;
uint32_t currentClients;
uint64_t defaultChannelId;
};
using EventCallback = std::function<void(const PluginEvent&)>;
using CommandHandler = std::function<void(uint64_t clientId, const std::vector<std::string>& args)>;
struct CommandInfo {
std::string name;
std::string description;
std::vector<std::string> aliases;
std::optional<std::string> usage;
bool requiresAdmin;
CommandHandler handler;
};
} // namespace Echoion::Api
-105
View File
@@ -1,105 +0,0 @@
#pragma once
#include "Types.hpp"
#include "TrackTypes.hpp"
#include "PluginTypes.hpp"
#include "ConfigTypes.hpp"
#include <string>
#include <vector>
#include <optional>
#include <functional>
namespace Echoion::Api {
enum class RpcMethod : uint8_t {
// Playback control
Play = 0,
Pause,
Resume,
Stop,
Skip,
Seek,
SetVolume,
// Queue management
QueueTrack,
RemoveFromQueue,
ClearQueue,
GetQueue,
MoveInQueue,
// Track info
GetCurrentTrack,
GetTrackInfo,
SearchTracks,
// Playlist
LoadPlaylist,
SavePlaylist,
GetPlaylists,
DeletePlaylist,
// Configuration
GetConfig,
SetConfig,
ReloadConfig,
// Plugin/Core management
GetStatus,
HotReload,
Shutdown,
// Admin
Authenticate,
Logout,
GetAuditLog,
ManageUsers
};
struct RpcRequest {
uint64_t id;
RpcMethod method;
std::optional<std::string> params;
std::optional<std::string> authToken;
std::chrono::system_clock::time_point timestamp;
};
struct RpcResponse {
uint64_t requestId;
bool success;
std::optional<std::string> result;
std::optional<std::string> error; // JSON string: {"code":N,"message":"...","source":"..."}
std::chrono::system_clock::time_point timestamp;
};
struct RpcNotification {
std::string event;
std::optional<std::string> data;
std::chrono::system_clock::time_point timestamp;
};
using RpcHandler = std::function<RpcResponse(const RpcRequest&)>;
struct RpcEndpoint {
RpcMethod method;
std::string name;
std::string description;
bool requiresAuth;
RpcHandler handler;
};
// Hot reload state preservation
struct HotReloadState {
PlaybackState playback;
std::vector<QueueEntry> queue;
std::optional<std::string> currentStreamUrl;
std::chrono::milliseconds playbackPosition;
BotConfig config;
std::map<std::string, std::string> sessionData;
[[nodiscard]] bool shouldPreservePlayback() const noexcept {
return playback.isPlaying && playback.currentTrack.has_value();
}
};
} // namespace Echoion::Api
-100
View File
@@ -1,100 +0,0 @@
#pragma once
#include "Types.hpp"
#include "AudioTypes.hpp"
#include <string>
#include <vector>
#include <chrono>
#include <optional>
namespace Echoion::Api {
enum class TrackSource : uint8_t {
Unknown = 0,
YouTube,
SoundCloud,
Spotify,
LocalFile,
URL
};
struct TrackInfo {
std::string id;
std::string title;
std::string artist;
std::string album;
std::optional<std::string> thumbnailUrl;
std::optional<std::chrono::milliseconds> duration;
TrackSource source;
std::string originalUrl;
std::optional<std::string> shortenedUrl; // faumaray.ru shortened link
std::optional<std::string> streamUrl;
std::optional<AudioStreamInfo> audioInfo;
std::chrono::system_clock::time_point addedAt;
std::string requestedBy;
// Format track as markdown link: [Title](shortenedUrl)
// Only uses shortened URL (faumaray), returns empty string if not available
[[nodiscard]] std::string formatWithLink() const {
if (shortenedUrl.has_value() && !shortenedUrl->empty()) {
return std::format("[{}]({})", title, *shortenedUrl);
}
return std::format("[{}]", title); // No link if no shortened URL
}
// Format track with artist and link
// Only uses shortened URL (faumaray), returns text only if not available
[[nodiscard]] std::string formatWithArtistAndLink() const {
std::string displayTitle = title;
if (!artist.empty()) {
displayTitle = std::format("{} by {}", title, artist);
}
if (shortenedUrl.has_value() && !shortenedUrl->empty()) {
return std::format("[{}]({})", displayTitle, *shortenedUrl);
}
return displayTitle; // No link if no shortened URL
}
};
struct PlaylistInfo {
std::string id;
std::string name;
std::string description;
std::optional<std::string> thumbnailUrl;
std::string owner;
std::vector<TrackInfo> tracks;
std::chrono::system_clock::time_point createdAt;
std::chrono::system_clock::time_point updatedAt;
};
struct QueueEntry {
uint64_t queueId;
TrackInfo track;
std::chrono::system_clock::time_point addedAt;
std::string addedBy;
bool isPlaying;
std::optional<std::chrono::milliseconds> position;
};
struct PlaybackState {
std::optional<QueueEntry> currentTrack;
std::vector<QueueEntry> queue;
bool isPlaying;
bool isPaused;
std::chrono::milliseconds position;
std::chrono::milliseconds buffered;
float volume;
bool repeat;
bool shuffle;
std::chrono::system_clock::time_point lastUpdate;
};
struct SearchResult {
std::vector<TrackInfo> tracks;
std::vector<PlaylistInfo> playlists;
std::string query;
std::optional<std::string> nextPageToken;
uint32_t totalResults;
};
} // namespace Echoion::Api
-74
View File
@@ -1,74 +0,0 @@
#pragma once
#include <cstdint>
#include <string>
#include <vector>
#include <optional>
#include <chrono>
#include <expected>
#include <format>
#include <thread>
namespace Echoion::Api {
using namespace std::chrono_literals;
enum class ErrorCode : uint32_t {
Success = 0,
InvalidArgument,
NotFound,
AlreadyExists,
NetworkError,
ParseError,
AudioError,
PluginError,
InvalidUrl,
NotAuthenticated,
Unauthorized,
PermissionDenied,
ServiceUnavailable,
DatabaseError,
NotSupported,
NotInitialized,
UnknownError
};
struct Error {
ErrorCode code;
std::string message;
std::string source;
std::chrono::system_clock::time_point timestamp;
Error() = default;
Error(ErrorCode c, std::string_view msg, std::string_view src = "")
: code(c), message(msg), source(src), timestamp(std::chrono::system_clock::now()) {}
[[nodiscard]] std::string toString() const {
return std::format("[{}] {} (from: {})",
static_cast<uint32_t>(code), message, source);
}
};
template<typename T>
using Result = std::expected<T, Error>;
enum class LogLevel : uint8_t {
Debug = 0,
Info,
Warning,
Error,
Critical
};
struct LogEntry {
LogLevel level;
std::string message;
std::string source;
std::string sourceFile;
uint32_t sourceLine = 0;
std::string function;
std::thread::id threadId;
std::chrono::system_clock::time_point timestamp;
};
} // namespace Echoion::Api
-134
View File
@@ -1,134 +0,0 @@
#pragma once
#include "Types.hpp"
#include "TrackTypes.hpp"
#include <string>
#include <vector>
#include <optional>
#include <chrono>
namespace Echoion::Api {
// YouTube-specific types for the extracted client algorithm
struct YouTubeFormat {
std::string itag;
std::string mimeType;
std::optional<std::string> url;
std::optional<std::string> signatureCipher;
int32_t bitrate;
int32_t width;
int32_t height;
std::optional<std::string> qualityLabel;
std::optional<std::string> audioQuality;
int32_t audioSampleRate;
int32_t audioChannels;
bool hasVideo;
bool hasAudio;
};
struct YouTubeVideoDetails {
std::string videoId;
std::string title;
std::string author;
std::optional<std::chrono::seconds> lengthSeconds;
std::vector<YouTubeFormat> formats;
std::vector<YouTubeFormat> adaptiveFormats;
std::optional<std::string> playerJsUrl;
std::optional<std::string> streamingData;
};
struct YouTubeSearchResult {
std::string videoId;
std::string title;
std::string channelTitle;
std::optional<std::chrono::seconds> duration;
std::optional<std::string> thumbnailUrl;
std::string publishedAt;
uint64_t viewCount;
};
struct YouTubePlaylistItem {
std::string videoId;
std::string title;
std::optional<std::chrono::seconds> duration;
std::optional<std::string> thumbnailUrl;
};
struct YouTubePlaylist {
std::string playlistId;
std::string title;
std::string author;
std::vector<YouTubePlaylistItem> videos;
std::optional<std::string> continuationToken;
};
struct YouTubePlayerConfig {
std::string innertubeApiKey;
std::string innertubeClientName;
std::string innertubeClientVersion;
std::string contextClientName;
std::string contextClientVersion;
std::string visitorData;
std::optional<std::string> poToken;
};
struct YouTubeClientContext {
std::string hl = "en";
std::string gl = "US";
std::string clientName = "WEB";
std::string clientVersion;
std::optional<std::string> visitorData;
std::optional<std::string> userAgent;
};
// Convert YouTube types to generic TrackInfo
[[nodiscard]] inline TrackInfo ConvertToTrackInfo(const YouTubeVideoDetails& details) {
TrackInfo info;
info.id = details.videoId;
info.title = details.title;
info.artist = details.author;
if (details.lengthSeconds.has_value()) {
info.duration = std::chrono::milliseconds(*details.lengthSeconds * 1000);
}
info.source = TrackSource::YouTube;
info.originalUrl = "https://youtube.com/watch?v=" + details.videoId;
return info;
}
[[nodiscard]] inline TrackInfo ConvertToTrackInfo(const YouTubeSearchResult& result) {
TrackInfo info;
info.id = result.videoId;
info.title = result.title;
info.artist = result.channelTitle;
if (result.duration.has_value()) {
info.duration = std::chrono::milliseconds(*result.duration * 1000);
}
info.thumbnailUrl = result.thumbnailUrl;
info.source = TrackSource::YouTube;
info.originalUrl = "https://youtube.com/watch?v=" + result.videoId;
return info;
}
[[nodiscard]] inline PlaylistInfo ConvertToPlaylistInfo(const YouTubePlaylist& playlist) {
PlaylistInfo info;
info.id = playlist.playlistId;
info.name = playlist.title;
info.owner = playlist.author;
// Convert playlist items to tracks
for (const auto& item : playlist.videos) {
TrackInfo track;
track.id = item.videoId;
track.title = item.title;
track.source = TrackSource::YouTube;
track.originalUrl = "https://youtube.com/watch?v=" + item.videoId;
if (item.duration.has_value()) {
track.duration = std::chrono::milliseconds(*item.duration * 1000);
}
track.thumbnailUrl = item.thumbnailUrl;
info.tracks.push_back(std::move(track));
}
return info;
}
} // namespace Echoion::Api
+122
View File
@@ -0,0 +1,122 @@
#pragma once
#include <MemoryPool.hpp>
#include <chrono>
#include <cstdint>
namespace Echoion::Api
{
enum class AudioFormat : uint8_t {
Unknown = 0,
MP3,
AAC,
Opus,
Vorbis,
FLAC,
WAV
};
enum class AudioQuality : uint8_t {
Low = 0, // 64-96 kbps
Medium, // 128-160 kbps
High, // 192-256 kbps
VeryHigh, // 320 kbps
Lossless // FLAC or equivalent
};
// Hardware acceleration types
enum class HwAccelType : uint8_t {
None = 0,
CUDA, // NVIDIA CUDA
VAAPI, // Video Acceleration API (Linux)
DXVA2, // DirectX Video Acceleration 2 (Windows)
D3D11VA, // Direct3D 11 Video Acceleration
VideoToolbox, // Apple VideoToolbox
Vulkan // Vulkan Video
};
struct AudioFrame {
std::vector<uint8_t> data;
std::chrono::milliseconds pts;
std::chrono::milliseconds duration;
bool isKeyFrame;
};
struct AudioStreamInfo {
AudioFormat format;
uint32_t sampleRate;
uint32_t channels;
uint32_t bitrate;
std::chrono::milliseconds duration;
std::optional<AudioQuality> quality;
bool hwAccelerated = false;
HwAccelType hwAccelType = HwAccelType::None;
};
// Zero-copy decoded audio using pooled memory (int16 for direct playback)
struct DecodedAudio {
// Use pooled buffer instead of std::vector for zero-copy
// Now using int16_t for direct TeamSpeak compatibility (no float
// conversion)
std::vector<int16_t> samples;
// Non-owning view into the data
Int16AudioView view;
uint32_t sampleRate;
uint32_t channels;
std::chrono::milliseconds timestamp;
// Backwards compatibility - returns the samples
[[nodiscard]] std::vector<int16_t> getSamples() const
{
return samples;
}
// Check if valid
[[nodiscard]] bool isValid() const { return !samples.empty(); }
// Apply volume in-place (int16 version)
void applyVolume(float volume)
{
if (samples.empty()) {
return;
}
int32_t volInt = static_cast<int32_t>(volume * 32768);
for (auto& sample : samples) {
int32_t scaled =
(static_cast<int32_t>(sample) * volInt) / 32768;
sample =
static_cast<int16_t>(std::clamp(scaled, -32768, 32767));
}
// Update view to point to new data
view = Int16AudioView(samples.data(), samples.size(), channels);
}
};
// Hardware acceleration configuration
struct HwAccelConfig {
HwAccelType type = HwAccelType::None;
int deviceIndex = -1; // -1 for auto-select
std::optional<std::string> deviceName;
[[nodiscard]] bool isEnabled() const
{
return type != HwAccelType::None;
}
};
// Audio processing options
struct AudioProcessOptions {
float volume = 1.0f;
bool normalize = false;
bool highPassFilter = false; // Remove DC offset
float highPassFreq = 20.0f; // Hz
bool limiter = false; // Prevent clipping
float limiterThreshold = 0.95f;
};
using AudioBuffer = std::vector<uint8_t>;
using AudioFramePtr = std::shared_ptr<AudioFrame>;
} // namespace Echoion::Api
+34
View File
@@ -0,0 +1,34 @@
#pragma once
#include <cstdint>
#include <string>
#include <vector>
namespace Echoion::Api
{
// Opaque state blob - contents are internal to Core
// Plugin should NEVER inspect or modify the data field
struct StateBlob {
std::vector<uint8_t>
data; // Serialized state data (JSON using glaze)
uint32_t version = 0; // Format version (for logging/debugging only)
std::string timestamp; // ISO 8601 timestamp when saved
bool empty() const { return data.empty(); }
size_t size() const { return data.size(); }
// Clear the state
void clear()
{
data.clear();
version = 0;
timestamp.clear();
}
};
// Constants for state management
constexpr uint32_t MAX_SUPPORTED_STATE_VERSION_AGE =
10; // Support 10 versions back
constexpr uint32_t STATE_VERSION_NONE = 0;
} // namespace Echoion::Api
+140
View File
@@ -0,0 +1,140 @@
#pragma once
#include <Void/Functional/Result.hpp>
#include <chrono>
#include <cstdint>
#include <expected>
#include <format>
#include <memory>
#include <optional>
#include <string>
#include <thread>
#include <vector>
namespace Echoion::Api
{
// Version constants
inline constexpr uint32_t VERSION_MAJOR = 1;
inline constexpr uint32_t VERSION_MINOR = 0;
inline constexpr uint32_t VERSION_PATCH = 0;
inline constexpr const char* VERSION_STRING = "1.0.0";
using namespace std::chrono_literals;
enum class ErrorCode : uint32_t {
Success = 0,
InvalidArgument,
NotFound,
AlreadyExists,
NetworkError,
ParseError,
AudioError,
PluginError,
InvalidUrl,
NotAuthenticated,
Unauthorized,
PermissionDenied,
ServiceUnavailable,
DatabaseError,
NotSupported,
NotInitialized,
IncompatibleVersion, // State version incompatible
UnknownError
};
struct Error {
ErrorCode code = ErrorCode::UnknownError;
std::string message;
std::string source;
std::chrono::system_clock::time_point timestamp;
// Optional underlying cause (set via with_context), forming a chain.
std::shared_ptr<const Error> cause;
Error() = default;
Error(ErrorCode c, std::string_view msg, std::string_view src = "")
: code(c), message(msg), source(src),
timestamp(std::chrono::system_clock::now())
{
}
// Void::Result context API: wrap this error as the cause of a new
// contextual layer, preserving the original ErrorCode and source.
[[nodiscard]] Error with_context(std::string ctx) const&
{
Error e(code, ctx, source);
e.cause = std::make_shared<const Error>(*this);
return e;
}
[[nodiscard]] Error with_context(std::string ctx) &&
{
Error e(code, ctx, source);
e.cause = std::make_shared<const Error>(std::move(*this));
return e;
}
[[nodiscard]] std::string toString() const
{
std::string out =
std::format("[{}] {} (from: {})",
static_cast<uint32_t>(code), message, source);
for (const Error* c = cause.get(); c; c = c->cause.get()) {
out += std::format("\n caused by: {}", c->message);
}
return out;
}
};
// Result<T> aliases Void::Result with Echoion's domain Error (which keeps
// the ErrorCode used across RPC and error handling). Void::Result::Result
// is itself std::expected<T, E>, so existing call sites are unaffected and
// Void::Result::ok/fail/with_context all work with Api::Error.
template <typename T>
using Result = Void::Result::Result<T, Error>;
enum class LogLevel : uint8_t { Debug = 0, Info, Warning, Error, Critical };
inline constexpr std::string LogLevelToString(const LogLevel level) noexcept
{
switch (level) {
case LogLevel::Debug:
return "Debug";
case LogLevel::Info:
return "Info";
case LogLevel::Warning:
return "Warning";
case LogLevel::Error:
return "Error";
case LogLevel::Critical:
return "Critical";
}
}
inline constexpr LogLevel StringToLogLevel(const std::string level) noexcept
{
if (level == "Info") {
return LogLevel::Info;
} else if (level == "Warning") {
return LogLevel::Warning;
} else if (level == "Error") {
return LogLevel::Error;
} else if (level == "Critical") {
return LogLevel::Critical;
}
return LogLevel::Debug;
}
struct LogEntry {
LogLevel level;
std::string message;
std::string source;
std::string sourceFile;
uint32_t sourceLine = 0;
std::string function;
std::thread::id threadId;
std::chrono::system_clock::time_point timestamp;
};
} // namespace Echoion::Api
@@ -0,0 +1,111 @@
#pragma once
#ifndef PLUGIN
#include "ConfigTypes.hpp"
#include <atomic>
#include <filesystem>
#include <functional>
#include <mutex>
#include <optional>
#include <shared_mutex>
namespace Echoion::Api
{
class ConfigManager
{
public:
using ConfigChangedCallback = std::function<void(const AppConfig&)>;
// Get singleton instance
static ConfigManager& instance();
// Delete copy/move
ConfigManager(const ConfigManager&) = delete;
ConfigManager& operator=(const ConfigManager&) = delete;
// Initialize with config file path (call once at startup)
[[nodiscard]] bool
initialize(const std::filesystem::path& configPath);
// Initialize with default path (~/.config/echoion/config.json)
[[nodiscard]] bool initialize();
// Get current config (thread-safe)
[[nodiscard]] AppConfig getConfig() const;
// Get config by reference (faster, but hold lock briefly)
template <typename Func>
auto withConfig(Func&& func) const
-> decltype(func(std::declval<const AppConfig&>()))
{
std::shared_lock lock(mutex_);
return func(config_);
}
// Direct accessors for config sections (convenience methods)
[[nodiscard]] const BotConfig& getBot() const;
[[nodiscard]] const YouTubeConfig& getYouTube() const;
[[nodiscard]] const NetworkConfig& getNetwork() const;
[[nodiscard]] const TeamSpeakConfig& getTeamSpeak() const;
[[nodiscard]] const SecurityConfig& getSecurity() const;
[[nodiscard]] const FeaturesConfig& getFeatures() const;
[[nodiscard]] const AdvancedConfig& getAdvanced() const;
// Reload configuration from file
[[nodiscard]] bool reload();
// Save current configuration to file
[[nodiscard]] bool save();
// Update config (and optionally save)
void updateConfig(const AppConfig& config, bool saveToFile = true);
// Check if initialized
[[nodiscard]] bool isInitialized() const;
// Get config file path
[[nodiscard]] std::filesystem::path getConfigPath() const;
// Get default config path (~/.config/echoion/config.json)
[[nodiscard]] static std::filesystem::path getDefaultConfigPath();
// Subscribe to config changes
void onConfigChanged(ConfigChangedCallback callback);
// Create default config file if it doesn't exist
[[nodiscard]] bool createDefaultConfigIfNeeded();
private:
ConfigManager() = default;
~ConfigManager() = default;
mutable std::shared_mutex mutex_;
AppConfig config_;
std::filesystem::path configPath_;
std::atomic<bool> initialized_{false};
std::vector<ConfigChangedCallback> callbacks_;
mutable std::shared_mutex callbackMutex_;
void notifyCallbacks();
[[nodiscard]] bool loadFromFileInternal();
[[nodiscard]] bool saveToFileInternal();
};
} // namespace Echoion::Api
// Convenience macros for accessing config
#define ECHOION_CONFIG (::Echoion::Api::ConfigManager::instance().getConfig())
#define ECHOION_BOT (::Echoion::Api::ConfigManager::instance().getBot())
#define ECHOION_YOUTUBE (::Echoion::Api::ConfigManager::instance().getYouTube())
#define ECHOION_NETWORK (::Echoion::Api::ConfigManager::instance().getNetwork())
#define ECHOION_TEAMSPEAK \
(::Echoion::Api::ConfigManager::instance().getTeamSpeak())
#define ECHOION_SECURITY \
(::Echoion::Api::ConfigManager::instance().getSecurity())
#define ECHOION_FEATURES \
(::Echoion::Api::ConfigManager::instance().getFeatures())
#define ECHOION_ADVANCED \
(::Echoion::Api::ConfigManager::instance().getAdvanced())
#endif
+165
View File
@@ -0,0 +1,165 @@
#pragma once
#ifndef PLUGIN
#include "AudioTypes.hpp"
#include "NetworkTypes.hpp"
#include "Types.hpp"
#include <chrono>
#include <map>
#include <optional>
#include <string>
#include <variant>
#include <vector>
namespace Echoion::Api
{
using ConfigValue = std::variant<std::monostate, bool, int64_t, double,
std::string, std::vector<std::string>>;
struct ConfigEntry {
std::string key;
ConfigValue value;
std::string description;
bool isSecret;
std::optional<ConfigValue> defaultValue;
std::optional<std::string> category;
};
// Core Bot Settings
struct BotConfig {
std::string botName = "Echoion";
std::string commandPrefix = "!";
float defaultVolume = 0.5f;
uint32_t maxQueueSize = 100;
std::chrono::milliseconds trackTimeout =
std::chrono::milliseconds(30000);
// Reconnection settings
bool autoReconnect = true;
std::chrono::milliseconds reconnectDelay =
std::chrono::milliseconds(5000);
uint32_t maxReconnectAttempts = 5;
// Audio quality settings
AudioQuality preferredQuality = AudioQuality::High;
bool allowPlaylistImports = true;
};
// YouTube Integration Settings
struct YouTubeConfig {
std::optional<std::string> youtubeApiKey;
std::optional<std::string> youtubeCookiesPath;
std::optional<std::string> cookiesFromBrowser;
size_t ytDlpMaxConcurrent = 4;
bool ytDlpAsyncEnabled = true;
bool enableUrlShortening = true;
};
// Network & Proxy Settings
struct NetworkConfig {
std::optional<ProxyConfig> proxy;
bool rpcEnabled = true;
uint16_t rpcPort = 8765;
std::string rpcBindAddress = "127.0.0.1";
};
// TeamSpeak Server Connection
struct TeamSpeakConfig {
std::string address = "localhost";
uint16_t port = 9987;
std::string serverPassword;
std::string nickname = "EchoionBot";
std::optional<std::string> defaultChannelId;
std::optional<std::string> channelPassword;
std::vector<uint64_t> adminGroups;
std::vector<uint64_t> djGroups;
std::vector<uint64_t> bannedGroups;
};
// Security & Authentication
struct SecurityConfig {
bool requireAuthForAdmin = true;
uint32_t maxLoginAttempts = 5;
std::chrono::milliseconds lockoutDuration =
std::chrono::milliseconds(300000);
std::chrono::milliseconds sessionTimeout =
std::chrono::milliseconds(3600000);
bool enableAuditLog = true;
std::optional<std::string> apiKey;
bool allowCors = false;
std::vector<std::string> corsOrigins;
};
// Feature Toggles
struct FeaturesConfig {
bool enableHotReload = true;
bool enableAutoReload = false;
bool enableAutoUpdateCheck = true;
// Playback behavior
bool autoStartOnSubscribe = true;
bool pauseOnEmptySubscribers = true;
bool resumeOnSubscriberReturn = true;
// Queue management
std::string shuffleMode = "random";
std::string repeatMode = "off";
uint32_t maxHistorySize = 50;
};
// Advanced Settings
struct AdvancedConfig {
// Audio configuration
uint32_t sampleRate = 192000;
uint32_t channels = 2;
uint32_t bufferSize = 7680;
// Thread pool configuration
uint32_t commandThreadPoolSize = 4;
uint32_t networkThreadPoolSize = 4;
uint32_t decoderThreads = 2;
// Cache settings
bool cacheEnabled = true;
std::string cacheMaxSize = "1GB";
uint32_t cacheTTL = 86400;
uint32_t tempCleanupInterval = 3600;
};
// ServerConfig for Plugin interface (mirrors PluginTypes.hpp version)
struct ServerConfig {
std::string address;
uint16_t port = 0;
std::string serverPassword;
std::string nickname;
std::optional<std::string> defaultChannelId;
std::optional<std::string> channelPassword;
std::vector<uint64_t> adminGroups;
std::vector<uint64_t> djGroups;
std::vector<uint64_t> bannedGroups;
};
struct AdminCredentials {
std::string username;
std::string passwordHash;
std::optional<std::string> salt;
std::vector<std::string> permissions;
std::chrono::system_clock::time_point createdAt;
std::optional<std::chrono::system_clock::time_point> lastLogin;
bool isActive;
};
struct AppConfig {
BotConfig bot;
YouTubeConfig youtube;
NetworkConfig network;
TeamSpeakConfig teamspeak;
SecurityConfig security;
FeaturesConfig features;
AdvancedConfig advanced;
AdminCredentials admin;
std::map<std::string, ConfigEntry> custom;
};
} // namespace Echoion::Api
#endif
+299
View File
@@ -0,0 +1,299 @@
#pragma once
#include "TrackTypes.hpp"
#include "Types.hpp"
#include <atomic>
#include <functional>
#include <memory>
#include <mutex>
#include <optional>
#include <shared_mutex>
#include <string>
#include <vector>
namespace Echoion::Api
{
// Forward declaration
class DatabaseImpl;
// Database configuration
struct DatabaseConfig {
std::string path = "echoion.db";
bool walMode = true; // Write-Ahead Logging for better concurrency
int maxConnections = 4;
std::chrono::seconds busyTimeout{5000};
};
// Playlist with tracks
struct Playlist {
uint64_t id;
std::string name;
std::string description;
uint64_t createdBy;
std::chrono::system_clock::time_point createdAt;
std::chrono::system_clock::time_point updatedAt;
std::vector<TrackInfo> tracks;
bool isPublic = false;
std::string externalId; // YouTube playlist ID, etc.
};
// Playback history entry
struct PlaybackHistoryEntry {
uint64_t id;
TrackInfo track;
uint64_t playedBy;
std::chrono::system_clock::time_point playedAt;
std::chrono::milliseconds duration; // How long it played
bool completed = false; // Did it play to the end
};
// User favorites
struct FavoriteTrack {
TrackInfo track;
uint64_t userId;
std::chrono::system_clock::time_point addedAt;
};
// Statistics
struct PlaybackStatistics {
uint64_t totalPlays = 0;
uint64_t totalTracks = 0;
uint64_t totalPlaytimeMs = 0;
std::optional<TrackInfo> mostPlayedTrack;
uint64_t mostPlayedCount = 0;
};
// Main database interface
class Database
{
public:
Database();
~Database();
// Non-copyable
Database(const Database&) = delete;
Database& operator=(const Database&) = delete;
// Initialization
Api::Result<void> initialize(const DatabaseConfig& config = {});
void shutdown();
[[nodiscard]] bool isInitialized() const;
// Migrations
Api::Result<void> migrate(); // Run pending migrations
[[nodiscard]] int getCurrentVersion() const;
// ===== Playlists =====
// Create a new playlist
[[nodiscard]] Api::Result<uint64_t>
createPlaylist(const std::string& name,
const std::string& description,
uint64_t createdBy,
bool isPublic = false,
const std::string& externalId = "");
// Get or create playlist by external ID (e.g., YouTube playlist ID)
// Returns existing playlist ID if found, creates new one otherwise
[[nodiscard]] Api::Result<uint64_t>
getOrCreatePlaylistByExternalId(const std::string& externalId,
const std::string& name,
const std::string& description,
uint64_t createdBy,
bool isPublic = false);
// Get playlist by ID
[[nodiscard]] Api::Result<std::optional<Playlist>>
getPlaylist(uint64_t id);
// Get all playlists for a user
[[nodiscard]] Api::Result<std::vector<Playlist>>
getUserPlaylists(uint64_t userId);
// Update playlist
Api::Result<void> updatePlaylist(
uint64_t id,
const std::optional<std::string>& name = std::nullopt,
const std::optional<std::string>& description = std::nullopt,
const std::optional<bool>& isPublic = std::nullopt);
// Delete playlist
Api::Result<void> deletePlaylist(uint64_t id);
// Add track to playlist
Api::Result<void> addTrackToPlaylist(uint64_t playlistId,
const TrackInfo& track,
uint32_t position = 0);
// Remove track from playlist
Api::Result<void> removeTrackFromPlaylist(uint64_t playlistId,
uint64_t trackId);
// Reorder playlist tracks
Api::Result<void> reorderPlaylistTrack(uint64_t playlistId,
uint64_t trackId,
uint32_t newPosition);
// ===== Playback History =====
// Record a playback
Api::Result<void> recordPlayback(const TrackInfo& track,
uint64_t playedBy,
std::chrono::milliseconds duration,
bool completed);
// Get playback history for a user
[[nodiscard]] Api::Result<std::vector<PlaybackHistoryEntry>>
getPlaybackHistory(uint64_t userId,
size_t limit = 100,
size_t offset = 0);
// Get recently played tracks
[[nodiscard]] Api::Result<std::vector<TrackInfo>>
getRecentlyPlayed(uint64_t userId, size_t limit = 20);
// ===== Favorites =====
// Add track to favorites
Api::Result<void> addFavorite(uint64_t userId,
const TrackInfo& track);
// Remove track from favorites
Api::Result<void> removeFavorite(uint64_t userId,
const std::string& trackUrl);
// Check if track is favorited
[[nodiscard]] Api::Result<bool>
isFavorite(uint64_t userId, const std::string& trackUrl);
// Get all favorites for a user
[[nodiscard]] Api::Result<std::vector<FavoriteTrack>>
getFavorites(uint64_t userId);
// ===== Statistics =====
// Get playback statistics
[[nodiscard]] Api::Result<PlaybackStatistics> getStatistics(
uint64_t userId,
std::optional<std::chrono::system_clock::time_point> since =
std::nullopt);
// Get most played tracks
[[nodiscard]] Api::Result<
std::vector<std::pair<TrackInfo, uint64_t>>>
getMostPlayed(uint64_t userId, size_t limit = 10);
// ===== Subscriptions =====
// Subscriber info
struct SubscriberInfo {
std::string uid;
std::string nickname;
std::chrono::system_clock::time_point subscribedAt;
};
// Add a subscriber (by UID)
Api::Result<void> addSubscriber(const std::string& uid,
const std::string& nickname);
// Remove a subscriber (by UID)
Api::Result<void> removeSubscriber(const std::string& uid);
// Check if client is subscribed (by UID)
[[nodiscard]] Api::Result<bool>
isSubscriber(const std::string& uid);
// Get all subscribers
[[nodiscard]] Api::Result<std::vector<SubscriberInfo>>
getAllSubscribers();
// Get subscriber count
[[nodiscard]] Api::Result<size_t> getSubscriberCount();
// Clear all subscribers
Api::Result<void> clearAllSubscribers();
// ===== RPC Authentication =====
// RPC token info
struct RpcTokenInfo {
std::string uid;
std::string token;
std::chrono::system_clock::time_point createdAt;
std::chrono::system_clock::time_point lastUsedAt;
bool isActive = true;
};
// Generate new RPC token for subscriber
[[nodiscard]] Api::Result<std::string>
generateRpcToken(const std::string& uid);
// Get existing RPC token for subscriber (if any)
[[nodiscard]] Api::Result<std::optional<std::string>>
getExistingRpcToken(const std::string& uid);
// Validate RPC token
[[nodiscard]] Api::Result<bool>
validateRpcToken(const std::string& token);
// Get UID from RPC token
[[nodiscard]] Api::Result<std::optional<std::string>>
getUidFromRpcToken(const std::string& token);
// Revoke RPC token
Api::Result<void> revokeRpcToken(const std::string& token);
// Get subscriber UID by nickname (case-insensitive)
[[nodiscard]] Api::Result<std::optional<std::string>>
getSubscriberByNickname(const std::string& nickname);
// Get all subscriber UIDs
[[nodiscard]] Api::Result<std::vector<std::string>>
getAllSubscriberUids();
// ===== Cache Management =====
// Clear old history (keep last N entries)
Api::Result<void> trimHistory(size_t keepCount = 10000);
// Clear all data for a user
Api::Result<void> clearUserData(uint64_t userId);
// Vacuum database (reclaim space)
Api::Result<void> vacuum();
// ===== Raw Query (for advanced use) =====
using RowCallback = std::function<void(
const std::vector<std::optional<std::string>>&)>;
Api::Result<void> executeQuery(const std::string& sql,
RowCallback callback = nullptr);
private:
std::unique_ptr<DatabaseImpl> impl_;
mutable std::shared_mutex
mutex_; // Shared mutex for read/write concurrency
std::atomic<bool> shutdown_{
false}; // Flag to prevent operations after shutdown
};
// Database manager (singleton)
class DatabaseManager
{
public:
static Database& instance();
static Api::Result<void>
initialize(const DatabaseConfig& config = {});
static void shutdown();
private:
DatabaseManager() = default;
};
} // namespace Echoion::Api
+292
View File
@@ -0,0 +1,292 @@
#pragma once
#include "ConfigTypes.hpp"
#include "PluginTypes.hpp"
#include "TrackTypes.hpp"
#include "Types.hpp"
#include <Void/Async/EventBus.hpp>
#include <cstdint>
#include <functional>
#include <utility>
namespace Echoion::Api
{
// Event handler type
template <typename T> using EventHandler = std::function<void(const T&)>;
// Subscription handle. Wraps the underlying Void::EventBus handler id so
// existing call sites that hold a token keep compiling; pass it back to
// EventBus::unsubscribe() to detach.
class SubscriptionToken
{
public:
using Id = Void::EventBus::EventBus::HandlerId;
SubscriptionToken() = default;
explicit SubscriptionToken(Id id) : id_(id), valid_(true) {}
[[nodiscard]] bool isValid() const { return valid_; }
[[nodiscard]] Id getId() const { return id_; }
private:
Id id_ = 0;
bool valid_ = false;
};
// Type-keyed publish/subscribe bus. Delegates to Void::EventBus in
// asynchronous mode: publish() snapshots handlers and dispatches them on a
// background worker, so handlers that do I/O (RPC broadcast, DB writes)
// never block the publishing thread.
class EventBus
{
public:
EventBus() = default;
EventBus(const EventBus&) = delete;
EventBus& operator=(const EventBus&) = delete;
EventBus(EventBus&&) = delete;
EventBus& operator=(EventBus&&) = delete;
// The Void async worker runs from construction; kept for API
// compatibility. stop() drains any in-flight dispatch.
void start() {}
void stop() { bus_.flush(); }
template <typename T> void publish(T event)
{
bus_.publish<T>(event);
}
template <typename T>
SubscriptionToken subscribe(EventHandler<T> handler)
{
return SubscriptionToken{bus_.subscribe<T>(std::move(handler))};
}
void unsubscribe(const SubscriptionToken& token)
{
if (token.isValid()) {
bus_.unsubscribe(token.getId());
}
}
// Block until every event published before this call is delivered.
void flush() { bus_.flush(); }
private:
Void::EventBus::EventBus bus_{Void::EventBus::Mode::Async};
};
// Global event bus singleton
class GlobalEventBus
{
public:
[[nodiscard]] static EventBus& instance();
private:
GlobalEventBus() = default;
};
// Common event types for Echoion
namespace Events
{
// Playback events
struct PlaybackStarted {
TrackInfo track;
uint64_t clientId;
std::chrono::milliseconds position;
};
struct PlaybackPaused {
TrackInfo track;
std::chrono::milliseconds position;
};
struct PlaybackResumed {
TrackInfo track;
std::chrono::milliseconds position;
};
struct PlaybackStopped {
std::optional<TrackInfo> lastTrack;
std::chrono::milliseconds finalPosition;
};
struct PlaybackPositionChanged {
TrackInfo track;
std::chrono::milliseconds position;
std::chrono::milliseconds duration;
float progressPercent; // 0.0 - 100.0
};
struct TrackFinished {
TrackInfo track;
bool autoSkipped;
std::chrono::milliseconds finalPosition;
};
struct VolumeChanged {
float oldVolume;
float newVolume;
uint64_t changedByClientId;
};
struct ShuffleChanged {
bool enabled;
uint64_t changedByClientId;
};
struct RepeatChanged {
bool enabled;
uint64_t changedByClientId;
};
// Queue events
struct TrackQueued {
TrackInfo track;
uint64_t queueId;
uint64_t addedByClientId;
uint32_t position;
uint32_t queueLength;
};
struct TrackRemoved {
TrackInfo track;
uint64_t queueId;
uint64_t removedByClientId;
uint32_t queueLength;
};
struct QueueCleared {
uint64_t clearedByClientId;
uint32_t previousLength;
};
struct QueueShuffled {
uint64_t triggeredByClientId;
};
struct QueueReordered {
uint64_t queueId;
uint32_t oldPosition;
uint32_t newPosition;
uint64_t changedByClientId;
};
// Playlist events
struct PlaylistLoadStarted {
std::string playlistId;
uint64_t requestedByClientId;
uint64_t databasePlaylistId;
};
struct PlaylistTrackLoaded {
std::string playlistId;
TrackInfo track;
uint32_t loadedCount;
uint32_t totalCount;
uint64_t databasePlaylistId;
};
struct PlaylistLoadCompleted {
std::string playlistId;
uint32_t totalTracksLoaded;
bool success;
std::optional<std::string> error;
};
// Subscription events
struct UserSubscribed {
std::string uid;
std::string nickname;
uint64_t clientId;
};
struct UserUnsubscribed {
std::string uid;
std::string nickname;
uint64_t clientId;
};
// Connection events
struct ClientConnected {
ClientInfo client;
};
struct ClientDisconnected {
uint64_t clientId;
std::string reason;
};
struct ChannelChanged {
uint64_t clientId;
uint64_t oldChannelId;
uint64_t newChannelId;
};
// Error events
struct PlaybackError {
ErrorCode code;
std::string message;
std::optional<TrackInfo> track;
};
struct NetworkError {
std::string url;
ErrorCode code;
std::string message;
};
// Configuration events
struct ConfigReloaded {
BotConfig newConfig;
};
struct ConfigChanged {
std::string key;
std::string oldValue;
std::string newValue;
};
// Cache events
struct CacheHit {
std::string key;
std::string type;
};
struct CacheMiss {
std::string key;
std::string type;
};
struct CacheEvicted {
std::string key;
std::string reason;
};
// Database persistence events (for audit/logging)
struct DatabasePersisted {
std::string
entityType; // "queue", "playback", "subscription", etc.
std::string operation; // "insert", "update", "delete"
bool success;
std::optional<std::string> error;
};
} // namespace Events
// Helper macros for event publishing/subscribing
#define ECHOION_PUBLISH(event) \
Echoion::Api::GlobalEventBus::instance().publish(event)
#define ECHOION_SUBSCRIBE(type, handler) \
Echoion::Api::GlobalEventBus::instance().subscribe<type>(handler)
} // namespace Echoion::Api
@@ -0,0 +1,158 @@
#pragma once
#include "OpaqueHandle.hpp"
#include "PluginTypes.hpp"
#include "StateBlob.hpp"
#include "Types.hpp"
#include <PluginInterface.hpp>
#include <expected>
#include <filesystem>
#include <functional>
#include <future>
#include <memory>
#include <string>
#include <vector>
namespace Echoion::Api
{
// Forward declarations - Core provides implementations
struct TrackInfo;
struct QueueEntry;
struct PlaylistInfo;
// Minimal PlaybackState for Plugin
struct PlaybackSummary {
std::optional<TrackSummary> currentTrack;
bool isPlaying = false;
bool isPaused = false;
std::chrono::milliseconds position{0};
float volume = 0.5f;
bool repeat = false;
bool shuffle = false;
};
// Callback types for async operations
using TrackCallback = std::function<void(const TrackSummary&)>;
using StateCallback = std::function<void(const PlaybackSummary&)>;
// Forward declarations
class ICoreInterface;
using CoreInterfacePtr = std::shared_ptr<ICoreInterface>;
using CoreCreateFunc = std::function<CoreInterfacePtr()>;
using CoreDestroyFunc = std::function<void(ICoreInterface*)>;
// Core interface that the Plugin will use to communicate with the Core
// MINIMAL VERSION - breaks dependencies on Core-specific types
class ICoreInterface
{
public:
virtual ~ICoreInterface() = default;
// Lifecycle
// Plugin passes config file path, Core loads config internally
virtual Result<void>
initialize(const std::filesystem::path& configPath) = 0;
virtual Result<void> shutdown() = 0;
virtual bool isInitialized() const noexcept = 0;
// Playback control - using string identifiers instead of TrackInfo
virtual Result<void> play(const std::string& trackId) = 0;
virtual Result<void> pause() = 0;
virtual Result<void> resume() = 0;
virtual Result<void> stop() = 0;
virtual Result<void> skip(uint32_t count = 1) = 0;
virtual Result<void> seek(std::chrono::milliseconds position) = 0;
virtual Result<void> setVolume(float volume) = 0;
// Queue management - using string identifiers
virtual Result<uint64_t> queueTrack(const std::string& trackId,
uint64_t clientId) = 0;
virtual Result<void> removeFromQueue(uint64_t queueId) = 0;
virtual Result<void> clearQueue() = 0;
// Get queue as summaries (minimal data)
[[nodiscard]] virtual Result<std::vector<TrackSummary>>
getQueueSummaries() const = 0;
virtual Result<void> moveInQueue(uint64_t queueId,
uint32_t newPosition) = 0;
// Track info - return summaries instead of full TrackInfo
[[nodiscard]] virtual Result<std::optional<TrackSummary>>
getCurrentTrackSummary() const = 0;
[[nodiscard]] virtual Result<PlaybackSummary>
getPlaybackSummary() const = 0;
// Playlist - using string identifiers
virtual Result<void> loadPlaylist(const std::string& playlistId,
uint64_t clientId) = 0;
[[nodiscard]] virtual Result<std::vector<std::string>>
getPlaylistIds() const = 0;
// Configuration - using serialization instead of AppConfig
// Plugin sends JSON string, Core parses internally
virtual Result<void>
updateConfigJson(const std::string& configJson) = 0;
[[nodiscard]] virtual Result<std::string> getConfigJson() const = 0;
// Hot reload - using serialization instead of HotReloadState
// Returns opaque handle that Plugin just passes back
[[nodiscard]] virtual Result<std::string> prepareForHotReload() = 0;
virtual Result<void>
restoreAfterHotReload(const std::string& state) = 0;
// Decoupled state management - Plugin never knows state internals
// Core handles all serialization/deserialization internally
// State format can change without Plugin rebuild
[[nodiscard]] virtual StateBlob saveState() = 0;
virtual Result<void> restoreState(const StateBlob& state) = 0;
// Version info for state compatibility checking
[[nodiscard]] virtual uint32_t getStateFormatVersion() const = 0;
[[nodiscard]] virtual bool
canRestoreStateVersion(uint32_t version) const = 0;
// Event handling
virtual void
registerEventCallback(const EventCallback& callback) = 0;
virtual void
unregisterEventCallback(const EventCallback& callback) = 0;
// Plugin event processing
virtual Result<void> onPluginEvent(const PluginEvent& event) = 0;
// Status
[[nodiscard]] virtual std::string getVersion() const = 0;
[[nodiscard]] virtual std::chrono::system_clock::time_point
getUptime() const = 0;
// Plugin interface
virtual void
setPluginInterface(PluginInterfacePtr pluginInterface) = 0;
// Trigger auto-connect (call after setPluginInterface)
virtual void triggerAutoConnect() = 0;
// === Advanced methods for Core-to-Core communication (not for
// Plugin) === These are only called by Core implementations, not
// Plugin They use OpaqueHandle for type safety without exposing
// types
// Full TrackInfo access (for internal use)
[[nodiscard]] virtual Result<OpaqueHandle<TrackInfo>>
getCurrentTrackHandle() const = 0;
// Full QueueEntry access (for internal use)
[[nodiscard]] virtual Result<std::vector<OpaqueHandle<QueueEntry>>>
getQueueHandles() const = 0;
// Raw config access (for internal use)
[[nodiscard]] virtual Result<AppConfigHandle>
getConfigHandle() const = 0;
virtual Result<void>
updateConfigFromHandle(AppConfigHandle config) = 0;
};
} // namespace Echoion::Api
+34
View File
@@ -0,0 +1,34 @@
#pragma once
#include "CoreInterface.hpp"
// Platform-specific export macros
#ifdef _WIN32
#ifdef ECHOION_API_EXPORT
#define ECHOION_API __declspec(dllexport)
#else
#define ECHOION_API __declspec(dllimport)
#endif
#else
#define ECHOION_API __attribute__((visibility("default")))
#endif
namespace Echoion::Api
{
// API export functions
extern "C" {
// Create a new core instance
ECHOION_API CoreInterfacePtr CreateCore();
// Destroy a core instance
ECHOION_API void DestroyCore(ICoreInterface* core);
// Get API version
ECHOION_API const char* GetApiVersion();
// Check if API is compatible
ECHOION_API bool IsApiCompatible(uint32_t major, uint32_t minor);
}
} // namespace Echoion::Api
@@ -0,0 +1,58 @@
#pragma once
#include <cstdint>
#include <memory>
namespace Echoion::Api
{
// Opaque handle types to avoid including full headers
// These are used in interfaces to break dependencies
// Forward declarations for Core types (Plugin never needs full definition)
struct AppConfig;
struct HotReloadState;
struct PlaybackState;
struct TrackInfo;
struct QueueEntry;
// Opaque handle wrapper - type-safe void pointer replacement
template <typename T> class OpaqueHandle
{
public:
OpaqueHandle() = default;
explicit OpaqueHandle(std::shared_ptr<T> ptr) : ptr_(std::move(ptr))
{
}
[[nodiscard]] bool isValid() const { return ptr_ != nullptr; }
[[nodiscard]] T* get() const { return ptr_.get(); }
[[nodiscard]] T& operator*() const { return *ptr_; }
[[nodiscard]] T* operator->() const { return ptr_.get(); }
void reset() { ptr_.reset(); }
void reset(T* ptr) { ptr_.reset(ptr); }
[[nodiscard]] std::shared_ptr<T> toSharedPtr() const
{
return ptr_;
}
private:
std::shared_ptr<T> ptr_;
};
// Specific handle types
using AppConfigHandle = OpaqueHandle<AppConfig>;
using HotReloadStateHandle = OpaqueHandle<HotReloadState>;
using PlaybackStateHandle = OpaqueHandle<PlaybackState>;
using TrackInfoHandle = OpaqueHandle<TrackInfo>;
using QueueEntryHandle = OpaqueHandle<QueueEntry>;
// Serialization helpers for cross-boundary communication
using SerializedConfig = std::string; // JSON string
using SerializedState = std::string; // JSON string
} // namespace Echoion::Api
@@ -0,0 +1,81 @@
#pragma once
#include "PluginTypes.hpp"
#include "Types.hpp"
#include <expected>
#include <filesystem>
#include <functional>
#include <future>
#include <memory>
#include <span>
#include <string>
#include <vector>
namespace Echoion::Api
{
// Forward declarations
class IPluginInterface;
using PluginInterfacePtr = std::shared_ptr<IPluginInterface>;
// Plugin interface that the Core will use
// MINIMAL VERSION - only depends on Types.hpp and PluginTypes.hpp
// NO dependencies on TrackTypes, ConfigTypes, RpcTypes, etc.
class IPluginInterface
{
public:
virtual ~IPluginInterface() = default;
// Lifecycle
virtual Result<void> initialize() = 0;
virtual Result<void> shutdown() = 0;
// Client operations
[[nodiscard]] virtual Result<std::vector<ClientInfo>>
getClients() = 0;
[[nodiscard]] virtual Result<std::optional<ClientInfo>>
getClient(uint64_t clientId) = 0;
virtual Result<void> moveClient(uint64_t clientId,
uint64_t channelId) = 0;
virtual Result<void> kickClient(uint64_t clientId,
const std::string& reason) = 0;
// Channel operations
[[nodiscard]] virtual Result<std::vector<ChannelInfo>>
getChannels() const = 0;
[[nodiscard]] virtual Result<std::optional<ChannelInfo>>
getChannel(uint64_t channelId) const = 0;
// Messaging
virtual Result<void>
sendTextMessage(uint64_t targetId,
const std::string& message) = 0;
virtual Result<void>
sendChannelMessage(uint64_t channelId,
const std::string& message) = 0;
virtual Result<void>
sendServerMessage(const std::string& message) = 0;
// Audio
virtual Result<void>
sendAudioData(const std::span<const short>& data) = 0;
virtual Result<void>
setWhisperList(const std::vector<uint64_t>& clientIds) = 0;
// Server connection
// ServerConfig is defined in PluginTypes.hpp (self-contained)
virtual Result<void>
connectToServer(const ServerConfig& config) = 0;
virtual Result<void> disconnectFromServer() = 0;
[[nodiscard]] virtual bool isConnected() const = 0;
virtual Result<void> reconnect() = 0;
// Event subscription
virtual void
registerEventCallback(const EventCallback& callback) = 0;
virtual void
unregisterEventCallback(const EventCallback& callback) = 0;
};
} // namespace Echoion::Api
@@ -0,0 +1,166 @@
#pragma once
#include "Types.hpp"
#include <format>
#include <functional>
#include <iostream>
#include <source_location>
#include <string>
namespace Echoion::Api
{
// Logger interface for the user's custom logger implementation
class ILogger
{
public:
virtual ~ILogger() = default;
// Core logging method
virtual void log(LogLevel level, std::string_view message,
std::source_location location =
std::source_location::current()) = 0;
// Convenience methods
virtual void debug(
std::string_view message,
std::source_location location = std::source_location::current())
{
log(LogLevel::Debug, message, location);
}
virtual void info(
std::string_view message,
std::source_location location = std::source_location::current())
{
log(LogLevel::Info, message, location);
}
virtual void warning(
std::string_view message,
std::source_location location = std::source_location::current())
{
log(LogLevel::Warning, message, location);
}
virtual void error(
std::string_view message,
std::source_location location = std::source_location::current())
{
log(LogLevel::Error, message, location);
}
virtual void critical(
std::string_view message,
std::source_location location = std::source_location::current())
{
log(LogLevel::Critical, message, location);
}
// Template method for formatted logging
template <typename... Args>
void logf(
LogLevel level, std::format_string<Args...> fmt, Args&&... args,
std::source_location location = std::source_location::current())
{
log(level, std::format(fmt, std::forward<Args>(args)...),
location);
}
// Set minimum log level
virtual void setMinLevel(LogLevel level) = 0;
[[nodiscard]] virtual LogLevel getMinLevel() const = 0;
// Register log callback
using LogCallback = std::function<void(const LogEntry&)>;
virtual void registerCallback(const LogCallback& callback) = 0;
virtual void unregisterCallback(const LogCallback& callback) = 0;
};
using LoggerPtr = std::shared_ptr<ILogger>;
// Global logger accessor
class LoggerRegistry
{
public:
static LoggerRegistry& instance()
{
static LoggerRegistry instance;
return instance;
}
void setLogger(LoggerPtr logger) { logger_ = std::move(logger); }
[[nodiscard]] LoggerPtr getLogger() const { return logger_; }
[[nodiscard]] bool hasLogger() const noexcept
{
return static_cast<bool>(logger_);
}
private:
LoggerRegistry() = default;
LoggerPtr logger_;
};
// Convenience macros
#define ECHOION_LOG_DEBUG(msg) \
do { \
if (auto logger = \
Echoion::Api::LoggerRegistry::instance().getLogger(); \
logger) { \
logger->debug(msg); \
} else { \
std::cout << "[DEBUG] Echoion: " << std::string(msg) << std::endl; \
} \
} while (0)
#define ECHOION_LOG_INFO(msg) \
do { \
if (auto logger = \
Echoion::Api::LoggerRegistry::instance().getLogger(); \
logger) { \
logger->info(msg); \
} else { \
std::cout << "[INFO] Echoion: " << std::string(msg) << std::endl; \
} \
} while (0)
#define ECHOION_LOG_WARNING(msg) \
do { \
if (auto logger = \
Echoion::Api::LoggerRegistry::instance().getLogger(); \
logger) { \
logger->warning(msg); \
} else { \
std::cout << "[WARNING] Echoion: " << std::string(msg) \
<< std::endl; \
} \
} while (0)
#define ECHOION_LOG_ERROR(msg) \
do { \
if (auto logger = \
Echoion::Api::LoggerRegistry::instance().getLogger(); \
logger) { \
logger->error(msg); \
} else { \
std::cerr << "[ERROR] Echoion: " << std::string(msg) << std::endl; \
} \
} while (0)
#define ECHOION_LOG_CRITICAL(msg) \
do { \
if (auto logger = \
Echoion::Api::LoggerRegistry::instance().getLogger(); \
logger) { \
logger->critical(msg); \
} else { \
std::cerr << "[CRITICAL] Echoion: " << std::string(msg) \
<< std::endl; \
} \
} while (0)
} // namespace Echoion::Api
@@ -0,0 +1,56 @@
#pragma once
#include "NetworkTypes.hpp"
#include "Types.hpp"
#include <future>
#include <optional>
#include <string>
#include <vector>
namespace Echoion::Api
{
// Network client interface
class INetworkClient
{
public:
virtual ~INetworkClient() = default;
// Initialize with optional proxy
virtual Result<void> initialize(
const std::optional<ProxyConfig>& proxy = std::nullopt) = 0;
virtual void shutdown() = 0;
// Synchronous requests
[[nodiscard]] virtual Result<HttpResponse>
get(std::string_view url,
const std::vector<HttpHeader>& headers = {}) = 0;
[[nodiscard]] virtual Result<HttpResponse>
post(std::string_view url, std::string_view body,
const std::vector<HttpHeader>& headers = {}) = 0;
[[nodiscard]] virtual Result<HttpResponse>
request(const HttpRequest& req) = 0;
// Asynchronous requests
[[nodiscard]] virtual std::future<Result<HttpResponse>>
getAsync(std::string_view url,
const std::vector<HttpHeader>& headers = {}) = 0;
[[nodiscard]] virtual std::future<Result<HttpResponse>>
postAsync(std::string_view url, std::string_view body,
const std::vector<HttpHeader>& headers = {}) = 0;
[[nodiscard]] virtual std::future<Result<HttpResponse>>
requestAsync(const HttpRequest& req) = 0;
// Proxy configuration
virtual void setProxy(const std::optional<ProxyConfig>& proxy) = 0;
[[nodiscard]] virtual std::optional<ProxyConfig>
getProxy() const = 0;
virtual void clearProxy() = 0;
// Retry configuration
virtual void setRetryConfig(const RetryConfig& config) = 0;
[[nodiscard]] virtual RetryConfig getRetryConfig() const = 0;
};
} // namespace Echoion::Api
@@ -0,0 +1,167 @@
#pragma once
#include "Types.hpp"
#include <cctype>
#include <chrono>
#include <map>
#include <optional>
#include <string>
#include <vector>
namespace Echoion::Api
{
enum class HttpMethod : uint8_t {
GET = 0,
POST,
PUT,
DELETE,
PATCH,
HEAD,
OPTIONS
};
enum class ProxyType : uint8_t { HTTP = 0, SOCKS5 };
struct ProxyConfig {
ProxyType type = ProxyType::HTTP;
std::string host;
uint16_t port;
std::optional<std::string> username;
std::optional<std::string> password;
std::optional<std::chrono::milliseconds> timeout;
[[nodiscard]] bool isValid() const noexcept
{
return !host.empty() && port > 0;
}
[[nodiscard]] bool requiresAuth() const noexcept
{
return username.has_value() && password.has_value();
}
[[nodiscard]] bool isSocks5() const noexcept
{
return type == ProxyType::SOCKS5;
}
[[nodiscard]] bool
operator==(const ProxyConfig& other) const = default;
[[nodiscard]] bool
operator!=(const ProxyConfig& other) const = default;
};
struct HttpHeader {
std::string name;
std::string value;
};
struct HttpRequest {
std::string url;
HttpMethod method = HttpMethod::GET;
std::vector<HttpHeader> headers;
std::optional<std::vector<uint8_t>> body;
std::optional<ProxyConfig> proxy;
std::chrono::milliseconds timeout = 30000ms;
bool followRedirects = true;
uint32_t maxRedirects = 10;
};
struct HttpResponse {
int32_t statusCode;
// Using vector to support multiple headers with same name (e.g.,
// Set-Cookie)
std::vector<std::pair<std::string, std::string>> headers;
std::string body;
std::chrono::milliseconds responseTime;
std::optional<std::string> contentType;
bool fromCache = false;
[[nodiscard]] bool isSuccess() const noexcept
{
return statusCode >= 200 && statusCode < 300;
}
[[nodiscard]] bool isRedirect() const noexcept
{
return statusCode >= 300 && statusCode < 400;
}
[[nodiscard]] bool isError() const noexcept
{
return statusCode >= 400 || statusCode == 0;
}
[[nodiscard]] std::string bodyAsString() const
{
return std::string(body.begin(), body.end());
}
// Helper to get first header value by name (case-insensitive)
[[nodiscard]] std::optional<std::string>
getHeader(std::string_view name) const
{
for (const auto& [key, value] : headers) {
if (key.size() == name.size()) {
bool match = true;
for (size_t i = 0; i < key.size(); ++i) {
if (std::tolower(
static_cast<unsigned char>(key[i])) !=
std::tolower(
static_cast<unsigned char>(name[i]))) {
match = false;
break;
}
}
if (match) {
return value;
}
}
}
return std::nullopt;
}
// Helper to get all header values by name (case-insensitive) -
// useful for Set-Cookie
[[nodiscard]] std::vector<std::string>
getHeaders(std::string_view name) const
{
std::vector<std::string> result;
for (const auto& [key, value] : headers) {
if (key.size() == name.size()) {
bool match = true;
for (size_t i = 0; i < key.size(); ++i) {
if (std::tolower(
static_cast<unsigned char>(key[i])) !=
std::tolower(
static_cast<unsigned char>(name[i]))) {
match = false;
break;
}
}
if (match) {
result.push_back(value);
}
}
}
return result;
}
};
struct RateLimitInfo {
uint32_t limit;
uint32_t remaining;
std::optional<std::chrono::system_clock::time_point> resetTime;
};
struct RetryConfig {
uint32_t maxRetries = 3;
std::chrono::milliseconds initialDelay = 1000ms;
std::chrono::milliseconds maxDelay = 30000ms;
float backoffMultiplier = 2.0f;
std::vector<int32_t> retryableStatusCodes = {408, 429, 500,
502, 503, 504};
};
} // namespace Echoion::Api
+129
View File
@@ -0,0 +1,129 @@
#pragma once
#ifndef PLUGIN
#include <ConfigTypes.hpp>
#endif
#include <chrono>
#include <cstdint>
#include <functional>
#include <optional>
#include <string>
#include <vector>
namespace Echoion::Api
{
// ===== Plugin Event Types =====
enum class PluginEventType : uint8_t {
ClientConnected = 0,
ClientDisconnected,
ClientMoved,
TextMessageReceived,
VoiceDataReceived,
PlayRequested,
PauseRequested,
SkipRequested,
StopRequested,
TrackQueued,
TrackRemoved,
QueueCleared,
QueueUpdated,
PlaybackStarted,
PlaybackPaused,
PlaybackResumed,
PlaybackStopped,
TrackFinished,
TrackSkipped,
VolumeChanged,
SeekPosition,
HotReloadRequested,
HotReloadCompleted,
ConfigurationChanged
};
// Minimal track info for Plugin (no internal types)
struct TrackSummary {
std::string id;
std::string title;
std::string artist;
std::optional<std::chrono::milliseconds> duration;
};
struct PluginEvent {
PluginEventType type;
std::optional<std::string> clientName;
std::optional<TrackSummary>
trackSummary; // Opaque summary instead of full TrackInfo
uint64_t clientId = 0;
std::optional<uint64_t> targetChannelId;
std::optional<std::string> message;
std::optional<float> volume;
std::optional<int> queuePosition;
std::chrono::system_clock::time_point timestamp;
};
// ===== Connection Types =====
struct ClientInfo {
uint64_t id = 0;
std::string nickname;
std::optional<std::string> uniqueIdentifier;
uint64_t channelId = 0;
bool isTalking = false;
bool isMuted = false;
bool isDeafened = false;
std::vector<uint64_t> serverGroups;
};
struct ChannelInfo {
uint64_t id = 0;
std::string name;
std::optional<uint64_t> parentId;
uint64_t order = 0;
bool isDefault = false;
bool hasPassword = false;
uint32_t maxClients = 0;
uint32_t currentClients = 0;
};
struct ServerInfo {
uint64_t id = 0;
std::string name;
std::string welcomeMessage;
uint32_t maxClients = 0;
uint32_t currentClients = 0;
uint64_t defaultChannelId = 0;
};
// ServerConfig is needed for Plugin's connectToServer()
// This is a minimal version without dependencies on AudioTypes, etc.
// Available to both Core and Plugin
#ifdef PLUGIN
struct ServerConfig {
std::string address;
uint16_t port = 0;
std::string serverPassword;
std::string nickname;
std::optional<std::string> defaultChannelId;
std::optional<std::string> channelPassword;
std::vector<uint64_t> adminGroups;
std::vector<uint64_t> djGroups;
std::vector<uint64_t> bannedGroups;
};
#endif
// ===== Callback Types =====
using EventCallback = std::function<void(const PluginEvent&)>;
using CommandHandler = std::function<void(
uint64_t clientId, const std::vector<std::string>& args)>;
struct CommandInfo {
std::string name;
std::string description;
std::vector<std::string> aliases;
std::optional<std::string> usage;
bool requiresAdmin = false;
CommandHandler handler;
};
} // namespace Echoion::Api
+112
View File
@@ -0,0 +1,112 @@
#pragma once
#include "ConfigTypes.hpp"
#include "TrackTypes.hpp"
#include <functional>
#include <map>
#include <optional>
#include <string>
#include <vector>
namespace Echoion::Api
{
enum class RpcMethod : uint8_t {
// Playback control
Play = 0,
Pause,
Resume,
Stop,
Skip,
Seek,
SetVolume,
// Queue management
QueueTrack,
RemoveFromQueue,
ClearQueue,
GetQueue,
MoveInQueue,
// Track info
GetCurrentTrack,
GetTrackInfo,
SearchTracks,
// Playlist
LoadPlaylist,
SavePlaylist,
GetPlaylists,
DeletePlaylist,
// Configuration
GetConfig,
SetConfig,
ReloadConfig,
// Plugin/Core management
GetStatus,
HotReload,
Shutdown,
// Admin
Authenticate,
Logout,
GetAuditLog,
ManageUsers,
// Server info
GetServerInfo,
RequestLoginToken,
ValidateLoginToken
};
struct RpcRequest {
uint64_t id;
RpcMethod method;
std::optional<std::string> params;
std::optional<std::string> authToken;
std::chrono::system_clock::time_point timestamp;
};
struct RpcResponse {
uint64_t requestId;
bool success;
std::optional<std::string> result;
std::optional<std::string>
error; // JSON string: {"code":N,"message":"...","source":"..."}
std::chrono::system_clock::time_point timestamp;
};
struct RpcNotification {
std::string event;
std::optional<std::string> data;
std::chrono::system_clock::time_point timestamp;
};
using RpcHandler = std::function<RpcResponse(const RpcRequest &)>;
struct RpcEndpoint {
RpcMethod method;
std::string name;
std::string description;
bool requiresAuth;
RpcHandler handler;
};
// Hot reload state preservation
struct HotReloadState {
PlaybackState playback;
std::vector<QueueEntry> queue;
std::optional<std::string> currentStreamUrl;
std::chrono::milliseconds playbackPosition;
BotConfig config;
std::map<std::string, std::string> sessionData;
[[nodiscard]] bool shouldPreservePlayback() const noexcept
{
return playback.isPlaying && playback.currentTrack.has_value();
}
};
} // namespace Echoion::Api
+196
View File
@@ -0,0 +1,196 @@
#pragma once
#include "AudioTypes.hpp"
#include "Types.hpp"
#include <Void/Data/Reflect.hpp> // Void::Json::Value + ReflectError
#include <chrono>
#include <expected>
#include <optional>
#include <string>
#include <vector>
namespace Echoion::Api
{
enum class TrackSource : uint8_t {
Unknown = 0,
YouTube,
SoundCloud,
Spotify,
LocalFile,
URL
};
struct TrackInfo {
std::string id;
std::string title;
std::string artist;
std::string album;
std::optional<std::string> thumbnailUrl;
std::optional<std::chrono::milliseconds> duration;
TrackSource source;
std::string originalUrl;
std::optional<std::string>
shortenedUrl; // faumaray.ru shortened link
std::optional<std::string> streamUrl;
std::optional<AudioStreamInfo> audioInfo;
std::chrono::system_clock::time_point addedAt;
std::string requestedBy;
// Format track as markdown link: [Title](shortenedUrl)
// Only uses shortened URL (faumaray), returns empty string if not
// available
[[nodiscard]] std::string formatWithLink() const
{
if (shortenedUrl.has_value() && !shortenedUrl->empty()) {
return std::format("[{}]({})", title, *shortenedUrl);
}
return std::format("[{}]",
title); // No link if no shortened URL
}
// Format track with artist and link
// Only uses shortened URL (faumaray), returns text only if not
// available
[[nodiscard]] std::string formatWithArtistAndLink() const
{
std::string displayTitle = title;
if (!artist.empty()) {
displayTitle = std::format("{} by {}", title, artist);
}
if (shortenedUrl.has_value() && !shortenedUrl->empty()) {
return std::format("[{}]({})", displayTitle, *shortenedUrl);
}
return displayTitle; // No link if no shortened URL
}
// ── Void::Json customization ──────────────────────────────────
// TrackInfo holds chrono and an optional nested AudioStreamInfo,
// neither of which Void::Json reflection covers, so it provides an
// explicit serializer. chrono is stored as integer milliseconds and
// the enum as its underlying value (stable round-trips). The
// transient audioInfo (re-derived on playback) is intentionally not
// persisted.
[[nodiscard]] Void::Json::Value to_json() const
{
using Void::Json::Value;
Value out = Void::Json::object();
auto& o = out.as_object();
o.emplace_back("id", Value{id});
o.emplace_back("title", Value{title});
o.emplace_back("artist", Value{artist});
o.emplace_back("album", Value{album});
o.emplace_back("thumbnailUrl", thumbnailUrl
? Value{*thumbnailUrl}
: Value{nullptr});
o.emplace_back(
"durationMs",
duration ? Value{static_cast<double>(duration->count())}
: Value{nullptr});
o.emplace_back("source",
Value{static_cast<double>(
static_cast<std::uint8_t>(source))});
o.emplace_back("originalUrl", Value{originalUrl});
o.emplace_back("shortenedUrl", shortenedUrl ? Value{*shortenedUrl}
: Value{nullptr});
o.emplace_back("streamUrl",
streamUrl ? Value{*streamUrl} : Value{nullptr});
o.emplace_back(
"addedAtMs",
Value{static_cast<double>(
std::chrono::duration_cast<std::chrono::milliseconds>(
addedAt.time_since_epoch())
.count())});
o.emplace_back("requestedBy", Value{requestedBy});
return out;
}
[[nodiscard]] static std::expected<TrackInfo, Void::Json::ReflectError>
from_json(const Void::Json::Value& j)
{
TrackInfo t;
const auto str = [&](const char* k) -> std::string {
const auto* v = j.find(k);
return (v && v->is_string()) ? v->as_string()
: std::string{};
};
const auto optStr =
[&](const char* k) -> std::optional<std::string> {
const auto* v = j.find(k);
if (v && v->is_string()) {
return v->as_string();
}
return std::nullopt;
};
t.id = str("id");
t.title = str("title");
t.artist = str("artist");
t.album = str("album");
t.thumbnailUrl = optStr("thumbnailUrl");
if (const auto* d = j.find("durationMs");
d && d->is_number()) {
t.duration = std::chrono::milliseconds(
static_cast<std::int64_t>(d->as_number()));
}
if (const auto* s = j.find("source"); s && s->is_number()) {
t.source = static_cast<TrackSource>(
static_cast<std::uint8_t>(s->as_number()));
} else {
t.source = TrackSource::Unknown;
}
t.originalUrl = str("originalUrl");
t.shortenedUrl = optStr("shortenedUrl");
t.streamUrl = optStr("streamUrl");
if (const auto* a = j.find("addedAtMs");
a && a->is_number()) {
t.addedAt = std::chrono::system_clock::time_point(
std::chrono::milliseconds(
static_cast<std::int64_t>(a->as_number())));
}
t.requestedBy = str("requestedBy");
return t;
}
};
struct PlaylistInfo {
std::string id;
std::string name;
std::string description;
std::optional<std::string> thumbnailUrl;
std::string owner;
std::vector<TrackInfo> tracks;
std::chrono::system_clock::time_point createdAt;
std::chrono::system_clock::time_point updatedAt;
};
struct QueueEntry {
uint64_t queueId;
TrackInfo track;
std::chrono::system_clock::time_point addedAt;
std::string addedBy;
bool isPlaying;
std::optional<std::chrono::milliseconds> position;
};
struct PlaybackState {
std::optional<QueueEntry> currentTrack;
std::vector<QueueEntry> queue;
bool isPlaying;
bool isPaused;
std::chrono::milliseconds position;
std::chrono::milliseconds buffered;
float volume;
bool repeat;
bool shuffle;
std::chrono::system_clock::time_point lastUpdate;
};
struct SearchResult {
std::vector<TrackInfo> tracks;
std::vector<PlaylistInfo> playlists;
std::string query;
std::optional<std::string> nextPageToken;
uint32_t totalResults;
};
} // namespace Echoion::Api
+147
View File
@@ -0,0 +1,147 @@
#pragma once
#include "Types.hpp"
#include <Void/Containers/BufferPool.hpp>
#include <cstdint>
#include <cstring>
#include <memory>
#include <span>
namespace Echoion::Api
{
// Reusable int16 audio sample buffer, recycled by the pool on drop.
using AudioSampleBuffer = Void::BufferPool::BufferPool<int16_t>::Buffer;
// Specialized audio buffer pool for int16 (direct TeamSpeak compatibility).
// Backed by Void::BufferPool, which pools by power-of-two size class and
// reuses storage across acquisitions (grow-on-demand, no fixed capacity).
class AudioBufferPool
{
public:
static constexpr size_t DEFAULT_BUFFER_SIZE =
1920; // 48000Hz * 2ch * 20ms
static constexpr size_t DEFAULT_POOL_SIZE =
256; // pre-warm hint (buffers)
static AudioBufferPool& instance();
void initialize(size_t bufferSize = DEFAULT_BUFFER_SIZE,
size_t poolSize = DEFAULT_POOL_SIZE);
void shutdown();
// Borrow an int16 buffer of the configured size. An empty Buffer is
// returned if the pool has not been initialized.
[[nodiscard]] AudioSampleBuffer acquireBuffer();
// Get buffer size
[[nodiscard]] size_t getBufferSize() const { return bufferSize_; }
// Get stats
[[nodiscard]] size_t getAvailableBuffers() const;
[[nodiscard]] size_t getTotalBuffers() const;
private:
AudioBufferPool() = default;
std::unique_ptr<Void::BufferPool::BufferPool<int16_t>> pool_;
size_t bufferSize_ = DEFAULT_BUFFER_SIZE;
};
// Zero-copy audio buffer view
template <typename T> class AudioBufferView
{
public:
AudioBufferView() = default;
AudioBufferView(T* data, size_t size, size_t channels = 2)
: data_(data), size_(size), channels_(channels)
{
}
[[nodiscard]] T* data() { return data_; }
[[nodiscard]] const T* data() const { return data_; }
[[nodiscard]] size_t size() const { return size_; }
[[nodiscard]] size_t channels() const { return channels_; }
[[nodiscard]] size_t samplesPerChannel() const
{
return size_ / channels_;
}
[[nodiscard]] T* channel(size_t ch) { return data_ + ch; }
[[nodiscard]] T& sample(size_t frame, size_t ch)
{
return data_[frame * channels_ + ch];
}
[[nodiscard]] const T& sample(size_t frame, size_t ch) const
{
return data_[frame * channels_ + ch];
}
// Span for single channel
[[nodiscard]] std::span<T> getChannelSpan(size_t ch)
{
return std::span<T>(data_ + ch, size_, channels_);
}
// Span for all data
[[nodiscard]] std::span<T> getSpan()
{
return std::span<T>(data_, size_);
}
[[nodiscard]] bool empty() const
{
return data_ == nullptr || size_ == 0;
}
void clear()
{
if (data_) {
std::memset(data_, 0, size_ * sizeof(T));
}
}
// Apply gain in-place
void applyGain(float gain)
{
if (!data_) {
return;
}
for (size_t i = 0; i < size_; ++i) {
data_[i] *= gain;
}
}
// Mix another buffer into this one
void mix(const AudioBufferView& other, float gain = 1.0f)
{
if (!data_ || !other.data_) {
return;
}
size_t mixSize = std::min(size_, other.size_);
for (size_t i = 0; i < mixSize; ++i) {
data_[i] += other.data_[i] * gain;
}
}
private:
T* data_ = nullptr;
size_t size_ = 0;
size_t channels_ = 2;
};
// Audio buffer view types - using int16 (short) for direct TeamSpeak
// compatibility
using Int16AudioView = AudioBufferView<int16_t>;
// Deprecated: Float audio view is no longer used, all audio is int16
using FloatAudioView = AudioBufferView<float>;
} // namespace Echoion::Api
@@ -0,0 +1,143 @@
#pragma once
#include "TrackTypes.hpp"
#include "Types.hpp"
#include <chrono>
#include <optional>
#include <string>
#include <vector>
namespace Echoion::Api
{
// YouTube-specific types for the extracted client algorithm
struct YouTubeFormat {
std::string itag;
std::string mimeType;
std::optional<std::string> url;
std::optional<std::string> signatureCipher;
int32_t bitrate;
int32_t width;
int32_t height;
std::optional<std::string> qualityLabel;
std::optional<std::string> audioQuality;
int32_t audioSampleRate;
int32_t audioChannels;
bool hasVideo;
bool hasAudio;
};
struct YouTubeVideoDetails {
std::string videoId;
std::string title;
std::string author;
std::optional<std::chrono::seconds> lengthSeconds;
std::vector<YouTubeFormat> formats;
std::vector<YouTubeFormat> adaptiveFormats;
std::optional<std::string> playerJsUrl;
std::optional<std::string> streamingData;
};
struct YouTubeSearchResult {
std::string videoId;
std::string title;
std::string channelTitle;
std::optional<std::chrono::seconds> duration;
std::optional<std::string> thumbnailUrl;
std::string publishedAt;
uint64_t viewCount;
};
struct YouTubePlaylistItem {
std::string videoId;
std::string title;
std::optional<std::chrono::seconds> duration;
std::optional<std::string> thumbnailUrl;
};
struct YouTubePlaylist {
std::string playlistId;
std::string title;
std::string author;
std::vector<YouTubePlaylistItem> videos;
std::optional<std::string> continuationToken;
};
struct YouTubePlayerConfig {
std::string innertubeApiKey;
std::string innertubeClientName;
std::string innertubeClientVersion;
std::string contextClientName;
std::string contextClientVersion;
std::string visitorData;
std::optional<std::string> poToken;
};
struct YouTubeClientContext {
std::string hl = "en";
std::string gl = "US";
std::string clientName = "WEB";
std::string clientVersion;
std::optional<std::string> visitorData;
std::optional<std::string> userAgent;
};
// Convert YouTube types to generic TrackInfo
[[nodiscard]] inline TrackInfo
ConvertToTrackInfo(const YouTubeVideoDetails& details)
{
TrackInfo info;
info.id = details.videoId;
info.title = details.title;
info.artist = details.author;
if (details.lengthSeconds.has_value()) {
info.duration =
std::chrono::milliseconds(*details.lengthSeconds * 1000);
}
info.source = TrackSource::YouTube;
info.originalUrl = "https://youtube.com/watch?v=" + details.videoId;
return info;
}
[[nodiscard]] inline TrackInfo
ConvertToTrackInfo(const YouTubeSearchResult& result)
{
TrackInfo info;
info.id = result.videoId;
info.title = result.title;
info.artist = result.channelTitle;
if (result.duration.has_value()) {
info.duration = std::chrono::milliseconds(*result.duration * 1000);
}
info.thumbnailUrl = result.thumbnailUrl;
info.source = TrackSource::YouTube;
info.originalUrl = "https://youtube.com/watch?v=" + result.videoId;
return info;
}
[[nodiscard]] inline PlaylistInfo
ConvertToPlaylistInfo(const YouTubePlaylist& playlist)
{
PlaylistInfo info;
info.id = playlist.playlistId;
info.name = playlist.title;
info.owner = playlist.author;
// Convert playlist items to tracks
for (const auto& item : playlist.videos) {
TrackInfo track;
track.id = item.videoId;
track.title = item.title;
track.source = TrackSource::YouTube;
track.originalUrl = "https://youtube.com/watch?v=" + item.videoId;
if (item.duration.has_value()) {
track.duration =
std::chrono::milliseconds(*item.duration * 1000);
}
track.thumbnailUrl = item.thumbnailUrl;
info.tracks.push_back(std::move(track));
}
return info;
}
} // namespace Echoion::Api