# 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 ```