Files
Echoion/docs/03-echoion-core.md
T
2026-02-01 23:09:22 +03:00

8.4 KiB

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.

flowchart TB
    subgraph "EchoionCore"
        CO[Core Controller]
        
        subgraph "Managers"
            MM[MusicManager<br/>Queue & Playback]
            CM[CommandManager<br/>Commands]
            SM[SubscriptionManager<br/>Listeners]
        end
        
        subgraph "Clients"
            YC[YouTubeClient<br/>yt-dlp]
            NC[NetworkClient<br/>HTTP]
        end
        
        subgraph "Audio"
            AD[AudioDecoder<br/>FFmpeg]
            MP[MemoryPool<br/>Buffers]
        end
        
        subgraph "API"
            RS[RpcServer<br/>WebSocket]
            DB[(Database<br/>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
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:

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:

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:

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:

flowchart LR
    Input[Input Stream<br/>MP3/AAC/Opus/etc] --> FFmpeg
    
    subgraph "FFmpeg Pipeline"
        Demux[Demuxer<br/>Container format]
        Decode[Decoder<br/>Audio codec]
        Resample[Resampler<br/>SWR]
    end
    
    FFmpeg --> Demux
    Demux --> Decode
    Decode --> Resample
    Resample --> Output[Output PCM<br/>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:

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:

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

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

flowchart TB
    subgraph "Threads"
        MT[Main Thread<br/>Event processing]
        PT[Playback Thread<br/>MusicManager]
        DT[Decode Thread<br/>AudioDecoder]
        NT[Network Thread Pool<br/>NetworkClient]
        RT[RPC Thread<br/>RpcServer]
        ET[Event Thread<br/>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

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