commit a583c17916d43a8499b631661c22b139bce13c6f Author: faumaray Date: Sun Feb 1 23:04:49 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/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..24e4e4e --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,125 @@ +cmake_minimum_required(VERSION 3.28) +project(EchoionCore VERSION 1.0.0 LANGUAGES CXX) +list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake") +set(CMAKE_CXX_STANDARD 26) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) +set(CMAKE_POSITION_INDEPENDENT_CODE ON) +add_definitions(-DECHOION_API_EXPORT) + +add_library(EchoionCore SHARED + src/Logger.cpp + src/NetworkClient.cpp + src/SignatureCipher.cpp + src/YouTubeClient.cpp + src/YtDlpManager.cpp + src/AudioDecoder.cpp + src/CommandManager.cpp + src/MusicManager.cpp + src/SubscriptionManager.cpp + src/Core.cpp + src/Export.cpp + src/EventBus.cpp + src/Cache.cpp + src/MemoryPool.cpp + src/Database.cpp + src/RpcServer.cpp + src/ConfigLoader.cpp +) + +add_library(Echoion::Core ALIAS EchoionCore) + +target_include_directories(EchoionCore PUBLIC + $ + $ +) + +target_link_libraries(EchoionCore PUBLIC Echoion::Api) + +find_package(glaze CONFIG REQUIRED) +find_package(PkgConfig REQUIRED) +pkg_check_modules(LIBAV REQUIRED IMPORTED_TARGET + libavformat + libavcodec + libswresample + libavutil +) + +CPMAddPackage( + NAME quickjs + GITHUB_REPOSITORY quickjs-ng/quickjs + GIT_TAG v0.11.0 +) + +set(AddBoost.cmake_VERSION 3.7.3) +CPMAddPackage( + NAME AddBoost.cmake + VERSION "${AddBoost.cmake_VERSION}" + URL "https://github.com/Arniiiii/AddBoost.cmake/archive/refs/tags/${AddBoost.cmake_VERSION}.tar.gz" +) +set(TRY_BOOST_VERSION "1.90.0") +set(BOOST_MY_OPTIONS "BOOST_ENABLE_PYTHON ON;") +set(BOOST_NOT_HEADER_ONLY_COMPONENTS_THAT_YOU_NEED "thread;system") +set(BOOST_HEADER_ONLY_COMPONENTS_THAT_YOU_NEED "asio;beast;uuid;container;cobalt;url") + +add_boost( + TRY_BOOST_VERSION BOOST_HEADER_ONLY_COMPONENTS_THAT_YOU_NEED + BOOST_NOT_HEADER_ONLY_COMPONENTS_THAT_YOU_NEED EchoionCore +) + + +find_package(Threads REQUIRED) +find_package(OpenSSL REQUIRED) +find_package(SQLite3 REQUIRED) +find_package(TBB REQUIRED) + +target_link_libraries(EchoionCore + PUBLIC + PkgConfig::LIBAV + TBB::tbb + SQLite::SQLite3 + PRIVATE + glaze::glaze + Threads::Threads + qjs + Boost::beast + Boost::url + Boost::asio + OpenSSL::SSL + OpenSSL::Crypto + +) + +if(MSVC) + target_compile_options(EchoionCore PRIVATE /W4 /WX-) + target_compile_definitions(EchoionCore PRIVATE _CRT_SECURE_NO_WARNINGS) +else() + target_compile_options(EchoionCore PRIVATE -Wall -Wextra -Wpedantic) +endif() + +set_target_properties(EchoionCore PROPERTIES + OUTPUT_NAME "Echoion" + PREFIX "" + SUFFIX ".ts" + RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin + LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib + ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib +) + +include(GNUInstallDirs) +install(TARGETS EchoionCore + EXPORT EchoionCoreTargets + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} +) + +install(EXPORT EchoionCoreTargets + FILE EchoionCoreTargets.cmake + NAMESPACE Echoion:: + DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/EchoionCore +) + +install(DIRECTORY include/ + DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} +) diff --git a/cmake/FindGStreamer.cmake b/cmake/FindGStreamer.cmake new file mode 100644 index 0000000..f16e861 --- /dev/null +++ b/cmake/FindGStreamer.cmake @@ -0,0 +1,458 @@ +# SPDX-FileCopyrightText: 2024 L. E. Segovia +# SPDX-License-Ref: LGPL-2.1-or-later + +#[=======================================================================[.rst: +FindGStreamer +------- + +Finds the GStreamer library. Requires ``pkg-config`` to be installed. + +Configuration +^^^^^^^^^^^^^ + +This module can be configured with the following variables: + +``GStreamer_STATIC`` + Link against GStreamer statically (see below). + +Imported Targets +^^^^^^^^^^^^^^^^ + +This module defines the following :prop_tgt:`IMPORTED` targets: + +``GStreamer::GStreamer`` + The GStreamer library. + +Result Variables +^^^^^^^^^^^^^^^^ + +This will define the following variables: + +``GStreamer_FOUND`` + True if the system has the GStreamer library. +``GStreamer_VERSION`` + The version of the GStreamer library which was found. +``GStreamer_INCLUDE_DIRS`` + Include directories needed to use GStreamer. +``GStreamer_LIBRARIES`` + Libraries needed to link to GStreamer. + +Cache Variables +^^^^^^^^^^^^^^^ + +The following cache variables may also be set: + +``GStreamer_INCLUDE_DIR`` + The directory containing ``gst/gstversion.h``. +``GStreamer_LIBRARY`` + The path to the GStreamer library. + +Configuration Variables +^^^^^^^^^^^^^^^ + +Setting the following variables is required, depending on the operating system: + +``GStreamer_ROOT_DIR`` + Installation prefix of the GStreamer SDK. + +``GStreamer_USE_STATIC_LIBS` + Set to ON to force the use of the static libraries. Default is OFF. + +``GStreamer_EXTRA_DEPS`` + pkg-config names of the extra dependencies that will be included whenever linking against GStreamer. + +#]=======================================================================] + +if(GStreamer_FOUND) + return() +endif() + +##################### +# Setup variables # +##################### + +if(NOT DEFINED GStreamer_ROOT_DIR AND DEFINED GSTREAMER_ROOT) + set(GStreamer_ROOT_DIR ${GSTREAMER_ROOT}) +endif() + +if(NOT GStreamer_ROOT_DIR) + set(GStreamer_ROOT_DIR "${CMAKE_CURRENT_LIST_DIR}/../../") +endif() + +if(NOT EXISTS "${GStreamer_ROOT_DIR}") + message(FATAL_ERROR "The directory GStreamer_ROOT_DIR=${GStreamer_ROOT_DIR} does not exist") +endif() + +if(NOT DEFINED GStreamer_USE_STATIC_LIBS) + set(GStreamer_USE_STATIC_LIBS OFF) +endif() + +# Set the environment for pkg-config +if(CMAKE_HOST_SYSTEM_NAME STREQUAL "Windows") + set(ENV{PKG_CONFIG_PATH} "${GStreamer_ROOT_DIR}/lib/pkgconfig;${GStreamer_ROOT_DIR}/lib/gstreamer-1.0/pkgconfig;${GStreamer_ROOT_DIR}/lib/gio/modules/pkgconfig") + # Block pkgconf's forced relocation for non-lib/pkgconfig modules on Windows -- https://github.com/pkgconf/pkgconf/commit/dcf529b83d621ed09e99e41fc35fdffd068bd87a + set(ENV{PKG_CONFIG_DONT_DEFINE_PREFIX} 1) +else() + set(ENV{PKG_CONFIG_PATH} "${GStreamer_ROOT_DIR}/lib/pkgconfig:${GStreamer_ROOT_DIR}/lib/gstreamer-1.0/pkgconfig:${GStreamer_ROOT_DIR}/lib/gio/modules/pkgconfig") +endif() + +# Set the list of extra dependencies +if(NOT DEFINED GStreamer_EXTRA_DEPS) + set(GStreamer_EXTRA_DEPS) + if(DEFINED GSTREAMER_EXTRA_DEPS) + set(GStreamer_EXTRA_DEPS ${GSTREAMER_EXTRA_DEPS}) + endif() +endif() + +# Find libraries. This is meant to be used with static libraries +# (hence the reprioritization) but I've added a fallback to shared libraries +# and stub modules in case any are non-existent. +function(_gst_find_library LOCAL_LIB GST_LOCAL_LIB) + if(DEFINED ${GST_LOCAL_LIB}) + return() + endif() + + set(_gst_suffixes ${CMAKE_FIND_LIBRARY_SUFFIXES}) + set(_gst_prefixes ${CMAKE_FIND_LIBRARY_PREFIXES}) + if(APPLE) + set(CMAKE_FIND_LIBRARY_SUFFIXES ".a" ".dylib" ".so" ".tbd") + set(CMAKE_FIND_LIBRARY_PREFIXES "" "lib") + elseif(UNIX) + set(CMAKE_FIND_LIBRARY_SUFFIXES ".a" ".so") + set(CMAKE_FIND_LIBRARY_PREFIXES "" "lib") + else() + set(CMAKE_FIND_LIBRARY_SUFFIXES ".a" ".lib") + set(CMAKE_FIND_LIBRARY_PREFIXES "" "lib") + endif() + + if("${LOCAL_LIB}" IN_LIST _gst_IGNORED_SYSTEM_LIBRARIES) + set(${GST_LOCAL_LIB} ${LOCAL_LIB} PARENT_SCOPE) + else() + find_library(${GST_LOCAL_LIB} + ${LOCAL_LIB} + HINTS ${ARGN} + NO_DEFAULT_PATH + NO_CMAKE_FIND_ROOT_PATH + REQUIRED + ) + set(${GST_LOCAL_LIB} "${${GST_LOCAL_LIB}}" PARENT_SCOPE) + if(NOT ${GST_LOCAL_LIB}) + message(FATAL_ERROR "${LOCAL_LIB} was unexpectedly not found.") + endif() + endif() + + set(CMAKE_FIND_LIBRARY_SUFFIXES ${_gst_suffixes}) + set(CMAKE_FIND_LIBRARY_PREFIXES ${_gst_prefixes}) +endfunction() + +macro(_gst_apply_link_libraries HIDE PC_LIBRARIES PC_HINTS GST_TARGET) + if(APPLE AND ${HIDE}) + target_link_directories(${GST_TARGET} INTERFACE + ${${PC_HINTS}} + ) + endif() + foreach(LOCAL_LIB IN LISTS ${PC_LIBRARIES}) + if(LOCAL_LIB MATCHES "${_gst_SRT_REGEX_PATCH}") + string(REGEX REPLACE "${_gst_SRT_REGEX_PATCH}" "\\1" LOCAL_LIB "${LOCAL_LIB}") + endif() + string(MAKE_C_IDENTIFIER "_gst_${LOCAL_LIB}" GST_LOCAL_LIB) + if(NOT ${GST_LOCAL_LIB}) + _gst_find_library(${LOCAL_LIB} ${GST_LOCAL_LIB} ${${PC_HINTS}}) + endif() + if("${${GST_LOCAL_LIB}}" IN_LIST _gst_IGNORED_SYSTEM_LIBRARIES) + target_link_libraries(${GST_TARGET} INTERFACE + ${${GST_LOCAL_LIB}}) + elseif(APPLE AND ${HIDE}) + set(LOCAL_FILE) + get_filename_component(LOCAL_FILE ${${GST_LOCAL_LIB}} NAME) + target_link_libraries(${GST_TARGET} INTERFACE + "-hidden-l${LOCAL_FILE}") + elseif((UNIX OR ANDROID) AND ${HIDE}) + target_link_libraries(${GST_TARGET} INTERFACE + -Wl,--exclude-libs,${${GST_LOCAL_LIB}}) + else() + target_link_libraries(${GST_TARGET} INTERFACE + ${${GST_LOCAL_LIB}}) + endif() + endforeach() +endmacro() + +macro(_gst_filter_missing_directories GST_INCLUDE_DIRS) + set(_gst_include_dirs) + foreach(DIR IN LISTS ${GST_INCLUDE_DIRS}) + string(MAKE_C_IDENTIFIER "${DIR}" _gst_dir_id) + if(DEFINED _gst_exists_${_gst_dir_id}) + if(_gst_exists_${_gst_dir_id}) + list(APPEND _gst_include_dirs "${DIR}") + endif() + elseif(EXISTS "${DIR}") + list(APPEND _gst_include_dirs "${DIR}") + set(_gst_exists_${_gst_dir_id} TRUE) + else() + message(WARNING "Skipping missing include folder ${DIR}.") + set(_gst_exists_${_gst_dir_id} FALSE) + endif() + endforeach() + set(${GST_INCLUDE_DIRS} "${_gst_include_dirs}") +endmacro() + +macro(_gst_apply_frameworks PC_STATIC_LDFLAGS_OTHER GST_TARGET) + if(APPLE) + # LDFLAGS_OTHER may include framework linkage. Because CMake + # iterates over arguments separated by spaces, it doesn't realise + # that those arguments must not be split. + set(new_ldflags) + set(assemble_framework FALSE) + foreach(_arg IN LISTS ${PC_STATIC_LDFLAGS_OTHER}) + if(assemble_framework) + set(assemble_framework FALSE) + find_library(GST_${_arg}_LIB ${_arg} REQUIRED) + target_link_libraries(${GST_TARGET} + INTERFACE + "${GST_${_arg}_LIB}" + ) + elseif(_arg STREQUAL "-framework") + set(assemble_framework TRUE) + else() + set(assemble_framework FALSE) + list(APPEND new_ldflags "${_arg}") + endif() + endforeach() + set_target_properties(${GST_TARGET} PROPERTIES + INTERFACE_LINK_OPTIONS "${new_ldflags}" + ) + else() + set_target_properties(${TARGET} PROPERTIES + INTERFACE_LINK_OPTIONS "${${PC_STATIC_LDFLAGS_OTHER}}" + ) + endif() +endmacro() + +################################ +# Set up the targets # +################################ + +find_package(PkgConfig REQUIRED) + +# GStreamer's pkg-config modules are a MUST -- but we'll test them below +pkg_check_modules(PC_GStreamer gstreamer-1.0 ${GStreamer_EXTRA_DEPS}) +# Simulate the list that'll be wholearchive'd. +# Unfortunately, this uses an option only available with pkgconf. +# set(_old_pkg_config_executable "${PKG_CONFIG_EXECUTABLE}") +# set(PKG_CONFIG_EXECUTABLE ${PKG_CONFIG_EXECUTABLE} --maximum-traverse-depth=1) +# pkg_check_modules(PC_GStreamer_NoDeps QUIET REQUIRED gstreamer-1.0 ${GStreamer_EXTRA_DEPS}) +# set(PKG_CONFIG_EXECUTABLE "${_old_pkg_config_executable}") + +set(GStreamer_VERSION "${PC_GStreamer_VERSION}") + +# Test validity of the paths +# NOTE: only paths that must be considered are those provided by pkg-config +# NOTE 2: also exclude sysroots +find_path(GStreamer_INCLUDE_DIR + NAMES gst/gstversion.h + PATHS ${PC_GStreamer_INCLUDE_DIRS} + PATH_SUFFIXES gstreamer-1.0 + NO_DEFAULT_PATH + NO_CMAKE_FIND_ROOT_PATH + REQUIRED +) + +find_library(GStreamer_LIBRARY + NAMES gstreamer-1.0 + PATHS ${PC_GStreamer_LIBRARY_DIRS} + NO_DEFAULT_PATH + NO_CMAKE_FIND_ROOT_PATH + REQUIRED +) + +# Android: Ignore these libraries when constructing the IMPORTED_LOCATION +set(_gst_IGNORED_SYSTEM_LIBRARIES c c++ unwind m dl atomic) +if(ANDROID) + list(APPEND _gst_IGNORED_SYSTEM_LIBRARIES log GLESv2 EGL OpenSLES android vulkan) +elseif(APPLE) + list(APPEND _gst_IGNORED_SYSTEM_LIBRARIES iconv resolv System) +endif() + +# Normalize library flags coming from srt/haisrt +# https://github.com/Haivision/srt/commit/b90b64d26f850fb0efcc4cdd8b31cbf74bd4db0c +set(_gst_SRT_REGEX_PATCH "^:lib(.+)\\.(a|so|lib|dylib)$") + +if(PC_GStreamer_FOUND AND (NOT TARGET GStreamer::GStreamer)) + # This is not UNKNOWN but INTERFACE, as we only intend to + # make a target suitable for downstream consumption. + # FindPkgConfig already takes care of things, however it is totally unable + # to discern between shared and static libraries when populating + # xxx_STATIC_LINK_LIBRARIES, so we need to populate them manually. + add_library(GStreamer::GStreamer INTERFACE IMPORTED) + + if(GStreamer_USE_STATIC_LIBS) + _gst_filter_missing_directories(PC_GStreamer_STATIC_INCLUDE_DIRS) + set_target_properties(GStreamer::GStreamer PROPERTIES + INTERFACE_COMPILE_OPTIONS "${PC_GStreamer_STATIC_CFLAGS_OTHER}" + ) + if(PC_GStreamer_STATIC_INCLUDE_DIRS) + set_target_properties(GStreamer::GStreamer PROPERTIES + INTERFACE_INCLUDE_DIRECTORIES "${PC_GStreamer_STATIC_INCLUDE_DIRS}" + ) + endif() + _gst_apply_frameworks(PC_GStreamer_STATIC_LDFLAGS_OTHER GStreamer::GStreamer) + else() + set_target_properties(GStreamer::GStreamer PROPERTIES + INTERFACE_COMPILE_OPTIONS "${PC_GStreamer_CFLAGS_OTHER}" + INTERFACE_INCLUDE_DIRECTORIES "${PC_GStreamer_INCLUDE_DIRS}" + INTERFACE_LINK_OPTIONS "${PC_GStreamer_LDFLAGS_OTHER}" + ) + endif() + + add_library(GStreamer::deps INTERFACE IMPORTED) + + if(NOT GStreamer_USE_STATIC_LIBS) + set_target_properties(GStreamer::deps PROPERTIES + INTERFACE_LINK_LIBRARIES "${PC_GStreamer_LINK_LIBRARIES}" + ) + # We're done + else() + # Handle all libraries, even those specified with -l:libfoo.a (srt) + # Due to the unavailability of pkgconf's `--maximum-traverse-depth` + # on stock pkg-config, I attempt to simulate it through the shared + # libraries listing. + # If pkgconf is available, replace all PC_GStreamer_ entries with + # PC_GStreamer_NoDeps and uncomment the code block above. + foreach(LOCAL_LIB IN LISTS PC_GStreamer_LIBRARIES) + # list(TRANSFORM REPLACE) is of no use here + # https://gitlab.kitware.com/cmake/cmake/-/issues/16899 + if(LOCAL_LIB MATCHES "${_gst_SRT_REGEX_PATCH}") + string(REGEX REPLACE "${_gst_SRT_REGEX_PATCH}" "\\1" LOCAL_LIB "${LOCAL_LIB}") + endif() + string(MAKE_C_IDENTIFIER "_gst_${LOCAL_LIB}" GST_LOCAL_LIB) + if(NOT ${GST_LOCAL_LIB}) + _gst_find_library(${LOCAL_LIB} ${GST_LOCAL_LIB} ${PC_GStreamer_STATIC_LIBRARY_DIRS}) + endif() + target_link_libraries(GStreamer::GStreamer INTERFACE + "${${GST_LOCAL_LIB}}" + ) + endforeach() + + _gst_apply_link_libraries(ON PC_GStreamer_STATIC_LIBRARIES PC_GStreamer_STATIC_LIBRARY_DIRS GStreamer::deps) + endif() + + target_link_libraries(GStreamer::GStreamer + INTERFACE + GStreamer::deps + ) +endif() + +foreach(_gst_PLUGIN IN LISTS GSTREAMER_PLUGINS) + # Safety valve for the custom targets above + if("${_gst_plugin}" IN_LIST _gst_CUSTOM_TARGETS) + continue() + endif() + + if(TARGET GStreamer::${_gst_PLUGIN}) + continue() + endif() + + if(GStreamer_FIND_REQUIRED_${_gst_PLUGIN}) + set(_gst_PLUGIN_REQUIRED REQUIRED) + else() + set(_gst_PLUGIN_REQUIRED) + endif() + + pkg_check_modules(PC_GStreamer_${_gst_PLUGIN} "gst${_gst_PLUGIN}") + + set(GStreamer_${_gst_PLUGIN}_FOUND "${PC_GStreamer_${_gst_PLUGIN}_FOUND}") + if(NOT GStreamer_${_gst_PLUGIN}_FOUND) + continue() + endif() + + add_library(GStreamer::${_gst_PLUGIN} INTERFACE IMPORTED) + _gst_filter_missing_directories(PC_GStreamer_${_gst_PLUGIN}_INCLUDE_DIRS) + set_target_properties(GStreamer::${_gst_PLUGIN} PROPERTIES + INTERFACE_COMPILE_OPTIONS "${PC_GStreamer_${_gst_PLUGIN}_CFLAGS_OTHER}" + ) + if(PC_GStreamer_${_gst_PLUGIN}_INCLUDE_DIRS) + set_target_properties(GStreamer::${_gst_PLUGIN} PROPERTIES + INTERFACE_INCLUDE_DIRECTORIES "${PC_GStreamer_${_gst_PLUGIN}_INCLUDE_DIRS}" + ) + endif() + if(GStreamer_USE_STATIC_LIBS) + _gst_apply_frameworks(PC_GStreamer_${_gst_PLUGIN}_STATIC_LDFLAGS_OTHER GStreamer::${_gst_PLUGIN}) + else() + set_target_properties(GStreamer::${_gst_PLUGIN} PROPERTIES + INTERFACE_LINK_OPTIONS "${PC_GStreamer_${_gst_PLUGIN}_LDFLAGS_OTHER}" + INTERFACE_LINK_LIBRARIES "${PC_GStreamer_${_gst_PLUGIN}_LINK_LIBRARIES}" + ) + # We're done + continue() + endif() + + # Handle all libraries, even those specified with -l:libfoo.a (srt) + _gst_apply_link_libraries(OFF PC_GStreamer_${_gst_PLUGIN}_STATIC_LIBRARIES PC_GStreamer_${_gst_PLUGIN}_STATIC_LIBRARY_DIRS GStreamer::${_gst_PLUGIN}) +endforeach() + +foreach(_gst_PLUGIN IN LISTS GSTREAMER_APIS) + # Safety valve for the custom targets above + if("${_gst_plugin}" IN_LIST _gst_CUSTOM_TARGETS) + continue() + endif() + + if(TARGET GStreamer::${_gst_PLUGIN}) + continue() + endif() + + if(GStreamer_FIND_REQUIRED_${_gst_PLUGIN}) + set(_gst_PLUGIN_REQUIRED REQUIRED) + else() + set(_gst_PLUGIN_REQUIRED) + endif() + + string(REGEX REPLACE "^api_(.+)" "\\1" _gst_PLUGIN_PC "${_gst_PLUGIN}") + string(REPLACE "_" "-" _gst_PLUGIN_PC "${_gst_PLUGIN_PC}") + + pkg_check_modules(PC_GStreamer_${_gst_PLUGIN} "gstreamer-${_gst_PLUGIN_PC}-1.0") + + set(GStreamer_${_gst_PLUGIN}_FOUND "${PC_GStreamer_${_gst_PLUGIN}_FOUND}") + if(NOT GStreamer_${_gst_PLUGIN}_FOUND) + continue() + endif() + + add_library(GStreamer::${_gst_PLUGIN} INTERFACE IMPORTED) + _gst_filter_missing_directories(PC_GStreamer_${_gst_PLUGIN}_INCLUDE_DIRS) + set_target_properties(GStreamer::${_gst_PLUGIN} PROPERTIES + INTERFACE_COMPILE_OPTIONS "${PC_GStreamer_${_gst_PLUGIN}_CFLAGS_OTHER}" + INTERFACE_LINK_OPTIONS "${PC_GStreamer_${_gst_PLUGIN}_LDFLAGS_OTHER}" + ) + if(PC_GStreamer_${_gst_PLUGIN}_INCLUDE_DIRS) + set_target_properties(GStreamer::${_gst_PLUGIN} PROPERTIES + INTERFACE_INCLUDE_DIRECTORIES "${PC_GStreamer_${_gst_PLUGIN}_INCLUDE_DIRS}" + ) + endif() + if(GStreamer_USE_STATIC_LIBS) + _gst_apply_frameworks(PC_GStreamer_${_gst_PLUGIN}_STATIC_LDFLAGS_OTHER GStreamer::${_gst_PLUGIN}) + else() + set_target_properties(GStreamer::${_gst_PLUGIN} PROPERTIES + INTERFACE_LINK_OPTIONS "${PC_GStreamer_${_gst_PLUGIN}_LDFLAGS_OTHER}" + INTERFACE_LINK_LIBRARIES "${PC_GStreamer_${_gst_PLUGIN}_LINK_LIBRARIES}" + ) + # We're done + continue() + endif() + + # Handle all libraries, even those specified with -l:libfoo.a (srt) + _gst_apply_link_libraries(OFF PC_GStreamer_${_gst_PLUGIN}_STATIC_LIBRARIES PC_GStreamer_${_gst_PLUGIN}_STATIC_LIBRARY_DIRS GStreamer::${_gst_PLUGIN}) +endforeach() + +# Perform final validation +include(FindPackageHandleStandardArgs) +set(_gst_handle_version_range) +if(CMAKE_VERSION VERSION_GREATER_EQUAL "3.19.0") + set(_gst_handle_version_range "HANDLE_VERSION_RANGE") +endif() +find_package_handle_standard_args(GStreamer + REQUIRED_VARS + GStreamer_LIBRARY + GStreamer_INCLUDE_DIR + VERSION_VAR GStreamer_VERSION + ${_gst_handle_version_range} + HANDLE_COMPONENTS +) diff --git a/include/echoion/core/AudioDecoder.hpp b/include/echoion/core/AudioDecoder.hpp new file mode 100644 index 0000000..4b89e31 --- /dev/null +++ b/include/echoion/core/AudioDecoder.hpp @@ -0,0 +1,145 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +// Forward declarations for FFmpeg +extern "C" { + struct AVFormatContext; + struct AVCodecContext; + struct AVFrame; + struct AVPacket; + struct SwrContext; + struct AVBufferRef; +} + +namespace Echoion::Core { + +class AudioDecoder { +public: + AudioDecoder(); + ~AudioDecoder(); + + // Initialize decoder with optional hardware acceleration + Api::Result initialize(const Api::HwAccelConfig& hwConfig = {}); + void shutdown(); + + // Open audio source (URL or file path) + Api::Result openSource(const std::string& url); + void closeSource(); + + // Decode audio - returns zero-copy pooled buffer + [[nodiscard]] Api::Result decodeFrame(); + + // Seek to position + Api::Result seek(std::chrono::milliseconds position); + + // Get audio info + [[nodiscard]] Api::Result getStreamInfo() const; + + // Get current position + [[nodiscard]] std::chrono::milliseconds getPosition() const; + + // Check if decoder has more data + [[nodiscard]] bool hasMoreData() const; + + // Set output format + void setOutputFormat(uint32_t sampleRate, uint32_t channels); + + // Set proxy configuration for network requests + void setProxyConfig(const std::optional& proxy); + + // Hardware acceleration + [[nodiscard]] bool isHardwareAccelerated() const { return hwAccelEnabled_; } + [[nodiscard]] Api::HwAccelType getHwAccelType() const { return hwAccelType_; } + + // Enable/disable zero-copy mode + void setZeroCopyEnabled(bool enabled) { zeroCopyEnabled_ = enabled; } + [[nodiscard]] bool isZeroCopyEnabled() const { return zeroCopyEnabled_; } + + // Get decoder statistics + struct Stats { + uint64_t framesDecoded = 0; + uint64_t framesDropped = 0; + uint64_t bytesDecoded = 0; + std::chrono::milliseconds totalDecodeTime{0}; + double averageDecodeTimeMs = 0.0; + bool hwAccelerationActive = false; + }; + [[nodiscard]] Stats getStats() const; + + // Get next S16 chunk (like reference implementation) + bool getNextChunk(std::vector& outChunk, bool blocking = false); + + // Check if decode is finished + [[nodiscard]] bool isFinished() const { return eof_.load(); } + +private: + void decodeThread(); + Api::Result readPacket(); + Api::Result convertFrame(); + void cleanupFfmpeg(); + + // Hardware acceleration setup + Api::Result initializeHardwareAccel(const Api::HwAccelConfig& config); + void cleanupHardwareAccel(); + + // Zero-copy frame conversion + Api::Result convertFrameZeroCopy(); + Api::Result convertFramePooled(); + + // FFmpeg contexts + AVFormatContext* formatContext_ = nullptr; + AVCodecContext* codecContext_ = nullptr; + AVFrame* frame_ = nullptr; + AVPacket* packet_ = nullptr; + SwrContext* swrContext_ = nullptr; + uint8_t* outputBuffer_ = nullptr; // For S16 output like reference + + // Hardware acceleration + AVBufferRef* hwDeviceContext_ = nullptr; + AVBufferRef* hwFramesContext_ = nullptr; + bool hwAccelEnabled_ = false; + Api::HwAccelType hwAccelType_ = Api::HwAccelType::None; + bool zeroCopyEnabled_ = true; + + // Stream info + int audioStreamIndex_ = -1; + Api::AudioStreamInfo streamInfo_; + + // Output format + uint32_t outputSampleRate_ = 48000; + uint32_t outputChannels_ = 2; + + // Threading + std::jthread decodeThread_; + mutable std::mutex mutex_; + std::condition_variable cv_; + std::queue decodedQueue_; + static constexpr size_t MAX_QUEUE_SIZE = 50; + + // S16 audio queue (like reference) - avoids float conversion + std::deque> int16Queue_; + static constexpr size_t MAX_INT16_QUEUE_SIZE = 100; + + // State + std::atomic initialized_{false}; + std::atomic decoding_{false}; + std::atomic eof_{false}; + std::atomic shouldExit_{false}; // For FFmpeg interrupt callback + std::chrono::milliseconds currentPosition_{0}; + std::string currentUrl_; + std::optional proxyConfig_; + + // Statistics + mutable std::mutex statsMutex_; + Stats stats_; +}; + +} // namespace Echoion::Core diff --git a/include/echoion/core/CommandManager.hpp b/include/echoion/core/CommandManager.hpp new file mode 100644 index 0000000..23eac18 --- /dev/null +++ b/include/echoion/core/CommandManager.hpp @@ -0,0 +1,124 @@ +#pragma once + +#include +#include "commands/Command.hpp" +#include "echoion/api/ConfigTypes.hpp" +#include +#include +#include +#include +#include +#include + +namespace Echoion::Core { + +class MusicManager; + +// Function to check if client has permission (set by Core) +using PermissionCheckFunc = std::function; + +/** + * @brief Manages command registration and dispatch. + * + * Usage: + * CommandManager mgr; + * mgr.registerCommand("play"); + * mgr.dispatch(clientId, "play song name", musicManager, replyFunc); + */ +class CommandManager { +public: + CommandManager(); + ~CommandManager() = default; + + // Disable copy + CommandManager(const CommandManager&) = delete; + CommandManager& operator=(const CommandManager&) = delete; + + // Enable move + CommandManager(CommandManager&&) = default; + CommandManager& operator=(CommandManager&&) = default; + + /** + * @brief Registers a command class. + * @tparam T The command class (must inherit Command). + * @param primaryName The primary name/trigger (e.g., "play"). + */ + template + void registerCommand(const std::string& primaryName) { + auto cmd = std::make_shared(); + + std::lock_guard lock(mutex_); + + // Register primary name + commands_[primaryName] = cmd; + uniqueCommands_.push_back({primaryName, cmd}); + + // Register aliases automatically from the class itself + for (auto alias : cmd->getAliases()) { + commands_[std::string(alias)] = cmd; + } + } + + /** + * @brief Dispatches a command message to the appropriate handler. + * @param clientId The client ID who invoked the command. + * @param message The full message (including prefix, e.g., "!play song"). + * @param musicManager Weak pointer to the MusicManager. + * @param replyFunc Function to call to send a reply. + * @param invokerName Name of the invoking user. + * @return true if a command was found and executed, false otherwise. + */ + [[nodiscard]] bool dispatch( + uint64_t clientId, + std::string_view message, + std::weak_ptr musicManager, + std::function replyFunc, + std::string_view invokerName = "" + ); + + [[nodiscard]] bool hasCommand(std::string_view name) const; + [[nodiscard]] std::optional getCommand(std::string_view name) const; + [[nodiscard]] std::vector> getAllCommands() const; + + // Get commands visible to a specific client (for help) + [[nodiscard]] std::vector> getVisibleCommands(uint64_t clientId) const; + + // Check if client can execute a command + [[nodiscard]] bool canExecuteCommand(uint64_t clientId, const CommandPtr& cmd) const; + + void setPrefix(std::string_view prefix); + [[nodiscard]] std::string_view getPrefix() const { return prefix_; } + + // Set permission check function + void setPermissionCheckFunc(PermissionCheckFunc func); + // Set server config for permission checks + void setServerConfig(const Api::AppConfig& config); + +private: + struct CommandEntry { + std::string primaryName; + CommandPtr instance; + }; + + void registerBuiltinCommands(); + + // Internal Help Command (defined in .cpp to access registry) + class HelpCommand; + void registerHelpCommand(); + + std::string prefix_ = "!"; + + // Map for fast lookup: "play" -> PlayCommand + std::map> commands_; + + // List for generating help: {"play", PlayCommand} + std::vector uniqueCommands_; + + mutable std::mutex mutex_; + + // Permission checking + PermissionCheckFunc permissionCheck_; + std::optional serverConfig_; +}; + +} // namespace Echoion::Core diff --git a/include/echoion/core/ConfigLoader.hpp b/include/echoion/core/ConfigLoader.hpp new file mode 100644 index 0000000..878b4c8 --- /dev/null +++ b/include/echoion/core/ConfigLoader.hpp @@ -0,0 +1,30 @@ +#pragma once + +#include +#include +#include + +namespace Echoion::Core { + +// Configuration loader for JSON config files (internal to Core) +class ConfigLoader { +public: + // Load configuration from JSON file + [[nodiscard]] static Api::Result loadFromFile(const std::filesystem::path& path); + + // Save configuration to JSON file + [[nodiscard]] static Api::Result saveToFile(const std::filesystem::path& path, const Api::AppConfig& config); + + // Get default configuration path + [[nodiscard]] static std::filesystem::path getDefaultConfigPath(); + + // Create default configuration + [[nodiscard]] static Api::AppConfig createDefaultConfig(); + +private: + // Parse quality string to enum + [[nodiscard]] static Api::AudioQuality parseQuality(const std::string& str); + [[nodiscard]] static std::string qualityToString(Api::AudioQuality quality); +}; + +} // namespace Echoion::Core diff --git a/include/echoion/core/Core.hpp b/include/echoion/core/Core.hpp new file mode 100644 index 0000000..9c34e66 --- /dev/null +++ b/include/echoion/core/Core.hpp @@ -0,0 +1,111 @@ +#pragma once + +#include +#include +#include "MusicManager.hpp" +#include "CommandManager.hpp" +#include "NetworkClient.hpp" +#include "RpcServer.hpp" +#include "ConfigLoader.hpp" +#include +#include +#include + +namespace Echoion::Core { + +// Main Core implementation of ICoreInterface +class Core : public Api::ICoreInterface { +public: + Core(); + ~Core() override; + + // ICoreInterface implementation + Api::Result initialize(const std::filesystem::path& configPath) override; + Api::Result shutdown() override; + [[nodiscard]] bool isInitialized() const noexcept override; + + // Playback control + Api::Result play(const Api::TrackInfo& track) override; + Api::Result pause() override; + Api::Result resume() override; + Api::Result stop() override; + Api::Result skip(uint32_t count) override; + Api::Result seek(std::chrono::milliseconds position) override; + Api::Result setVolume(float volume) override; + + // Queue management + Api::Result queueTrack(const Api::TrackInfo& track, uint64_t clientId) override; + Api::Result removeFromQueue(uint64_t queueId) override; + Api::Result clearQueue() override; + [[nodiscard]] Api::Result> getQueue() const override; + Api::Result moveInQueue(uint64_t queueId, uint32_t newPosition) override; + + // Track info + [[nodiscard]] Api::Result> getCurrentTrack() const override; + [[nodiscard]] Api::Result getPlaybackState() const override; + + // Playlist + Api::Result loadPlaylist(const std::string& playlistId, uint64_t clientId) override; + [[nodiscard]] Api::Result> getPlaylists() const override; + + // Configuration + Api::Result updateConfig(const Api::AppConfig& config) override; + [[nodiscard]] Api::Result getConfig() const override; + // Reload config from disk (stored path from initialize) + Api::Result reloadConfig(); + + // Hot reload + Api::Result prepareForHotReload() override; + Api::Result restoreAfterHotReload(const Api::HotReloadState& state) override; + + // Event handling + void registerEventCallback(const Api::EventCallback& callback) override; + void unregisterEventCallback(const Api::EventCallback& callback) override; + + // Plugin event processing + Api::Result onPluginEvent(const Api::PluginEvent& event) override; + + // Status + [[nodiscard]] std::string getVersion() const override; + [[nodiscard]] std::chrono::system_clock::time_point getUptime() const override; + + // Additional methods for plugin integration + void setPluginInterface(Api::PluginInterfacePtr pluginInterface) override; + void setAudioDataCallback(const MusicManager::AudioDataCallback& callback); + void triggerAutoConnect() override; + +private: + void onMusicEvent(const Api::PluginEvent& event); + void broadcastEvent(const Api::PluginEvent& event); + [[nodiscard]] bool isAdmin(uint64_t clientId) const; + void updateWhisperList(); + void setupRpcHandlers(); + + // Components + std::shared_ptr networkClient_; + std::shared_ptr musicManager_; + std::unique_ptr commandManager_; + Api::PluginInterfacePtr pluginInterface_; + + // State + Api::AppConfig config_; // Config loaded internally + std::filesystem::path configPath_; // Path to config file for reload + std::chrono::system_clock::time_point startTime_; + std::atomic initialized_{false}; + + // Event callbacks + std::vector eventCallbacks_; + mutable std::mutex eventMutex_; + + // Admin tracking + std::vector adminClients_; + mutable std::mutex adminMutex_; + + // Database for persistence + std::shared_ptr database_; + + // RPC server for Desktop/API clients + std::shared_ptr rpcServer_; +}; + +} // namespace Echoion::Core diff --git a/include/echoion/core/Logger.hpp b/include/echoion/core/Logger.hpp new file mode 100644 index 0000000..272579e --- /dev/null +++ b/include/echoion/core/Logger.hpp @@ -0,0 +1,77 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Echoion::Core { + +// Log file info for rotation +struct LogFileInfo { + std::filesystem::path path; + std::ofstream stream; + uint64_t size = 0; + std::chrono::system_clock::time_point createdAt; +}; + +class Logger : public Api::ILogger { +public: + explicit Logger(std::string_view logDir = "logs", std::string_view baseName = "echoion"); + ~Logger() override; + + void log(Api::LogLevel level, std::string_view message, + std::source_location location) override; + void setMinLevel(Api::LogLevel level) override; + [[nodiscard]] Api::LogLevel getMinLevel() const override; + void registerCallback(const LogCallback& callback) override; + void unregisterCallback(const LogCallback& callback) override; + + void flush(); + void setConsoleOutput(bool enabled); + void setFileOutput(bool enabled); + void setMaxFileSize(uint64_t bytes); + void setMaxFiles(uint32_t count); + +private: + void logWorker(); + void rotateIfNeeded(Api::LogLevel level); + void openLogFiles(); + void cleanupOldLogs(); + [[nodiscard]] std::string formatLogEntry(const Api::LogEntry& entry); + [[nodiscard]] std::string levelToString(Api::LogLevel level); + [[nodiscard]] std::filesystem::path generateLogFilePath(Api::LogLevel level); + [[nodiscard]] std::string formatTimestamp(const std::chrono::system_clock::time_point& tp); + void writeToFile(Api::LogLevel level, const std::string& formattedEntry); + + std::filesystem::path logDir_; + std::string baseName_; + + // Separate files for each level + combined file + std::map levelFiles_; + LogFileInfo combinedFile_; + + std::mutex fileMutex_; + std::mutex queueMutex_; + std::queue logQueue_; + std::thread workerThread_; + std::condition_variable cv_; + std::atomic running_{true}; + std::atomic minLevel_{Api::LogLevel::Info}; + std::atomic consoleOutput_{true}; + std::atomic fileOutput_{true}; + std::atomic maxFileSize_{10 * 1024 * 1024}; // 10 MB per file + std::atomic maxFiles_{5}; + std::vector callbacks_; + std::mutex callbackMutex_; +}; + +} // namespace Echoion::Core diff --git a/include/echoion/core/MusicManager.hpp b/include/echoion/core/MusicManager.hpp new file mode 100644 index 0000000..48da4f2 --- /dev/null +++ b/include/echoion/core/MusicManager.hpp @@ -0,0 +1,133 @@ +#pragma once + +#include +#include "NetworkClient.hpp" +#include "YouTubeClient.hpp" +#include "AudioDecoder.hpp" +#include "SubscriptionManager.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Echoion::Core { + +class MusicManager { +public: + MusicManager(); + ~MusicManager(); + + Api::Result initialize(const Api::BotConfig& config, + std::shared_ptr networkClient, + std::shared_ptr database = nullptr); + void shutdown(); + + [[nodiscard]] Api::Result play(const std::string& query, uint64_t clientId); + [[nodiscard]] Api::Result pause(); + [[nodiscard]] Api::Result resume(); + [[nodiscard]] Api::Result stop(); + [[nodiscard]] Api::Result skip(uint32_t count = 1); + [[nodiscard]] Api::Result seek(std::chrono::milliseconds position); + [[nodiscard]] Api::Result setVolume(float volume); + + [[nodiscard]] Api::Result queueTrack(const Api::TrackInfo& track, uint64_t clientId); + [[nodiscard]] Api::Result removeFromQueue(uint32_t position); + [[nodiscard]] Api::Result clearQueue(); + [[nodiscard]] Api::Result> getQueue() const; + [[nodiscard]] Api::Result moveInQueue(uint32_t from, uint32_t to); + [[nodiscard]] Api::Result toggleShuffle(); + [[nodiscard]] Api::Result toggleRepeat(); + + [[nodiscard]] Api::Result loadPlaylist(const std::string& playlistId, uint64_t clientId); + [[nodiscard]] Api::Result> getPlaylists() const; + + [[nodiscard]] Api::Result> getCurrentTrack() const; + [[nodiscard]] Api::Result getPlaybackState() const; + + [[nodiscard]] Api::Result search(const std::string& query); + + // Search result selection (client-specific) + void storePendingSearch(uint64_t clientId, const std::vector& results); + [[nodiscard]] std::optional> getPendingSearch(uint64_t clientId); + [[nodiscard]] Api::Result selectSearchResult( + uint64_t clientId, uint32_t index, const std::string& invokerName); + + // Help command + [[nodiscard]] std::string getHelpText() const; + + // Subscription management + [[nodiscard]] Api::Result subscribe(uint64_t clientId); + [[nodiscard]] Api::Result unsubscribe(uint64_t clientId); + [[nodiscard]] bool isSubscribed(uint64_t clientId) const; + [[nodiscard]] std::set getSubscribedClients() const; + [[nodiscard]] bool hasSubscribers() const; + + [[nodiscard]] Api::HotReloadState getStateForHotReload() const; + [[nodiscard]] Api::Result restoreFromHotReload(const Api::HotReloadState& state); + + using AudioDataCallback = std::function)>; + void setAudioDataCallback(const AudioDataCallback& callback); + + using SubscriptionChangeCallback = std::function; + void setSubscriptionChangeCallback(const SubscriptionChangeCallback& callback); + + // Called when a client leaves the server + void onClientDisconnected(uint64_t clientId); + +private: + void playbackThread(); + [[nodiscard]] Api::Result resolveQuery(const std::string& query); + [[nodiscard]] Api::Result getStreamUrl(const Api::TrackInfo& track); + void onTrackFinished(); + [[nodiscard]] Api::TrackInfo getNextTrack(); + void shuffleQueue(); + + // Download audio through proxy for playback + [[nodiscard]] Api::Result downloadAudioForPlayback(const std::string& url); + void cleanupTempFile(const std::string& filepath); + + // Temporary file tracking + std::set tempFiles_; + mutable std::mutex tempFilesMutex_; + + std::shared_ptr networkClient_; + std::unique_ptr youTubeClient_; + std::unique_ptr audioDecoder_; + std::unique_ptr subscriptionManager_; + + Api::BotConfig config_; + std::vector queue_; + std::optional currentTrack_; + bool isPlaying_ = false; + bool isPaused_ = false; + bool wasPausedForNoSubscribers_ = false; // Track if we auto-paused + float volume_ = 0.5f; + bool shuffle_ = false; + bool repeat_ = false; + uint64_t nextQueueId_ = 1; + + std::jthread playbackThread_; + mutable std::mutex mutex_; + std::condition_variable cv_; + + // Pending search results per client (for select command) + std::unordered_map> pendingSearches_; + mutable std::mutex pendingSearchMutex_; + + AudioDataCallback audioCallback_; + SubscriptionChangeCallback subscriptionChangeCallback_; + std::mt19937 rng_{std::random_device{}()}; + + static constexpr uint32_t TEAMSPEAK_SAMPLE_RATE = 192000; // Match reference + static constexpr uint32_t TEAMSPEAK_CHANNELS = 2; + static constexpr size_t AUDIO_BUFFER_SIZE = 7680; // 20ms @ 192kHz stereo + static constexpr uint32_t CONCURRENT_LOAD_THREADS = 4; +}; + +} // namespace Echoion::Core diff --git a/include/echoion/core/NetworkClient.hpp b/include/echoion/core/NetworkClient.hpp new file mode 100644 index 0000000..5a2bcb8 --- /dev/null +++ b/include/echoion/core/NetworkClient.hpp @@ -0,0 +1,202 @@ +#pragma once + +#include "boost/asio/ssl/context.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +// Boost.Beast includes needed for template function +#include +#include + + + + + +namespace Echoion::Core { + +// Forward declaration for URL parsing +struct UrlComponents; + +class NetworkClient : public Api::INetworkClient { +public: + NetworkClient(); + ~NetworkClient() override; + + // Initialize with optional proxy + Api::Result initialize(const std::optional& proxy = std::nullopt); + void shutdown(); + + // Synchronous requests + [[nodiscard]] Api::Result get(std::string_view url, + const std::vector& headers = {}); + [[nodiscard]] Api::Result post(std::string_view url, + std::string_view body, const std::vector& headers = {}); + [[nodiscard]] Api::Result request(const Api::HttpRequest& req); + + // Asynchronous requests + [[nodiscard]] std::future> getAsync(std::string_view url, + const std::vector& headers = {}); + [[nodiscard]] std::future> postAsync(std::string_view url, + std::string_view body, const std::vector& headers = {}); + [[nodiscard]] std::future> requestAsync(const Api::HttpRequest& req); + + // Concurrent batch requests + [[nodiscard]] std::vector> requestBatch( + const std::vector& requests); + + // JSON helpers using glaze + template + [[nodiscard]] Api::Result getJson(std::string_view url, + const std::vector& headers = {}) { + auto response = get(url, headers); + if (!response) { + return std::unexpected(response.error()); + } + + T result; + auto ec = glz::read_json(result, response->bodyAsString()); + if (ec) { + return std::unexpected(Api::Error(Api::ErrorCode::ParseError, + std::format("JSON parse error: {}", glz::format_error(ec, response->bodyAsString())))); + } + return result; + } + + template + [[nodiscard]] Api::Result postJson(std::string_view url, const Body& body, + const std::vector& headers = {}) { + std::string jsonBody = glz::write_json(body); + auto response = post(url, jsonBody, headers); + if (!response) { + return std::unexpected(response.error()); + } + + T result; + auto ec = glz::read_json(result, response->bodyAsString()); + if (ec) { + return std::unexpected(Api::Error(Api::ErrorCode::ParseError, + std::format("JSON parse error: {}", glz::format_error(ec, response->bodyAsString())))); + } + return result; + } + + // Proxy configuration + void setProxy(const std::optional& proxy); + [[nodiscard]] std::optional getProxy() const; + void clearProxy(); + + // Retry configuration + void setRetryConfig(const Api::RetryConfig& config); + [[nodiscard]] Api::RetryConfig getRetryConfig() const; + +private: + // Request execution + [[nodiscard]] Api::Result executeWithRetry(const Api::HttpRequest& req); + [[nodiscard]] Api::Result executeRequest(const Api::HttpRequest& req); + + // Proxy and direct execution methods + [[nodiscard]] Api::HttpResponse executeWithProxy( + boost::asio::io_context& ioc, + boost::asio::ssl::context& ctx, + const UrlComponents& urlComp, + const Api::HttpRequest& req, + const Api::ProxyConfig& proxy, + std::chrono::seconds timeout); + + [[nodiscard]] Api::HttpResponse executeWithHttpProxy( + boost::asio::io_context& ioc, + boost::asio::ssl::context& ctx, + const UrlComponents& urlComp, + const Api::HttpRequest& req, + const Api::ProxyConfig& proxy, + std::chrono::seconds timeout); + + [[nodiscard]] Api::HttpResponse executeWithSocks5Proxy( + boost::asio::io_context& ioc, + boost::asio::ssl::context& ctx, + const UrlComponents& urlComp, + const Api::HttpRequest& req, + const Api::ProxyConfig& proxy, + std::chrono::seconds timeout); + + [[nodiscard]] Api::HttpResponse executeDirect( + boost::asio::io_context& ioc, + boost::asio::ssl::context& ctx, + const UrlComponents& urlComp, + const Api::HttpRequest& req, + std::chrono::seconds timeout); + + // HTTP request methods + // Note: sendHttpsRequest is a template, implemented in header below + template + [[nodiscard]] Api::HttpResponse sendHttpsRequest( + Stream& stream, + const UrlComponents& urlComp, + const Api::HttpRequest& req); + + [[nodiscard]] Api::HttpResponse sendHttpRequest( + boost::asio::ip::tcp::socket& socket, + const UrlComponents& urlComp, + const Api::HttpRequest& req); + + [[nodiscard]] Api::HttpResponse sendHttpRequestThroughProxy( + boost::asio::ip::tcp::socket& socket, + const UrlComponents& urlComp, + const Api::HttpRequest& req, + const Api::ProxyConfig& proxy); + + // Request/Response building + [[nodiscard]] boost::beast::http::request buildBeastRequest( + const UrlComponents& urlComp, + const Api::HttpRequest& req); + + [[nodiscard]] Api::HttpResponse convertBeastResponse( + const boost::beast::http::response& beastResponse); + + [[nodiscard]] std::vector addDefaultHeaders(const std::vector& headers); + + std::optional proxy_; + Api::RetryConfig retryConfig_; + mutable std::mutex mutex_; + std::atomic initialized_{false}; + std::atomic requestId_{0}; + + // Thread pool for async operations + std::vector threadPool_; + std::queue()>> taskQueue_; + std::mutex taskMutex_; + std::condition_variable taskCv_; + std::atomic stopThreads_{false}; + static constexpr size_t THREAD_POOL_SIZE = 4; +}; + +// Template implementation for sendHttpsRequest +template +Api::HttpResponse NetworkClient::sendHttpsRequest( + Stream& stream, + const UrlComponents& urlComp, + const Api::HttpRequest& req) { + namespace http = boost::beast::http; + + // Build request + http::request request = buildBeastRequest(urlComp, req); + + // Send + http::write(stream, request); + + // Read response + boost::beast::flat_buffer buffer; + http::response response; + http::read(stream, buffer, response); + + // Convert to Api::HttpResponse + return convertBeastResponse(response); +} + +} // namespace Echoion::Core diff --git a/include/echoion/core/RpcServer.hpp b/include/echoion/core/RpcServer.hpp new file mode 100644 index 0000000..b4d1523 --- /dev/null +++ b/include/echoion/core/RpcServer.hpp @@ -0,0 +1,81 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Echoion::Core { + +namespace asio = boost::asio; +namespace beast = boost::beast; +namespace websocket = beast::websocket; + +class RpcServer : public std::enable_shared_from_this { +public: + using CommandHandler = std::function(const std::string& params, uint64_t clientId)>; + + RpcServer(); + ~RpcServer(); + + // Initialize and start the server + Api::Result start(uint16_t port = 8765); + void stop(); + [[nodiscard]] bool isRunning() const { return running_; } + [[nodiscard]] uint16_t getPort() const { return port_; } + + // Register command handlers + void registerHandler(const std::string& method, CommandHandler handler); + void unregisterHandler(const std::string& method); + + // Authentication + void setAuthToken(const std::string& token); + [[nodiscard]] bool authenticate(const std::string& token); + void addAuthenticatedClient(uint64_t clientId); + void removeAuthenticatedClient(uint64_t clientId); + [[nodiscard]] bool isClientAuthenticated(uint64_t clientId); + + // Broadcast events to all connected clients + void broadcastEvent(const std::string& event, const std::string& data); + + // Send event to specific client + void sendEvent(uint64_t clientId, const std::string& event, const std::string& data); + +private: + void acceptLoop(); + void handleClient(std::shared_ptr> ws); + void processMessage(uint64_t clientId, const std::string& message); + void sendResponse(uint64_t clientId, const Api::RpcResponse& response); + void sendNotification(uint64_t clientId, const Api::RpcNotification& notification); + + asio::io_context ioContext_; + std::optional acceptor_; + std::thread serverThread_; + std::atomic running_{false}; + uint16_t port_ = 8765; + + // Connected clients + std::unordered_map>> clients_; + std::mutex clientsMutex_; + std::atomic nextClientId_{1}; + + // Client threads (for proper cleanup) + std::vector clientThreads_; + std::mutex clientThreadsMutex_; + + // Authenticated clients + std::set authenticatedClients_; + std::mutex authMutex_; + std::string authToken_; + + // Command handlers + std::unordered_map handlers_; + std::mutex handlersMutex_; +}; + +} // namespace Echoion::Core diff --git a/include/echoion/core/SignatureCipher.hpp b/include/echoion/core/SignatureCipher.hpp new file mode 100644 index 0000000..6284d9c --- /dev/null +++ b/include/echoion/core/SignatureCipher.hpp @@ -0,0 +1,129 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace Echoion::Core { + +/** + * Signature cipher for YouTube stream URLs + * Uses QuickJS (when available) to execute the JavaScript decipher functions from player JS + * + * Based on yt-dlp's signature extraction logic + */ +class SignatureCipher { +public: + SignatureCipher(); + ~SignatureCipher(); + + // Disable copy, enable move + SignatureCipher(const SignatureCipher&) = delete; + SignatureCipher& operator=(const SignatureCipher&) = delete; + SignatureCipher(SignatureCipher&&) noexcept; + SignatureCipher& operator=(SignatureCipher&&) noexcept; + + /** + * Initialize the QuickJS solver with core libraries + * Must be called before using the cipher + */ + void initialize(); + + /** + * Set the player JS code and extract decipher functions + * @param playerJsCode The raw player JavaScript code from YouTube + * @return true if extraction succeeded + */ + bool setPlayerJs(std::string_view playerJsCode); + + /** + * Check if the cipher is ready (has valid decipher function) + */ + [[nodiscard]] bool isReady() const; + + /** + * Decipher a signature cipher string + * Format: s=ENCODED_SIG&sp=SIG_PARAM&url=ENCODED_URL + * @param signatureCipher The signature cipher string + * @return The full deciphered URL or empty string on failure + */ + [[nodiscard]] std::string decipher(std::string_view signatureCipher); + + /** + * Solve a challenge (signature or n-param) using the preprocessed player + * @param challenge The challenge string to solve + * @param type "sig" for signature, "n" for n-parameter + * @return The solved challenge or empty string on failure + */ + [[nodiscard]] std::string solveChallenge(const std::string& challenge, const std::string& type); + + /** + * Decipher the n-parameter for throttling + * @param nParam The encoded n parameter + * @return The deciphered n parameter + */ + [[nodiscard]] std::string decipherNParam(std::string_view nParam); + + /** + * Clear the cipher state + */ + void clear(); + + /** + * Check if cipher has been initialized + */ + [[nodiscard]] bool isInitialized() const; + +private: + /** + * Initialize QuickJS runtime and context with solver libraries + */ + void initSolver(); + + /** + * Download solver libraries from remote URL + * @param url The URL to download from + * @return The downloaded JS code or empty string on failure + */ + [[nodiscard]] std::optional downloadSolverLibrary( + std::string_view url); + + /** + * Get cache directory for storing solver libraries + */ + [[nodiscard]] std::filesystem::path getCacheDir(); + + /** + * Execute JavaScript code in QuickJS and return result + */ + [[nodiscard]] std::optional executeJS( + std::string_view code, + std::string_view filename = "