Hot reload fix

This commit is contained in:
faumaray committed 2026-02-03 04:48:29 +03:00
1 parent 8b8a7f4f9a
commit 0fa9db4691
6 files changed
+677 -178

No files matched your search

+12 -15
View File
@@ -5,12 +5,14 @@ set(CMAKE_CXX_STANDARD 26)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
CPMAddPackage(
NAME dylib
GITHUB_REPOSITORY martin-olivier/dylib
GIT_TAG "v3.0.1"
OPTIONS "CMAKE_POSITION_INDEPENDENT_CODE ON"
)
add_library(EchoionPlugin SHARED
src/PluginInterface.cpp
src/CoreLoader.cpp
@@ -56,19 +58,14 @@ if(TARGET dylib)
set_target_properties(dylib PROPERTIES POSITION_INDEPENDENT_CODE ON)
endif()
include(GNUInstallDirs)
install(TARGETS EchoionPlugin
EXPORT EchoionPluginTargets
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}/plugins
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}/plugins
)
install(EXPORT EchoionPluginTargets
FILE EchoionPluginTargets.cmake
NAMESPACE Echoion::
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/EchoionPlugin
)
install(DIRECTORY include/
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
# PackageProject.cmake configuration
packageProject(
NAME EchoionPlugin
VERSION ${PROJECT_VERSION}
NAMESPACE Echoion
BINARY_DIR ${PROJECT_BINARY_DIR}
INCLUDE_DIR ${PROJECT_SOURCE_DIR}/include
INCLUDE_DESTINATION include
COMPATIBILITY SameMajorVersion
DISABLE_VERSION_SUFFIX YES
)
+18
View File
@@ -11,6 +11,7 @@
#include <thread>
#include <condition_variable>
#include <queue>
#include <functional>
namespace Echoion::Plugin {
@@ -32,6 +33,10 @@ public:
void enableAutoReload();
void disableAutoReload();
[[nodiscard]] bool isAutoReloadEnabled() const noexcept;
// Callback for hot reload completion (called after auto-reload finishes)
using HotReloadCallback = std::function<void()>;
void setHotReloadCallback(HotReloadCallback callback) { hotReloadCallback_ = std::move(callback); }
private:
Api::Result<void> loadLibraryInternal(const std::filesystem::path& path);
@@ -54,7 +59,20 @@ private:
FileWatcher fileWatcher_;
std::atomic<bool> autoReloadEnabled_{false};
// Deferred reload - waits for current track to finish
std::thread deferredReloadThread_;
std::atomic<bool> hasPendingReload_{false};
std::filesystem::path pendingReloadPath_;
std::string pendingTrackId_; // Track ID that was playing when reload scheduled
mutable std::mutex pendingReloadMutex_;
// Hot reload completion callback
HotReloadCallback hotReloadCallback_;
void onCoreFileChanged();
void waitForTrackAndReload(const std::filesystem::path& targetPath, const std::string& trackId);
[[nodiscard]] bool isPlaybackActive() const;
[[nodiscard]] bool isSameTrackPlaying(const std::string& trackId) const;
};
} // namespace Echoion::Plugin
+76 -36
View File
@@ -1,13 +1,15 @@
#pragma once
#include <echoion/api.hpp>
#include <atomic>
#include <condition_variable>
#include <dylib.hpp>
#include <echoion/api.hpp>
#include <future>
#include <map>
#include <memory>
#include <mutex>
#include <atomic>
#include <thread>
#include <queue>
#include <condition_variable>
#include <thread>
// TeamSpeak SDK headers
#include "ts3_functions.h"
@@ -18,9 +20,16 @@ namespace Echoion::Plugin {
struct AudioDeviceConfig {
static constexpr const char* DEVICE_ID = "echoion_audio_device";
static constexpr const char* DEVICE_NAME = "Echoion Music Bot Audio";
static constexpr int SAMPLE_RATE = 192000; // Match reference implementation
static constexpr int CHANNELS = 2;
static constexpr int SAMPLE_SIZE = sizeof(int16_t);
static constexpr int SAMPLE_RATE =
192000; // 192kHz for high quality audio (CODEC_OPUS_MUSIC)
static constexpr int CHANNELS = 2;
static constexpr int SAMPLE_SIZE = sizeof(int16_t);
};
// Server groups cache entry
struct ServerGroupsCacheEntry {
std::vector<uint64_t> groups;
std::chrono::steady_clock::time_point timestamp;
};
// Plugin implementation of IPluginInterface for the Core to use
@@ -37,14 +46,19 @@ public:
Api::Result<void> shutdown() override;
// Client operations
[[nodiscard]] Api::Result<std::vector<Api::ClientInfo>> getClients() const override;
[[nodiscard]] Api::Result<std::optional<Api::ClientInfo>> getClient(uint64_t clientId) const override;
Api::Result<void> moveClient(uint64_t clientId, uint64_t channelId) override;
Api::Result<void> kickClient(uint64_t clientId, const std::string& reason) override;
[[nodiscard]] Api::Result<std::vector<Api::ClientInfo>>
getClients() override;
[[nodiscard]] Api::Result<std::optional<Api::ClientInfo>>
getClient(uint64_t clientId) override;
Api::Result<void> moveClient(uint64_t clientId,
uint64_t channelId) override;
Api::Result<void> kickClient(uint64_t clientId,
const std::string& reason) override;
// Channel operations
[[nodiscard]] Api::Result<std::vector<Api::ChannelInfo>> getChannels() const override;
[[nodiscard]] Api::Result<std::optional<Api::ChannelInfo>> getChannel(uint64_t channelId) const override;
// Channel operations
[[nodiscard]] Api::Result<std::vector<Api::ChannelInfo>>
getChannels() const override;
[[nodiscard]] Api::Result<std::optional<Api::ChannelInfo>> getChannel(uint64_t channelId) const override;
// Messaging
Api::Result<void> sendTextMessage(uint64_t targetId, const std::string& message) override;
@@ -52,12 +66,15 @@ public:
Api::Result<void> sendServerMessage(const std::string& message) override;
// Audio
Api::Result<void> sendAudioData(const std::span<const uint8_t>& data) override;
Api::Result<void> setWhisperList(const std::vector<uint64_t>& clientIds) override;
Api::Result<void>
sendAudioData(const std::span<const short>& data) override;
Api::Result<void>
setWhisperList(const std::vector<uint64_t>& clientIds) override;
// Event subscription
void registerEventCallback(const Api::EventCallback& callback) override;
// Event subscription
void registerEventCallback(const Api::EventCallback& callback) override;
void unregisterEventCallback(const Api::EventCallback& callback) override;
void clearEventCallbacks();
// TeamSpeak event handlers (called by TeamSpeak SDK)
void onClientConnected(uint64_t serverConnectionHandlerId, uint64_t clientId);
@@ -68,13 +85,19 @@ public:
void onVoiceDataReceived(uint64_t serverConnectionHandlerId, uint64_t clientId,
const std::span<const uint8_t>& data);
// Server connection management (IPluginInterface implementation)
Api::Result<void> connectToServer(const Api::ServerConfig& config) override;
Api::Result<void> disconnectFromServer() override;
[[nodiscard]] bool isConnected() const override;
Api::Result<void> reconnect() override;
// Server group list callback (called by TeamSpeak SDK)
void onServerGroupByClientID(uint64_t serverConnectionHandlerId,
uint64_t clientDatabaseId,
const char* groupName, uint64_t serverGroupId,
uint64_t clientId);
// Audio device management
// Server connection management (IPluginInterface implementation)
Api::Result<void> connectToServer(const Api::ServerConfig& config) override;
Api::Result<void> disconnectFromServer() override;
[[nodiscard]] bool isConnected() const override;
Api::Result<void> reconnect() override;
// Audio device management
Api::Result<void> registerAudioDevice();
Api::Result<void> unregisterAudioDevice();
Api::Result<void> openAudioDevice();
@@ -87,31 +110,48 @@ public:
[[nodiscard]] uint64_t getServerConnectionHandlerId() const;
// Audio data submission (for internal use)
void submitAudioData(const std::span<const int16_t> samples);
void submitAudioData(const std::span<const short> samples);
// Automatic configuration
Api::Result<void> configureAudioProfile();
Api::Result<void> checkAndHandleFirstRun();
private:
void broadcastEvent(const Api::PluginEvent& event);
std::string getClientName(uint64_t clientId) const;
std::string getChannelName(uint64_t channelId) const;
TS3Functions* ts3Functions_ = nullptr;
uint64_t serverConnectionHandlerId_ = 0;
std::atomic<bool> initialized_{false};
std::atomic<bool> audioDeviceRegistered_{false};
std::atomic<bool> audioDeviceOpen_{false};
// Fetch server groups for a client (returns future that completes when
// groups are received)
std::future<std::vector<uint64_t>> fetchServerGroups(uint64_t clientId);
std::vector<Api::EventCallback> eventCallbacks_;
// Get cached server groups (or empty if not cached)
std::vector<uint64_t> getCachedServerGroups(uint64_t clientId);
TS3Functions* ts3Functions_ = nullptr;
uint64_t serverConnectionHandlerId_ = 0;
std::atomic<bool> initialized_{false};
std::atomic<bool> audioDeviceRegistered_{false};
std::atomic<bool> audioDeviceOpen_{false};
std::vector<Api::EventCallback> eventCallbacks_;
mutable std::mutex eventMutex_;
// Audio data queue
std::queue<std::vector<int16_t>> audioQueue_;
std::mutex audioMutex_;
std::condition_variable audioCv_;
std::queue<std::vector<short>> audioQueue_;
std::mutex audioMutex_;
std::condition_variable audioCv_;
std::atomic<bool> stopAudioThread_{false};
std::jthread audioThread_;
// Connection info
Api::ServerConfig currentServerConfig_;
// Server groups cache
mutable std::mutex serverGroupsMutex_;
std::map<uint64_t, ServerGroupsCacheEntry> serverGroupsCache_;
std::map<uint64_t, std::promise<std::vector<uint64_t>>>
pendingServerGroupRequests_;
// Connection info
Api::ServerConfig currentServerConfig_;
};
} // namespace Echoion::Plugin
+101 -5
View File
@@ -47,20 +47,116 @@ void CoreLoader::onCoreFileChanged() {
return;
}
ECHOION_LOG_INFO("Core file changed, triggering hot reload...");
ECHOION_LOG_INFO("Core file changed, scheduling hot reload after current track...");
// Small delay to ensure file write is complete
std::this_thread::sleep_for(std::chrono::milliseconds(500));
auto result = hotReload(currentLibraryPath_);
if (!result) {
ECHOION_LOG_ERROR(std::format("Auto hot-reload failed: {}", result.error().message));
// Check if playback is active - if so, defer reload
if (isPlaybackActive()) {
std::string currentTrackId;
{
std::lock_guard<std::mutex> lock(pendingReloadMutex_);
hasPendingReload_ = true;
pendingReloadPath_ = currentLibraryPath_;
// Capture current track ID
auto state = core_->getPlaybackState();
if (state && state->currentTrack.has_value()) {
pendingTrackId_ = state->currentTrack->track.id;
currentTrackId = pendingTrackId_;
}
}
ECHOION_LOG_INFO(std::format("Playback active (track: {}), deferring reload until track finishes", currentTrackId));
// Start background thread to wait for track end
if (deferredReloadThread_.joinable()) {
deferredReloadThread_.join();
}
deferredReloadThread_ = std::thread([this, currentTrackId]() {
waitForTrackAndReload(pendingReloadPath_, currentTrackId);
});
} else {
ECHOION_LOG_INFO("Auto hot-reload completed successfully");
// No playback, reload immediately
auto result = hotReload(currentLibraryPath_);
if (!result) {
ECHOION_LOG_ERROR(std::format("Auto hot-reload failed: {}", result.error().message));
} else {
ECHOION_LOG_INFO("Auto hot-reload completed successfully");
// Notify Plugin to re-register callbacks
if (hotReloadCallback_) {
hotReloadCallback_();
}
}
}
}
bool CoreLoader::isPlaybackActive() const {
if (!core_) {
return false;
}
auto state = core_->getPlaybackState();
if (!state) {
return false;
}
// Check if currently playing a track
return state->isPlaying && state->currentTrack.has_value();
}
bool CoreLoader::isSameTrackPlaying(const std::string& trackId) const {
if (!core_ || trackId.empty()) {
return false;
}
auto state = core_->getPlaybackState();
if (!state || !state->currentTrack.has_value()) {
return false;
}
return state->currentTrack->track.id == trackId;
}
void CoreLoader::waitForTrackAndReload(const std::filesystem::path& targetPath, const std::string& trackId) {
ECHOION_LOG_INFO(std::format("Waiting for track {} to finish before reload...", trackId));
// Poll every 500ms to check if the specific track finished
// (playback may continue with next track, but we only care about THIS track)
while (isSameTrackPlaying(trackId)) {
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
ECHOION_LOG_INFO("Track finished, starting hot reload");
// Clear pending flag
{
std::lock_guard<std::mutex> lock(pendingReloadMutex_);
hasPendingReload_ = false;
pendingTrackId_.clear();
}
// Now do the reload
auto result = hotReload(targetPath);
if (!result) {
ECHOION_LOG_ERROR(std::format("Deferred hot-reload failed: {}", result.error().message));
} else {
ECHOION_LOG_INFO("Deferred hot-reload completed successfully");
// Notify Plugin to re-register callbacks
if (hotReloadCallback_) {
hotReloadCallback_();
}
}
}
CoreLoader::~CoreLoader() {
// Stop any deferred reload thread
if (deferredReloadThread_.joinable()) {
// We can't really stop it gracefully, but we can detach it
// to avoid hanging on shutdown
deferredReloadThread_.detach();
}
unload();
cleanupTempFiles();
}
+90 -24
View File
@@ -103,6 +103,10 @@ TS3_PLUGIN_API void ts3plugin_registerPluginID(const char *id)
std::cout << std::format("[Echoion] Plugin ID: {}", pluginID) << std::endl;
}
// Forward declarations for helper functions
static bool reregisterPluginInterface();
static bool reloadCoreWithInterface();
static bool ensureCoreLoaded() {
if (g_coreLoader && g_coreLoader->isLoaded()) {
return true;
@@ -111,6 +115,11 @@ static bool ensureCoreLoaded() {
try {
if (!g_coreLoader) {
g_coreLoader = std::make_unique<CoreLoader>();
// Set up callback for auto-reload to re-register plugin interface
g_coreLoader->setHotReloadCallback([]() {
std::cout << "[Echoion] Auto-reload callback triggered, re-registering interface..." << std::endl;
reregisterPluginInterface();
});
}
// Pass config path to CoreLoader (Core will load config internally)
@@ -149,24 +158,25 @@ void deferredInitialization() {
g_deferredInitRunning = true;
// Wait 3 seconds for TeamSpeak GUI to fully initialize
std::this_thread::sleep_for(std::chrono::seconds(3));
// Wait for TS functions to be set (up to 2 more seconds)
int waitCount = 0;
while (!g_ts3FunctionsReady.load() && waitCount < 20) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
waitCount++;
}
if (!g_ts3FunctionsReady.load()) {
std::cerr << "[Echoion] TS3 functions not ready, aborting init" << std::endl;
g_deferredInitRunning = false;
std::this_thread::sleep_for(std::chrono::seconds(30));
// Wait for TS functions to be set (up to 2 more seconds)
int waitCount = 0;
while (!g_ts3FunctionsReady.load() && waitCount < 20) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
waitCount++;
}
if (!g_ts3FunctionsReady.load()) {
std::cerr << "[Echoion] TS3 functions not ready, aborting init"
<< std::endl;
g_deferredInitRunning = false;
return;
}
std::cout << "[Echoion] Starting deferred initialization..." << std::endl;
try {
}
std::cout << "[Echoion] Starting deferred initialization..." << std::endl;
try {
// Create plugin interface
g_pluginInterface = std::make_shared<PluginInterface>();
@@ -297,16 +307,74 @@ TS3_PLUGIN_API void ts3plugin_onClientMoveTimeoutEvent(uint64 serverConnectionHa
}
}
// Helper to re-register plugin interface after hot reload (Core already reloaded)
static bool reregisterPluginInterface() {
if (!g_coreLoader) {
std::cerr << "[Echoion] Cannot re-register: CoreLoader not available" << std::endl;
return false;
}
std::cout << "[Echoion] Re-registering plugin interface after hot reload..." << std::endl;
// Get the new core instance
auto core = g_coreLoader->getCore();
if (!core) {
std::cerr << "[Echoion] ERROR: Core is null!" << std::endl;
return false;
}
if (!g_pluginInterface) {
std::cerr << "[Echoion] ERROR: PluginInterface is null!" << std::endl;
return false;
}
std::cout << std::format("[Echoion] New Core pointer: {}", reinterpret_cast<uintptr_t>(core.get())) << std::endl;
// Set the plugin interface first (before registering callbacks)
core->setPluginInterface(g_pluginInterface);
std::cout << "[Echoion] Plugin interface set on new Core" << std::endl;
// Clear old callbacks (they point to destroyed Core) and register new one
std::cout << "[Echoion] About to clear callbacks..." << std::endl;
g_pluginInterface->clearEventCallbacks();
std::cout << "[Echoion] Old event callbacks cleared" << std::endl;
std::cout << "[Echoion] About to register new callback..." << std::endl;
g_pluginInterface->registerEventCallback([core](const Api::PluginEvent& event) {
core->onPluginEvent(event);
});
std::cout << "[Echoion] New event callback registered" << std::endl;
std::cout << "[Echoion] Re-registration complete - bot should respond to commands" << std::endl;
return true;
}
// Helper to reload core and re-register plugin interface (for manual reload)
static bool reloadCoreWithInterface() {
if (!g_coreLoader) {
std::cerr << "[Echoion] Cannot reload: CoreLoader not available" << std::endl;
return false;
}
std::cout << "[Echoion] Starting hot reload (Plugin)..." << std::endl;
auto result = g_coreLoader->hotReload(getCorePath());
if (!result) {
std::cerr << std::format("[Echoion] Hot reload failed: {}", result.error().message) << std::endl;
return false;
}
// Now re-register the plugin interface
return reregisterPluginInterface();
}
// Handle plugin commands from TS3
TS3_PLUGIN_API void ts3plugin_onPluginCommandEvent(uint64 serverConnectionHandlerId,
const char* pluginName, const char* command) {
if (std::strcmp(command, "reload") == 0) {
if (ensureCoreLoaded()) {
auto result = g_coreLoader->hotReload(getCorePath());
if (!result) {
std::cerr << std::format("[Echoion] Hot reload failed: {}", result.error().message) << std::endl;
}
reloadCoreWithInterface();
}
}
}
@@ -339,9 +407,7 @@ TS3_PLUGIN_API void ts3plugin_onMenuItemEvent(uint64 serverConnectionHandlerId,
core->stop();
break;
case 4: // Hot Reload Core
if (auto result = g_coreLoader->hotReload(getCorePath()); !result) {
std::cerr << std::format("[Echoion] Hot reload failed: {}", result.error().message) << std::endl;
}
reloadCoreWithInterface();
break;
case 5: // Connect/Disconnect
if (g_pluginInterface) {
+380 -98
View File
@@ -1,8 +1,9 @@
#include "echoion/plugin/PluginInterface.hpp"
#include "echoion/api/LoggerInterface.hpp"
#include "echoion/plugin/PluginInterface.hpp"
#include "teamspeak/public_definitions.h"
#include <format>
#include "teamspeak/public_rare_definitions.h"
#include <cstring>
#include <format>
#include <teamspeak/public_errors.h>
namespace Echoion::Plugin {
@@ -22,12 +23,9 @@ Api::Result<void> PluginInterface::initialize(TS3Functions* ts3Functions) {
ts3Functions_ = ts3Functions;
// Note: Audio device registration is now deferred to allow TeamSpeak GUI to initialize
// It will be called from Plugin::deferredInitialization() after a 3-second delay
// Start audio processing thread (will wait until device is registered)
stopAudioThread_ = false;
audioThread_ = std::jthread([this] {
// Start audio processing thread (will wait until device is registered)
stopAudioThread_ = false;
audioThread_ = std::jthread([this] {
while (!stopAudioThread_) {
std::unique_lock<std::mutex> lock(audioMutex_);
audioCv_.wait(lock, [this] { return !audioQueue_.empty() || stopAudioThread_; });
@@ -112,74 +110,114 @@ Api::Result<void> PluginInterface::shutdown() {
return {};
}
Api::Result<std::vector<Api::ClientInfo>> PluginInterface::getClients() const {
if (!initialized_ || !ts3Functions_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"Plugin interface not initialized"));
}
Api::Result<std::vector<Api::ClientInfo>> PluginInterface::getClients()
{
if (!initialized_ || !ts3Functions_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"Plugin interface not initialized"));
}
std::vector<Api::ClientInfo> clients;
anyID* clientList = nullptr;
std::vector<Api::ClientInfo> clients;
anyID* clientList = nullptr;
unsigned int error = ts3Functions_->getClientList(serverConnectionHandlerId_, &clientList);
if (error != ERROR_ok) {
return std::unexpected(Api::Error(Api::ErrorCode::NetworkError,
std::format("Failed to get client list: {}", error)));
}
unsigned int error =
ts3Functions_->getClientList(serverConnectionHandlerId_, &clientList);
if (error != ERROR_ok) {
return std::unexpected(
Api::Error(Api::ErrorCode::NetworkError,
std::format("Failed to get client list: {}", error)));
}
if (clientList) {
for (int i = 0; clientList[i] != 0; ++i) {
Api::ClientInfo info;
if (clientList) {
for (int i = 0; clientList[i] != 0; ++i) {
Api::ClientInfo info;
info.id = clientList[i];
char* name = nullptr;
if (ts3Functions_->getClientVariableAsString(serverConnectionHandlerId_,
clientList[i], CLIENT_NICKNAME, &name) == ERROR_ok && name) {
info.nickname = name;
ts3Functions_->freeMemory(name);
}
uint64 channelId = 0;
if (ts3Functions_->getChannelOfClient(serverConnectionHandlerId_,
clientList[i], &channelId) == ERROR_ok) {
info.channelId = channelId;
}
// Get nickname
char* name = nullptr;
if (ts3Functions_->getClientVariableAsString(
serverConnectionHandlerId_, clientList[i], CLIENT_NICKNAME,
&name) == ERROR_ok &&
name) {
info.nickname = name;
ts3Functions_->freeMemory(name);
}
clients.push_back(info);
}
ts3Functions_->freeMemory(clientList);
}
// Get unique identifier (UID)
char* uid = nullptr;
if (ts3Functions_->getClientVariableAsString(
serverConnectionHandlerId_, clientList[i],
CLIENT_UNIQUE_IDENTIFIER, &uid) == ERROR_ok &&
uid) {
info.uniqueIdentifier = uid;
ts3Functions_->freeMemory(uid);
}
return clients;
// Get channel ID
uint64 channelId = 0;
if (ts3Functions_->getChannelOfClient(serverConnectionHandlerId_,
clientList[i],
&channelId) == ERROR_ok) {
info.channelId = channelId;
}
// Get cached server groups
info.serverGroups = getCachedServerGroups(clientList[i]);
clients.push_back(info);
}
ts3Functions_->freeMemory(clientList);
}
return clients;
}
Api::Result<std::optional<Api::ClientInfo>> PluginInterface::getClient(uint64_t clientId) const {
if (!initialized_ || !ts3Functions_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"Plugin interface not initialized"));
}
Api::Result<std::optional<Api::ClientInfo>>
PluginInterface::getClient(uint64_t clientId)
{
if (!initialized_ || !ts3Functions_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"Plugin interface not initialized"));
}
Api::ClientInfo info;
info.id = clientId;
Api::ClientInfo info;
info.id = clientId;
char* name = nullptr;
if (ts3Functions_->getClientVariableAsString(serverConnectionHandlerId_,
static_cast<anyID>(clientId), CLIENT_NICKNAME, &name) != ERROR_ok) {
return std::nullopt;
}
// Get client nickname
char* name = nullptr;
if (ts3Functions_->getClientVariableAsString(
serverConnectionHandlerId_, static_cast<anyID>(clientId),
CLIENT_NICKNAME, &name) != ERROR_ok) {
return std::nullopt;
}
if (name) {
info.nickname = name;
ts3Functions_->freeMemory(name);
}
if (name) {
info.nickname = name;
ts3Functions_->freeMemory(name);
}
uint64 channelId = 0;
if (ts3Functions_->getChannelOfClient(serverConnectionHandlerId_,
static_cast<anyID>(clientId), &channelId) == ERROR_ok) {
info.channelId = channelId;
}
// Get client unique identifier (UID)
char* uid = nullptr;
if (ts3Functions_->getClientVariableAsString(
serverConnectionHandlerId_, static_cast<anyID>(clientId),
CLIENT_UNIQUE_IDENTIFIER, &uid) == ERROR_ok &&
uid) {
info.uniqueIdentifier = uid;
ts3Functions_->freeMemory(uid);
}
return info;
// Get client channel ID
uint64 channelId = 0;
if (ts3Functions_->getChannelOfClient(serverConnectionHandlerId_,
static_cast<anyID>(clientId),
&channelId) == ERROR_ok) {
info.channelId = channelId;
}
// Get cached server groups
info.serverGroups = getCachedServerGroups(clientId);
return info;
}
Api::Result<void> PluginInterface::moveClient(uint64_t clientId, uint64_t channelId) {
@@ -331,40 +369,59 @@ Api::Result<void> PluginInterface::sendServerMessage(const std::string& message)
return {};
}
Api::Result<void> PluginInterface::sendAudioData(const std::span<const uint8_t>& data) {
static int callCount = 0;
callCount++;
if (!initialized_ || !ts3Functions_) {
if (callCount <= 10) {
ECHOION_LOG_ERROR(std::format("sendAudioData {}: not initialized", callCount));
}
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"Plugin interface not initialized"));
}
Api::Result<void>
PluginInterface::sendAudioData(const std::span<const short>& data)
{
static int callCount = 0;
static int nonZeroTotal = 0;
callCount++;
if (!audioDeviceOpen_) {
if (callCount <= 10) {
ECHOION_LOG_ERROR(std::format("sendAudioData {}: audio device not open", callCount));
}
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"Audio device not open"));
}
// Debug: Check audio data on first few calls
if (callCount <= 5) {
int nonZero = 0;
int maxSample = 0;
for (size_t i = 0; i < std::min(size_t(100), data.size()); ++i) {
if (data[i] != 0) {
nonZero++;
}
maxSample =
std::max(maxSample, std::abs(static_cast<int>(data[i])));
}
nonZeroTotal += nonZero;
ECHOION_LOG_DEBUG(std::format(
"sendAudioData {}: {} samples, nonZero={}/100, maxSample={}, "
"queueSize={}",
callCount, data.size(), nonZero, maxSample, audioQueue_.size()));
}
// Convert bytes to int16 samples
size_t sampleCount = data.size() / sizeof(int16_t);
std::vector<int16_t> samples(sampleCount);
std::memcpy(samples.data(), data.data(), data.size());
if (!initialized_ || !ts3Functions_) {
if (callCount <= 10) {
ECHOION_LOG_ERROR(
std::format("sendAudioData {}: not initialized", callCount));
}
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"Plugin interface not initialized"));
}
submitAudioData(samples);
if (!audioDeviceOpen_) {
if (callCount <= 10) {
ECHOION_LOG_ERROR(std::format(
"sendAudioData {}: audio device not open", callCount));
}
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"Audio device not open"));
}
return {};
submitAudioData(data);
return {};
}
void PluginInterface::submitAudioData(const std::span<const int16_t> samples) {
std::lock_guard<std::mutex> lock(audioMutex_);
audioQueue_.push(std::vector<int16_t>(samples.begin(), samples.end()));
audioCv_.notify_one();
void PluginInterface::submitAudioData(const std::span<const short> samples)
{
std::lock_guard<std::mutex> lock(audioMutex_);
audioQueue_.push(std::vector<short>(samples.begin(), samples.end()));
audioCv_.notify_one();
}
Api::Result<void> PluginInterface::setWhisperList(const std::vector<uint64_t>& clientIds) {
@@ -400,6 +457,7 @@ Api::Result<void> PluginInterface::setWhisperList(const std::vector<uint64_t>& c
void PluginInterface::registerEventCallback(const Api::EventCallback& callback) {
std::lock_guard<std::mutex> lock(eventMutex_);
eventCallbacks_.push_back(callback);
ECHOION_LOG_INFO(std::format("Event callback registered, total callbacks: {}", eventCallbacks_.size()));
}
void PluginInterface::unregisterEventCallback(const Api::EventCallback& callback) {
@@ -409,6 +467,12 @@ void PluginInterface::unregisterEventCallback(const Api::EventCallback& callback
});
}
void PluginInterface::clearEventCallbacks() {
std::lock_guard<std::mutex> lock(eventMutex_);
ECHOION_LOG_INFO(std::format("Clearing {} event callbacks", eventCallbacks_.size()));
eventCallbacks_.clear();
}
void PluginInterface::onClientConnected(uint64_t serverConnectionHandlerId, uint64_t clientId) {
if (serverConnectionHandlerId != serverConnectionHandlerId_) return;
@@ -702,13 +766,22 @@ Api::Result<void> PluginInterface::openAudioDevice() {
ts3Functions_->getErrorMessage(err, &msg);
std::string errStr = msg;
ts3Functions_->freeMemory(msg);
ECHOION_LOG_WARNING(std::format("Failed to open capture device: {}", errStr));
// Continue without capture - bot only needs playback
}
ECHOION_LOG_WARNING(
std::format("Failed to open capture device: {}", errStr));
}
audioDeviceOpen_ = true;
audioDeviceOpen_ = true;
ECHOION_LOG_INFO("Audio device opened successfully");
return {};
// Configure audio profile for optimal music playback
auto profileResult = configureAudioProfile();
if (!profileResult) {
ECHOION_LOG_WARNING(std::format("Failed to configure audio profile: {}",
profileResult.error().message));
// Continue anyway - audio will still work with default settings
}
return {};
}
Api::Result<void> PluginInterface::closeAudioDevice() {
@@ -749,11 +822,18 @@ uint64_t PluginInterface::getServerConnectionHandlerId() const {
void PluginInterface::broadcastEvent(const Api::PluginEvent& event) {
std::lock_guard<std::mutex> lock(eventMutex_);
for (const auto& callback : eventCallbacks_) {
if (eventCallbacks_.empty()) {
ECHOION_LOG_WARNING("No event callbacks registered, event will be dropped!");
return;
}
ECHOION_LOG_DEBUG(std::format("Broadcasting event to {} callbacks", eventCallbacks_.size()));
for (size_t i = 0; i < eventCallbacks_.size(); ++i) {
try {
callback(event);
ECHOION_LOG_DEBUG(std::format("Calling callback {}...", i));
eventCallbacks_[i](event);
ECHOION_LOG_DEBUG(std::format("Callback {} completed", i));
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Event callback error: {}", e.what()));
ECHOION_LOG_ERROR(std::format("Event callback {} error: {}", i, e.what()));
}
}
}
@@ -784,4 +864,206 @@ std::string PluginInterface::getChannelName(uint64_t channelId) const {
return "Unknown";
}
std::vector<uint64_t> PluginInterface::getCachedServerGroups(uint64_t clientId)
{
if (!ts3Functions_) {
return {};
}
std::lock_guard<std::mutex> lock(serverGroupsMutex_);
// Check cache first
auto it = serverGroupsCache_.find(clientId);
if (it != serverGroupsCache_.end()) {
// Check if cache is still valid (5 minutes)
auto now = std::chrono::steady_clock::now();
auto age = std::chrono::duration_cast<std::chrono::minutes>(
now - it->second.timestamp);
if (age.count() < 5) {
return it->second.groups;
}
}
// Fetch server groups directly using CLIENT_SERVERGROUPS
// This returns a comma-separated string of group IDs
char* groupsStr = nullptr;
unsigned int error =
ts3Functions_->getClientVariableAsString(serverConnectionHandlerId_,
static_cast<anyID>(clientId),
CLIENT_SERVERGROUPS,
&groupsStr);
if (error != ERROR_ok || !groupsStr) {
return {};
}
// Parse comma-separated group IDs
std::vector<uint64_t> groups;
std::string groupsString(groupsStr);
ts3Functions_->freeMemory(groupsStr);
size_t start = 0;
size_t end = groupsString.find(',');
while (end != std::string::npos) {
try {
uint64_t groupId =
std::stoull(groupsString.substr(start, end - start));
groups.push_back(groupId);
} catch (...) {
// Ignore parse errors
}
start = end + 1;
end = groupsString.find(',', start);
}
// Parse last group
if (start < groupsString.size()) {
try {
uint64_t groupId = std::stoull(groupsString.substr(start));
groups.push_back(groupId);
} catch (...) {
// Ignore parse errors
}
}
// Cache the result
auto& entry = serverGroupsCache_[clientId];
entry.groups = groups;
entry.timestamp = std::chrono::steady_clock::now();
return groups;
}
void PluginInterface::onServerGroupByClientID(
uint64_t serverConnectionHandlerId, uint64_t clientDatabaseId,
const char* groupName, uint64_t serverGroupId, uint64_t clientId)
{
if (serverConnectionHandlerId != serverConnectionHandlerId_) {
return;
}
// This callback is not used when fetching via CLIENT_SERVERGROUPS
// It's kept for compatibility with the async API if needed later
}
Api::Result<void> PluginInterface::configureAudioProfile()
{
if (!ts3Functions_ || serverConnectionHandlerId_ == 0) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"Not connected to server"));
}
ECHOION_LOG_INFO("Configuring audio profile for music bot...");
// Configure preprocessor settings (noise reduction, echo cancellation,
// etc.) These settings optimize the audio for music playback rather than
// voice
// Disable denoiser (noise reduction) - we want to keep the full audio
// signal
unsigned int error = ts3Functions_->setPreProcessorConfigValue(
serverConnectionHandlerId_, "denoise", "false");
if (error != ERROR_ok) {
ECHOION_LOG_WARNING(
std::format("Failed to disable denoiser: {}", error));
}
// Disable AGC (Automatic Gain Control) - we handle volume ourselves
error = ts3Functions_->setPreProcessorConfigValue(
serverConnectionHandlerId_, "agc", "false");
if (error != ERROR_ok) {
ECHOION_LOG_WARNING(std::format("Failed to disable AGC: {}", error));
}
// Disable VAD (Voice Activity Detection) - we use continuous transmission
error = ts3Functions_->setPreProcessorConfigValue(
serverConnectionHandlerId_, "vad", "false");
if (error != ERROR_ok) {
ECHOION_LOG_WARNING(std::format("Failed to disable VAD: {}", error));
}
// Disable echo cancellation
error = ts3Functions_->setPreProcessorConfigValue(
serverConnectionHandlerId_, "echocancel", "false");
if (error != ERROR_ok) {
ECHOION_LOG_WARNING(
std::format("Failed to disable echo cancellation: {}", error));
}
// Disable echo reduction
error = ts3Functions_->setPreProcessorConfigValue(
serverConnectionHandlerId_, "echo_reduction", "false");
if (error != ERROR_ok) {
ECHOION_LOG_WARNING(
std::format("Failed to disable echo reduction: {}", error));
}
// Configure playback settings
// Disable typing attenuation (don't lower volume when typing)
error = ts3Functions_->setPlaybackConfigValue(serverConnectionHandlerId_,
"typing_attenuation", "0");
if (error != ERROR_ok) {
ECHOION_LOG_WARNING(
std::format("Failed to disable typing attenuation: {}", error));
}
// Enable continuous transmission (no voice activation)
// This is done by setting input deactivated to 0 (active)
error = ts3Functions_->setClientSelfVariableAsInt(
serverConnectionHandlerId_, CLIENT_INPUT_DEACTIVATED, 0);
if (error != ERROR_ok) {
ECHOION_LOG_WARNING(
std::format("Failed to enable continuous transmission: {}", error));
}
const char* returnCode = nullptr;
// Flush the changes
ts3Functions_->flushClientSelfUpdates(serverConnectionHandlerId_,
returnCode);
ECHOION_LOG_INFO("Audio profile configured successfully");
return {};
}
Api::Result<void> PluginInterface::checkAndHandleFirstRun()
{
if (!ts3Functions_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"TS3 functions not available"));
}
ECHOION_LOG_INFO("Checking for first-run setup...");
// Check if we have a valid client identity
// TeamSpeak requires accepting TOS on first run, which is handled by the
// client We can detect if the client is properly configured by checking the
// identity
char* identity = nullptr;
unsigned int error = ts3Functions_->getClientLibVersion(&identity);
if (error != ERROR_ok || !identity) {
ECHOION_LOG_WARNING(
"TeamSpeak client library not properly initialized");
ECHOION_LOG_INFO(
"Please ensure TeamSpeak client is properly configured:");
ECHOION_LOG_INFO(" 1. Accept the Terms of Service");
ECHOION_LOG_INFO(" 2. Create/obtain your identity");
ECHOION_LOG_INFO(" 3. Complete the initial setup wizard");
if (identity) {
ts3Functions_->freeMemory(identity);
}
return std::unexpected(
Api::Error(Api::ErrorCode::NotInitialized,
"TeamSpeak client not properly initialized. Please "
"complete first-run setup."));
}
if (identity) {
ts3Functions_->freeMemory(identity);
}
ECHOION_LOG_INFO("TeamSpeak client is properly initialized");
return {};
}
} // namespace Echoion::Plugin