commit cf48f2f350f53e5434ff5fb3ec4bfc988dbf6352 Author: faumaray Date: Sat Jul 11 15:06:50 2026 +0300 New arch Signed-off-by: faumaray diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..5733ceb --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,70 @@ +# EchoionStandalone — the daemon that runs Core without a TeamSpeak client. +# +# It reuses the plugin's (TeamSpeak-independent) CoreLoader/FileWatcher to load +# and hot-reload Core, but implements IPluginInterface with EchoionProtocol's +# native UDP client. Built with PLUGIN=1 so it shares the plugin's minimal-API +# ABI contract with Core (self-contained ServerConfig, no ConfigTypes). + +cmake_minimum_required(VERSION 4.0.0) +project(EchoionStandalone VERSION 1.0.0 LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 26) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + +# dylib for the Core hot-reload loader (same version the plugin uses). +CPMAddPackage( + NAME dylib + GITHUB_REPOSITORY martin-olivier/dylib + GIT_TAG "v3.0.1" +) + +find_package(PkgConfig REQUIRED) +pkg_check_modules(SWRESAMPLE REQUIRED IMPORTED_TARGET libswresample libavutil) +pkg_check_modules(OPUS REQUIRED IMPORTED_TARGET opus) +find_package(Threads REQUIRED) + +set(PLUGIN_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../EchoionPlugin") + +add_executable(EchoionStandalone + src/main.cpp + src/StandaloneClientInterface.cpp + src/AudioEncoder.cpp + # Reused, TeamSpeak-independent loader from the plugin (transition shim; + # a shared EchoionHostCommon lib can extract these later). + "${PLUGIN_DIR}/src/CoreLoader.cpp" + "${PLUGIN_DIR}/src/FileWatcher.cpp" +) + +# PLUGIN=1 gives the self-contained ServerConfig + minimal API, matching the +# ABI Core was built against for the plugin path. +target_compile_definitions(EchoionStandalone PRIVATE PLUGIN=1) + +target_include_directories(EchoionStandalone PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/include" + "${PLUGIN_DIR}/include" +) + +target_link_libraries(EchoionStandalone PRIVATE + Echoion::Protocol + Echoion::ApiBase + Echoion::ApiPlugin + Echoion::ApiOpaque + Echoion::ApiPluginInterface + Echoion::ApiCoreInterface + Echoion::ApiLogger + Void::Data + Void::Log + Void::Stacktrace + dylib + Threads::Threads + PkgConfig::SWRESAMPLE + PkgConfig::OPUS +) + +set_target_properties(EchoionStandalone PROPERTIES + OUTPUT_NAME "echoiond" + RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin +) + +install(TARGETS EchoionStandalone RUNTIME DESTINATION bin) diff --git a/include/echoion/standalone/AudioEncoder.hpp b/include/echoion/standalone/AudioEncoder.hpp new file mode 100644 index 0000000..bd40cd7 --- /dev/null +++ b/include/echoion/standalone/AudioEncoder.hpp @@ -0,0 +1,42 @@ +#pragma once + +// Converts Echoion's internal PCM (192 kHz stereo S16, delivered in 20 ms +// chunks) into TeamSpeak-ready Opus frames: resample to 48 kHz stereo, then +// Opus-encode in exact 20 ms (960 samples/ch) frames. A small PCM ring absorbs +// the resampler's priming latency so every emitted frame is exactly 960/ch. + +#include +#include +#include + +struct SwrContext; +struct OpusEncoder; + +namespace Echoion::Standalone +{ + + class AudioEncoder + { + public: + + // inRate defaults to Echoion's 192 kHz internal pipeline. + explicit AudioEncoder(int bitrate = 96000, int inRate = 192000); + ~AudioEncoder(); + + AudioEncoder(const AudioEncoder&) = delete; + AudioEncoder& operator=(const AudioEncoder&) = delete; + + // Feed one chunk of interleaved stereo S16 at inRate. Returns zero or + // more complete Opus frames (each a 20 ms packet). + std::vector> + encode(std::span interleaved); + + private: + + SwrContext* swr_ = nullptr; + OpusEncoder* enc_ = nullptr; + int inRate_ = 192000; + std::vector pcm_; // resampled 48 kHz interleaved stereo + }; + +} // namespace Echoion::Standalone diff --git a/include/echoion/standalone/StandaloneClientInterface.hpp b/include/echoion/standalone/StandaloneClientInterface.hpp new file mode 100644 index 0000000..8910b06 --- /dev/null +++ b/include/echoion/standalone/StandaloneClientInterface.hpp @@ -0,0 +1,117 @@ +#pragma once + +// Implements Echoion's IPluginInterface against the native TeamSpeak UDP +// protocol (EchoionProtocol) instead of the TS3 Client Plugin SDK. This is the +// single seam that lets the whole Core run as a standalone application: Core +// only ever talks to IPluginInterface, so swapping this implementation in for +// the plugin drops the TeamSpeak-client dependency entirely. + +#include + +#include "echoion/protocol/Identity.hpp" +#include "echoion/protocol/TsClient.hpp" + +#include +#include +#include +#include +#include +#include + +namespace Echoion::Standalone +{ + + class AudioEncoder; + + // Runtime knobs the protocol client needs that ServerConfig does not carry. + // Sourced from environment / defaults by main(), so no Core changes are + // required. + struct StandaloneSettings { + std::string identityPath; // where to load/persist the TS identity + int securityLevel = 8; + int opusBitrate = 96000; + }; + + class StandaloneClientInterface : public Api::IPluginInterface + { + public: + + explicit StandaloneClientInterface(StandaloneSettings settings); + ~StandaloneClientInterface() override; + + // Lifecycle + Api::Result initialize() override; + Api::Result shutdown() override; + + // Clients + [[nodiscard]] Api::Result> + getClients() override; + [[nodiscard]] Api::Result> + getClient(uint64_t clientId) override; + Api::Result moveClient(uint64_t clientId, + uint64_t channelId) override; + Api::Result kickClient(uint64_t clientId, + const std::string& reason) override; + + // Channels + [[nodiscard]] Api::Result> + getChannels() const override; + [[nodiscard]] Api::Result> + getChannel(uint64_t channelId) const override; + + // Messaging + Api::Result + sendTextMessage(uint64_t targetId, + const std::string& message) override; + Api::Result + sendChannelMessage(uint64_t channelId, + const std::string& message) override; + Api::Result + sendServerMessage(const std::string& message) override; + + // Audio + Api::Result + sendAudioData(const std::span& data) override; + Api::Result + setWhisperList(const std::vector& clientIds) override; + + // Connection + Api::Result + connectToServer(const Api::ServerConfig& config) override; + Api::Result disconnectFromServer() override; + [[nodiscard]] bool isConnected() const override; + Api::Result reconnect() override; + + // Events + void + registerEventCallback(const Api::EventCallback& cb) override; + void + unregisterEventCallback(const Api::EventCallback& cb) override; + + private: + + void wireCallbacks(); + void onCommand(const Protocol::ParsedCommand& parsed); + void onTextMessage(const Protocol::CommandParams& params); + void broadcast(const Api::PluginEvent& event); + void upsertClientGroup(const Protocol::CommandParams& p, + bool emitConnected); + + StandaloneSettings settings_; + std::unique_ptr identity_; + std::unique_ptr client_; + std::unique_ptr encoder_; + + Api::ServerConfig currentConfig_{}; + std::atomic initialized_{false}; + + mutable std::mutex mirrorMutex_; + std::map clients_; + std::map channels_; + std::vector whisperList_; + + std::mutex cbMutex_; + std::vector callbacks_; + }; + +} // namespace Echoion::Standalone diff --git a/src/AudioEncoder.cpp b/src/AudioEncoder.cpp new file mode 100644 index 0000000..f99f330 --- /dev/null +++ b/src/AudioEncoder.cpp @@ -0,0 +1,102 @@ +#include "echoion/standalone/AudioEncoder.hpp" + +extern "C" { +#include +#include +#include +#include +#include +} + +#include + +namespace Echoion::Standalone +{ + namespace + { + constexpr int OUT_RATE = 48000; + constexpr int CHANNELS = 2; + constexpr int FRAME_SAMPLES = 960; // 20 ms @ 48 kHz per channel + constexpr int FRAME_SHORTS = FRAME_SAMPLES * CHANNELS; + constexpr int MAX_OPUS = 4000; + } // namespace + + AudioEncoder::AudioEncoder(int bitrate, int inRate) : inRate_(inRate) + { + AVChannelLayout stereo = AV_CHANNEL_LAYOUT_STEREO; + if (swr_alloc_set_opts2(&swr_, &stereo, AV_SAMPLE_FMT_S16, OUT_RATE, + &stereo, AV_SAMPLE_FMT_S16, inRate_, 0, + nullptr) < 0 || + swr_init(swr_) < 0) { + throw std::runtime_error("AudioEncoder: swresample init failed"); + } + + int err = 0; + enc_ = opus_encoder_create(OUT_RATE, CHANNELS, OPUS_APPLICATION_AUDIO, + &err); + if (err != OPUS_OK || !enc_) { + throw std::runtime_error("AudioEncoder: opus encoder init failed"); + } + opus_encoder_ctl(enc_, OPUS_SET_BITRATE(bitrate)); + opus_encoder_ctl(enc_, OPUS_SET_SIGNAL(OPUS_SIGNAL_MUSIC)); + } + + AudioEncoder::~AudioEncoder() + { + if (enc_) { + opus_encoder_destroy(enc_); + } + if (swr_) { + swr_free(&swr_); + } + } + + std::vector> + AudioEncoder::encode(std::span interleaved) + { + std::vector> out; + + const int inSamplesPerCh = + static_cast(interleaved.size() / CHANNELS); + if (inSamplesPerCh <= 0) { + return out; + } + + // Upper bound on resampled samples for this chunk. + int maxOut = static_cast( + av_rescale_rnd(swr_get_delay(swr_, inRate_) + inSamplesPerCh, + OUT_RATE, inRate_, AV_ROUND_UP)); + std::vector resampled( + static_cast(maxOut) * CHANNELS, 0); + + const uint8_t* inPtr = + reinterpret_cast(interleaved.data()); + uint8_t* outPtr = reinterpret_cast(resampled.data()); + int gotPerCh = swr_convert(swr_, &outPtr, maxOut, &inPtr, + inSamplesPerCh); + if (gotPerCh < 0) { + return out; + } + pcm_.insert(pcm_.end(), resampled.begin(), + resampled.begin() + + static_cast(gotPerCh) * CHANNELS); + + // Emit as many full 20 ms frames as we have buffered. + size_t consumed = 0; + while (pcm_.size() - consumed >= static_cast(FRAME_SHORTS)) { + uint8_t packet[MAX_OPUS]; + int n = opus_encode(enc_, pcm_.data() + consumed, FRAME_SAMPLES, + packet, MAX_OPUS); + if (n > 0) { + out.emplace_back(packet, packet + n); + } + consumed += FRAME_SHORTS; + } + if (consumed > 0) { + pcm_.erase(pcm_.begin(), + pcm_.begin() + static_cast(consumed)); + } + return out; + } + +} // namespace Echoion::Standalone diff --git a/src/StandaloneClientInterface.cpp b/src/StandaloneClientInterface.cpp new file mode 100644 index 0000000..5104807 --- /dev/null +++ b/src/StandaloneClientInterface.cpp @@ -0,0 +1,495 @@ +#include "echoion/standalone/StandaloneClientInterface.hpp" +#include "echoion/standalone/AudioEncoder.hpp" + +#include "echoion/protocol/Command.hpp" + +#include + +#include +#include + +namespace Echoion::Standalone +{ + namespace + { + constexpr const char* LOG = "Standalone"; + + uint64_t toU64(const std::string& s) + { + try { + return std::stoull(s); + } catch (...) { + return 0; + } + } + + std::string get(const Protocol::CommandParams& p, const char* k) + { + auto it = p.find(k); + return it == p.end() ? std::string{} : it->second; + } + } // namespace + + StandaloneClientInterface::StandaloneClientInterface( + StandaloneSettings settings) + : settings_(std::move(settings)) + { + } + + StandaloneClientInterface::~StandaloneClientInterface() + { + (void)shutdown(); + } + + Api::Result StandaloneClientInterface::initialize() + { + if (initialized_.exchange(true)) { + return {}; + } + encoder_ = std::make_unique(settings_.opusBitrate); + client_ = std::make_unique(); + Void::Log::info(LOG, "Standalone client interface initialized"); + return {}; + } + + Api::Result StandaloneClientInterface::shutdown() + { + if (!initialized_.exchange(false)) { + return {}; + } + if (client_) { + client_->forceClose(); + client_.reset(); + } + encoder_.reset(); + return {}; + } + + // ---- Connection -------------------------------------------------------- + + Api::Result + StandaloneClientInterface::connectToServer(const Api::ServerConfig& config) + { + if (!client_) { + return Api::fail(Api::ErrorCode::NotInitialized, + "interface not initialized"); + } + currentConfig_ = config; + + // Load or create the persistent identity. + try { + std::filesystem::path idPath(settings_.identityPath); + if (!idPath.empty() && std::filesystem::exists(idPath)) { + identity_ = std::make_unique( + Protocol::Identity::load(idPath.string())); + Void::Log::info(LOG, "Loaded identity (uid={})", + identity_->uid()); + } else { + Void::Log::info(LOG, + "Generating identity (security level {})...", + settings_.securityLevel); + identity_ = std::make_unique( + Protocol::Identity::generate(settings_.securityLevel)); + if (!idPath.empty()) { + std::filesystem::create_directories(idPath.parent_path()); + identity_->save(idPath.string()); + } + Void::Log::info(LOG, "Identity ready (uid={})", + identity_->uid()); + } + } catch (const std::exception& e) { + return Api::fail(Api::ErrorCode::PluginError, + std::string("identity error: ") + e.what()); + } + + wireCallbacks(); + + Protocol::TsClientOptions opts; + opts.host = config.address; + opts.port = config.port ? config.port : 9987; + opts.identity = identity_.get(); + opts.nickname = config.nickname.empty() ? "EchoionBot" : config.nickname; + opts.serverPassword = config.serverPassword; + opts.defaultChannel = + config.defaultChannelId.value_or(std::string{}); + opts.channelPassword = config.channelPassword.value_or(std::string{}); + + try { + client_->connect(opts); + } catch (const std::exception& e) { + return Api::fail(Api::ErrorCode::NetworkError, + std::string("connect failed: ") + e.what()); + } + Void::Log::info(LOG, "Connecting to {}:{} as {}", opts.host, opts.port, + opts.nickname); + return {}; + } + + void StandaloneClientInterface::wireCallbacks() + { + Protocol::TsClientCallbacks cb; + cb.onConnected = [this] { + // Ask the server to reveal all clients so the presence mirror fills. + client_->sendCommand("channelsubscribeall"); + Api::PluginEvent ev; + ev.type = Api::PluginEventType::ConnectionEstablished; + ev.timestamp = std::chrono::system_clock::now(); + broadcast(ev); + }; + cb.onDisconnected = [this] { + Void::Log::warn(LOG, "Disconnected from server"); + }; + cb.onError = [](const std::string& msg) { + Void::Log::error(LOG, "Protocol error: {}", msg); + }; + cb.onCommand = [this](const Protocol::ParsedCommand& p) { + onCommand(p); + }; + cb.onTextMessage = [this](const Protocol::CommandParams& p) { + onTextMessage(p); + }; + cb.onDebug = [](const std::string& msg) { + Void::Log::debug(LOG, "{}", msg); + }; + client_->setCallbacks(std::move(cb)); + } + + Api::Result StandaloneClientInterface::disconnectFromServer() + { + if (client_) { + client_->disconnect(); + } + return {}; + } + + bool StandaloneClientInterface::isConnected() const + { + return client_ && + client_->state() == Protocol::ClientState::Connected; + } + + Api::Result StandaloneClientInterface::reconnect() + { + (void)disconnectFromServer(); + return connectToServer(currentConfig_); + } + + // ---- Event mirror ------------------------------------------------------ + + void StandaloneClientInterface::upsertClientGroup( + const Protocol::CommandParams& p, bool emitConnected) + { + uint64_t clid = toU64(get(p, "clid")); + if (clid == 0) { + return; + } + Api::ClientInfo info; + { + std::lock_guard lock(mirrorMutex_); + info = clients_[clid]; + info.id = clid; + if (auto n = get(p, "client_nickname"); !n.empty()) { + info.nickname = n; + } + if (auto u = get(p, "client_unique_identifier"); !u.empty()) { + info.uniqueIdentifier = u; + } + if (auto c = get(p, "ctid"); !c.empty()) { + info.channelId = toU64(c); + } else if (auto cid = get(p, "cid"); !cid.empty()) { + info.channelId = toU64(cid); + } + clients_[clid] = info; + } + if (emitConnected) { + Api::PluginEvent ev; + ev.type = Api::PluginEventType::ClientConnected; + ev.clientId = clid; + ev.clientName = info.nickname; + ev.timestamp = std::chrono::system_clock::now(); + broadcast(ev); + } + } + + void StandaloneClientInterface::onCommand(const Protocol::ParsedCommand& p) + { + const auto& groups = + p.groups.empty() + ? std::vector{p.params} + : p.groups; + + if (p.name == "notifycliententerview") { + for (const auto& g : groups) { + upsertClientGroup(g, true); + } + } else if (p.name == "notifyclientleftview") { + for (const auto& g : groups) { + uint64_t clid = toU64(get(g, "clid")); + if (clid == 0) { + continue; + } + std::string name; + { + std::lock_guard lock(mirrorMutex_); + auto it = clients_.find(clid); + if (it != clients_.end()) { + name = it->second.nickname; + clients_.erase(it); + } + } + Api::PluginEvent ev; + ev.type = Api::PluginEventType::ClientDisconnected; + ev.clientId = clid; + ev.clientName = name; + ev.timestamp = std::chrono::system_clock::now(); + broadcast(ev); + } + } else if (p.name == "notifyclientmoved") { + for (const auto& g : groups) { + uint64_t clid = toU64(get(g, "clid")); + uint64_t ctid = toU64(get(g, "ctid")); + if (clid == 0) { + continue; + } + { + std::lock_guard lock(mirrorMutex_); + clients_[clid].id = clid; + clients_[clid].channelId = ctid; + } + Api::PluginEvent ev; + ev.type = Api::PluginEventType::ClientMoved; + ev.clientId = clid; + ev.targetChannelId = ctid; + ev.timestamp = std::chrono::system_clock::now(); + broadcast(ev); + } + } else if (p.name == "channellist" || p.name == "notifychannellist") { + std::lock_guard lock(mirrorMutex_); + for (const auto& g : groups) { + uint64_t cid = toU64(get(g, "cid")); + if (cid == 0) { + continue; + } + Api::ChannelInfo ch = channels_[cid]; + ch.id = cid; + if (auto n = get(g, "channel_name"); !n.empty()) { + ch.name = n; + } + if (auto pid = get(g, "pid"); !pid.empty()) { + ch.parentId = toU64(pid); + } + channels_[cid] = ch; + } + } + } + + void StandaloneClientInterface::onTextMessage( + const Protocol::CommandParams& params) + { + uint64_t invoker = toU64(get(params, "invokerid")); + if (client_ && invoker == client_->clientId()) { + return; // ignore our own messages + } + Api::PluginEvent ev; + ev.type = Api::PluginEventType::TextMessageReceived; + ev.clientId = invoker; + ev.clientName = get(params, "invokername"); + ev.message = get(params, "msg"); + if (auto t = get(params, "target"); !t.empty()) { + ev.targetChannelId = toU64(t); + } + ev.timestamp = std::chrono::system_clock::now(); + broadcast(ev); + } + + void StandaloneClientInterface::broadcast(const Api::PluginEvent& event) + { + std::vector cbs; + { + std::lock_guard lock(cbMutex_); + cbs = callbacks_; + } + for (const auto& cb : cbs) { + cb(event); + } + } + + // ---- Clients / channels ------------------------------------------------ + + Api::Result> + StandaloneClientInterface::getClients() + { + std::lock_guard lock(mirrorMutex_); + std::vector out; + out.reserve(clients_.size()); + for (const auto& [id, c] : clients_) { + out.push_back(c); + } + return out; + } + + Api::Result> + StandaloneClientInterface::getClient(uint64_t clientId) + { + std::lock_guard lock(mirrorMutex_); + auto it = clients_.find(clientId); + if (it == clients_.end()) { + return std::optional{}; + } + return std::optional{it->second}; + } + + Api::Result> + StandaloneClientInterface::getChannels() const + { + std::lock_guard lock(mirrorMutex_); + std::vector out; + out.reserve(channels_.size()); + for (const auto& [id, c] : channels_) { + out.push_back(c); + } + return out; + } + + Api::Result> + StandaloneClientInterface::getChannel(uint64_t channelId) const + { + std::lock_guard lock(mirrorMutex_); + auto it = channels_.find(channelId); + if (it == channels_.end()) { + return std::optional{}; + } + return std::optional{it->second}; + } + + Api::Result + StandaloneClientInterface::moveClient(uint64_t clientId, uint64_t channelId) + { + if (!client_) { + return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); + } + Protocol::CommandParams p; + p["clid"] = std::to_string(clientId); + p["cid"] = std::to_string(channelId); + client_->sendCommand(Protocol::buildCommand("clientmove", p)); + return {}; + } + + Api::Result + StandaloneClientInterface::kickClient(uint64_t clientId, + const std::string& reason) + { + if (!client_) { + return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); + } + Protocol::CommandParams p; + p["clid"] = std::to_string(clientId); + p["reasonid"] = "5"; // kick from server + p["reasonmsg"] = reason; + client_->sendCommand(Protocol::buildCommand("clientkick", p)); + return {}; + } + + // ---- Messaging --------------------------------------------------------- + + Api::Result + StandaloneClientInterface::sendTextMessage(uint64_t targetId, + const std::string& message) + { + if (!client_) { + return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); + } + Protocol::CommandParams p; + p["targetmode"] = "1"; // client + p["target"] = std::to_string(targetId); + p["msg"] = message; + client_->sendCommand(Protocol::buildCommand("sendtextmessage", p)); + return {}; + } + + Api::Result + StandaloneClientInterface::sendChannelMessage(uint64_t channelId, + const std::string& message) + { + if (!client_) { + return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); + } + Protocol::CommandParams p; + p["targetmode"] = "2"; // channel + p["target"] = std::to_string(channelId); + p["msg"] = message; + client_->sendCommand(Protocol::buildCommand("sendtextmessage", p)); + return {}; + } + + Api::Result + StandaloneClientInterface::sendServerMessage(const std::string& message) + { + if (!client_) { + return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); + } + Protocol::CommandParams p; + p["targetmode"] = "3"; // server + p["msg"] = message; + client_->sendCommand(Protocol::buildCommand("sendtextmessage", p)); + return {}; + } + + // ---- Audio ------------------------------------------------------------- + + Api::Result + StandaloneClientInterface::sendAudioData(const std::span& data) + { + if (!client_ || !encoder_ || + client_->state() != Protocol::ClientState::Connected) { + return {}; + } + std::vector whisper; + { + std::lock_guard lock(mirrorMutex_); + whisper = whisperList_; + } + auto frames = encoder_->encode(data); + for (const auto& f : frames) { + if (whisper.empty()) { + client_->sendVoice(f); + } else { + std::vector clients; + clients.reserve(whisper.size()); + for (uint64_t c : whisper) { + clients.push_back(static_cast(c)); + } + client_->sendWhisper(f, {}, clients); + } + } + return {}; + } + + Api::Result StandaloneClientInterface::setWhisperList( + const std::vector& clientIds) + { + std::lock_guard lock(mirrorMutex_); + whisperList_ = clientIds; + return {}; + } + + // ---- Events ------------------------------------------------------------ + + void StandaloneClientInterface::registerEventCallback( + const Api::EventCallback& cb) + { + std::lock_guard lock(cbMutex_); + callbacks_.push_back(cb); + } + + void StandaloneClientInterface::unregisterEventCallback( + const Api::EventCallback&) + { + // Callbacks are not individually comparable (std::function); the host + // registers a single Core callback for the process lifetime, so a full + // clear on unregister is sufficient and matches usage. + std::lock_guard lock(cbMutex_); + callbacks_.clear(); + } + +} // namespace Echoion::Standalone diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..f40cff7 --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,166 @@ +// Standalone Echoion host. +// +// Replaces the TeamSpeak-client + plugin sandwich: loads the same hot-reloadable +// Core shared library via the (TeamSpeak-independent) CoreLoader, but backs +// IPluginInterface with a native TeamSpeak UDP protocol client instead of the +// TS3 Client Plugin SDK. The bot therefore runs as a plain daemon — no +// TeamSpeak client, no Weston/RDP, no plugin directory. + +#include "echoion/plugin/CoreLoader.hpp" +#include "echoion/standalone/StandaloneClientInterface.hpp" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + std::atomic g_stop{false}; + std::condition_variable g_cv; + std::mutex g_mu; + + void onSignal(int) + { + g_stop = true; + g_cv.notify_all(); + } + + std::filesystem::path configDir() + { + if (const char* x = std::getenv("XDG_CONFIG_HOME")) { + return std::filesystem::path(x) / "echoion"; + } + if (const char* h = std::getenv("HOME")) { + return std::filesystem::path(h) / ".config" / "echoion"; + } + return std::filesystem::path(".") / "echoion"; + } + + std::string envOr(const char* key, const std::string& fallback) + { + const char* v = std::getenv(key); + return v ? std::string(v) : fallback; + } + + int envInt(const char* key, int fallback) + { + const char* v = std::getenv(key); + if (!v) { + return fallback; + } + try { + return std::stoi(v); + } catch (...) { + return fallback; + } + } + + // Locate the Core shared library ("Echoion.ts"). + std::filesystem::path corePath() + { + if (const char* p = std::getenv("ECHOION_CORE_PATH")) { + return p; + } + for (const char* c : + {"./Echoion.ts", "./bin/Echoion.ts", "./plugins/Echoion.ts"}) { + if (std::filesystem::exists(c)) { + return c; + } + } + return "./Echoion.ts"; + } +} // namespace + +int main(int argc, char** argv) +{ + std::set_terminate([] { + const auto frames = Void::Stacktrace::capture_stacktrace(); + std::cerr << Void::Stacktrace::format_stacktrace(frames) << '\n'; + std::abort(); + }); + + std::filesystem::path cfgDir = configDir(); + std::filesystem::path cfgPath = cfgDir / "config.json"; + // Optional CLI: --config + for (int i = 1; i + 1 < argc; ++i) { + if (std::string(argv[i]) == "--config") { + cfgPath = argv[i + 1]; + } + } + + Echoion::Standalone::StandaloneSettings settings; + settings.identityPath = + envOr("ECHOION_IDENTITY_PATH", (cfgDir / "identity.txt").string()); + settings.securityLevel = envInt("ECHOION_SECURITY_LEVEL", 8); + settings.opusBitrate = envInt("ECHOION_OPUS_BITRATE", 96000); + + auto interface = std::make_shared( + settings); + if (auto r = interface->initialize(); !r) { + Void::Log::error("main", "interface init failed: {}", + r.error().message); + return 1; + } + + Echoion::Plugin::CoreLoader loader; + loader.setConfigPath(cfgPath); + + auto corePathResolved = corePath(); + Void::Log::info("main", "Loading Core from {}", corePathResolved.string()); + if (auto r = loader.load(corePathResolved); !r) { + Void::Log::error("main", "failed to load Core: {}", r.error().message); + return 1; + } + + auto core = loader.getCore(); + if (!core) { + Void::Log::error("main", "Core not available after load"); + return 1; + } + + core->setPluginInterface(interface); + interface->registerEventCallback([core](const Echoion::Api::PluginEvent& ev) { + std::ignore = core->onPluginEvent(ev); + }); + // Re-register the Core callback after each hot reload (new Core instance). + loader.setHotReloadCallback([&loader, interface] { + if (auto c = loader.getCore()) { + c->setPluginInterface(interface); + interface->registerEventCallback( + [c](const Echoion::Api::PluginEvent& ev) { + std::ignore = c->onPluginEvent(ev); + }); + c->triggerAutoConnect(); + } + }); + + core->triggerAutoConnect(); + loader.enableAutoReload(); + + std::signal(SIGINT, onSignal); + std::signal(SIGTERM, onSignal); + Void::Log::info("main", "Echoion standalone running. Ctrl-C to stop."); + + { + std::unique_lock lock(g_mu); + g_cv.wait(lock, [] { return g_stop.load(); }); + } + + Void::Log::info("main", "Shutting down..."); + loader.disableAutoReload(); + (void)interface->disconnectFromServer(); + (void)loader.unload(); + (void)interface->shutdown(); + return 0; +}