commit b4073ddf1eeb16cb07309ec0830069f03c822f9f Author: faumaray Date: Sun Feb 1 23:05:41 2026 +0300 Initial commit diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..1c0ed4b --- /dev/null +++ b/.clang-format @@ -0,0 +1,272 @@ +--- +BasedOnStyle: LLVM +AccessModifierOffset: 0 +AlignAfterOpenBracket: Align +AlignArrayOfStructures: None +AlignConsecutiveAssignments: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: true +AlignConsecutiveBitFields: + Enabled: true + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveDeclarations: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveMacros: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveShortCaseStatements: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCaseArrows: false + AlignCaseColons: false +AlignConsecutiveTableGenBreakingDAGArgColons: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveTableGenCondOperatorColons: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveTableGenDefinitionColons: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignEscapedNewlines: Right +AlignOperands: Align +AlignTrailingComments: + Kind: Always + OverEmptyLines: 0 +AllowAllArgumentsOnNextLine: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowBreakBeforeNoexceptSpecifier: Never +AllowShortBlocksOnASingleLine: Never +AllowShortCaseExpressionOnASingleLine: true +AllowShortCaseLabelsOnASingleLine: false +AllowShortCompoundRequirementOnASingleLine: true +AllowShortEnumsOnASingleLine: true +AllowShortFunctionsOnASingleLine: All +AllowShortIfStatementsOnASingleLine: Never +AllowShortLambdasOnASingleLine: All +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AttributeMacros: + - __capability +BinPackArguments: true +BinPackParameters: true +BitFieldColonSpacing: Both +BraceWrapping: + AfterCaseLabel: true + AfterClass: true + AfterControlStatement: Never + AfterEnum: false + AfterFunction: true + AfterNamespace: true + AfterObjCDeclaration: false + AfterStruct: true + AfterUnion: false + AfterExternBlock: false + BeforeCatch: false + BeforeElse: true + BeforeLambdaBody: true + BeforeWhile: true + IndentBraces: true + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true +BreakAdjacentStringLiterals: true +BreakAfterAttributes: Leave +BreakAfterJavaFieldAnnotations: false +BreakAfterReturnType: None +BreakArrays: true +BreakBeforeBinaryOperators: None +BreakBeforeBraces: Linux +BreakBeforeConceptDeclarations: Always +BreakBeforeInlineASMColon: OnlyMultiline +BreakBeforeTernaryOperators: true +BreakConstructorInitializers: BeforeColon +BreakFunctionDefinitionParameters: false +BreakInheritanceList: BeforeColon +BreakStringLiterals: true +BreakTemplateDeclarations: MultiLine +ColumnLimit: 80 +CommentPragmas: "" +CompactNamespaces: false +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: true +DerivePointerAlignment: true +DisableFormat: false +EmptyLineAfterAccessModifier: Always +EmptyLineBeforeAccessModifier: LogicalBlock +ExperimentalAutoDetectBinPacking: true +FixNamespaceComments: true +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +IfMacros: + - KJ_IF_MAYBE +IncludeBlocks: Preserve +IncludeCategories: + - Regex: ^"(llvm|llvm-c|clang|clang-c)/ + Priority: 2 + SortPriority: 0 + CaseSensitive: true + - Regex: ^(<|"(gtest|gmock|isl|json)/) + Priority: 3 + SortPriority: 0 + CaseSensitive: true + - Regex: .* + Priority: 1 + SortPriority: 0 + CaseSensitive: true +IncludeIsMainRegex: (Test)?$ +IncludeIsMainSourceRegex: "" +IndentAccessModifiers: true +IndentCaseBlocks: true +IndentCaseLabels: true +IndentExternBlock: AfterExternBlock +IndentGotoLabels: true +IndentPPDirectives: None +IndentRequiresClause: true +IndentWidth: 4 +IndentWrappedFunctionNames: true +InsertBraces: true +InsertNewlineAtEOF: true +InsertTrailingCommas: None +IntegerLiteralSeparator: + Binary: 0 + BinaryMinDigits: 0 + Decimal: 0 + DecimalMinDigits: 0 + Hex: 0 + HexMinDigits: 0 +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLines: + AtEndOfFile: false + AtStartOfBlock: true + AtStartOfFile: true +LambdaBodyIndentation: Signature +LineEnding: DeriveLF +MacroBlockBegin: "" +MacroBlockEnd: "" +MainIncludeChar: AngleBracket +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: All +ObjCBinPackProtocolList: Auto +ObjCBlockIndentWidth: 2 +ObjCBreakBeforeNestedBlockParam: true +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: true +PPIndentWidth: -1 +PackConstructorInitializers: BinPack +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakOpenParenthesis: 0 +PenaltyBreakScopeResolution: 500 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 +PenaltyIndentedWhitespace: 0 +PenaltyReturnTypeOnItsOwnLine: 60 +PointerAlignment: Right +QualifierAlignment: Leave +ReferenceAlignment: Pointer +ReflowComments: true +RemoveBracesLLVM: false +RemoveParentheses: Leave +RemoveSemicolon: false +RequiresClausePosition: OwnLine +RequiresExpressionIndentation: OuterScope +SeparateDefinitionBlocks: Leave +ShortNamespaceLines: 1 +SkipMacroDefinitionBody: false +SortIncludes: CaseSensitive +SortJavaStaticImport: Before +SortUsingDeclarations: LexicographicNumeric +SpaceAfterCStyleCast: false +SpaceAfterLogicalNot: false +SpaceAfterTemplateKeyword: true +SpaceAroundPointerQualifiers: Default +SpaceBeforeAssignmentOperators: true +SpaceBeforeCaseColon: false +SpaceBeforeCpp11BracedList: false +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeJsonColon: false +SpaceBeforeParens: ControlStatements +SpaceBeforeParensOptions: + AfterControlStatements: true + AfterForeachMacros: true + AfterFunctionDeclarationName: false + AfterFunctionDefinitionName: false + AfterIfMacros: true + AfterOverloadedOperator: false + AfterPlacementOperator: true + AfterRequiresInClause: false + AfterRequiresInExpression: false + BeforeNonEmptyParentheses: false +SpaceBeforeRangeBasedForLoopColon: true +SpaceBeforeSquareBrackets: false +SpaceInEmptyBlock: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: Never +SpacesInContainerLiterals: true +SpacesInLineCommentPrefix: + Minimum: 1 + Maximum: -1 +SpacesInParens: Never +SpacesInParensOptions: + ExceptDoubleParentheses: false + InConditionalStatements: false + InCStyleCasts: false + InEmptyParentheses: false + Other: false +SpacesInSquareBrackets: false +Standard: Latest +StatementAttributeLikeMacros: + - Q_EMIT +StatementMacros: + - Q_UNUSED + - QT_REQUIRE_VERSION +TabWidth: 4 +TableGenBreakInsideDAGArg: DontBreak +UseTab: Always +VerilogBreakBetweenInstancePorts: true +WhitespaceSensitiveMacros: + - BOOST_PP_STRINGIZE + - CF_SWIFT_NAME + - NS_SWIFT_NAME + - PP_STRINGIZE + - STRINGIZE diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e2a12fb --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +*build* +.cache +.idea +AGENTS.md \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..7c7977f --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,47 @@ +cmake_minimum_required(VERSION 3.28) +project(EchoionApi VERSION 1.0.0 LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 26) +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) + +add_library(Echoion::Api ALIAS EchoionApi) + +target_include_directories(EchoionApi INTERFACE + $ + $ +) + +# Require glaze for JSON serialization (header-only) +find_package(glaze CONFIG REQUIRED) +target_link_libraries(EchoionApi INTERFACE glaze::glaze) + +find_package(Threads REQUIRED) +target_link_libraries(EchoionApi INTERFACE Threads::Threads) + +# Compiler-specific options (interface library, so use INTERFACE) +if(MSVC) + target_compile_options(EchoionApi INTERFACE /W4 /WX-) +else() + target_compile_options(EchoionApi INTERFACE -Wall -Wextra -Wpedantic) +endif() + +# Installation (header-only library, no archive) +include(GNUInstallDirs) +install(TARGETS EchoionApi + EXPORT EchoionApiTargets +) + +install(EXPORT EchoionApiTargets + FILE EchoionApiTargets.cmake + NAMESPACE Echoion:: + DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/EchoionApi +) + +install(DIRECTORY include/ + DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} +) diff --git a/include/echoion/api.hpp b/include/echoion/api.hpp new file mode 100644 index 0000000..2fef165 --- /dev/null +++ b/include/echoion/api.hpp @@ -0,0 +1,20 @@ +#pragma once + +// Main Echoion API header - includes all types + +#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" diff --git a/include/echoion/api/AudioTypes.hpp b/include/echoion/api/AudioTypes.hpp new file mode 100644 index 0000000..2d21efb --- /dev/null +++ b/include/echoion/api/AudioTypes.hpp @@ -0,0 +1,113 @@ +#pragma once + +#include "Types.hpp" +#include "MemoryPool.hpp" +#include +#include +#include + +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 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 quality; + bool hwAccelerated = false; + HwAccelType hwAccelType = HwAccelType::None; +}; + +// Zero-copy decoded audio using pooled memory +struct DecodedAudio { + // Use pooled buffer instead of std::vector for zero-copy + PooledPtr pooledSamples; + + // Non-owning view into the data + FloatAudioView view; + + uint32_t sampleRate; + uint32_t channels; + std::chrono::milliseconds timestamp; + + // Backwards compatibility - creates a copy + [[nodiscard]] std::vector getSamples() const { + if (view.empty()) { + return {}; + } + return std::vector(view.data(), view.data() + view.size()); + } + + // Check if valid + [[nodiscard]] bool isValid() const { + return !view.empty(); + } + + // Apply volume in-place + void applyVolume(float volume) { + view.applyGain(volume); + } +}; + +// Hardware acceleration configuration +struct HwAccelConfig { + HwAccelType type = HwAccelType::None; + int deviceIndex = -1; // -1 for auto-select + std::optional 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; +using AudioFramePtr = std::shared_ptr; + +} // namespace Echoion::Api diff --git a/include/echoion/api/Cache.hpp b/include/echoion/api/Cache.hpp new file mode 100644 index 0000000..6cd6b49 --- /dev/null +++ b/include/echoion/api/Cache.hpp @@ -0,0 +1,389 @@ +#pragma once + +#include "Types.hpp" +#include "NetworkTypes.hpp" +#include "TrackTypes.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Echoion::Api { + +// Cache entry with metadata +template +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(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 +class LruCache { +public: + using Entry = CacheEntry; + using Loader = std::function(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 get(const Key& key, Loader loader = nullptr) { + std::unique_lock 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 ttl = std::nullopt, + size_t estimatedSize = 0) { + + std::unique_lock 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 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 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 lock(mutex_); + return cache_.find(key) != cache_.end(); + } + + // Get cache statistics + [[nodiscard]] CacheStats getStats() const { + std::shared_lock lock(mutex_); + CacheStats stats = stats_; + stats.currentSize = cache_.size(); + stats.maxSize = maxSize_; + stats.memoryUsage = memoryUsage_; + return stats; + } + + // Reset statistics + void resetStats() { + std::unique_lock lock(mutex_); + stats_ = CacheStats{}; + } + + // Set max size + void setMaxSize(size_t maxSize) { + std::unique_lock 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 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 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::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::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::iterator it) { + order_.erase(it); + } + + mutable std::shared_mutex mutex_; + std::unordered_map cache_; + std::list 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; +using HttpCache = LruCache; +using TrackCache = LruCache; + +// 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 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 diff --git a/include/echoion/api/ConfigManager.hpp b/include/echoion/api/ConfigManager.hpp new file mode 100644 index 0000000..518cac7 --- /dev/null +++ b/include/echoion/api/ConfigManager.hpp @@ -0,0 +1,96 @@ +#pragma once + +#include "ConfigTypes.hpp" +#include +#include +#include +#include +#include + +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; + + // 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 + auto withConfig(Func&& func) const -> decltype(func(std::declval())) { + 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 initialized_{false}; + std::vector 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()) diff --git a/include/echoion/api/ConfigTypes.hpp b/include/echoion/api/ConfigTypes.hpp new file mode 100644 index 0000000..91aa331 --- /dev/null +++ b/include/echoion/api/ConfigTypes.hpp @@ -0,0 +1,93 @@ +#pragma once + +#include "Types.hpp" +#include "NetworkTypes.hpp" +#include "echoion/api/AudioTypes.hpp" +#include +#include +#include +#include +#include + +namespace Echoion::Api { + +using ConfigValue = std::variant< + std::monostate, + bool, + int64_t, + double, + std::string, + std::vector +>; + +struct ConfigEntry { + std::string key; + ConfigValue value; + std::string description; + bool isSecret; + std::optional defaultValue; + std::optional 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 proxy; + std::optional 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 youtubeCookiesPath; + + // Alternative: use cookies from browser directly + // e.g., "chrome", "firefox", "safari", "edge" + std::optional cookiesFromBrowser; +}; + +struct ServerConfig { + std::string address; + uint16_t port; + std::string serverPassword; + std::string nickname; + std::optional defaultChannelId; + std::optional channelPassword; + std::vector adminGroups; + std::vector djGroups; + std::vector bannedGroups; +}; + +struct AdminCredentials { + std::string username; + std::string passwordHash; + std::optional salt; + std::vector permissions; + std::chrono::system_clock::time_point createdAt; + std::optional 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 custom; +}; + +} // namespace Echoion::Api diff --git a/include/echoion/api/CoreInterface.hpp b/include/echoion/api/CoreInterface.hpp new file mode 100644 index 0000000..dc5bc45 --- /dev/null +++ b/include/echoion/api/CoreInterface.hpp @@ -0,0 +1,163 @@ +#pragma once + +#include "Types.hpp" +#include "TrackTypes.hpp" +#include "PluginTypes.hpp" +#include "ConfigTypes.hpp" +#include "RpcTypes.hpp" +#include "NetworkTypes.hpp" +#include +#include +#include +#include +#include + +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 initialize(const std::optional& proxy = std::nullopt) = 0; + virtual void shutdown() = 0; + + // Synchronous requests + [[nodiscard]] virtual Result get(std::string_view url, + const std::vector& headers = {}) = 0; + [[nodiscard]] virtual Result post(std::string_view url, + std::string_view body, const std::vector& headers = {}) = 0; + [[nodiscard]] virtual Result request(const HttpRequest& req) = 0; + + // Asynchronous requests + [[nodiscard]] virtual std::future> getAsync(std::string_view url, + const std::vector& headers = {}) = 0; + [[nodiscard]] virtual std::future> postAsync(std::string_view url, + std::string_view body, const std::vector& headers = {}) = 0; + [[nodiscard]] virtual std::future> requestAsync(const HttpRequest& req) = 0; + + // Proxy configuration + virtual void setProxy(const std::optional& proxy) = 0; + [[nodiscard]] virtual std::optional 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 initialize() = 0; + virtual Result shutdown() = 0; + + // Client operations + [[nodiscard]] virtual Result> getClients() const = 0; + [[nodiscard]] virtual Result> getClient(uint64_t clientId) const = 0; + virtual Result moveClient(uint64_t clientId, uint64_t channelId) = 0; + virtual Result kickClient(uint64_t clientId, const std::string& reason) = 0; + + // Channel operations + [[nodiscard]] virtual Result> getChannels() const = 0; + [[nodiscard]] virtual Result> getChannel(uint64_t channelId) const = 0; + + // Messaging + virtual Result sendTextMessage(uint64_t targetId, const std::string& message) = 0; + virtual Result sendChannelMessage(uint64_t channelId, const std::string& message) = 0; + virtual Result sendServerMessage(const std::string& message) = 0; + + // Audio + virtual Result sendAudioData(const std::span& data) = 0; + virtual Result setWhisperList(const std::vector& clientIds) = 0; + + // Server connection + virtual Result connectToServer(const ServerConfig& config) = 0; + virtual Result disconnectFromServer() = 0; + [[nodiscard]] virtual bool isConnected() const = 0; + virtual Result reconnect() = 0; + + // Event subscription + virtual void registerEventCallback(const EventCallback& callback) = 0; + virtual void unregisterEventCallback(const EventCallback& callback) = 0; +}; + +using PluginInterfacePtr = std::shared_ptr; + +// 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 initialize(const std::filesystem::path& configPath) = 0; + virtual Result shutdown() = 0; + virtual bool isInitialized() const noexcept = 0; + + // Playback control + virtual Result play(const TrackInfo& track) = 0; + virtual Result pause() = 0; + virtual Result resume() = 0; + virtual Result stop() = 0; + virtual Result skip(uint32_t count = 1) = 0; + virtual Result seek(std::chrono::milliseconds position) = 0; + virtual Result setVolume(float volume) = 0; + + // Queue management + virtual Result queueTrack(const TrackInfo& track, uint64_t clientId) = 0; + virtual Result removeFromQueue(uint64_t queueId) = 0; + virtual Result clearQueue() = 0; + [[nodiscard]] virtual Result> getQueue() const = 0; + virtual Result moveInQueue(uint64_t queueId, uint32_t newPosition) = 0; + + // Track info + [[nodiscard]] virtual Result> getCurrentTrack() const = 0; + [[nodiscard]] virtual Result getPlaybackState() const = 0; + + // Playlist + virtual Result loadPlaylist(const std::string& playlistId, uint64_t clientId) = 0; + virtual Result> getPlaylists() const = 0; + + // Configuration + virtual Result updateConfig(const AppConfig& config) = 0; + [[nodiscard]] virtual Result getConfig() const = 0; + + // Hot reload + virtual Result prepareForHotReload() = 0; + virtual Result 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 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; +using CoreCreateFunc = std::function; +using CoreDestroyFunc = std::function; + +} // namespace Echoion::Api diff --git a/include/echoion/api/Database.hpp b/include/echoion/api/Database.hpp new file mode 100644 index 0000000..36408c2 --- /dev/null +++ b/include/echoion/api/Database.hpp @@ -0,0 +1,210 @@ +#pragma once + +#include "Types.hpp" +#include "TrackTypes.hpp" +#include +#include +#include +#include +#include + +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 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 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 initialize(const DatabaseConfig& config = {}); + void shutdown(); + [[nodiscard]] bool isInitialized() const; + + // Migrations + Api::Result migrate(); // Run pending migrations + [[nodiscard]] int getCurrentVersion() const; + + // ===== Playlists ===== + + // Create a new playlist + [[nodiscard]] Api::Result createPlaylist( + const std::string& name, + const std::string& description, + uint64_t createdBy, + bool isPublic = false); + + // Get playlist by ID + [[nodiscard]] Api::Result> getPlaylist(uint64_t id); + + // Get all playlists for a user + [[nodiscard]] Api::Result> getUserPlaylists(uint64_t userId); + + // Update playlist + Api::Result updatePlaylist(uint64_t id, + const std::optional& name = std::nullopt, + const std::optional& description = std::nullopt, + const std::optional& isPublic = std::nullopt); + + // Delete playlist + Api::Result deletePlaylist(uint64_t id); + + // Add track to playlist + Api::Result addTrackToPlaylist(uint64_t playlistId, + const TrackInfo& track, uint32_t position = 0); + + // Remove track from playlist + Api::Result removeTrackFromPlaylist(uint64_t playlistId, uint64_t trackId); + + // Reorder playlist tracks + Api::Result reorderPlaylistTrack(uint64_t playlistId, + uint64_t trackId, uint32_t newPosition); + + // ===== Playback History ===== + + // Record a playback + Api::Result recordPlayback(const TrackInfo& track, + uint64_t playedBy, + std::chrono::milliseconds duration, + bool completed); + + // Get playback history for a user + [[nodiscard]] Api::Result> getPlaybackHistory( + uint64_t userId, + size_t limit = 100, + size_t offset = 0); + + // Get recently played tracks + [[nodiscard]] Api::Result> getRecentlyPlayed( + uint64_t userId, + size_t limit = 20); + + // ===== Favorites ===== + + // Add track to favorites + Api::Result addFavorite(uint64_t userId, const TrackInfo& track); + + // Remove track from favorites + Api::Result removeFavorite(uint64_t userId, const std::string& trackUrl); + + // Check if track is favorited + [[nodiscard]] Api::Result isFavorite(uint64_t userId, const std::string& trackUrl); + + // Get all favorites for a user + [[nodiscard]] Api::Result> getFavorites(uint64_t userId); + + // ===== Statistics ===== + + // Get playback statistics + [[nodiscard]] Api::Result getStatistics( + uint64_t userId, + std::optional since = std::nullopt); + + // Get most played tracks + [[nodiscard]] Api::Result>> getMostPlayed( + uint64_t userId, + size_t limit = 10); + + // ===== Subscriptions ===== + + // Add a subscriber + Api::Result addSubscriber(uint64_t clientId); + + // Remove a subscriber + Api::Result removeSubscriber(uint64_t clientId); + + // Check if client is subscribed + [[nodiscard]] Api::Result isSubscriber(uint64_t clientId); + + // Get all subscribers + [[nodiscard]] Api::Result> getAllSubscribers(); + + // Get subscriber count + [[nodiscard]] Api::Result getSubscriberCount(); + + // ===== Cache Management ===== + + // Clear old history (keep last N entries) + Api::Result trimHistory(size_t keepCount = 10000); + + // Clear all data for a user + Api::Result clearUserData(uint64_t userId); + + // Vacuum database (reclaim space) + Api::Result vacuum(); + + // ===== Raw Query (for advanced use) ===== + + using RowCallback = std::function>&)>; + Api::Result executeQuery(const std::string& sql, RowCallback callback = nullptr); + +private: + std::unique_ptr impl_; +}; + +// Database manager (singleton) +class DatabaseManager { +public: + static Database& instance(); + + static Api::Result initialize(const DatabaseConfig& config = {}); + static void shutdown(); + +private: + DatabaseManager() = default; +}; + +} // namespace Echoion::Api diff --git a/include/echoion/api/EventBus.hpp b/include/echoion/api/EventBus.hpp new file mode 100644 index 0000000..d20273b --- /dev/null +++ b/include/echoion/api/EventBus.hpp @@ -0,0 +1,269 @@ +#pragma once + +#include "Types.hpp" +#include "echoion/api/ConfigTypes.hpp" +#include "echoion/api/PluginTypes.hpp" +#include "echoion/api/TrackTypes.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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 +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 +using EventHandler = std::function; + +// Subscription token for unsubscribing +class SubscriptionToken { +public: + using Id = uint64_t; + + SubscriptionToken() = default; + explicit SubscriptionToken(Id id, std::type_index type, + std::weak_ptr&)>> 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&)>> 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 + void publish(T event) { + auto evt = std::make_shared>(std::move(event)); + { + std::lock_guard lock(queueMutex_); + eventQueue_.push(evt); + } + queueCv_.notify_one(); + } + + // Subscribe to events (thread-safe) + template + [[nodiscard]] SubscriptionToken subscribe(EventHandler handler) { + auto wrappedHandler = std::make_shared&)>>( + [h = std::move(handler)](const std::shared_ptr& evt) { + if (auto typedEvt = std::dynamic_pointer_cast>(evt)) { + h(typedEvt->data); + } + } + ); + + std::type_index type(typeid(T)); + auto id = nextId_++; + + { + std::unique_lock 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&)>>>> handlers_; + + mutable std::mutex queueMutex_; + std::queue> eventQueue_; + std::condition_variable queueCv_; + + std::atomic running_{false}; + std::atomic stopRequested_{false}; + std::jthread eventThread_; + + std::atomic 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 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(handler) + +} // namespace Echoion::Api diff --git a/include/echoion/api/Export.hpp b/include/echoion/api/Export.hpp new file mode 100644 index 0000000..da99dd2 --- /dev/null +++ b/include/echoion/api/Export.hpp @@ -0,0 +1,39 @@ +#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 diff --git a/include/echoion/api/LoggerInterface.hpp b/include/echoion/api/LoggerInterface.hpp new file mode 100644 index 0000000..9c61679 --- /dev/null +++ b/include/echoion/api/LoggerInterface.hpp @@ -0,0 +1,104 @@ +#pragma once + +#include "Types.hpp" +#include +#include +#include +#include + +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 + void logf(LogLevel level, std::format_string fmt, Args&&... args, + std::source_location location = std::source_location::current()) { + log(level, std::format(fmt, std::forward(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; + virtual void registerCallback(const LogCallback& callback) = 0; + virtual void unregisterCallback(const LogCallback& callback) = 0; +}; + +using LoggerPtr = std::shared_ptr; + +// 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(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 diff --git a/include/echoion/api/MemoryPool.hpp b/include/echoion/api/MemoryPool.hpp new file mode 100644 index 0000000..7e367ad --- /dev/null +++ b/include/echoion/api/MemoryPool.hpp @@ -0,0 +1,287 @@ +#pragma once + +#include "Types.hpp" +#include +#include +#include +#include +#include +#include + +namespace Echoion::Api { + +// Custom allocator for audio buffers +template +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 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 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 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 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 storage_; + std::queue freeList_; + mutable std::mutex mutex_; + std::atomic available_; +}; + +// Smart pointer for pooled memory +template +class PooledPtr { +public: + PooledPtr() = default; + + PooledPtr(T* ptr, MemoryPool* 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* pool_ = nullptr; +}; + +// Specialized audio buffer pool +class AudioBufferPool { +public: + static constexpr size_t DEFAULT_BUFFER_SIZE = 1920; // 48000Hz * 2ch * 20ms + static constexpr size_t DEFAULT_POOL_SIZE = 256; // ~7.5MB for float 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 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> pool_; + size_t bufferSize_ = DEFAULT_BUFFER_SIZE; +}; + +// Zero-copy audio buffer view +template +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 getChannelSpan(size_t ch) { + return std::span(data_ + ch, size_, channels_); + } + + // Span for all data + [[nodiscard]] std::span getSpan() { + return std::span(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; +}; + +using FloatAudioView = AudioBufferView; + +} // namespace Echoion::Api diff --git a/include/echoion/api/NetworkTypes.hpp b/include/echoion/api/NetworkTypes.hpp new file mode 100644 index 0000000..bc7831c --- /dev/null +++ b/include/echoion/api/NetworkTypes.hpp @@ -0,0 +1,145 @@ +#pragma once + +#include "Types.hpp" +#include +#include +#include +#include +#include +#include + +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 username; + std::optional password; + std::optional 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 headers; + std::optional> body; + std::optional 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> headers; + std::string body; + std::chrono::milliseconds responseTime; + std::optional 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 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(key[i])) != + std::tolower(static_cast(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 getHeaders(std::string_view name) const { + std::vector 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(key[i])) != + std::tolower(static_cast(name[i]))) { + match = false; + break; + } + } + if (match) result.push_back(value); + } + } + return result; + } +}; + +struct RateLimitInfo { + uint32_t limit; + uint32_t remaining; + std::optional resetTime; +}; + +struct RetryConfig { + uint32_t maxRetries = 3; + std::chrono::milliseconds initialDelay = 1000ms; + std::chrono::milliseconds maxDelay = 30000ms; + float backoffMultiplier = 2.0f; + std::vector retryableStatusCodes = {408, 429, 500, 502, 503, 504}; +}; + +} // namespace Echoion::Api diff --git a/include/echoion/api/PluginTypes.hpp b/include/echoion/api/PluginTypes.hpp new file mode 100644 index 0000000..f16421a --- /dev/null +++ b/include/echoion/api/PluginTypes.hpp @@ -0,0 +1,107 @@ +#pragma once + +#include "Types.hpp" +#include "TrackTypes.hpp" +#include +#include +#include +#include + +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 clientName; + uint64_t clientId; + std::optional targetChannelId; + std::optional message; + std::optional trackInfo; + std::optional volume; + std::optional queuePosition; + std::chrono::system_clock::time_point timestamp; +}; + +struct ClientInfo { + uint64_t id; + std::string nickname; + std::optional uniqueIdentifier; + uint64_t channelId; + bool isTalking; + bool isMuted; + bool isDeafened; + std::vector serverGroups; +}; + +struct ChannelInfo { + uint64_t id; + std::string name; + std::optional 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; +using CommandHandler = std::function& args)>; + +struct CommandInfo { + std::string name; + std::string description; + std::vector aliases; + std::optional usage; + bool requiresAdmin; + CommandHandler handler; +}; + +} // namespace Echoion::Api diff --git a/include/echoion/api/RpcTypes.hpp b/include/echoion/api/RpcTypes.hpp new file mode 100644 index 0000000..5f56439 --- /dev/null +++ b/include/echoion/api/RpcTypes.hpp @@ -0,0 +1,105 @@ +#pragma once + +#include "Types.hpp" +#include "TrackTypes.hpp" +#include "PluginTypes.hpp" +#include "ConfigTypes.hpp" +#include +#include +#include +#include + +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 params; + std::optional authToken; + std::chrono::system_clock::time_point timestamp; +}; + +struct RpcResponse { + uint64_t requestId; + bool success; + std::optional result; + std::optional error; // JSON string: {"code":N,"message":"...","source":"..."} + std::chrono::system_clock::time_point timestamp; +}; + +struct RpcNotification { + std::string event; + std::optional data; + std::chrono::system_clock::time_point timestamp; +}; + +using RpcHandler = std::function; + +struct RpcEndpoint { + RpcMethod method; + std::string name; + std::string description; + bool requiresAuth; + RpcHandler handler; +}; + +// Hot reload state preservation +struct HotReloadState { + PlaybackState playback; + std::vector queue; + std::optional currentStreamUrl; + std::chrono::milliseconds playbackPosition; + BotConfig config; + std::map sessionData; + + [[nodiscard]] bool shouldPreservePlayback() const noexcept { + return playback.isPlaying && playback.currentTrack.has_value(); + } +}; + +} // namespace Echoion::Api diff --git a/include/echoion/api/TrackTypes.hpp b/include/echoion/api/TrackTypes.hpp new file mode 100644 index 0000000..1d4bc2f --- /dev/null +++ b/include/echoion/api/TrackTypes.hpp @@ -0,0 +1,77 @@ +#pragma once + +#include "Types.hpp" +#include "AudioTypes.hpp" +#include +#include +#include +#include + +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 thumbnailUrl; + std::optional duration; + TrackSource source; + std::string originalUrl; + std::optional streamUrl; + std::optional audioInfo; + std::chrono::system_clock::time_point addedAt; + std::string requestedBy; +}; + +struct PlaylistInfo { + std::string id; + std::string name; + std::string description; + std::optional thumbnailUrl; + std::string owner; + std::vector 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 position; +}; + +struct PlaybackState { + std::optional currentTrack; + std::vector 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 tracks; + std::vector playlists; + std::string query; + std::optional nextPageToken; + uint32_t totalResults; +}; + +} // namespace Echoion::Api diff --git a/include/echoion/api/Types.hpp b/include/echoion/api/Types.hpp new file mode 100644 index 0000000..6f4862f --- /dev/null +++ b/include/echoion/api/Types.hpp @@ -0,0 +1,73 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +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, + 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(code), message, source); + } +}; + +template +using Result = std::expected; + +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 diff --git a/include/echoion/api/YouTubeTypes.hpp b/include/echoion/api/YouTubeTypes.hpp new file mode 100644 index 0000000..f9480ad --- /dev/null +++ b/include/echoion/api/YouTubeTypes.hpp @@ -0,0 +1,134 @@ +#pragma once + +#include "Types.hpp" +#include "TrackTypes.hpp" +#include +#include +#include +#include + +namespace Echoion::Api { + +// YouTube-specific types for the extracted client algorithm + +struct YouTubeFormat { + std::string itag; + std::string mimeType; + std::optional url; + std::optional signatureCipher; + int32_t bitrate; + int32_t width; + int32_t height; + std::optional qualityLabel; + std::optional audioQuality; + int32_t audioSampleRate; + int32_t audioChannels; + bool hasVideo; + bool hasAudio; +}; + +struct YouTubeVideoDetails { + std::string videoId; + std::string title; + std::string author; + std::optional lengthSeconds; + std::vector formats; + std::vector adaptiveFormats; + std::optional playerJsUrl; + std::optional streamingData; +}; + +struct YouTubeSearchResult { + std::string videoId; + std::string title; + std::string channelTitle; + std::optional duration; + std::optional thumbnailUrl; + std::string publishedAt; + uint64_t viewCount; +}; + +struct YouTubePlaylistItem { + std::string videoId; + std::string title; + std::optional duration; + std::optional thumbnailUrl; +}; + +struct YouTubePlaylist { + std::string playlistId; + std::string title; + std::string author; + std::vector videos; + std::optional continuationToken; +}; + +struct YouTubePlayerConfig { + std::string innertubeApiKey; + std::string innertubeClientName; + std::string innertubeClientVersion; + std::string contextClientName; + std::string contextClientVersion; + std::string visitorData; + std::optional poToken; +}; + +struct YouTubeClientContext { + std::string hl = "en"; + std::string gl = "US"; + std::string clientName = "WEB"; + std::string clientVersion; + std::optional visitorData; + std::optional 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