commit 1e174a078968c49b2a29f71bb6363578d5cba2fe Author: faumaray Date: Sun Feb 1 23:09:22 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/.gitmodules b/.gitmodules new file mode 100644 index 0000000..7819e1e --- /dev/null +++ b/.gitmodules @@ -0,0 +1,12 @@ +[submodule "EchoionApi"] + path = EchoionApi + url = ssh://git@git.faumaray.ru:2222/void/echoionapi.git +[submodule "EchoionCore"] + path = EchoionCore + url = ssh://git@git.faumaray.ru:2222/void/echoioncore.git +[submodule "EchoionPlugin"] + path = EchoionPlugin + url = ssh://git@git.faumaray.ru:2222/void/echoionplugin.git +[submodule "EchoionDesktop"] + path = EchoionDesktop + url = ssh://git@git.faumaray.ru:2222/void/echoiondesktop.git diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..c0659c6 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,60 @@ +cmake_minimum_required(VERSION 3.28) +project(Echoion VERSION 1.0.0 LANGUAGES CXX) +file( + DOWNLOAD + https://github.com/cpm-cmake/CPM.cmake/releases/download/v0.40.8/CPM.cmake + ${CMAKE_CURRENT_BINARY_DIR}/cmake/CPM.cmake + EXPECTED_HASH SHA256=78ba32abdf798bc616bab7c73aac32a17bbd7b06ad9e26a6add69de8f3ae4791 +) +include(${CMAKE_CURRENT_BINARY_DIR}/cmake/CPM.cmake) +set(CMAKE_CXX_STANDARD 23) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + +# Enable folder organization in IDEs +set_property(GLOBAL PROPERTY USE_FOLDERS ON) + +# Options +option(BUILD_API "Build EchoionApi" ON) +option(BUILD_CORE "Build EchoionCore" ON) +option(BUILD_PLUGIN "Build EchoionPlugin" ON) +option(BUILD_DESKTOP "Build EchoionDesktop" ON) +option(BUILD_TESTS "Build tests" OFF) + +# Find packages +find_package(Threads REQUIRED) + +# Add subdirectories +if(BUILD_API) + add_subdirectory(EchoionApi) +endif() + +if(BUILD_CORE) + add_subdirectory(EchoionCore) +endif() + +if(BUILD_PLUGIN) + add_subdirectory(EchoionPlugin) +endif() + +if(BUILD_DESKTOP) + add_subdirectory(EchoionDesktop) +endif() + +# Tests +if(BUILD_TESTS) + enable_testing() + # add_subdirectory(tests) +endif() + +# Print configuration summary +message(STATUS "") +message(STATUS "Echoion Configuration:") +message(STATUS " Version: ${PROJECT_VERSION}") +message(STATUS " C++ Standard: ${CMAKE_CXX_STANDARD}") +message(STATUS " Build API: ${BUILD_API}") +message(STATUS " Build Core: ${BUILD_CORE}") +message(STATUS " Build Plugin: ${BUILD_PLUGIN}") +message(STATUS " Build Desktop: ${BUILD_DESKTOP}") +message(STATUS " Build Tests: ${BUILD_TESTS}") +message(STATUS "") diff --git a/EchoionApi b/EchoionApi new file mode 160000 index 0000000..b4073dd --- /dev/null +++ b/EchoionApi @@ -0,0 +1 @@ +Subproject commit b4073ddf1eeb16cb07309ec0830069f03c822f9f diff --git a/EchoionCore b/EchoionCore new file mode 160000 index 0000000..a583c17 --- /dev/null +++ b/EchoionCore @@ -0,0 +1 @@ +Subproject commit a583c17916d43a8499b631661c22b139bce13c6f diff --git a/EchoionDesktop b/EchoionDesktop new file mode 160000 index 0000000..6238a79 --- /dev/null +++ b/EchoionDesktop @@ -0,0 +1 @@ +Subproject commit 6238a798544f653bfcbc856cce0cd6baebff7bd9 diff --git a/EchoionPlugin b/EchoionPlugin new file mode 160000 index 0000000..8b8a7f4 --- /dev/null +++ b/EchoionPlugin @@ -0,0 +1 @@ +Subproject commit 8b8a7f4f9a0cc17c34145582d366e19e487f0a47 diff --git a/README.md b/README.md new file mode 100644 index 0000000..30951c0 --- /dev/null +++ b/README.md @@ -0,0 +1,137 @@ +# Echoion Music Bot + +A modern music bot for TeamSpeak 3, featuring YouTube integration, playlist support, and hot-reload capabilities. + +## Features + +- 🎵 **YouTube Integration** - Play music directly from YouTube URLs or search queries +- 📋 **Playlist Support** - Queue management with shuffle, repeat, and skip functionality +- 🎧 **High Quality Audio** - Supports up to 48kHz stereo audio +- 🔄 **Hot Reload** - Update the bot without disconnecting from the server +- ⚙️ **Configurable** - JSON-based configuration system +- 🔊 **TeamSpeak Native** - Uses TeamSpeak's native audio system for best quality + +## Building + +### Requirements + +- C++26 compatible compiler (GCC 15+, Clang 18+, or MSVC 2022+) +- CMake 3.28+ +- Qt6 (for desktop client) +- FFmpeg (for audio decoding) +- Glaze library (JSON parsing) +- TeamSpeak 3 Client SDK + +### Build Instructions + +```bash +mkdir build && cd build +cmake .. +cmake --build . +``` + +## Configuration + +Copy `config.example.json` to your config directory: + +- **Linux**: `~/.config/echoion/config.json` +- **Windows**: `%APPDATA%\echoion\config.json` +- **macOS**: `~/Library/Application Support/echoion/config.json` + +Edit the configuration file with your server details: + +```json +{ + "server": { + "address": "your.server.com", + "port": 9987, + "nickname": "MusicBot", + "serverPassword": "" + } +} +``` + +## Installation + +### TeamSpeak Plugin + +1. Build the project +2. Copy the plugin to your TeamSpeak plugins folder: + - **Linux**: `~/.ts3client/plugins/` + - **Windows**: `%APPDATA%\TS3Client\plugins\` +3. Enable the plugin in TeamSpeak's plugins menu + +## Commands + +All commands use the configured prefix (default: `!`) + +| Command | Description | Example | +|---------|-------------|---------| +| `!play ` | Play a song or add to queue | `!play never gonna give you up` | +| `!pause` | Pause playback | `!pause` | +| `!resume` | Resume playback | `!resume` | +| `!stop` | Stop playback | `!stop` | +| `!skip` | Skip current track | `!skip` | +| `!queue` | Show current queue | `!queue` | +| `!clear` | Clear the queue | `!clear` | +| `!shuffle` | Toggle shuffle mode | `!shuffle` | +| `!repeat` | Toggle repeat mode | `!repeat` | +| `!volume <0-100>` | Set volume | `!volume 50` | +| `!nowplaying` | Show current track | `!nowplaying` | +| `!search ` | Search YouTube | `!search daft punk` | + +## Architecture + +The bot consists of three main components: + +1. **EchoionApi** - Shared interfaces and types +2. **EchoionCore** - Core music playback logic (hot-reloadable) +3. **EchoionPlugin** - TeamSpeak plugin wrapper + +### Audio Flow + +``` +YouTube URL → NetworkClient → AudioDecoder → MusicManager → Core → PluginInterface → TeamSpeak +``` + +Audio is decoded using FFmpeg, processed at 48kHz stereo, and sent to TeamSpeak's custom audio device. + +## Development + +### Hot Reload + +The core library can be hot-reloaded without disconnecting from the server: + +1. Build the new core: `cmake --build . --target EchoionCore` +2. Use the "Reload Core" menu item or send plugin command `reload` + +### Adding Commands + +To add a new command: + +1. Create a new command class in `EchoionCore/src/commands/` +2. Inherit from `CommandBase` +3. Register in `CommandManager::initialize()` + +Example: + +```cpp +class MyCommand : public CommandBase { +public: + MyCommand() : CommandBase("mycommand", "Description") {} + + Api::Result execute(uint64_t clientId, const std::vector& args) override { + return "Hello, World!"; + } +}; +``` + +## License + +MIT License - See LICENSE file for details + +## Credits + +- TeamSpeak Systems GmbH for the TeamSpeak SDK +- FFmpeg team for audio decoding +- Glaze library for JSON handling diff --git a/config.example.json b/config.example.json new file mode 100644 index 0000000..ef99ca4 --- /dev/null +++ b/config.example.json @@ -0,0 +1,44 @@ +{ + "bot": { + "botName": "Echoion", + "commandPrefix": "!", + "defaultVolume": 0.5, + "autoReconnect": true, + "reconnectDelay": 5000, + "maxReconnectAttempts": 5, + "preferredQuality": "High", + "allowPlaylistImports": true, + "maxQueueSize": 100, + "trackTimeout": 30000, + "proxyHost": null, + "proxyPort": null, + "proxyUsername": null, + "proxyPassword": null, + "proxyType": "HTTP", + "youtubeApiKey": null, + "rpcPort": 8765, + "_comment_youtube_cookies": "To fix YouTube 'Sign in to confirm you're not a bot' error, use ONE of these options:", + "_comment_option_1": "Option 1: Path to a cookies.txt file exported from your browser", + "youtubeCookiesPath": null, + "_comment_option_2": "Option 2: Use cookies directly from browser (chrome, firefox, safari, edge)", + "cookiesFromBrowser": null + }, + "server": { + "address": "localhost", + "port": 9987, + "serverPassword": "", + "nickname": "EchoionBot", + "defaultChannelId": null, + "channelPassword": null, + "adminGroups": [6, 7], + "djGroups": [8], + "bannedGroups": [] + }, + "security": { + "requireAuthForAdmin": true, + "maxLoginAttempts": 5, + "lockoutDuration": 300000, + "sessionTimeout": 3600000, + "enableAuditLog": true + } +} diff --git a/docs/01-overview.md b/docs/01-overview.md new file mode 100644 index 0000000..1025f78 --- /dev/null +++ b/docs/01-overview.md @@ -0,0 +1,226 @@ +# Echoion Music Bot - System Overview + +## What is Echoion? + +Echoion is a modern music bot for TeamSpeak 3 that plays music from YouTube and other sources directly into voice channels. It features high-quality audio, playlist management, and a unique hot-reload capability that allows updating the bot without disconnecting from the server. + +## System Architecture + +```mermaid +graph TB + subgraph "User Interfaces" + TS[TeamSpeak Client] + DT[Desktop Client
Qt6 Application] + end + + subgraph "Echoion System" + PL[EchoionPlugin
TeamSpeak Plugin] + CL[CoreLoader
Dynamic Loader] + CO[EchoionCore
Music Engine] + API[EchoionApi
Shared Interfaces] + end + + subgraph "External Services" + YT[YouTube
via yt-dlp] + DB[(SQLite
Database)] + end + + TS <-->|TS3 SDK| PL + DT <-->|WebSocket RPC| CO + PL <-->|Hot Reload| CL + CL <-->|Load/Unload| CO + PL <-->|ICoreInterface| CO + CO <-->|IPluginInterface| PL + CO -->|Stream| YT + CO -->|Persist| DB + API -.->|Types/Interfaces| PL + API -.->|Types/Interfaces| CO + API -.->|Types/Interfaces| DT +``` + +## Component Responsibilities + +### EchoionApi (The Contract) +Provides the shared language between all components: +- Data types (tracks, queues, playback state) +- Interfaces (how components talk to each other) +- Utilities (caching, events, database access) + +### EchoionCore (The Brain) +The main music engine that handles: +- Fetching music from YouTube +- Decoding audio with FFmpeg +- Managing the playback queue +- Processing user commands +- Serving the WebSocket API for desktop clients + +**Key feature**: Can be updated while running (hot reload) + +### EchoionPlugin (The Bridge) +Connects EchoionCore to TeamSpeak: +- Receives chat messages from users +- Sends audio to TeamSpeak's voice system +- Manages server connections +- Handles user events (join/leave/move) + +### EchoionDesktop (The Remote) +A separate Qt6 application that: +- Connects to EchoionCore via WebSocket +- Provides a graphical control interface +- Shows playback status and queue +- Allows remote administration + +## How Components Communicate + +### Plugin ↔ Core Communication +The Plugin and Core talk through well-defined interfaces: + +```mermaid +sequenceDiagram + participant User + participant TS as TeamSpeak + participant PL as Plugin + participant CO as Core + + User->>TS: Type !play song + TS->>PL: onTextMessage + PL->>CO: onPluginEvent + CO->>CO: CommandManager + CO->>PL: sendTextMessage("Playing...") + PL->>TS: Display message + CO->>PL: sendAudioData (continuous) + PL->>TS: Voice transmission + TS->>User: Hear music +``` + +### Desktop Client Communication +The Desktop app connects remotely: + +```mermaid +sequenceDiagram + participant UI as Desktop UI + participant CC as CoreClient + participant RS as RpcServer + participant MM as MusicManager + + UI->>CC: Click Play + CC->>RS: WebSocket: play + RS->>MM: Execute command + MM->>RS: Broadcast: playbackStarted + RS->>CC: Event notification + CC->>UI: Update display +``` + +## Data Flow Overview + +### Playing a Song + +```mermaid +flowchart LR + A[User Command] --> B[CommandManager] + B --> C{YouTube URL?} + C -->|Yes| D[Extract ID] + C -->|No| E[Search YouTube] + E --> F[Select Video] + D --> G[Get Stream URL] + F --> G + G --> H[Queue Track] + H --> I{Playing?} + I -->|No| J[Start Playback] + I -->|Yes| K[Wait in Queue] + J --> L[FFmpeg Decode] + L --> M[Apply Volume] + M --> N[Send to TS] +``` + +### Audio Pipeline + +```mermaid +flowchart TB + subgraph "Source" + YT[YouTube/URL] + end + + subgraph "Processing" + NC[NetworkClient
Download stream] + AD[AudioDecoder
FFmpeg decode] + MM[MusicManager
Volume/Queue] + end + + subgraph "Output" + PI[PluginInterface] + TS[TeamSpeak Voice] + end + + YT --> NC + NC --> AD + AD -->|Float PCM| MM + MM -->|Int16 PCM| PI + PI --> TS +``` + +## Key Features + +### Hot Reload +Unlike traditional bots, Echoion can update its core logic without disconnecting: + +```mermaid +sequenceDiagram + participant PL as Plugin + participant CL as CoreLoader + participant Old as Old Core + participant New as New Core + + PL->>CL: Trigger reload + CL->>Old: Save state
Queue, Position, Config + CL->>Old: Unload library + CL->>New: Load new library + CL->>New: Restore state + New->>PL: Resume playback +``` + +### Multi-Client Support +Three ways to interact with the bot: +1. **TeamSpeak Chat** - Type commands in channel +2. **Desktop App** - Graphical interface via WebSocket +3. **Future: Web Interface** - Same RPC protocol + +### High-Quality Audio +- Supports up to 48kHz stereo +- Hardware acceleration (CUDA, VAAPI, etc.) +- Efficient memory pooling +- Minimal audio latency + +## Technology Stack + +| Purpose | Technology | +|---------|------------| +| Language | C++23 | +| Build | CMake 3.28+ | +| JSON | Glaze | +| Networking | Boost.Asio/Beast | +| Audio | FFmpeg | +| YouTube | yt-dlp | +| Database | SQLite3 | +| Desktop GUI | Qt6 | +| Plugin SDK | TeamSpeak 3 | + +## Directory Structure + +``` +Echoion/ +├── EchoionApi/ # Shared interfaces & types +├── EchoionCore/ # Music engine (hot-reloadable) +├── EchoionPlugin/ # TeamSpeak plugin wrapper +├── EchoionDesktop/ # Qt6 control client +├── docs/ # This documentation +├── config.example.json # Example configuration +└── CMakeLists.txt # Build configuration +``` + +## Next Steps + +- Learn about the [Shared API Layer](02-echoion-api.md) +- Understand the [Core Music Logic](03-echoion-core.md) +- Explore [TeamSpeak Integration](04-echoion-plugin.md) +- See [Data Flows](06-data-flow.md) in detail diff --git a/docs/02-echoion-api.md b/docs/02-echoion-api.md new file mode 100644 index 0000000..c09ce49 --- /dev/null +++ b/docs/02-echoion-api.md @@ -0,0 +1,291 @@ +# EchoionApi - Shared API Layer + +## Purpose + +EchoionApi is the foundation that all other components build upon. It defines the common language, data structures, and contracts that enable Plugin, Core, and Desktop to communicate seamlessly. + +Think of it as the "vocabulary" that all components share. + +## What's Inside + +### 1. Core Types & Error Handling + +Defines how the system represents success and failure: + +```mermaid +flowchart LR + A[Operation] --> B{Success?} + B -->|Yes| C[Return Value] + B -->|No| D[Error Code + Message] + C --> E[Result] + D --> E +``` + +**Error Categories:** +- Network errors (connection failed, timeout) +- Audio errors (decode failed, format unsupported) +- Permission errors (unauthorized, not admin) +- Input errors (invalid URL, not found) + +### 2. Track & Playback Types + +The data models for music: + +```mermaid +classDiagram + class TrackInfo { + +string id + +string title + +string artist + +duration milliseconds + +TrackSource source + +string originalUrl + +string streamUrl + } + + class QueueEntry { + +uint64 queueId + +TrackInfo track + +string addedBy + +bool isPlaying + } + + class PlaybackState { + +QueueEntry currentTrack + +QueueEntry[] queue + +bool isPlaying + +bool isPaused + +float volume + +bool repeat + +bool shuffle + } + + TrackInfo --> QueueEntry + QueueEntry --> PlaybackState +``` + +### 3. Core Interfaces + +The contracts between components: + +#### ICoreInterface (What Core provides) + +```mermaid +classDiagram + class ICoreInterface { + +initialize(configPath) + +play(TrackInfo) + +pause() + +resume() + +stop() + +skip(count) + +queueTrack(TrackInfo, clientId) + +removeFromQueue(queueId) + +getQueue() + +prepareForHotReload() HotReloadState + +restoreAfterHotReload(state) + } +``` + +**Key Methods:** +- **Playback Control**: play, pause, resume, stop, skip +- **Queue Management**: queueTrack, removeFromQueue, clearQueue +- **Hot Reload**: prepareForHotReload, restoreAfterHotReload + +#### IPluginInterface (What Plugin provides) + +```mermaid +classDiagram + class IPluginInterface { + +sendTextMessage(targetId, message) + +sendChannelMessage(channelId, message) + +sendAudioData(data) + +setWhisperList(clientIds) + +getClients() ClientInfo[] + +moveClient(clientId, channelId) + +connectToServer(config) + } +``` + +**Key Methods:** +- **Messaging**: Send text to users/channels +- **Audio**: Send PCM audio data to TeamSpeak +- **Client Management**: Get user info, move users + +### 4. Event System (EventBus) + +A publish-subscribe mechanism for decoupled communication: + +```mermaid +flowchart TB + subgraph "Publishers" + MM[MusicManager] + AD[AudioDecoder] + NC[NetworkClient] + end + + subgraph "EventBus" + Q[Event Queue] + R[Router] + end + + subgraph "Subscribers" + CM[CommandManager] + PI[PluginInterface] + RS[RpcServer] + LG[Logger] + end + + MM -->|TrackQueued| Q + AD -->|PlaybackError| Q + NC -->|NetworkError| Q + Q --> R + R --> CM + R --> PI + R --> RS + R --> LG +``` + +**Event Types:** +- Playback events: PlaybackStarted, PlaybackPaused, TrackFinished +- Queue events: TrackQueued, TrackRemoved, QueueCleared +- Connection events: ClientConnected, ClientDisconnected +- Error events: PlaybackError, NetworkError + +### 5. Cache System + +Multi-tier caching for performance: + +```mermaid +flowchart LR + Request --> Cache{In Cache?} + Cache -->|Yes| Return[Return Cached] + Cache -->|No| Fetch[Fetch from Source] + Fetch --> Store[Store in Cache] + Store --> Return + + subgraph "Cache Types" + HTTP[HTTP Cache
5 min TTL] + Track[Track Info
1 hour TTL] + Meta[Metadata
30 min TTL] + end +``` + +**Features:** +- LRU (Least Recently Used) eviction +- TTL (Time To Live) expiration +- Memory usage tracking +- Thread-safe access + +### 6. Database Interface + +Persistence layer for user data: + +```mermaid +flowchart TB + subgraph "Database" + P[(Playlists)] + H[(Playback History)] + F[(Favorites)] + S[(Subscriptions)] + end + + subgraph "Operations" + CRUD[CRUD Operations] + MIG[Schema Migrations] + Q[Queries] + end + + CO[Core] --> CRUD + CRUD --> P + CRUD --> H + CRUD --> F + CRUD --> S +``` + +**Stored Data:** +- User playlists +- Playback history +- Favorite tracks +- Bot subscribers + +## Component Communication Flow + +```mermaid +sequenceDiagram + participant PL as Plugin + participant API as EchoionApi + participant CO as Core + participant DB as Database + + PL->>API: ICoreInterface.play(track) + API->>CO: Virtual call + CO->>CO: Process command + CO->>DB: Record in history + CO->>API: ECHOION_PUBLISH(PlaybackStarted) + API->>PL: Event callback + PL->>PL: Update UI +``` + +## Design Principles + +### 1. Type Safety +All data structures are strongly typed with no void* or raw pointers crossing component boundaries. + +### 2. Error Explicitness +Every operation that can fail returns a Result - you must check for errors. + +### 3. Thread Safety +All public APIs are thread-safe, using internal locking where needed. + +### 4. Zero-Copy Where Possible +Audio data uses memory pooling to avoid unnecessary copying. + +### 5. Version Compatibility +Interfaces are designed to be extended without breaking existing implementations. + +## Usage Pattern + +```mermaid +flowchart LR + subgraph "Your Component" + A[Include headers] + B[Use types] + C[Implement interface] + end + + subgraph "EchoionApi" + T[Types] + I[Interfaces] + U[Utilities] + end + + A --> T + B --> T + C --> I + B --> U +``` + +1. **Include** the API headers +2. **Use** the shared types (TrackInfo, Result, etc.) +3. **Implement** interfaces (ICoreInterface, IPluginInterface) +4. **Utilize** utilities (EventBus, Cache, Database) + +## Hot Reload State + +Special structure for preserving state during hot reload: + +```mermaid +flowchart LR + subgraph "HotReloadState" + P[PlaybackState] + Q[Queue] + POS[Position] + CFG[Config] + end + + Old[Old Core] -->|Extract| HotReloadState + HotReloadState -->|Restore| New[New Core] +``` + +This allows the new Core to resume exactly where the old one left off. diff --git a/docs/03-echoion-core.md b/docs/03-echoion-core.md new file mode 100644 index 0000000..a8141b7 --- /dev/null +++ b/docs/03-echoion-core.md @@ -0,0 +1,381 @@ +# EchoionCore - Music Playback Engine + +## What is EchoionCore? + +EchoionCore is the heart of the music bot - a dynamically loadable library that handles all music-related functionality. It's designed as a separate shared library to enable hot reloading. + +```mermaid +flowchart TB + subgraph "EchoionCore" + CO[Core Controller] + + subgraph "Managers" + MM[MusicManager
Queue & Playback] + CM[CommandManager
Commands] + SM[SubscriptionManager
Listeners] + end + + subgraph "Clients" + YC[YouTubeClient
yt-dlp] + NC[NetworkClient
HTTP] + end + + subgraph "Audio" + AD[AudioDecoder
FFmpeg] + MP[MemoryPool
Buffers] + end + + subgraph "API" + RS[RpcServer
WebSocket] + DB[(Database
SQLite)] + end + end + + CO --> MM + CO --> CM + CO --> SM + MM --> YC + MM --> AD + YC --> NC + AD --> MP + CO --> RS + CO --> DB +``` + +## Core Components + +### 1. Core (The Controller) + +The main entry point that: +- Initializes all subsystems +- Routes events between Plugin and internal components +- Manages configuration +- Coordinates the RPC server +- Handles hot reload state extraction/restoration + +```mermaid +flowchart LR + subgraph "Core" + I[Initialize] + E[Event Router] + C[Config Manager] + H[Hot Reload Handler] + end + + Plugin -->|Events| E + E -->|Commands| CommandManager + E -->|Control| MusicManager + C -->|Settings| All + H -->|State| MusicManager +``` + +### 2. MusicManager (The DJ) + +Central hub for all music operations: + +```mermaid +stateDiagram-v2 + [*] --> Idle + Idle --> Resolving: play() called + Resolving --> Buffering: URL obtained + Buffering --> Playing: Audio ready + Playing --> Paused: pause() + Paused --> Playing: resume() + Playing --> Idle: track finished + Playing --> Idle: stop() + Playing --> Buffering: skip() + + note right of Resolving + Search YouTube or + parse URL + end note + + note right of Buffering + FFmpeg opens + stream and + decodes first + frames + end note +``` + +**Responsibilities:** +- Queue management (add, remove, reorder) +- Playback control (play, pause, stop, skip) +- Track resolution (URL → stream) +- Volume control +- Shuffle and repeat modes +- Subscription management (who hears the bot) + +### 3. CommandManager (The Dispatcher) + +Routes text commands to handlers: + +```mermaid +flowchart TB + Input[Command String] --> Parse{Parse} + Parse -->|Extract| Cmd[Command] + Parse -->|Extract| Args[Arguments] + + Cmd --> Lookup{Find Handler} + Lookup -->|Found| Check{Check Permissions} + Lookup -->|Not Found| Error[Unknown Command] + + Check -->|Allowed| Execute[Execute Handler] + Check -->|Denied| PermissionError[No Permission] + + Execute --> Reply[Send Reply] +``` + +**Command Categories:** +- **Music**: play, search, select +- **Playback**: pause, resume, stop, skip, seek, volume +- **Queue**: queue, clear, shuffle, repeat, remove, move +- **Utility**: help, nowplaying, subscribe, unsubscribe +- **Admin**: reload, reloadconfig + +### 4. YouTubeClient (The Fetcher) + +Interfaces with YouTube via yt-dlp: + +```mermaid +sequenceDiagram + participant MM as MusicManager + participant YC as YouTubeClient + participant YM as YtDlpManager + participant YT as YouTube + + MM->>YC: search("query") + YC->>YM: execute yt-dlp + YM->>YT: Search request + YT-->>YM: Results + YM-->>YC: Video list + YC-->>MM: TrackInfo array + + MM->>YC: getVideoInfo(id) + YC->>YM: execute yt-dlp -f bestaudio + YM->>YT: Get stream URL + YT-->>YM: Stream URL + YM-->>YC: Video details + YC-->>MM: TrackInfo with streamUrl +``` + +**Features:** +- Automatic yt-dlp download/update +- Video search +- Playlist support +- Stream URL extraction +- Cookie-based authentication + +### 5. AudioDecoder (The Converter) + +Uses FFmpeg to decode audio streams: + +```mermaid +flowchart LR + Input[Input Stream
MP3/AAC/Opus/etc] --> FFmpeg + + subgraph "FFmpeg Pipeline" + Demux[Demuxer
Container format] + Decode[Decoder
Audio codec] + Resample[Resampler
SWR] + end + + FFmpeg --> Demux + Demux --> Decode + Decode --> Resample + Resample --> Output[Output PCM
192kHz Stereo] + + subgraph "Hardware Acceleration" + CUDA[NVIDIA CUDA] + VAAPI[Intel/AMD VAAPI] + VT[Apple VideoToolbox] + end + + Decode -.->|Optional| CUDA + Decode -.->|Optional| VAAPI + Decode -.->|Optional| VT +``` + +**Supported Formats:** +- MP3, AAC, Opus, Vorbis +- FLAC (lossless) +- WebM (YouTube) +- And more via FFmpeg + +**Output Format:** +- 192kHz sample rate (TeamSpeak requirement) +- Stereo (2 channels) +- 16-bit signed integer PCM + +### 6. RpcServer (The API) + +WebSocket server for remote control: + +```mermaid +flowchart TB + subgraph "RpcServer" + A[Acceptor] + H[Handler Registry] + B[Broadcast] + end + + subgraph "Clients" + D1[Desktop Client 1] + D2[Desktop Client 2] + D3[Desktop Client 3] + end + + A <-->|WebSocket| D1 + A <-->|WebSocket| D2 + A <-->|WebSocket| D3 + + D1 -->|Request| H + H -->|Execute| Core + Core -->|Event| B + B --> D1 + B --> D2 + B --> D3 +``` + +**Capabilities:** +- Playback control (play, pause, skip) +- Queue management +- Real-time events (track changes, volume) +- Authentication +- Multiple simultaneous clients + +### 7. SubscriptionManager (The Audience) + +Manages who receives bot audio: + +```mermaid +flowchart TB + subgraph "Subscription Model" + direction TB + + All[All in Channel] -->|Option| Sub[Subscribers Only] + + subgraph "Subscribers" + S1[User A] + S2[User B] + S3[User C] + end + + Sub --> S1 + Sub --> S2 + Sub --> S3 + end + + subgraph "Behavior" + NoSub[No Subscribers] --> Pause[Auto-Pause] + FirstSub[First Subscriber] --> Resume[Auto-Resume] + end +``` + +**Use Case:** +- Users subscribe to hear the bot +- Bot only plays when subscribers exist +- Saves bandwidth and resources + +## Audio Data Flow + +```mermaid +sequenceDiagram + participant YT as YouTube + participant NC as NetworkClient + participant YC as YouTubeClient + participant MM as MusicManager + participant AD as AudioDecoder + participant PI as PluginInterface + participant TS as TeamSpeak + + loop Every 20ms + AD->>YT: Read packet (via FFmpeg) + YT-->>AD: Encoded data + AD->>AD: Decode to PCM + AD->>MM: Float PCM buffer + MM->>MM: Apply volume + MM->>PI: Int16 PCM chunk + PI->>TS: Voice transmission + end +``` + +## Threading Model + +```mermaid +flowchart TB + subgraph "Threads" + MT[Main Thread
Event processing] + PT[Playback Thread
MusicManager] + DT[Decode Thread
AudioDecoder] + NT[Network Thread Pool
NetworkClient] + RT[RPC Thread
RpcServer] + ET[Event Thread
EventBus] + end + + subgraph "Synchronization" + M1[Mutex: Queue] + M2[Mutex: State] + CV[Condition Variables] + end + + MT --> M1 + MT --> M2 + PT --> M1 + PT --> CV + DT --> CV +``` + +## Hot Reload Support + +```mermaid +sequenceDiagram + participant CL as CoreLoader + participant Old as Old Core + participant State as HotReloadState + participant New as New Core + + CL->>Old: prepareForHotReload() + Old->>Old: Extract playback state + Old->>Old: Copy queue + Old->>Old: Get position + Old-->>State: Return state + + CL->>Old: shutdown() + CL->>Old: unload library + + CL->>New: load library + CL->>New: initialize() + CL->>New: restoreAfterHotReload(state) + + New->>New: Restore queue + New->>New: Resume playback + New->>New: Seek to position +``` + +## Key Design Decisions + +### 1. Shared Library Architecture +- Enables hot reload +- Plugin and Core can be updated independently +- Clean separation of concerns + +### 2. FFmpeg for Audio +- Supports virtually all audio formats +- Hardware acceleration support +- Mature and well-tested + +### 3. yt-dlp for YouTube +- More reliable than official API +- No API key required +- Supports age-restricted content (with cookies) + +### 4. WebSocket RPC +- Bidirectional communication +- Real-time events +- Easy to implement clients + +### 5. Subscription Model +- Saves resources when unused +- Users opt-in to receive audio +- Prevents unwanted playback diff --git a/docs/04-echoion-plugin.md b/docs/04-echoion-plugin.md new file mode 100644 index 0000000..d9860a9 --- /dev/null +++ b/docs/04-echoion-plugin.md @@ -0,0 +1,430 @@ +# EchoionPlugin - TeamSpeak Integration + +## Purpose + +EchoionPlugin is the bridge between EchoionCore and TeamSpeak 3. It handles all TeamSpeak-specific functionality, translating between the TeamSpeak SDK's C API and Echoion's modern C++ interfaces. + +```mermaid +flowchart TB + subgraph "TeamSpeak 3" + TS[TeamSpeak Client] + SDK[TeamSpeak SDK
C API] + end + + subgraph "EchoionPlugin" + PI[PluginInterface
IPluginInterface] + CL[CoreLoader
Dynamic Loader] + EP[Entry Points
ts3plugin_*] + end + + subgraph "EchoionCore" + CO[Core Library
Shared Object] + end + + TS <-->|Voice & Chat| SDK + SDK <-->|Callbacks| EP + EP --> PI + PI <-->|ICoreInterface| CO + CL <-->|Load/Unload| CO +``` + +## Architecture + +### Three Layers + +```mermaid +flowchart TB + subgraph "Layer 1: TeamSpeak SDK Interface" + EP[Entry Points] + CB[Event Callbacks] + + EP -->|ts3plugin_init| Init + EP -->|ts3plugin_shutdown| Shutdown + CB -->|onTextMessage| Events + CB -->|onClientMove| Events + end + + subgraph "Layer 2: Plugin Interface" + PI[PluginInterface] + + PI -->|sendTextMessage| Out + PI -->|sendAudioData| Out + PI -->|getClients| Query + end + + subgraph "Layer 3: Core Management" + CL[CoreLoader] + FW[FileWatcher] + + CL -->|load| Core + CL -->|unload| Core + CL -->|hotReload| Core + FW -->|trigger| CL + end +``` + +## Component Details + +### 1. Entry Points (TS3 Callbacks) + +TeamSpeak calls these functions: + +```mermaid +sequenceDiagram + participant TS as TeamSpeak + participant EP as Entry Points + participant PI as PluginInterface + participant CO as Core + + TS->>EP: ts3plugin_init() + EP->>EP: deferredInitialization() + EP->>PI: initialize() + EP->>CL: load Core + CL->>CO: createCore() + CO-->>EP: Core ready + + TS->>EP: onTextMessageEvent(msg) + EP->>PI: onTextMessageReceived(msg) + PI->>CO: onPluginEvent(event) + CO->>CO: processCommand() + CO-->>PI: send reply + PI-->>TS: display message + + TS->>EP: ts3plugin_shutdown() + EP->>CL: unload Core + EP->>PI: shutdown() +``` + +**Key Events Handled:** +- `onTextMessageEvent` - User sends chat message +- `onClientMoveEvent` - User joins/leaves/moves +- `onConnectStatusChange` - Connection state changes +- `onPluginCommandEvent` - Plugin menu commands + +### 2. PluginInterface (The Bridge) + +Implements IPluginInterface for Core communication: + +```mermaid +classDiagram + class IPluginInterface { + +sendTextMessage(target, message) + +sendAudioData(pcmData) + +getClients() + +moveClient(clientId, channel) + } + + class PluginInterface { + -TS3Functions* ts3Functions + -audioQueue + +initialize(ts3Functions) + +onTextMessageReceived(msg) + +onClientConnected(id) + +registerAudioDevice() + } + + IPluginInterface <|-- PluginInterface +``` + +**Audio Flow:** + +```mermaid +flowchart LR + Core -->|Float PCM| Convert[Convert to Int16] + Convert -->|Queue| AQ[Audio Queue] + AQ -->|20ms chunks| TS[TeamSpeak SDK] + TS -->|Voice| Channel[Voice Channel] +``` + +### 3. CoreLoader (Dynamic Manager) + +Manages the Core shared library lifecycle: + +```mermaid +stateDiagram-v2 + [*] --> Unloaded + Unloaded --> Loading: load() + Loading --> Loaded: Success + Loading --> Error: Failure + + Loaded --> Saving: hotReload() + Saving --> Unloading: extract state + Unloading --> Loading: load new + Loading --> Restoring: restore state + Restoring --> Loaded: Success + + Loaded --> Unloading: unload() + Unloading --> Unloaded + Error --> Unloaded +``` + +**Features:** +- Dynamic library loading +- Symbol resolution +- Hot reload state preservation +- Auto-reload on file change + +### 4. FileWatcher (Auto-Reload) + +Monitors Core library for updates: + +```mermaid +flowchart TB + File[Core Library File] -->|Modify| FW[FileWatcher] + FW -->|Debounce| Trigger{Check} + Trigger -->|Different| Reload[Trigger Hot Reload] + Trigger -->|Same| Ignore[Ignore] + Reload -->|Success| Updated[New Version Active] + Reload -->|Fail| Rollback[Keep Old Version] +``` + +## Initialization Sequence + +```mermaid +sequenceDiagram + participant TS as TeamSpeak + participant EP as Entry Points + participant PI as PluginInterface + participant CL as CoreLoader + participant CO as Core + + TS->>EP: ts3plugin_init() + Note over EP: Start deferred thread + + par Deferred Initialization + EP->>EP: Wait 3 seconds + EP->>EP: Wait for TS functions + and Continue + EP-->>TS: Return 0 (success) + end + + EP->>PI: initialize(TS3Functions) + PI->>PI: Register audio device + + EP->>CL: setConfigPath() + EP->>CL: load(libraryPath) + CL->>CO: createCore() + CO->>CO: initialize(config) + + EP->>CO: setPluginInterface(PI) + CO->>CO: triggerAutoConnect() + + opt Auto Reload Enabled + CL->>FW: startWatching() + end +``` + +## Event Handling + +### Text Message Flow + +```mermaid +flowchart TB + User[User Types] -->|!play song| TS[TeamSpeak] + TS -->|Callback| EP[Entry Point] + EP -->|Parse| Filter{Filter} + + Filter -->|From self| Drop[Ignore] + Filter -->|From other| PI[PluginInterface] + + PI -->|Create Event| Event[PluginEvent] + Event -->|TextMessageReceived| CO[Core] + CO -->|Dispatch| CM[CommandManager] + CM -->|Execute| Handler[Command Handler] + Handler -->|Result| CO + CO -->|Reply| PI + PI -->|Send| TS2[TeamSpeak] + TS2 -->|Display| User2[All Users] +``` + +### Client Movement Flow + +```mermaid +flowchart LR + User[User Action] -->|Join/Leave/Move| TS[TeamSpeak] + TS -->|onClientMoveEvent| EP[Entry Points] + EP -->|Determine type| Type{Type} + + Type -->|oldChannel=0| Connect[ClientConnected] + Type -->|newChannel=0| Disconnect[ClientDisconnected] + Type -->|Both non-zero| Move[ClientMoved] + + Connect --> PI[PluginInterface] + Disconnect --> PI + Move --> PI + + PI -->|Event| CO[Core] + CO -->|Update| Lists[Admin/Subscriber Lists] +``` + +## Audio System + +### Custom Audio Device + +```mermaid +flowchart TB + subgraph "Registration" + PI[PluginInterface] -->|registerCustomDevice| SDK[TS3 SDK] + SDK -->|Device ID| Device[echoion_audio_device] + end + + subgraph "Usage" + CO[Core] -->|PCM Data| PI2[PluginInterface] + PI2 -->|Queue| AQ[Audio Queue] + AQ -->|Thread| Play[Playback Thread] + Play -->|processCustomCaptureData| SDK2[TS3 SDK] + SDK2 -->|Voice| VC[Voice Channel] + end +``` + +**Device Configuration:** +- Sample Rate: 192 kHz +- Channels: Stereo (2) +- Format: 16-bit signed integer +- Chunk Size: 20ms + +### Audio Queue Management + +```mermaid +flowchart LR + Core -->|Push| Queue[Audio Queue] + Queue -->|Pop| Thread[Audio Thread] + Thread -->|Play| TS[TeamSpeak] + + Queue -.->|Full| Wait[Core Waits] + Queue -.->|Empty| Silence[Send Silence] +``` + +## Hot Reload Integration + +### Manual Reload + +```mermaid +sequenceDiagram + participant User as User Menu + participant EP as Entry Points + participant CL as CoreLoader + participant Old as Old Core + participant New as New Core + + User->>EP: Click "Reload Core" + EP->>CL: hotReload() + CL->>Old: prepareForHotReload() + Old-->>CL: HotReloadState + CL->>Old: shutdown() + CL->>Old: unload() + CL->>New: load() + CL->>New: initialize() + CL->>New: restoreAfterHotReload(state) + New->>CL: Ready + CL-->>EP: Success +``` + +### Auto Reload + +```mermaid +flowchart TB + Dev[Developer] -->|Build| New[New Core Binary] + New -->|File Change| FW[FileWatcher] + FW -->|Debounce 1s| Check{Loaded?} + Check -->|Yes| Reload[Trigger Hot Reload] + Check -->|No| Wait + Reload -->|Success| Active[New Version] + Reload -->|Fail| Keep[Keep Old] +``` + +## Menu Integration + +### Right-Click Menu Items + +```mermaid +flowchart TB + User[User Right-Click] --> Menu[TS3 Menu] + Menu -->|Play/Pause| A[Toggle Playback] + Menu -->|Skip| B[Next Track] + Menu -->|Stop| C[Stop Playback] + Menu -->|Reload Core| D[Hot Reload] + Menu -->|Connect/Disconnect| E[Toggle Connection] + + A --> EP[Entry Point] + B --> EP + C --> EP + D --> EP + E --> EP + + EP -->|Menu ID| Handler[Handle Menu Event] + Handler -->|1| PlayPause[Core::pause/resume] + Handler -->|2| SkipTrack[Core::skip] + Handler -->|3| StopTrack[Core::stop] + Handler -->|4| Reload[CoreLoader::hotReload] + Handler -->|5| Connect[Toggle Connection] +``` + +## Shutdown Sequence + +```mermaid +sequenceDiagram + participant TS as TeamSpeak + participant EP as Entry Points + participant PI as PluginInterface + participant CL as CoreLoader + participant CO as Core + + TS->>EP: ts3plugin_shutdown() + + EP->>EP: Stop deferred init if running + EP->>PI: disconnectFromServer() + + EP->>CL: disableAutoReload() + EP->>CL: unload() + CL->>CO: shutdown() + CL->>CO: destroyCore() + + EP->>PI: shutdown() + PI->>PI: unregisterAudioDevice() + + EP->>EP: Cleanup globals +``` + +## Thread Safety + +```mermaid +flowchart TB + subgraph "Main Thread (TS3 Callbacks)" + A[Text Messages] + B[Client Events] + C[Menu Events] + end + + subgraph "Audio Thread" + D[Audio Queue Processing] + end + + subgraph "Core Threads" + E[Playback] + F[Decode] + G[Network] + end + + A -->|Mutex| Shared[Shared State] + B -->|Mutex| Shared + C -->|Mutex| Shared + D -->|Mutex| Shared +``` + +## Platform Differences + +### Windows +- DLL files (.dll) +- Requires temp copy for hot reload (file locking) +- Uses Windows-specific paths + +### Linux +- Shared objects (.so) +- Can overwrite loaded libraries +- Uses XDG directories + +### macOS +- Bundles (.dylib) +- Similar to Linux +- Uses macOS-specific paths diff --git a/docs/05-echoion-desktop.md b/docs/05-echoion-desktop.md new file mode 100644 index 0000000..b9ea135 --- /dev/null +++ b/docs/05-echoion-desktop.md @@ -0,0 +1,426 @@ +# EchoionDesktop - Desktop Control Client + +## Purpose + +EchoionDesktop is a standalone Qt6 application that provides a graphical interface for controlling the Echoion music bot remotely. Unlike the TeamSpeak plugin interface, this desktop client connects via WebSocket to offer rich visual feedback and easier control. + +```mermaid +flowchart TB + subgraph "EchoionDesktop" + UI[Qt6 GUI] + CC[CoreClient] + WS[QWebSocket] + end + + subgraph "EchoionCore" + RS[RpcServer] + MM[MusicManager] + end + + subgraph "Connection" + Protocol[WebSocket Protocol
Port 8765] + end + + UI <-->|Signals/Slots| CC + CC <-->|JSON-RPC| WS + WS <-->|WebSocket| Protocol + Protocol <-->|JSON-RPC| RS + RS <-->|Commands| MM +``` + +## Architecture + +### Three-Layer Design + +```mermaid +flowchart TB + subgraph "Presentation Layer" + MW[MainWindow] + LD[LoginDialog] + + subgraph "Widgets" + PC[Playback Controls] + SP[Search Panel] + QV[Queue View] + SB[Status Bar] + end + + MW --> PC + MW --> SP + MW --> QV + MW --> SB + end + + subgraph "Business Logic Layer" + CC[CoreClient] + Auth[Authentication] + + CC --> Auth + end + + subgraph "Network Layer" + WS[QWebSocket] + JR[JSON-RPC Handler] + end + + PC -->|User Actions| CC + CC -->|State Updates| PC + CC --> WS + WS --> JR +``` + +## User Interface + +### Main Window Layout + +```mermaid +flowchart TB + subgraph "MainWindow" + direction TB + + TB2[Title Bar
Login/Settings] + + subgraph "Playback Section" + NP[Now Playing
Title - Artist] + PB[Progress Bar
[=====> ] 2:34/4:12] + CTRL[Buttons: Play Pause Stop Skip Shuffle Repeat] + VOL[Volume: [====> ] 50%] + end + + subgraph "Main Content" + direction LR + + subgraph "Search Panel" + SI[Search Input] + SR[Search Results List] + end + + subgraph "Queue Panel" + QL[Queue List] + QB[Clear / Remove] + end + end + + ST[Status Bar
Connected ● | Authenticated ●] + end + + TB2 --> Playback Section + Playback Section --> Main Content + Main Content --> ST +``` + +### Screen Flow + +```mermaid +stateDiagram-v2 + [*] --> Disconnected + Disconnected --> Connecting: Start application + Connecting --> Connected: WebSocket open + Connecting --> Disconnected: Connection failed + + Connected --> Authenticating: Login clicked + Authenticating --> Authenticated: Valid credentials + Authenticating --> Connected: Login failed + + Authenticated --> Connected: Logout + Authenticated --> Disconnected: Connection lost + + Connected --> Disconnected: Disconnect + Disconnected --> [*]: Close application +``` + +## Components + +### 1. MainWindow (The UI) + +Central widget containing all controls: + +**Sections:** +- **Playback Controls**: Play, pause, stop, skip, shuffle, repeat buttons +- **Progress Display**: Current position, duration, progress bar +- **Volume Control**: Slider for volume adjustment +- **Search Panel**: Input field and results list +- **Queue View**: Current queue with drag-and-drop reordering +- **Status Bar**: Connection and authentication status + +**State Synchronization:** + +```mermaid +sequenceDiagram + participant UI as MainWindow + participant CC as CoreClient + participant RS as RpcServer + + UI->>CC: Request playback state + CC->>RS: getPlaybackState + RS-->>CC: PlaybackState + CC-->>UI: playbackStateReceived + UI->>UI: Update all widgets + + loop Real-time updates + RS->>CC: Event notification + CC-->>UI: trackStarted/volumeChanged/etc + UI->>UI: Update specific widget + end +``` + +### 2. CoreClient (The Connector) + +Manages WebSocket connection to EchoionCore: + +**Responsibilities:** +- Establish and maintain WebSocket connection +- Handle authentication +- Send RPC requests +- Receive and dispatch events +- Auto-reconnection on disconnect + +```mermaid +flowchart TB + subgraph "CoreClient" + State[Connection State] + Pending[Pending Requests] + Handlers[Response Handlers] + end + + subgraph "Operations" + Connect[connectToCore] + Auth[authenticate] + Call[RPC Calls] + Events[Event Handling] + end + + State --> Connect + Connect --> Auth + Auth --> Call + Call --> Pending + Pending --> Handlers + Handlers --> Events +``` + +### 3. LoginDialog (Authentication) + +Simple dialog for admin login: + +```mermaid +flowchart LR + Dialog[LoginDialog] -->|Show| User[User Input] + User -->|Username| Field1[Username Field] + User -->|Password| Field2[Password Field] + Field1 --> Validate + Field2 --> Validate + Validate -->|OK| Return[Return Credentials] + Validate -->|Cancel| Close[Close Dialog] +``` + +## Communication Protocol + +### Message Types + +```mermaid +flowchart TB + subgraph "Client → Core (Requests)" + R1[Method Call
id + method + params] + R2[Authentication
username + password] + end + + subgraph "Core → Client (Responses)" + S1[Success Response
id + result] + S2[Error Response
id + error code + message] + S3[Event Notification
event name + data] + end +``` + +### Request Flow + +```mermaid +sequenceDiagram + participant User + participant UI as MainWindow + participant CC as CoreClient + participant RS as RpcServer + participant MM as MusicManager + + User->>UI: Click Play + UI->>CC: play(query) + CC->>CC: Generate request ID + CC->>RS: Send JSON-RPC request + RS->>MM: Execute play + MM-->>RS: Result + RS-->>CC: JSON-RPC response + CC->>CC: Match to pending request + CC-->>UI: Handle response + UI->>UI: Update display +``` + +### Event Flow + +```mermaid +sequenceDiagram + participant MM as MusicManager + participant RS as RpcServer + participant CC as CoreClient + participant UI as MainWindow + + MM->>RS: Track started + RS->>RS: Broadcast to all clients + RS->>CC: WebSocket message + CC->>CC: Parse event type + CC-->>UI: Emit trackStarted signal + UI->>UI: Update now playing +``` + +## Supported Operations + +### Playback Control + +| Action | UI Element | RPC Method | +|--------|-----------|------------| +| Play | Play button / Search double-click | `play` | +| Pause | Pause button | `pause` | +| Resume | Play button (when paused) | `resume` | +| Stop | Stop button | `stop` | +| Skip | Skip button | `skip` | +| Seek | Progress bar drag | `seek` | +| Volume | Volume slider | `setVolume` | + +### Queue Management + +| Action | UI Element | RPC Method | +|--------|-----------|------------| +| Add to queue | Add button / Context menu | `queueTrack` | +| Remove | Delete key / Remove button | `removeFromQueue` | +| Reorder | Drag & drop | `moveInQueue` | +| Clear | Clear button | `clearQueue` | +| Shuffle | Shuffle button | `toggleShuffle` | +| Repeat | Repeat button | `toggleRepeat` | + +### Search + +| Action | UI Element | RPC Method | +|--------|-----------|------------| +| Search | Search button | `searchTracks` | +| Select result | Double-click | `play` or `queueTrack` | + +## Auto-Reconnection + +```mermaid +stateDiagram-v2 + Connected --> Disconnected: Connection lost + Disconnected --> Reconnecting: Auto-retry enabled + Reconnecting --> Connected: Success + Reconnecting --> Disconnected: Max retries exceeded + Reconnecting --> Reconnecting: Retry (delay increases) +``` + +**Reconnection Strategy:** +1. Detect disconnection +2. Wait 1 second (increases with each retry) +3. Attempt reconnection +4. If successful, restore authentication if previously authenticated +5. If max retries (5) exceeded, show error dialog + +## Threading Model + +```mermaid +flowchart TB + subgraph "Main Thread (Qt)" + UI[UI Updates] + Signals[Signal/Slot Processing] + end + + subgraph "Qt Network Thread" + WS[QWebSocket I/O] + end + + subgraph "Callback Thread" + Handler[Response Handler] + EventProc[Event Processor] + end + + WS -->|Qt::QueuedConnection| Signals + Signals --> UI + Handler -->|Emit signals| Signals + EventProc -->|Emit signals| Signals +``` + +All UI updates happen on the main thread via Qt's signal/slot mechanism. + +## Error Handling + +```mermaid +flowchart TB + Error{Error Type} --> Net[Network Error] + Error --> Auth[Auth Error] + Error --> RPC[RPC Error] + + Net -->|Show| Dialog1[Connection Failed Dialog] + Net -->|Auto| Retry[Retry Connection] + + Auth -->|Show| Dialog2[Login Failed Message] + Auth -->|Clear| Token[Clear Token] + + RPC -->|Show| Status[Status Bar Message] +``` + +## State Synchronization Strategy + +### 1. Polling (Backup) + +```mermaid +loop Every 5 seconds + UI->>CC: Request current state + CC->>RS: getPlaybackState + RS-->>CC: State + CC-->>UI: Update UI +end +``` + +### 2. Event-Driven (Primary) + +```mermaid +RS->>CC: playbackStarted event +CC->>UI: Update now playing +RS->>CC: volumeChanged event +CC->>UI: Update volume slider +RS->>CC: trackQueued event +CC->>UI: Add to queue list +``` + +### 3. Optimistic Updates + +```mermaid +User->>UI: Click volume up +UI->>UI: Immediately update slider +UI->>CC: setVolume +CC->>RS: RPC call +RS-->>CC: Success +Note over UI,CC: No UI change needed +``` + +## Multi-Client Support + +Multiple desktop clients can connect simultaneously: + +```mermaid +flowchart TB + subgraph "Core RpcServer" + B[Broadcast Events] + end + + subgraph "Connected Clients" + C1[Desktop Client 1] + C2[Desktop Client 2] + C3[Desktop Client 3] + end + + B --> C1 + B --> C2 + B --> C3 + + C1 -->|Control| Core + C2 -->|Control| Core + C3 -->|Control| Core +``` + +All clients receive the same events and stay synchronized. diff --git a/docs/06-data-flow.md b/docs/06-data-flow.md new file mode 100644 index 0000000..64b556d --- /dev/null +++ b/docs/06-data-flow.md @@ -0,0 +1,505 @@ +# Data Flow and Communication + +## Overview + +This document describes how data moves through the Echoion system, from user input to audio output, and the protocols used for communication between components. + +## System Communication Overview + +```mermaid +flowchart TB + subgraph "Input" + TS[TeamSpeak Chat] + DT[Desktop Client] + end + + subgraph "Processing" + PL[EchoionPlugin] + CO[EchoionCore] + end + + subgraph "External" + YT[YouTube] + DB[(Database)] + end + + subgraph "Output" + VC[Voice Channel] + end + + TS -->|Text Commands| PL + DT <-->|WebSocket| CO + PL <-->|ICoreInterface| CO + CO -->|HTTP| YT + CO -->|SQL| DB + PL -->|Voice| VC +``` + +## Communication Protocols + +### 1. Plugin ↔ Core (In-Process) + +```mermaid +flowchart LR + subgraph "Process Boundary" + PL[Plugin] + CO[Core] + end + + PL <-->|Virtual Function Calls| CO + + subgraph "Interface Contract" + I1[ICoreInterface
Plugin → Core] + I2[IPluginInterface
Core → Plugin] + end + + PL -.->|Uses| I1 + CO -.->|Uses| I2 +``` + +**Characteristics:** +- Same process, different threads +- Virtual function calls through shared library boundary +- Thread-safe with internal locking +- No serialization overhead + +### 2. Desktop ↔ Core (WebSocket RPC) + +```mermaid +sequenceDiagram + participant D as Desktop + participant WS as WebSocket + participant RS as RpcServer + participant C as Core + + D->>WS: Connect + WS-->>D: Connected + + D->>WS: {"method": "authenticate", ...} + WS->>RS: Forward + RS->>C: Validate + C-->>RS: Token + RS-->>WS: {"success": true, ...} + WS-->>D: Response + + D->>WS: {"method": "play", "params": {...}} + WS->>RS: Forward + RS->>C: Execute + C-->>RS: Result + RS-->>WS: {"result": {...}} + WS-->>D: Response + + C->>RS: Event: playbackStarted + RS->>WS: Broadcast + WS-->>D: {"event": "playbackStarted", ...} +``` + +**Protocol Stack:** +``` +Application: JSON-RPC 2.0 +Transport: WebSocket +Network: TCP +``` + +### 3. Core Internal (EventBus) + +```mermaid +flowchart TB + subgraph "Publishers" + MM[MusicManager] + AD[AudioDecoder] + NC[NetworkClient] + end + + subgraph "EventBus" + Q[Thread-Safe Queue] + D[Dispatcher] + end + + subgraph "Subscribers" + CM[CommandManager] + PI[PluginInterface] + RS[RpcServer] + LG[Logger] + end + + MM -->|TrackQueued| Q + AD -->|PlaybackError| Q + NC -->|NetworkError| Q + + Q --> D + + D --> CM + D --> PI + D --> RS + D --> LG +``` + +**Event Flow:** +1. Publisher calls `publish(event)` +2. Event queued thread-safely +3. EventBus thread processes queue +4. Event dispatched to all subscribers +5. Each subscriber handles event asynchronously + +## Complete Data Flows + +### 1. Playing a Song (Full Flow) + +```mermaid +sequenceDiagram + actor User + participant TS as TeamSpeak + participant PL as Plugin + participant CO as Core + participant CM as CommandManager + participant MM as MusicManager + participant YC as YouTubeClient + participant YT as YouTube + participant AD as AudioDecoder + participant VC as Voice Channel + + User->>TS: Type "!play song name" + TS->>PL: onTextMessage + PL->>CO: onPluginEvent(TextMessage) + CO->>CM: dispatch + CM->>MM: play("song name") + + MM->>YC: search("song name") + YC->>YT: HTTP Request + YT-->>YC: Search Results + YC-->>MM: TrackInfo + + MM->>MM: Add to queue + MM->>CO: Event: TrackQueued + CO->>PL: sendTextMessage("Added to queue") + PL->>TS: Display message + + MM->>YC: getStreamUrl(videoId) + YC->>YT: Get stream URL + YT-->>YC: Stream URL + + MM->>AD: openSource(streamUrl) + AD->>YT: Connect stream + + loop Every 20ms + AD->>AD: Decode frame + AD-->>MM: PCM Data + MM->>MM: Apply volume + MM->>CO: audioCallback + CO->>PL: sendAudioData + PL->>VC: Voice transmission + end +``` + +### 2. Queue Management Flow + +```mermaid +flowchart TB + subgraph "Adding to Queue" + A1[User: !play song] --> A2[CommandManager] + A2 --> A3[MusicManager.queueTrack] + A3 --> A4{Playing?} + A4 -->|No| A5[Start Playback] + A4 -->|Yes| A6[Add to Queue] + A5 --> A7[Broadcast: TrackQueued] + A6 --> A7 + A7 --> A8[Reply to User] + end + + subgraph "Queue Processing" + B1[Current Track Ends] --> B2{Repeat?} + B2 -->|Yes| B3[Replay Current] + B2 -->|No| B4{Queue Empty?} + B4 -->|No| B5{Shuffle?} + B5 -->|Yes| B6[Pick Random] + B5 -->|No| B7[Pick Next] + B6 --> B8[Start Track] + B7 --> B8 + B4 -->|Yes| B9[Stop Playback] + end +``` + +### 3. Hot Reload State Transfer + +```mermaid +flowchart TB + subgraph "Before Reload" + Old[Old Core] + State[Playback State] + Queue[Queue Contents] + Pos[Current Position] + Cfg[Configuration] + end + + subgraph "State Extraction" + Old -->|prepareForHotReload| Extract[Extract State] + Extract --> State + Extract --> Queue + Extract --> Pos + Extract --> Cfg + end + + subgraph "Transfer" + State --> HRS[HotReloadState] + Queue --> HRS + Pos --> HRS + Cfg --> HRS + end + + subgraph "After Reload" + HRS -->|restoreAfterHotReload| New[New Core] + New -->|Resume| Playback[Continue Playback] + end +``` + +### 4. Audio Pipeline Data Transformations + +```mermaid +flowchart LR + subgraph "Source" + YT[YouTube Stream
AAC/Opus/MP3] + end + + subgraph "Decoding" + FFmpeg[FFmpeg Decoder] + Raw[Raw PCM
Float 32-bit
Variable Rate] + end + + subgraph "Processing" + Vol[Volume Control] + Resamp[Resampler
SWR] + Proc[Processed PCM
Float 192kHz Stereo] + end + + subgraph "Output" + Conv[Convert to Int16] + PCM[Int16 192kHz Stereo
20ms chunks] + TS[TeamSpeak Voice] + end + + YT --> FFmpeg + FFmpeg --> Raw + Raw --> Vol + Vol --> Resamp + Resamp --> Proc + Proc --> Conv + Conv --> PCM + PCM --> TS +``` + +### 5. Desktop Client Synchronization + +```mermaid +sequenceDiagram + participant D as Desktop + participant C as Core + participant MM as MusicManager + + D->>C: Connect WebSocket + C-->>D: Connected + + D->>C: Request current state + C->>MM: Get playback state + MM-->>C: State + C-->>D: Full state snapshot + D->>D: Initialize UI + + Note over D,MM: Real-time updates via events + + User->>C: !skip (from TS) + C->>MM: Skip + MM->>C: Event: TrackFinished + MM->>C: Event: PlaybackStarted + C->>D: Broadcast: TrackFinished + C->>D: Broadcast: PlaybackStarted + D->>D: Update UI +``` + +## Message Formats + +### Plugin Events (Internal) + +```mermaid +classDiagram + class PluginEvent { + +EventType type + +uint64 clientId + +string message + +TrackInfo trackInfo + +float volume + } + + class EventType { + TextMessageReceived + ClientConnected + ClientDisconnected + PlayRequested + TrackQueued + PlaybackStarted + VolumeChanged + } +``` + +### RPC Messages (WebSocket) + +**Request:** +```mermaid +json +{ + "jsonrpc": "2.0", + "id": 42, + "method": "play", + "params": { + "query": "song name" + } +} +``` + +**Success Response:** +```mermaid +json +{ + "jsonrpc": "2.0", + "id": 42, + "result": { + "trackId": "abc123", + "title": "Song Name", + "artist": "Artist Name" + } +} +``` + +**Error Response:** +```mermaid +json +{ + "jsonrpc": "2.0", + "id": 42, + "error": { + "code": -32600, + "message": "Invalid Request", + "data": { + "details": "No results found" + } + } +} +``` + +**Event Notification:** +```mermaid +json +{ + "jsonrpc": "2.0", + "method": "event", + "params": { + "event": "playbackStarted", + "data": { + "track": {...}, + "position": 0 + } + } +} +``` + +## Error Propagation + +```mermaid +flowchart TB + subgraph "Error Sources" + Net[Network Error] + Aud[Audio Error] + Cmd[Command Error] + end + + subgraph "Error Handling" + Catch[Catch Error] + Wrap[Wrap in Result] + Log[Log Error] + Notify[Notify User] + end + + subgraph "Recovery" + Retry[Retry Operation] + Skip[Skip Track] + Stop[Stop Playback] + Inform[Show Error Message] + end + + Net --> Catch + Aud --> Catch + Cmd --> Catch + + Catch --> Wrap + Wrap --> Log + Wrap --> Notify + + Notify -->|Network| Retry + Notify -->|Audio| Skip + Notify -->|Critical| Stop + Notify -->|User| Inform +``` + +## Data Persistence Flow + +```mermaid +flowchart TB + subgraph "Memory" + MM[MusicManager] + CM[CommandManager] + end + + subgraph "Events" + E1[TrackPlayed] + E2[PlaylistCreated] + E3[FavoriteAdded] + end + + subgraph "Database" + DB[(SQLite)] + Hist[History Table] + Play[Playlists Table] + Fav[Favorites Table] + end + + MM -->|Publish| E1 + CM -->|Publish| E2 + CM -->|Publish| E3 + + E1 -->|Subscribe| DB + E2 -->|Subscribe| DB + E3 -->|Subscribe| DB + + DB --> Hist + DB --> Play + DB --> Fav +``` + +## Caching Strategy + +```mermaid +flowchart TB + Request[Data Request] --> Check{In Cache?} + + Check -->|Yes| Fresh{Fresh?} + Fresh -->|Yes| Return[Return Cached] + Fresh -->|No| Fetch + + Check -->|No| Fetch[Fetch Source] + + Fetch --> YouTube[YouTube API] + Fetch --> HTTP[HTTP Request] + + YouTube --> Store[Store in Cache] + HTTP --> Store + + Store --> Return + + subgraph "Cache Tiers" + L1[Memory Cache
LRU Policy] + L2[Persistent Cache
SQLite] + end + + Store --> L1 + L1 -.->|Eviction| L2 +``` diff --git a/docs/07-configuration.md b/docs/07-configuration.md new file mode 100644 index 0000000..891ff1e --- /dev/null +++ b/docs/07-configuration.md @@ -0,0 +1,301 @@ +# Configuration System + +## Overview + +Echoion uses a unified JSON-based configuration shared between all components. The configuration is stored in a platform-specific location and can be reloaded at runtime without restart. + +## Configuration File Location + +| Platform | Path | +|----------|------| +| Linux | `~/.config/echoion/config.json` | +| macOS | `~/Library/Application Support/echoion/config.json` | +| Windows | `%APPDATA%/echoion/config.json` | + +## Configuration Architecture + +```mermaid +flowchart TB + subgraph "Configuration System" + CM[ConfigManager
Singleton] + + subgraph "Sources" + File[Config File
JSON] + Env[Environment
Variables] + Default[Default
Values] + end + + subgraph "Consumers" + Core[EchoionCore] + Plugin[EchoionPlugin] + Desktop[EchoionDesktop] + end + end + + File -->|Load| CM + Env -->|Override| CM + Default -->|Fallback| CM + + CM -->|Get Config| Core + CM -->|Get Config| Plugin + CM -->|Get Config| Desktop + + CM -->|Notify| Core + CM -->|Notify| Plugin +``` + +## Configuration Structure + +```mermaid +classDiagram + class AppConfig { + +BotConfig bot + +ServerConfig server + +SecurityConfig security + } + + class BotConfig { + +string commandPrefix + +float defaultVolume + +bool autoReconnect + +int maxQueueSize + +string preferredQuality + } + + class ServerConfig { + +string address + +int port + +string nickname + +int[] adminGroups + +int[] djGroups + } + + class SecurityConfig { + +bool requireAuthForAdmin + +int maxLoginAttempts + +int lockoutDuration + +bool enableAuditLog + } + + AppConfig --> BotConfig + AppConfig --> ServerConfig + AppConfig --> SecurityConfig +``` + +## Configuration Sections + +### Bot Configuration + +Controls bot behavior and music playback: + +| Field | Description | Default | +|-------|-------------|---------| +| `commandPrefix` | Prefix for chat commands | `!` | +| `defaultVolume` | Initial playback volume (0.0-1.0) | `0.5` | +| `autoReconnect` | Reconnect on disconnect | `true` | +| `maxQueueSize` | Maximum tracks in queue | `100` | +| `preferredQuality` | Audio quality preference | `High` | + +### Server Configuration + +TeamSpeak server connection settings: + +| Field | Description | Default | +|-------|-------------|---------| +| `address` | Server hostname or IP | `localhost` | +| `port` | Server port | `9987` | +| `nickname` | Bot display name | `EchoionBot` | +| `adminGroups` | Server group IDs with admin rights | `[6, 7]` | +| `djGroups` | Server group IDs with DJ rights | `[8]` | + +### Security Configuration + +Authentication and protection settings: + +| Field | Description | Default | +|-------|-------------|---------| +| `requireAuthForAdmin` | Require password for admin commands | `true` | +| `maxLoginAttempts` | Failed attempts before lockout | `5` | +| `lockoutDuration` | Lockout time in milliseconds | `300000` (5 min) | +| `sessionTimeout` | Session expiration in milliseconds | `3600000` (1 hour) | + +## Access Pattern + +```mermaid +flowchart LR + Request[Config Request] --> CM[ConfigManager] + CM --> Check{Cached?} + + Check -->|Yes| Return[Return Config] + Check -->|No| Load[Load from Disk] + + Load --> Parse[Parse JSON] + Parse --> Validate[Validate Values] + Validate --> Cache[Cache Config] + Cache --> Return + + Return --> Use[Use Values] +``` + +## Configuration Reload + +```mermaid +sequenceDiagram + participant User + participant CM as ConfigManager + participant File as Config File + participant Core + participant Plugin + + User->>CM: Trigger reload + CM->>File: Read config.json + File-->>CM: JSON content + + CM->>CM: Parse & validate + CM->>CM: Update cache + + CM->>Core: onConfigChanged event + CM->>Plugin: onConfigChanged event + + Core->>Core: Apply new settings + Plugin->>Plugin: Apply new settings + + CM-->>User: Reload success +``` + +### Reload Triggers + +```mermaid +flowchart TB + subgraph "Reload Triggers" + Chat["Chat Command
!reloadconfig"] + Menu["TS Menu
Right-click → Reload"] + Code["Programmatic
reload()"] + Auto["File Watcher
Auto-detect changes"] + end + + Chat --> CM[ConfigManager] + Menu --> CM + Code --> CM + Auto --> CM + + CM --> Reload[Reload Config] + Reload --> Notify[Notify Subscribers] +``` + +## Permission Groups + +### Group Hierarchy + +```mermaid +flowchart TB + subgraph "Permission Groups" + Admin[Admin Groups
Full Control] + DJ[DJ Groups
Queue Management] + User[Regular Users
Basic Commands] + Banned[Banned Groups
No Access] + end + + Admin --> DJ + DJ --> User + + Banned -.->|Blocked| User +``` + +### Permission Matrix + +| Capability | Admin | DJ | User | Banned | +|------------|-------|-----|------|--------| +| Play/Pause | ✓ | ✓ | ✓ | ✗ | +| Skip Track | ✓ | ✓ | ✓ | ✗ | +| Queue Management | ✓ | ✓ | ✗ | ✗ | +| Volume Control | ✓ | ✓ | ✓ | ✗ | +| Reload Core | ✓ | ✗ | ✗ | ✗ | +| Reload Config | ✓ | ✗ | ✗ | ✗ | + +## YouTube Authentication + +For accessing age-restricted or region-blocked content: + +```mermaid +flowchart LR + subgraph "Authentication Methods" + Cookies[Cookie File
cookies.txt] + Browser[Browser Cookies
chrome/firefox/edge] + ApiKey[YouTube API Key
Optional] + end + + Cookies --> YT[YouTube Access] + Browser --> YT + ApiKey -.->|Alternative| YT +``` + +| Method | Use Case | +|--------|----------| +| **Cookie File** | Export cookies from browser to file | +| **Browser** | Directly use browser's cookies | +| **API Key** | Higher rate limits (optional) | + +## Proxy Configuration + +```mermaid +flowchart LR + Bot[Echoion Bot] --> Proxy{Proxy?} + Proxy -->|Yes| HTTP[HTTP Proxy] + Proxy -->|Yes| SOCKS[SOCKS5 Proxy] + Proxy -->|No| Direct[Direct Connection] + + HTTP --> YouTube + SOCKS --> YouTube + Direct --> YouTube +``` + +## Configuration Lifecycle + +```mermaid +stateDiagram-v2 + [*] --> Default: First start + [*] --> Loading: Config exists + + Default --> Create: Create default + Create --> Save: Write to disk + + Loading --> Validate: Parse JSON + Validate --> Active: Valid + Validate --> Error: Invalid + + Error --> Default: Use defaults + + Active --> Reload: Trigger reload + Reload --> Validate: Re-parse + + Active --> [*]: Shutdown +``` + +## Environment Overrides + +| Variable | Overrides | +|----------|-----------| +| `ECHOION_CONFIG_PATH` | Config file location | +| `ECHOION_RPC_PORT` | RPC server port | +| `ECHOION_LOG_LEVEL` | Logging verbosity | + +## Validation Flow + +```mermaid +flowchart TB + Load[Load Config] --> Required{Required
Fields?} + Required -->|Missing| Error1[Error: Missing Field] + + Required -->|OK| Range{Value
Ranges?} + Range -->|Invalid| Error2[Error: Out of Range] + + Range -->|OK| Type{Correct
Types?} + Type -->|Invalid| Error3[Error: Type Mismatch] + + Type -->|OK| Success[Config Valid] + + Error1 --> Backup[Restore from Backup] + Error2 --> Backup + Error3 --> Backup +``` diff --git a/docs/08-commands.md b/docs/08-commands.md new file mode 100644 index 0000000..8508c6c --- /dev/null +++ b/docs/08-commands.md @@ -0,0 +1,338 @@ +# Command System + +## Overview + +Echoion processes user commands from TeamSpeak chat messages. Commands are prefixed (default: `!`) and dispatched to appropriate handlers based on the command name. + +## Command Architecture + +```mermaid +flowchart TB + subgraph "Command Flow" + User[User Message] --> Plugin[PluginInterface] + Plugin --> Core[EchoionCore] + Core --> CM[CommandManager] + + CM --> Parse[Parse Command] + Parse --> Lookup[Lookup Handler] + Lookup --> Check{Check
Permissions} + + Check -->|Denied| Deny[Permission Denied] + Check -->|Allowed| Execute[Execute Handler] + + Execute --> Reply[Send Reply] + Deny --> Reply + end + + subgraph "Handler Registry" + H1[play → PlayHandler] + H2[pause → PauseHandler] + H3[skip → SkipHandler] + H4[volume → VolumeHandler] + end + + Lookup --> H1 + Lookup --> H2 + Lookup --> H3 + Lookup --> H4 +``` + +## Command Processing Flow + +```mermaid +sequenceDiagram + actor User + participant TS as TeamSpeak + participant PL as Plugin + participant CO as Core + participant CM as CommandManager + + User->>TS: Type "!play song name" + TS->>PL: onTextMessageReceived + PL->>CO: onPluginEvent + CO->>CM: dispatch + + CM->>CM: Parse command + CM->>CM: Extract arguments + CM->>CM: Find handler + CM->>CM: Check permissions + + alt Permission Granted + CM->>CM: Execute handler + CM->>CO: Process result + CO->>PL: sendTextMessage + PL->>TS: Display result + TS->>User: See response + else Permission Denied + CM->>CO: Permission error + CO->>PL: send error + PL->>TS: Display error + end +``` + +## Command Categories + +```mermaid +flowchart TB + subgraph "Command Categories" + Music[Music Commands
Search & Play] + Playback[Playback Commands
Control Audio] + Queue[Queue Commands
Manage Queue] + Utility[Utility Commands
Help & Info] + Admin[Admin Commands
System Control] + end + + Music --> Play[play, search] + Playback --> Ctrl[pause, resume, skip, volume] + Queue --> Q[queue, clear, shuffle, remove] + Utility --> Util[help, nowplaying, subscribe] + Admin --> Adm[reload, reloadconfig] +``` + +### Category Permissions + +| Category | Description | Who Can Use | +|----------|-------------|-------------| +| **Music** | Search and play songs | All users | +| **Playback** | Control playback | All users | +| **Queue** | Queue management | Admin, DJ | +| **Utility** | General utilities | All users | +| **Admin** | System operations | Admin only | + +## Available Commands + +### Music Commands + +```mermaid +flowchart LR + subgraph "Music" + Play["!play
Play or queue song"] + Search["!search
Search YouTube"] + Select["!select
Pick from search"] + end + + UserInput["User types..."] --> Play + UserInput --> Search + Search --> Results["Show results
[1] Song A
[2] Song B"] + Results --> Select +``` + +| Command | Aliases | Description | Permission | +|---------|---------|-------------|------------| +| `play ` | `p` | Play song or add to queue | User | +| `search ` | - | Search YouTube for tracks | User | +| `select ` | - | Select track from search | User | + +### Playback Commands + +```mermaid +flowchart LR + subgraph "Playback Controls" + Pause["!pause
Pause playback"] + Resume["!resume
Continue playing"] + Stop["!stop
Stop & clear"] + Skip["!skip [n]
Skip track(s)"] + Seek["!seek
Jump to position"] + Vol["!volume <0-100>
Set volume"] + end +``` + +| Command | Aliases | Description | Permission | +|---------|---------|-------------|------------| +| `pause` | - | Pause current playback | User | +| `resume` | `unpause`, `continue` | Resume paused playback | User | +| `stop` | - | Stop and clear current | User | +| `skip [count]` | `next`, `s` | Skip to next track | User | +| `seek ` | `jump` | Seek to position (MM:SS) | User | +| `volume <0-100>` | `vol`, `v` | Set playback volume | User | + +### Queue Commands + +```mermaid +flowchart TB + subgraph "Queue Management" + Show["!queue
Show queue"] + Clear["!clear
Clear all"] + Shuffle["!shuffle
Toggle shuffle"] + Repeat["!repeat
Toggle repeat"] + Remove["!remove
Remove track"] + Move["!move
Reorder"] + end +``` + +| Command | Aliases | Description | Permission | +|---------|---------|-------------|------------| +| `queue` | `q`, `list` | Display current queue | User | +| `clear` | `empty` | Remove all tracks | Admin, DJ | +| `shuffle` | `random` | Toggle shuffle mode | Admin, DJ | +| `repeat` | `loop` | Toggle repeat mode | Admin, DJ | +| `remove ` | `rm`, `delete` | Remove specific track | Admin, DJ | +| `move ` | - | Reorder tracks | Admin, DJ | + +### Utility Commands + +| Command | Aliases | Description | Permission | +|---------|---------|-------------|------------| +| `help [command]` | - | Show help information | User | +| `nowplaying` | `np`, `current` | Show current track | User | +| `subscribe` | `sub`, `join` | Subscribe to audio | User | +| `unsubscribe` | `unsub`, `leave` | Unsubscribe from audio | User | + +### Admin Commands + +```mermaid +flowchart LR + subgraph "Admin Only" + Reload["!reload
Hot reload core"] + Config["!reloadconfig
Reload config"] + end + + style Admin fill:#f96,stroke:#333 +``` + +| Command | Aliases | Description | Permission | +|---------|---------|-------------|------------| +| `reload` | `reloadcore` | Hot reload Core library | Admin | +| `reloadconfig` | - | Reload configuration | Admin | + +## Command Dispatch Flow + +```mermaid +flowchart TB + Input["Input: !play song name"] --> Prefix{Starts with
prefix?} + Prefix -->|No| Ignore[Ignore] + Prefix -->|Yes| Extract + + Extract["Extract: command='play'
args='song name'"] --> Find{Handler
found?} + + Find -->|No| Unknown["Reply: Unknown command"] + Find -->|Yes| Perm{Check
permission} + + Perm -->|Denied| NoPerm["Reply: No permission"] + Perm -->|Allowed| Context["Create Context
clientId, args, reply"] + + Context --> Execute["Execute Handler"] + Execute --> Result{Result} + + Result -->|Success| SuccessReply["Reply: Success message"] + Result -->|Error| ErrorReply["Reply: Error message"] +``` + +## Permission Check Flow + +```mermaid +flowchart TB + Request[Command Request] --> Banned{Is Banned?} + Banned -->|Yes| Deny1[Deny Access] + Banned -->|No| AdminCmd{Admin
Command?} + + AdminCmd -->|Yes| IsAdmin{Is Admin?} + IsAdmin -->|No| Deny2[Deny Access] + IsAdmin -->|Yes| Allow1[Allow] + + AdminCmd -->|No| QueueCmd{Queue
Command?} + QueueCmd -->|Yes| IsDJ{Is Admin/DJ?} + IsDJ -->|No| Deny3[Deny Access] + IsDJ -->|Yes| Allow2[Allow] + + QueueCmd -->|No| Allow3[Allow
Basic User] +``` + +## Error Handling + +```mermaid +flowchart TB + Error{Error Type} --> NotFound["Command Not Found
'Unknown command'"] + Error --> NoPerm["Permission Denied
'No permission'"] + Error --> BadArgs["Invalid Arguments
'Usage: !play '"] + Error --> NotAvail["Not Available
'Music manager offline'"] + + NotFound --> Reply + NoPerm --> Reply + BadArgs --> Reply + NotAvail --> Reply + + Reply[Send Reply to User] +``` + +## Adding New Commands + +```mermaid +flowchart LR + subgraph "Adding a Command" + Create[Create Handler Class] + Impl[Implement execute] + Meta[Define Metadata] + Reg[Register in Manager] + end + + Create --> Impl + Impl --> Meta + Meta --> Reg + Reg --> Test[Test] +``` + +### Command Structure + +```mermaid +classDiagram + class Command { + <> + +execute(context) + +getDescription() + +getUsage() + +getCategory() + +getAliases() + +requiresAdmin() + } + + class PlayCommand { + +execute() + +getDescription() "Play a song" + +getCategory() Music + +getAliases() [p] + } + + class PauseCommand { + +execute() + +getDescription() "Pause playback" + +getCategory() Playback + } + + Command <|-- PlayCommand + Command <|-- PauseCommand +``` + +## Reply Formatting + +```mermaid +flowchart TB + subgraph "Reply Types" + Text["Plain Text
'Track added'"] + Rich["Rich Format
'[b]Now Playing[/b]'"] + Error["Error Message
'[color=red]Error[/color]'"] + Multi["Multi-line
Track info"] + end + + Text --> TS[TeamSpeak Display] + Rich --> TS + Error --> TS + Multi --> TS +``` + +## Command Aliases + +```mermaid +flowchart LR + subgraph "Alias Resolution" + A1["!p"] --> Play["!play"] + A2["!q"] --> Queue["!queue"] + A3["!np"] --> Now["!nowplaying"] + A4["!vol"] --> Volume["!volume"] + end + + Play --> Handler[Same Handler] + Queue --> Handler + Now --> Handler + Volume --> Handler +``` diff --git a/docs/09-audio-pipeline.md b/docs/09-audio-pipeline.md new file mode 100644 index 0000000..497ec30 --- /dev/null +++ b/docs/09-audio-pipeline.md @@ -0,0 +1,365 @@ +# Audio Pipeline + +## Overview + +The audio pipeline processes music from various sources and delivers it to TeamSpeak's voice system. It handles decoding, format conversion, volume control, and memory management. + +## Pipeline Architecture + +```mermaid +flowchart TB + subgraph "Input Sources" + YT[YouTube Stream] + URL[Direct URL] + File[Local File] + end + + subgraph "Decoding" + NC[NetworkClient
Download] + AD[AudioDecoder
FFmpeg] + Raw[Raw PCM
Float 32-bit] + end + + subgraph "Processing" + MM[MusicManager] + Vol[Volume Control] + Resamp[Resampler
192kHz] + end + + subgraph "Output" + PI[PluginInterface] + Queue[Audio Queue
20ms chunks] + TS[TeamSpeak Voice] + end + + YT --> NC + URL --> NC + File --> AD + NC --> AD + AD --> Raw + Raw --> MM + MM --> Vol + Vol --> Resamp + Resamp --> PI + PI --> Queue + Queue --> TS +``` + +## Data Transformations + +```mermaid +flowchart LR + subgraph "Source" + A[AAC/Opus/MP3
Any format] + end + + subgraph "Decode" + B[Float PCM
Variable rate] + end + + subgraph "Process" + C[Float PCM
192kHz Stereo] + end + + subgraph "Output" + D[Int16 PCM
20ms chunks] + end + + A -->|FFmpeg
Demux + Decode| B + B -->|Volume + Resample| C + C -->|Convert| D +``` + +## Supported Input Formats + +| Format | Decoder | Common Source | +|--------|---------|---------------| +| MP3 | FFmpeg native | General | +| AAC | FFmpeg native | YouTube | +| Opus | FFmpeg native | YouTube/Spotify | +| Vorbis | FFmpeg native | OGG | +| FLAC | FFmpeg native | Lossless | +| WebM | FFmpeg + libopus | YouTube | + +## Audio Format Specifications + +```mermaid +classDiagram + class InputFormat { + +string codec + +int sampleRate + +int channels + +SampleFormat format + } + + class InternalFormat { + +float samples + +int sampleRate: 192000 + +int channels: 2 + +SampleFormat: Float + } + + class OutputFormat { + +int16 samples + +int sampleRate: 192000 + +int channels: 2 + +SampleFormat: Int16 + +int chunkSize: 20ms + } + + InputFormat --> InternalFormat : Decode + InternalFormat --> OutputFormat : Process +``` + +### Format Details + +| Stage | Sample Rate | Channels | Format | Notes | +|-------|-------------|----------|--------|-------| +| Input | Variable | 1-8 | Various | Source dependent | +| Internal | 192 kHz | 2 (stereo) | Float 32-bit | Processing | +| Output | 192 kHz | 2 (stereo) | Int16 | TeamSpeak req | + +## Decoder Components + +```mermaid +flowchart TB + subgraph "FFmpeg Pipeline" + FC[Format Context
Container] + CC[Codec Context
Decoder] + SW[SWR Context
Resampler] + end + + Input[Input Stream] --> FC + FC -->|Packets| CC + CC -->|Frames| SW + SW -->|PCM| Output[Audio Buffer] + + subgraph "Hardware Acceleration" + CUDA[NVIDIA CUDA] + VAAPI[Intel/AMD VAAPI] + VT[Apple VideoToolbox] + end + + CC -.->|Optional| CUDA + CC -.->|Optional| VAAPI + CC -.->|Optional| VT +``` + +## Hardware Acceleration + +```mermaid +flowchart TB + subgraph "HW Acceleration Types" + Detect{Detect GPU} + + Detect -->|NVIDIA| CUDA[CUDA
NVDEC] + Detect -->|Intel/AMD Linux| VAAPI[VAAPI] + Detect -->|Windows| DXVA[DXVA2/D3D11VA] + Detect -->|macOS| VT[VideoToolbox] + Detect -->|None| SW[Software
Decode] + end + + CUDA --> FFmpeg + VAAPI --> FFmpeg + DXVA --> FFmpeg + VT --> FFmpeg + SW --> FFmpeg +``` + +| Type | Platform | Notes | +|------|----------|-------| +| CUDA | Windows/Linux | NVIDIA GPUs | +| VAAPI | Linux | Intel/AMD | +| DXVA2 | Windows | Legacy | +| D3D11VA | Windows | Modern | +| VideoToolbox | macOS | Native | + +## Memory Management + +```mermaid +flowchart TB + subgraph "Memory Pool" + Pool[Buffer Pool] + Acquire[Acquire Buffer] + Use[Use Buffer] + Release[Release Buffer] + end + + Request[Audio Request] --> Acquire + Acquire -->|Get from pool| Buffer[Buffer] + Buffer --> Use + Use --> Release + Release -->|Return to pool| Pool + + subgraph "Zero-Copy" + View[Audio View
Non-owning] + Data[Raw Data] + end + + Buffer -.-> View + View --> Data +``` + +## Volume Control + +```mermaid +flowchart LR + Input[Float PCM] --> Volume{Apply Volume} + Volume -->|Gain * sample| Output[Float PCM] + + subgraph "Volume Curve" + User[User: 0-100] + Linear[Linear: 0.0-1.0] + Perceptual[Perceptual Curve] + end + + User -->|/100| Linear + Linear -->|^(2.0)| Perceptual +``` + +### Volume Characteristics + +| User Setting | Linear Gain | Perceptual | +|--------------|-------------|------------| +| 0 | 0.0 | Silent | +| 25 | 0.25 | ~6% | +| 50 | 0.5 | ~25% | +| 75 | 0.75 | ~56% | +| 100 | 1.0 | 100% | + +## Threading Model + +```mermaid +flowchart TB + subgraph "Audio Threads" + DT[Decode Thread
FFmpeg] + PT[Playback Thread
MusicManager] + AT[Audio Thread
PluginInterface] + end + + subgraph "Synchronization" + Q1[Decoded Queue
Mutex + CV] + Q2[Audio Queue
Mutex + CV] + end + + DT -->|Push| Q1 + PT -->|Pop| Q1 + PT -->|Push| Q2 + AT -->|Pop| Q2 +``` + +## Resampling + +```mermaid +flowchart LR + Source{Source Rate} -->|44.1kHz| Up1[Upsample to 192kHz] + Source -->|48kHz| Up2[Upsample to 192kHz] + Source -->|192kHz| Pass[Pass Through] + + Up1 --> SWR[SWR Context] + Up2 --> SWR + Pass --> SWR + + SWR --> Output[192kHz Stereo] +``` + +## Buffer Management + +```mermaid +flowchart TB + subgraph "Audio Queue" + Push[Core Push] --> Queue[Queue] + Queue --> Pop[Plugin Pop] + + Queue -->|Full| Wait1[Wait] + Queue -->|Empty| Silence[Send Silence] + end + + subgraph "Chunk Processing" + Decode[Decode Frame] --> Buffer[Accumulate] + Buffer -->|7680 bytes| Chunk[20ms Chunk] + Chunk --> TS[TeamSpeak] + end +``` + +## Audio Output Flow + +```mermaid +sequenceDiagram + participant AD as AudioDecoder + participant MM as MusicManager + participant PI as PluginInterface + participant TS as TeamSpeak + + loop Every 20ms + AD->>AD: Decode frame + AD-->>MM: Float PCM + MM->>MM: Apply volume + MM->>MM: Convert to Int16 + MM->>PI: Audio callback + PI->>PI: Queue chunk + PI->>TS: processCustomCaptureData + end +``` + +## Performance Considerations + +```mermaid +flowchart TB + subgraph "Optimizations" + Pool[Memory Pooling] + SIMD[SIMD Operations] + HW[Hardware Decode] + Buffer[Buffer Sizing] + end + + Pool -->|Reduce allocations| Fast[Low Latency] + SIMD -->|Vectorized ops| Fast + HW -->|GPU offload| Fast + Buffer -->|20ms chunks| Fast +``` + +| Optimization | Benefit | +|--------------|---------| +| Memory Pool | Reduces allocation overhead | +| SIMD | Faster volume application | +| Hardware Decode | Lower CPU usage | +| 20ms Chunks | Balance latency vs efficiency | + +## Error Handling + +```mermaid +flowchart TB + Error{Error Type} --> DecodeErr["Decode Error
Skip track"] + Error --> NetworkErr["Network Error
Retry with backoff"] + Error --> BufferErr["Buffer Underrun
Increase buffer"] + Error --> FormatErr["Format Error
Skip track"] + + DecodeErr --> Log[Log Error] + NetworkErr --> Log + BufferErr --> Log + FormatErr --> Log + + Log --> Notify[Notify User] +``` + +## Audio Statistics + +```mermaid +classDiagram + class AudioStats { + +uint64 framesDecoded + +uint64 framesDropped + +uint64 bytesDecoded + +double avgDecodeTimeMs + +bool hwAccelerationActive + +HwAccelType accelType + } +``` + +| Metric | Description | +|--------|-------------| +| Frames Decoded | Total audio frames processed | +| Frames Dropped | Frames skipped (buffer issues) | +| Decode Time | Average time per frame | +| HW Acceleration | Whether GPU decode is active | diff --git a/docs/10-database-cache.md b/docs/10-database-cache.md new file mode 100644 index 0000000..6058081 --- /dev/null +++ b/docs/10-database-cache.md @@ -0,0 +1,366 @@ +# Database and Caching Systems + +## Overview + +Echoion uses SQLite for persistent storage (playlists, history, favorites) and an in-memory LRU cache for frequently accessed data to improve performance. + +## Database Architecture + +```mermaid +flowchart TB + subgraph "Database Layer" + API[Database API] + Impl[DatabaseImpl] + + subgraph "SQLite" + Conn[Connection] + Migrations[Schema Migrations] + end + end + + subgraph "Stored Data" + Playlists[(Playlists)] + History[(History)] + Favorites[(Favorites)] + Subs[(Subscriptions)] + end + + Core --> API + API --> Impl + Impl --> Conn + Conn --> Playlists + Conn --> History + Conn --> Favorites + Conn --> Subs + + Impl --> Migrations +``` + +## Database Schema + +```mermaid +erDiagram + PLAYLISTS { + int id PK + string name + string description + int created_by + int created_at + bool is_public + } + + PLAYLIST_TRACKS { + int id PK + int playlist_id FK + string track_id + string title + string artist + int position + } + + PLAYBACK_HISTORY { + int id PK + string track_id + string title + string artist + int played_by + int played_at + int duration_ms + bool completed + } + + FAVORITES { + int id PK + int user_id + string track_id + string title + string artist + int added_at + } + + SUBSCRIPTIONS { + int client_id PK + int subscribed_at + } + + SCHEMA_VERSION { + int version PK + } + + PLAYLISTS ||--o{ PLAYLIST_TRACKS : contains +``` + +## Data Flow + +```mermaid +flowchart TB + subgraph "Write Path" + W1[User Action] --> W2[Publish Event] + W2 --> W3[Database Subscribe] + W3 --> W4[Insert/Update] + end + + subgraph "Read Path" + R1[Data Request] --> R2[Query Database] + R2 --> R3[Return Results] + end +``` + +## Cache Architecture + +```mermaid +flowchart TB + subgraph "Cache System" + CM[CacheManager
Singleton] + + subgraph "Cache Types" + HTTP[HTTP Cache
5 min TTL] + Track[Track Cache
1 hour TTL] + Meta[Metadata Cache
30 min TTL] + end + + subgraph "LRU Cache" + LRU[LRU Policy] + TTL[TTL Expiration] + end + end + + Request[Data Request] --> CM + CM --> HTTP + CM --> Track + CM --> Meta + + HTTP --> LRU + Track --> LRU + Meta --> LRU + + LRU --> TTL +``` + +## Cache-Aside Pattern + +```mermaid +flowchart TB + Request[Data Request] --> Check{In Cache?} + + Check -->|Hit| Return[Return Cached] + Check -->|Miss| Fetch[Fetch Source] + + Fetch --> DB[Database] + Fetch --> HTTP[HTTP/YouTube] + + DB --> Store[Store in Cache] + HTTP --> Store + Store --> Return + + Return --> Use[Use Data] +``` + +## Cache Entry Lifecycle + +```mermaid +stateDiagram-v2 + [*] --> Empty: Create + Empty --> Filled: Put value + + Filled --> Accessed: Get + Accessed --> Accessed: Get again + Accessed --> Filled: TTL expires + + Filled --> Evicted: LRU eviction + Accessed --> Evicted: LRU eviction + + Filled --> Expired: TTL expires + Expired --> Empty: Remove + Evicted --> Empty: Remove + + Empty --> [*]: Destroy +``` + +## Integration Flow + +```mermaid +sequenceDiagram + participant C as Component + participant Cache as CacheManager + participant DB as Database + participant Source as External Source + + C->>Cache: Request data + + alt Cache Hit + Cache-->>C: Return cached + else Cache Miss + Cache->>DB: Query database + + alt DB Hit + DB-->>Cache: Return data + Cache->>Cache: Store in cache + Cache-->>C: Return data + else DB Miss + DB-->>Cache: Not found + Cache->>Source: Fetch from source + Source-->>Cache: Return data + Cache->>DB: Persist + Cache->>Cache: Store in cache + Cache-->>C: Return data + end + end +``` + +## Cache Eviction Policies + +| Policy | Description | Use Case | +|--------|-------------|----------| +| **LRU** | Least Recently Used | General purpose | +| **LFU** | Least Frequently Used | Hot data | +| **FIFO** | First In First Out | Time-sensitive | +| **TTL** | Time To Live only | Temporary data | + +## Cache Configuration + +```mermaid +classDiagram + class CacheConfig { + +size_t maxSize + +milliseconds defaultTtl + +EvictionPolicy policy + } + + class HttpCache { + +maxSize: 1000 + +ttl: 5 minutes + } + + class TrackCache { + +maxSize: 500 + +ttl: 1 hour + } + + class MetadataCache { + +maxSize: 1000 + +ttl: 30 minutes + } + + CacheConfig <|-- HttpCache + CacheConfig <|-- TrackCache + CacheConfig <|-- MetadataCache +``` + +## Cache Statistics + +```mermaid +classDiagram + class CacheStats { + +size_t hits + +size_t misses + +size_t evictions + +size_t inserts + +size_t currentSize + +double hitRate() + } +``` + +| Metric | Description | +|--------|-------------| +| Hits | Successful cache lookups | +| Misses | Failed lookups (fetch required) | +| Hit Rate | Hits / (Hits + Misses) | +| Evictions | Items removed due to size limit | +| Current Size | Active entries in cache | + +## Database Optimization + +```mermaid +flowchart LR + subgraph "Optimizations" + WAL[WAL Mode] + Index[Indexing] + Prep[Prepared Statements] + Batch[Batch Operations] + end + + WAL -->|Concurrent reads| Perf[Better Performance] + Index -->|Fast lookups| Perf + Prep -->|Reuse plans| Perf + Batch -->|Fewer commits| Perf +``` + +| Technique | Benefit | +|-----------|---------| +| WAL Mode | Concurrent reads during writes | +| Indexing | Fast column lookups | +| Prepared Statements | Reuse query plans | +| Batch Operations | Fewer transaction commits | + +## Schema Migrations + +```mermaid +flowchart TB + Start[Start Migration] --> Check{Current
Version?} + + Check -->|v1| M1[Migration 1→2
Add favorites table] + Check -->|v2| M2[Migration 2→3
Add duration column] + Check -->|v3| M3[Migration 3→4
Add indexes] + Check -->|Latest| Done[No migration needed] + + M1 --> Update[Update version] + M2 --> Update + M3 --> Update + Update --> Verify{Success?} + + Verify -->|Yes| Done2[Migration complete] + Verify -->|No| Rollback[Rollback changes] +``` + +## Performance Tuning + +### Cache Size Guidelines + +| Cache Type | Size | TTL | Rationale | +|------------|------|-----|-----------| +| HTTP | 100-1000 | 5 min | Short-lived responses | +| Track Info | 500-2000 | 1 hour | Stable metadata | +| Metadata | 1000-5000 | 30 min | Moderate change | +| Search Results | 100-500 | 10 min | Fresh results | + +### Database Tuning + +```mermaid +flowchart TB + subgraph "SQLite PRAGMAs" + WAL["journal_mode = WAL"] + SYNC["synchronous = NORMAL"] + CACHE["cache_size = 10000"] + TEMP["temp_store = MEMORY"] + end + + WAL --> Throughput[Better Throughput] + SYNC --> Safety[Durability/Speed Balance] + CACHE --> Memory[More Memory Cache] + TEMP --> Speed[Faster Temp Tables] +``` + +## Monitoring + +```mermaid +flowchart TB + subgraph "Metrics Collection" + CacheM[Cache Metrics] + DBM[Database Metrics] + Health[Health Checks] + end + + CacheM -->|Export| Metrics[Metrics Endpoint] + DBM -->|Export| Metrics + Health -->|Export| Metrics + + Metrics --> Dashboard[Dashboard] + Metrics --> Alerts[Alerts] +``` + +| Category | Metrics | +|----------|---------| +| Cache | Hit rate, size, memory, evictions | +| Database | Query time, connections, cache hits | +| Health | Availability, error rates | diff --git a/docs/11-events.md b/docs/11-events.md new file mode 100644 index 0000000..f7286c5 --- /dev/null +++ b/docs/11-events.md @@ -0,0 +1,413 @@ +# Event System + +## Overview + +Echoion uses a publish-subscribe event system for decoupled communication between components. The EventBus allows components to communicate without direct dependencies. + +## Event System Architecture + +```mermaid +flowchart TB + subgraph "Publishers" + MM[MusicManager] + AD[AudioDecoder] + NC[NetworkClient] + YC[YouTubeClient] + end + + subgraph "EventBus" + Queue[Event Queue] + Router[Event Router] + end + + subgraph "Subscribers" + CM[CommandManager] + PI[PluginInterface] + RS[RpcServer] + LG[Logger] + DB[Database] + end + + MM -->|TrackQueued| Queue + AD -->|PlaybackError| Queue + NC -->|NetworkError| Queue + YC -->|TrackResolved| Queue + + Queue --> Router + Router --> CM + Router --> PI + Router --> RS + Router --> LG + Router --> DB +``` + +## Event Flow + +```mermaid +sequenceDiagram + participant Pub as Publisher + participant Bus as EventBus + participant Q as Queue + participant D as Dispatcher + participant Sub1 as Subscriber 1 + participant Sub2 as Subscriber 2 + + Pub->>Bus: publish(event) + Bus->>Q: enqueue(event) + + loop Event Processing Thread + Q->>D: dequeue() + D->>D: Lookup handlers + par Parallel Dispatch + D->>Sub1: handle(event) + D->>Sub2: handle(event) + end + end +``` + +## Event Types + +### Playback Events + +```mermaid +classDiagram + class PlaybackStarted { + +TrackInfo track + +uint64 clientId + +timestamp + } + + class PlaybackPaused { + +duration position + +timestamp + } + + class PlaybackResumed { + +duration position + +timestamp + } + + class PlaybackStopped { + +timestamp + } + + class TrackFinished { + +TrackInfo track + +bool autoSkipped + +timestamp + } + + class VolumeChanged { + +float oldVolume + +float newVolume + +uint64 changedBy + } +``` + +### Queue Events + +```mermaid +classDiagram + class TrackQueued { + +TrackInfo track + +uint64 queueId + +uint64 addedBy + +uint32 position + } + + class TrackRemoved { + +uint64 queueId + +uint64 removedBy + } + + class QueueCleared { + +uint64 clearedBy + } + + class QueueShuffled { + +uint64 triggeredBy + } +``` + +### Connection Events + +```mermaid +classDiagram + class ClientConnected { + +ClientInfo client + +timestamp + } + + class ClientDisconnected { + +uint64 clientId + +string reason + +timestamp + } + + class ChannelChanged { + +uint64 clientId + +uint64 oldChannelId + +uint64 newChannelId + } +``` + +### Error Events + +```mermaid +classDiagram + class PlaybackError { + +ErrorCode code + +string message + +TrackInfo track + } + + class NetworkError { + +string url + +ErrorCode code + +string message + } + + class DecodeError { + +string source + +string error + } +``` + +### Configuration Events + +```mermaid +classDiagram + class ConfigReloaded { + +BotConfig newConfig + } + + class ConfigChanged { + +string key + +string oldValue + +string newValue + } + + class HotReloadCompleted { + +bool success + +string version + } +``` + +## EventBus Structure + +```mermaid +classDiagram + class EventBus { + +publish(event) + +subscribe(handler) SubscriptionToken + +unsubscribe(token) + +processOne() + +start() + +stop() + } + + class SubscriptionToken { + +Id id + +type_index type + +isValid() + } + + class IEvent { + +type_index getType() + +timestamp + } + + class HandlerRegistry { + -Map~type_index, Handlers~ handlers + +register(type, handler) + +dispatch(event) + } + + EventBus --> HandlerRegistry + EventBus --> SubscriptionToken + SubscriptionToken --> IEvent +``` + +## Usage Patterns + +### Publishing Events + +```mermaid +flowchart LR + Component[Component] --> Create[Create Event] + Create --> Publish["ECHOION_PUBLISH(event)"] + Publish --> Bus[EventBus] + Bus --> Queue[Queue Event] +``` + +### Subscribing to Events + +```mermaid +flowchart LR + Component[Component] --> Subscribe["ECHOION_SUBscribe(EventType, handler)"] + Subscribe --> Token[Get Token] + Token --> Store[Store Token] + Store --> Receive[Receive Events] +``` + +### Unsubscription + +```mermaid +flowchart LR + Token[SubscriptionToken] -->|RAII| Auto[Auto-unsubscribe
on destruction] + Token -->|Explicit| Manual[call unsubscribe()] +``` + +## Event Flow Examples + +### Track Playback Flow + +```mermaid +sequenceDiagram + participant User + participant CM as CommandManager + participant MM as MusicManager + participant Bus as EventBus + participant PI as PluginInterface + participant RS as RpcServer + participant DB as Database + + User->>CM: !play song + CM->>MM: queueTrack() + MM->>Bus: publish(TrackQueued) + + Bus->>PI: TrackQueued + PI->>User: Reply "Added to queue" + + Bus->>RS: TrackQueued + RS->>RS: Broadcast to Desktop + + MM->>MM: Start playback + MM->>Bus: publish(PlaybackStarted) + + Bus->>PI: PlaybackStarted + Bus->>RS: PlaybackStarted + Bus->>DB: PlaybackStarted + + DB->>DB: Record in history +``` + +### Error Handling Flow + +```mermaid +sequenceDiagram + participant AD as AudioDecoder + participant Bus as EventBus + participant MM as MusicManager + participant PI as PluginInterface + participant LG as Logger + + AD->>AD: decodeFrame() fails + AD->>Bus: publish(PlaybackError) + + Bus->>MM: PlaybackError + MM->>MM: Skip to next track + + Bus->>PI: PlaybackError + PI->>PI: Send error to channel + + Bus->>LG: PlaybackError + LG->>LG: Log detailed error +``` + +## Thread Safety + +```mermaid +flowchart TB + subgraph "Thread-Safe Operations" + Publish[Publish from any thread] + Subscribe[Subscribe from any thread] + Unsubscribe[Unsubscribe from any thread] + end + + subgraph "Internal Protection" + QueueMutex[Queue Mutex] + HandlerMutex[Handler Registry
Shared Mutex] + end + + Publish --> QueueMutex + Subscribe --> HandlerMutex + Unsubscribe --> HandlerMutex +``` + +## Event Processing Modes + +```mermaid +flowchart TB + subgraph "Processing Options" + Async[Asynchronous
Queued processing] + Direct[Direct
Immediate call] + Ordered[Ordered
Sequential dispatch] + end + + Async -->|Default| LowLatency[Low Publisher Latency] + Direct -->|Optional| Immediate[Immediate Response] + Ordered -->|Guaranteed| Sequence[Event Order Preserved] +``` + +## Comparison: EventBus vs Plugin Events + +| Feature | EventBus | PluginEvent | +|---------|----------|-------------| +| Purpose | Internal communication | Plugin ↔ Core | +| Type-safe | Yes (templates) | Yes (enum) | +| Decoupled | Full | Partial | +| Thread-safe | Yes | Yes | +| Persistence | No | No | +| Use case | Component events | User actions | + +## Best Practices + +```mermaid +flowchart TB + subgraph "Best Practices" + Fast[Keep handlers fast] + Unsub[Unsubscribe when done] + RAII[Use RAII for tokens] + Circular[Avoid circular deps] + end + + Fast -->|Offload| Async[Async operations] + Unsub -->|Prevent| Leaks[Memory leaks] + RAII -->|Auto| Cleanup[Auto-cleanup] + Circular -->|Ensure| DAG[DAG structure] +``` + +1. **Keep handlers fast** - Long operations should be offloaded +2. **Unsubscribe when done** - Prevents memory leaks +3. **Use RAII** - Store tokens as members for auto-cleanup +4. **Avoid circular dependencies** - Events should flow in one direction + +## Debugging Events + +```mermaid +flowchart LR + subgraph "Debugging Tools" + Logger[Event Logger
Log all events] + Counter[Event Counter
Track rate] + Inspector[Event Inspector
View details] + end + + Bus --> Logger + Bus --> Counter + Bus --> Inspector +``` + +## Creating Custom Events + +```mermaid +flowchart LR + Define[Define Struct] --> Publish[Publish Event] + Publish --> Subscribe[Subscribe Handler] + Subscribe --> Handle[Handle Event] +``` + +1. Define event struct with timestamp +2. Publish using `ECHOION_PUBLISH(event)` +3. Subscribe using `ECHOION_SUBSCRIBE(EventType, handler)` +4. Handle in callback function diff --git a/docs/12-hot-reload.md b/docs/12-hot-reload.md new file mode 100644 index 0000000..fd9d02f --- /dev/null +++ b/docs/12-hot-reload.md @@ -0,0 +1,347 @@ +# Hot Reload System + +## Overview + +Echoion's hot reload system allows the Core library to be updated without restarting TeamSpeak or disconnecting from the server. This enables rapid development and bug fixes with minimal disruption. + +## Hot Reload Architecture + +```mermaid +flowchart TB + subgraph "Static (Plugin)" + CL[CoreLoader] + PI[PluginInterface] + end + + subgraph "Dynamic (Core)" + Old[Old Core Library] + New[New Core Library] + end + + subgraph "State Preservation" + State[HotReloadState] + Playback[Playback State] + Queue[Queue Contents] + Position[Current Position] + Config[Configuration] + end + + CL <-->|Load/Unload| Old + CL <-->|Load/Unload| New + + Old -->|Extract| State + State -->|Restore| New + + State --> Playback + State --> Queue + State --> Position + State --> Config +``` + +## Hot Reload Process + +```mermaid +flowchart TB + Start[Trigger Reload] --> Save[1. Save State] + Save --> Unload[2. Unload Old Core] + Unload --> Load[3. Load New Core] + Load --> Restore[4. Restore State] + Restore --> Resume[5. Resume Operation] + + subgraph "State Save" + Save --> Extract[Extract state] + Extract --> Copy[Copy queue] + Copy --> Pos[Get position] + end + + subgraph "State Restore" + Restore --> Queue2[Restore queue] + Restore --> Play[Resume playback] + Restore --> Seek[Seek to position] + end +``` + +## Step-by-Step Flow + +```mermaid +sequenceDiagram + participant User + participant CL as CoreLoader + participant Old as Old Core + participant State as HotReloadState + participant New as New Core + + User->>CL: Trigger reload + + CL->>Old: prepareForHotReload() + Old->>Old: Extract playback state + Old->>Old: Copy queue vector + Old->>Old: Get playback position + Old-->>State: Return HotReloadState + + CL->>Old: shutdown() + CL->>Old: unload library + + Note over CL: Brief pause (100ms) + + CL->>New: load library + CL->>New: initialize() + CL->>New: restoreAfterHotReload(state) + + New->>New: Restore queue + New->>New: Resume playback + New->>New: Seek to position + + New-->>CL: Ready + CL-->>User: Reload complete +``` + +## State Preservation + +### What Gets Preserved + +```mermaid +flowchart LR + subgraph "Preserved State" + Queue[Queue
✓ Full track list] + Track[Current Track
✓ Position & URL] + Volume[Volume
✓ Level] + Mode[Modes
✓ Shuffle & Repeat] + Subs[Subscribers
✓ Re-populated] + Config[Config
✓ All settings] + end +``` + +| State | Preserved | Notes | +|-------|-----------|-------| +| Queue | ✓ | Full track list maintained | +| Current track | ✓ | May need fresh stream URL | +| Playback position | ✓ | Seek after restore | +| Volume | ✓ | Stored in state | +| Repeat/Shuffle | ✓ | Stored in state | +| Subscribers | ✓ | Re-populated after reload | +| Config | ✓ | Full config restored | +| Database | ✓ | Persistent anyway | + +### What Doesn't Get Preserved + +```mermaid +flowchart LR + subgraph "Not Preserved" + Cache[Cache
✗ In-memory only] + Buffer[Audio Buffer
✗ Must re-decode] + Network[Network Connections
✗ Re-established] + end +``` + +## CoreLoader Lifecycle + +```mermaid +stateDiagram-v2 + [*] --> Unloaded + Unloaded --> Loading: load() + Loading --> Loaded: Success + Loading --> Error: Failure + + Loaded --> Saving: hotReload() + Saving --> Unloading: Extract state + Unloading --> Loading: Load new + Loading --> Restoring: restore state + Restoring --> Loaded: Success + Restoring --> Error: Failure + + Loaded --> Unloading: unload() + Unloading --> Unloaded + Error --> Unloaded +``` + +## Reload Triggers + +```mermaid +flowchart TB + subgraph "Trigger Sources" + Menu["TS Menu
Right-click → Reload Core"] + Cmd["Chat Command
!reload"] + File["File Watcher
Auto-detect change"] + Code["Programmatic
hotReload()"] + end + + Menu --> CL[CoreLoader] + Cmd --> CL + File --> CL + Code --> CL + + CL --> Process[Reload Process] +``` + +## File Watcher Auto-Reload + +```mermaid +flowchart TB + Dev[Developer] -->|Build| Build[New Binary] + Build -->|File change| FW[FileWatcher] + FW -->|Debounce 1s| Check{Loaded?} + + Check -->|Yes| Reload[Trigger Reload] + Check -->|No| Wait[Wait for load] + + Reload -->|Success| Active[New Version Active] + Reload -->|Fail| Keep[Keep Old Version] + + FW -->|Disable| Manual[Manual reload only] +``` + +## State Transfer Details + +### State Extraction + +```mermaid +flowchart TB + subgraph "Extract from Old Core" + GetPS[Get PlaybackState] + GetQ[Get Queue] + GetPos[Get Position] + GetCfg[Get Config] + end + + GetPS --> State[HotReloadState] + GetQ --> State + GetPos --> State + GetCfg --> State + + State --> Serialize[Serialize for transfer] +``` + +### State Restoration + +```mermaid +flowchart TB + subgraph "Restore to New Core" + Parse[Parse HotReloadState] + RestoreQ[Restore Queue] + RestoreP[Restore Playback] + RestoreV[Restore Volume] + end + + Parse --> RestoreQ + RestoreQ --> RestoreP + RestoreP --> RestoreV + + RestoreP --> Fresh{Need fresh
stream URL?} + Fresh -->|Yes| Fetch[Fetch new URL] + Fresh -->|No| Resume[Resume] + Fetch --> Resume +``` + +## Error Handling + +```mermaid +flowchart TB + Error{Reload Error} --> LoadFail["Load Failed"] + Error --> RestoreFail["Restore Failed"] + + LoadFail -->|Has state| Rollback1[Rollback to old] + LoadFail -->|No state| Fail1[Fail - no recovery] + + RestoreFail -->|Can rollback| Rollback2[Rollback to old] + RestoreFail -->|Critical| Fail2[Fail - restart needed] + + Rollback1 -->|Try| RestoreOld[Restore old core] + Rollback2 -->|Try| RestoreOld + + RestoreOld -->|Success| Continue[Continue with old] + RestoreOld -->|Fail| Fail3[Complete failure] +``` + +## Platform Differences + +```mermaid +flowchart TB + subgraph "Windows" + W[DLL File] -->|Locked| Copy[Copy to temp] + Copy --> Load[Load temp copy] + end + + subgraph "Linux/macOS" + L[SO/DYLIB File] -->|Can overwrite| Load2[Load directly] + end +``` + +| Platform | Behavior | Notes | +|----------|----------|-------| +| **Windows** | Copy to temp before load | File locking prevents overwrite | +| **Linux** | Load directly | Can overwrite loaded libraries | +| **macOS** | Load directly | Similar to Linux | + +## Potential Issues + +### Stream URL Expiration + +```mermaid +flowchart LR + Old[Old Core] -->|Save URL| State + State -->|URL expired?| Check{Check} + Check -->|Yes| Refresh[Re-fetch URL] + Check -->|No| Use[Use saved URL] + Refresh --> New[New Core] + Use --> New +``` + +**Solution**: Re-fetch stream URL on restore if expired + +### Audio Gap + +```mermaid +flowchart LR + Stop[Stop Playback] --> Unload[Unload Core] + Unload --> Load[Load New Core] + Load --> Start[Start Playback] + + subgraph "Gap" + Gap[100-500ms
Interruption] + end + + Unload --> Gap + Gap --> Load +``` + +**Mitigation**: +- Pre-buffer before reload +- Keep gap under 500ms +- Consider seamless handoff (future) + +## Development Workflow + +```mermaid +flowchart LR + subgraph "Hot Reload Dev Workflow" + Start[Start TS with Plugin] --> Play[Play Music] + Play --> Code[Edit Code] + Code --> Build[Build Core] + Build --> Reload[Auto/Manual Reload] + Reload --> Verify[Verify State] + Verify -->|More changes| Code + Verify -->|Done| Stop[Stop] + end +``` + +## Best Practices + +```mermaid +flowchart TB + subgraph "Best Practices" + Early[Save Early] -->|Before destructive| Safe[Safe State] + Validate[Validate State] -->|Version check| Compatible[Compatibility] + PlanB[Have Rollback] -->|Always| Recover[Recoverable] + Minimal[Minimal State] -->|Only necessary| Efficient[Efficient] + Test[Thorough Testing] -->|Edge cases| Reliable[Reliable] + Log[Log Everything] -->|Debug info| Debuggable[Debuggable] + end +``` + +1. **Save Early** - Extract state before any destructive operations +2. **Validate State** - Check version compatibility before restoration +3. **Have Rollback** - Always have a fallback plan +4. **Minimal State** - Only preserve what's necessary +5. **Thorough Testing** - Hot reload is complex, test edge cases +6. **Log Everything** - Detailed logging helps debug issues diff --git a/docs/13-security.md b/docs/13-security.md new file mode 100644 index 0000000..76c9fb5 --- /dev/null +++ b/docs/13-security.md @@ -0,0 +1,380 @@ +# Security System + +## Overview + +Echoion implements a multi-layered security system including role-based access control, authentication, session management, and audit logging to ensure safe operation. + +## Security Architecture + +```mermaid +flowchart TB + subgraph "Authentication Layer" + TSID[TeamSpeak ID
Implicit] + Pass[Password
Admin/DJ] + Token[Session Token
Desktop] + end + + subgraph "Authorization Layer" + Perm[Permission Check] + Groups[Server Groups] + end + + subgraph "Protection Layer" + Rate[Rate Limiting] + Lock[Account Lockout] + Audit[Audit Logging] + end + + TSID --> Perm + Pass --> Perm + Token --> Perm + + Perm --> Groups + Groups --> Admin[Admin Groups] + Groups --> DJ[DJ Groups] + Groups --> Banned[Banned Groups] + + Perm --> Rate + Rate --> Lock + Lock --> Audit +``` + +## Authentication Methods + +```mermaid +flowchart TB + subgraph "Authentication" + Req[Request] --> Method{Method} + + Method -->|TS Chat| TSID[TeamSpeak ID
+ Server Groups] + Method -->|Desktop| Pass[Username + Password] + Method -->|WebSocket| Token[Session Token] + end + + TSID --> VerifyTS{Verify Groups} + Pass --> VerifyPass{Verify Credentials} + Token --> VerifyToken{Verify Token} + + VerifyTS -->|Success| AuthTS[Authenticated] + VerifyPass -->|Success| AuthPass[Authenticated] + VerifyToken -->|Success| AuthToken[Authenticated] +``` + +### TeamSpeak Server Groups + +```mermaid +flowchart LR + User[TeamSpeak User] -->|Has groups| Check{Check Groups} + + Check -->|In| Admin[Admin Groups
Full Access] + Check -->|In| DJ[DJ Groups
Queue Control] + Check -->|Not in banned| User2[Regular User
Basic Commands] + Check -->|In| Banned[Banned Groups
No Access] +``` + +## Permission Matrix + +```mermaid +flowchart TB + subgraph "Permission Levels" + Admin[Admin] --> All[All Commands] + DJ[DJ] --> Queue[Queue Commands] + DJ --> Basic1[Basic Commands] + User[User] --> Basic2[Basic Commands] + Banned[Banned] --> None[No Access] + end + + All --> Reload[reload, reloadconfig] + Queue --> Shuffle[shuffle, clear, remove] + Basic1 --> Play[play, pause, skip] + Basic2 --> Play +``` + +| Command | Category | Admin | DJ | User | Banned | +|---------|----------|-------|-----|------|--------| +| play | Music | ✓ | ✓ | ✓ | ✗ | +| pause | Playback | ✓ | ✓ | ✓ | ✗ | +| skip | Playback | ✓ | ✓ | ✓ | ✗ | +| queue | Queue | ✓ | ✓ | ✓ | ✗ | +| shuffle | Queue | ✓ | ✓ | ✗ | ✗ | +| clear | Queue | ✓ | ✓ | ✗ | ✗ | +| reload | Admin | ✓ | ✗ | ✗ | ✗ | +| reloadconfig | Admin | ✓ | ✗ | ✗ | ✗ | + +## Permission Check Flow + +```mermaid +flowchart TB + Request[Command Request] --> Banned{Is Banned?} + Banned -->|Yes| Deny1[Deny: Banned] + Banned -->|No| Admin{Admin
Command?} + + Admin -->|Yes| IsAdmin{Is Admin?} + IsAdmin -->|Yes| Allow1[Allow] + IsAdmin -->|No| Deny2[Deny: Admin Only] + + Admin -->|No| Queue{Queue
Command?} + Queue -->|Yes| IsDJ{Is Admin/DJ?} + IsDJ -->|Yes| Allow2[Allow] + IsDJ -->|No| Deny3[Deny: DJ Only] + + Queue -->|No| Allow3[Allow: User] +``` + +## Rate Limiting + +```mermaid +flowchart TB + Request[Command Request] --> Check{Check Limit} + + Check -->|Under limit| Allow[Allow] + Check -->|Over limit| Deny[Deny] + + Allow --> Record[Record Request] + Record --> History[Command History] + + History --> Cleanup[Cleanup Old
>1 min] + + subgraph "Limits" + Play["play: 10/min"] + Search["search: 5/min"] + Skip["skip: 3/min"] + Vol["volume: 20/min"] + end +``` + +| Command | Limit | Window | +|---------|-------|--------| +| play | 10 | 1 minute | +| search | 5 | 1 minute | +| skip | 3 | 1 minute | +| volume | 20 | 1 minute | + +## Login Protection + +```mermaid +flowchart TB + Login[Login Attempt] --> Locked{Account
Locked?} + + Locked -->|Yes| CheckTime{Lockout
Expired?} + CheckTime -->|No| Deny[Deny: Locked] + CheckTime -->|Yes| Unlock[Unlock Account] + + Locked -->|No| Verify{Credentials
Valid?} + Unlock --> Verify + + Verify -->|Yes| Success[Login Success] + Verify -->|No| Fail[Login Failed] + + Fail --> Record[Record Attempt] + Record --> Count{Max Attempts
Reached?} + + Count -->|Yes| Lock[Lock Account
5 minutes] + Count -->|No| Remaining[Return Attempts
Remaining] + + Success --> Clear[Clear Failed
Attempts] + Success --> Token[Create Session
Token] +``` + +### Lockout Configuration + +| Setting | Default | Description | +|---------|---------|-------------| +| Max attempts | 5 | Failed logins before lockout | +| Lockout duration | 5 min | Time before retry allowed | +| Session timeout | 1 hour | Token expiration | + +## Session Management + +```mermaid +flowchart LR + subgraph "Session Lifecycle" + Create[Create Session
On login] --> Active[Active Session] + Active -->|Activity| Extend[Extend Timeout] + Active -->|Timeout| Expire[Expire Session] + Active -->|Logout| Destroy[Destroy Session] + end +``` + +## Audit Logging + +```mermaid +flowchart TB + Action[User Action] --> Log{Audit Log
Enabled?} + + Log -->|Yes| Create[Create Audit Event] + Log -->|No| Skip[Skip Logging] + + Create --> Types{Event Type} + + Types -->|Command| CmdLog[Log Command] + Types -->|Config| CfgLog[Log Config Change] + Types -->|Auth| AuthLog[Log Auth Event] + Types -->|Admin| AdminLog[Log Admin Action] + + CmdLog --> Write[Write to Log] + CfgLog --> Write + AuthLog --> Write + AdminLog --> Write + + Write --> File[Log File] + Write --> DB[(Database)] +``` + +### Audit Event Types + +| Type | Description | Example | +|------|-------------|---------| +| CommandExecuted | User ran command | `!play song` | +| ConfigChanged | Setting modified | Volume changed | +| UserAuthenticated | Login success | Desktop client | +| UserLoginFailed | Login failed | Wrong password | +| HotReloadPerformed | Core reloaded | Developer action | +| TrackPlayed | Song started | YouTube track | +| QueueModified | Queue changed | Track removed | + +## Secure Configuration + +### Password Storage + +```mermaid +flowchart LR + Password[Plain Password] --> Salt[Add Salt] + Salt --> Hash[Hash
bcrypt/scrypt] + Hash --> Store[Store Hash] + + Verify[Verify Attempt] --> AddSalt[Add Same Salt] + AddSalt --> Hash2[Hash] + Hash2 --> Compare{Compare
Hashes} + Compare -->|Match| Valid[Valid] + Compare -->|No Match| Invalid[Invalid] +``` + +### Token Generation + +```mermaid +flowchart LR + Random[CSPRNG] --> Bytes[32 Random Bytes] + Bytes --> Encode[Base64URL Encode] + Encode --> Token[Session Token] + Token --> Store[Store with
Expiration] +``` + +## Network Security + +### TLS Configuration + +```mermaid +flowchart TB + subgraph "TLS Settings" + Version[TLS 1.2+ Only] + Ciphers[Strong Ciphers] + Cert[Valid Certificate] + end + + Client[Client] -->|WebSocket| TLS[TLS Connection] + TLS --> Server[Server] + + Version --> TLS + Ciphers --> TLS + Cert --> TLS +``` + +### Proxy Configuration + +```mermaid +flowchart LR + Bot[Echoion Bot] --> Proxy{Proxy Type} + + Proxy -->|HTTP| HTTP[HTTP Proxy] + Proxy -->|SOCKS5| SOCKS[SOCKS5 Proxy] + Proxy -->|None| Direct[Direct] + + HTTP --> YouTube + SOCKS --> YouTube + Direct --> YouTube +``` + +## Security Checklist + +### Deployment + +```mermaid +flowchart TB + subgraph "Deployment Security" + Default[Change Default
Credentials] + Groups[Configure Server
Groups] + Audit[Enable Audit
Logging] + TLS[Use HTTPS/WSS] + Update[Keep yt-dlp
Updated] + end + + Default --> Secure + Groups --> Secure + Audit --> Secure + TLS --> Secure + Update --> Secure + + Secure[Secure Deployment] +``` + +| Item | Status | Description | +|------|--------|-------------| +| Default credentials | Change | Set strong admin password | +| Server groups | Configure | Set adminGroups, djGroups | +| Audit logging | Enable | Track all admin actions | +| Session timeout | Set | 1 hour recommended | +| TLS/WSS | Use | For remote connections | +| Dependencies | Update | Keep yt-dlp, FFmpeg current | + +### Development + +```mermaid +flowchart TB + subgraph "Development Security" + Validate[Validate All
Inputs] + SQL[Parameterized
Queries] + Secrets[No Secrets in
Logs] + Errors[Safe Error
Messages] + Clear[Clear Sensitive
Memory] + end +``` + +| Practice | Description | +|----------|-------------| +| Input validation | Validate all user inputs | +| SQL injection | Use parameterized queries | +| Logging | Don't log passwords/tokens | +| Error handling | Don't leak sensitive info | +| Memory | Clear secrets after use | + +## Threat Model + +```mermaid +flowchart TB + subgraph "Threats" + Spoof[Identity Spoofing] + Tamper[Tampering] + Repudiation[Repudiation] + InfoDisclosure[Info Disclosure] + DoS[Denial of Service] + Elevation[Elevation of Privilege] + end + + subgraph "Mitigations" + TSAuth[TS Auth] + TokenAuth[Token Auth] + Audit[Audit Logs] + Encrypt[Encryption] + RateLimit[Rate Limiting] + Perms[Permissions] + end + + Spoof --> TSAuth + Spoof --> TokenAuth + Tamper --> Encrypt + Repudiation --> Audit + InfoDisclosure --> Encrypt + DoS --> RateLimit + Elevation --> Perms +``` diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..d93f941 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,197 @@ +# Echoion Music Bot - Technical Documentation + +## Overview + +This documentation provides comprehensive technical information about the Echoion Music Bot architecture, components, data flows, and development guidelines. + +## System Architecture + +```mermaid +flowchart TB + subgraph "User Interfaces" + TS[TeamSpeak Client] + DT[Desktop Client
Qt6 Application] + end + + subgraph "Echoion System" + PL[EchoionPlugin
TeamSpeak Plugin] + CL[CoreLoader
Dynamic Loader] + CO[EchoionCore
Music Engine] + API[EchoionApi
Shared Interfaces] + end + + subgraph "External Services" + YT[YouTube
via yt-dlp] + DB[(SQLite
Database)] + end + + TS <-->|TS3 SDK| PL + DT <-->|WebSocket RPC| CO + PL <-->|Hot Reload| CL + CL <-->|Load/Unload| CO + PL <-->|ICoreInterface| CO + CO <-->|IPluginInterface| PL + CO -->|Stream| YT + CO -->|Persist| DB + API -.->|Types/Interfaces| PL + API -.->|Types/Interfaces| CO + API -.->|Types/Interfaces| DT +``` + +## Documentation Index + +### Getting Started + +| Document | Description | +|----------|-------------| +| **[01-overview.md](01-overview.md)** | Project overview, high-level architecture, key features, technology stack | + +### Component Documentation + +| Document | Component | Topics | +|----------|-----------|--------| +| **[02-echoion-api.md](02-echoion-api.md)** | EchoionApi | Core types, interfaces (ICoreInterface, IPluginInterface), EventBus, Cache, Database | +| **[03-echoion-core.md](03-echoion-core.md)** | EchoionCore | MusicManager, AudioDecoder, NetworkClient, YouTubeClient, CommandManager, RpcServer | +| **[04-echoion-plugin.md](04-echoion-plugin.md)** | EchoionPlugin | Plugin lifecycle, PluginInterface, CoreLoader, TeamSpeak SDK integration | +| **[05-echoion-desktop.md](05-echoion-desktop.md)** | EchoionDesktop | Qt6 GUI, CoreClient, WebSocket RPC, authentication | + +### System Documentation + +| Document | Topic | Coverage | +|----------|-------|----------| +| **[06-data-flow.md](06-data-flow.md)** | Data Flow | Communication protocols, sequence diagrams, message formats, audio pipeline | +| **[07-configuration.md](07-configuration.md)** | Configuration | Config locations, structure, reloading, YouTube auth, proxy settings | +| **[08-commands.md](08-commands.md)** | Commands | Command system, available commands, permissions, adding commands | +| **[09-audio-pipeline.md](09-audio-pipeline.md)** | Audio | Pipeline architecture, formats, FFmpeg, hardware acceleration | +| **[10-database-cache.md](10-database-cache.md)** | Persistence | Database schema, SQLite, LRU cache, performance tuning | +| **[11-events.md](11-events.md)** | Events | EventBus architecture, event types, pub-sub patterns | +| **[12-hot-reload.md](12-hot-reload.md)** | Hot Reload | State preservation, reload process, auto-reload | +| **[13-security.md](13-security.md)** | Security | Authentication, permissions, rate limiting, audit logging | +| **[14-building.md](14-building.md)** | Building | Build requirements, platform instructions, development workflow | + +## Architecture Overview + +### Component Interaction + +```mermaid +sequenceDiagram + actor User + participant TS as TeamSpeak + participant PL as EchoionPlugin + participant CO as EchoionCore + participant YT as YouTube + + User->>TS: Type !play song + TS->>PL: onTextMessage + PL->>CO: Process command + CO->>YT: Fetch stream URL + YT-->>CO: Stream URL + CO->>CO: Start playback + CO->>PL: Audio data + PL->>TS: Voice transmission + TS->>User: Hear music +``` + +### Key Interfaces + +```mermaid +classDiagram + class IPluginInterface { + +sendTextMessage(targetId, message) + +sendAudioData(data) + +getClients() + +moveClient(clientId, channelId) + } + + class ICoreInterface { + +play(track) + +pause() + +resume() + +stop() + +skip(count) + +queueTrack(track, clientId) + +getQueue() + } + + Plugin ..> ICoreInterface : uses + Core ..> IPluginInterface : uses +``` + +## Configuration + +### Config File Locations + +| Platform | Path | +|----------|------| +| Linux | `~/.config/echoion/config.json` | +| macOS | `~/Library/Application Support/echoion/config.json` | +| Windows | `%APPDATA%/echoion/config.json` | + +### Configuration Architecture + +```mermaid +flowchart TB + subgraph "Configuration" + File[config.json] + Env[Environment Vars] + Code[Default Values] + end + + CM[ConfigManager] --> Load[Load Config] + File --> Load + Env -->|Override| Load + Code -->|Fallback| Load + + Load --> Core + Load --> Plugin + Load --> Desktop +``` + +## Development Workflow + +### Quick Commands + +```mermaid +flowchart LR + subgraph "Common Tasks" + Build[Build] --> Reload[Hot Reload] + Test[Test] --> Debug[Debug] + end + + subgraph "Commands" + B["cmake --build build"] + R["cmake --build build --target EchoionCore"] + T["cd build && ctest"] + D["gdb ./build/test"] + end + + Build --> B + Reload --> R + Test --> T + Debug --> D +``` + +| Task | Command | +|------|---------| +| Build all | `cmake -B build && cmake --build build` | +| Hot reload Core | `cmake --build build --target EchoionCore` | +| Run tests | `cd build && ctest` | +| Debug | `gdb ./build/EchoionCore_test` | + +## Documentation Diagrams + +All documentation files contain Mermaid diagrams for: + +- **Architecture diagrams** - Component relationships +- **Sequence diagrams** - Interaction flows +- **Data flow diagrams** - How data moves through the system +- **Class diagrams** - Data structures and interfaces +- **State diagrams** - Lifecycle management + +## Contributing + +Refer to [14-building.md](14-building.md) for development guidelines and AGENTS.md for coding conventions. + +## License + +MIT License - See LICENSE file for details